auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
@Test public void conditionalHitUpdatesCache() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(0, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=30") .addHeader("Allow: GET, HEAD") .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); server.enqueue(new MockResponse() .setBody("B")); long t0 = System.currentTimeMillis(); Response response1 = get(server.url("/a")); assertThat(response1.body().string()).isEqualTo("A"); assertThat(response1.header("Allow")).isNull(); assertThat((double) (response1.receivedResponseAtMillis() - t0)).isCloseTo( (double) 0, offset(250.0)); Thread.sleep(500); long t1 = System.currentTimeMillis(); Response response2 = get(server.url("/a")); assertThat(response2.code()).isEqualTo(HttpURLConnection.HTTP_OK); assertThat(response2.body().string()).isEqualTo("A"); assertThat(response2.header("Allow")).isEqualTo("GET, HEAD"); Long originalTimestamp = response2.receivedResponseAtMillis(); assertThat((double) (originalTimestamp - t1)).isCloseTo( (double) 0, offset(250.0)); Thread.sleep(500); long t2 = System.currentTimeMillis(); assertThat((double) (t2 - t1)).isCloseTo((double) 500, offset(250.0)); Response response3 = get(server.url("/a")); assertThat(response3.body().string()).isEqualTo("A"); assertThat(response3.header("Allow")).isEqualTo("GET, HEAD"); assertThat(response3.receivedResponseAtMillis()).isEqualTo(originalTimestamp); assertThat(server.getRequestCount()).isEqualTo(2); }

Target:
@Test public void conditionalHitUpdatesCache() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(0, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=30") .addHeader("Allow: GET, HEAD") .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); server.enqueue(new MockResponse() .setBody("B")); long t0 = System.currentTimeMillis(); Response response1 = get(server.url("/a")); assertThat(response1.body().string()).isEqualTo("A"); assertThat(response1.header("Allow")).isNull(); assertThat((double) (response1.receivedResponseAtMillis() - t0)).isCloseTo( (double) 0, offset(250.0)); Thread.sleep(500); long t1 = System.currentTimeMillis(); Response response2 = get(server.url("/a")); assertThat(response2.code()).isEqualTo(HttpURLConnection.HTTP_OK); assertThat(response2.body().string()).isEqualTo("A"); assertThat(response2.header("Allow")).isEqualTo("GET, HEAD"); Long originalTimestamp = response2.receivedResponseAtMillis(); assertThat((double) (originalTimestamp - t1)).isCloseTo( (double) 0, offset(250.0)); Thread.sleep(500); long t2 = System.currentTimeMillis(); Response response3 = get(server.url("/a")); assertThat(response3.body().string()).isEqualTo("A"); assertThat(response3.header("Allow")).isEqualTo("GET, HEAD"); assertThat(response3.receivedResponseAtMillis()).isEqualTo(originalTimestamp); assertThat(server.getRequestCount()).isEqualTo(2); }
Source:
public void testFlows(@ArquillianResource @OperateOnDeployment(WAR1) URL war1Context, @ArquillianResource @OperateOnDeployment(WAR2) URL war2Context) throws FailingHttpStatusCodeException, MalformedURLException, IOException { WebClient client = new WebClient(); HtmlPage page = client.getPage(war1Context + "/index.faces"); HtmlSubmitInput startFlowButton = (HtmlSubmitInput) page .getElementById("start-simple-flow"); page = startFlowButton.click(); }

Target:
public void testFlows(@ArquillianResource @OperateOnDeployment(WAR1) URL war1Context, @ArquillianResource @OperateOnDeployment(WAR2) URL war2Context) throws FailingHttpStatusCodeException, MalformedURLException, IOException { WebClient client = new WebClient(); testFlow(client, war1Context); testFlow(client, war2Context); }
Source:
public void run() { try { synchronized (lock) { final LeaderLatch latch = leaderLatch.get(); if (latch == null || !latch.hasLeadership()) { log.info("LEGGO MY EGGO. [%s] is leader.", latch == null ? null : latch.getLeader().getId()); stopBeingLeader(); return; } } List<Boolean> allStarted = Arrays.asList( metadataSegmentManager.isStarted(), serverInventoryView.isStarted() ); for (Boolean aBoolean : allStarted) { if (!aBoolean) { log.error("InventoryManagers not started[%s]", allStarted); stopBeingLeader(); return; } } BalancerStrategyFactory factory = new CostBalancerStrategyFactory(getDynamicConfigs().getBalancerComputeThreads()); DruidCoordinatorRuntimeParams params = DruidCoordinatorRuntimeParams.newBuilder() .withStartTime(startTime) .withDatasources(metadataSegmentManager.getInventory()) .withDynamicConfigs(getDynamicConfigs()) .withEmitter(emitter) .withBalancerStrategyFactory(factory) .build(); try { for (DruidCoordinatorHelper helper : helpers) { if (leader && startingLeaderCounter == leaderCounter) { params = helper.run(params); } } } finally { if (params.getBalancerStrategyFactory() != null) { params.getBalancerStrategyFactory().close(); } } } catch (Exception e) { log.makeAlert(e, "Caught exception, ignoring so that schedule keeps going.").emit(); } }

Target:
public void run() { try { synchronized (lock) { final LeaderLatch latch = leaderLatch.get(); if (latch == null || !latch.hasLeadership()) { log.info("LEGGO MY EGGO. [%s] is leader.", latch == null ? null : latch.getLeader().getId()); stopBeingLeader(); return; } } List<Boolean> allStarted = Arrays.asList( metadataSegmentManager.isStarted(), serverInventoryView.isStarted() ); for (Boolean aBoolean : allStarted) { if (!aBoolean) { log.error("InventoryManagers not started[%s]", allStarted); stopBeingLeader(); return; } } try (BalancerStrategyFactory factory = new CostBalancerStrategyFactory(getDynamicConfigs().getBalancerComputeThreads())) { DruidCoordinatorRuntimeParams params = DruidCoordinatorRuntimeParams.newBuilder() .withStartTime(startTime) .withDatasources(metadataSegmentManager.getInventory()) .withDynamicConfigs(getDynamicConfigs()) .withEmitter(emitter) .withBalancerStrategyFactory(factory) .build(); for (DruidCoordinatorHelper helper : helpers) { if (leader && startingLeaderCounter == leaderCounter) { params = helper.run(params); } } } } catch (Exception e) { log.makeAlert(e, "Caught exception, ignoring so that schedule keeps going.").emit(); } }
Source:
public void test_SystemProperties() { Properties originalProperties = System.getProperties(); try { Properties testProperties = new Properties(); testProperties.put("testIncInt", "notInt"); System.setProperties(testProperties); assertNull("returned incorrect default Integer", Integer.getInteger("testIncInt")); assertEquals(Integer.getInteger("testIncInt", 4), new Integer(4)); assertEquals(Integer.getInteger("testIncInt", new Integer(4)), new Integer(4)); } finally { System.setProperties(originalProperties); } }

Target:
public void test_SystemProperties() { Properties originalProperties = System.getProperties(); try { Properties testProperties = new Properties(); testProperties.put("testIncInt", "notInt"); System.setProperties(testProperties); assertNull("returned incorrect default Integer", Integer.getInteger("testIncInt")); assertEquals(new Integer(4), Integer.getInteger("testIncInt", 4)); assertEquals(new Integer(4), Integer.getInteger("testIncInt", new Integer(4))); } finally { System.setProperties(originalProperties); } }
Source:
private Vector3d getRotation() { ListNBT listnbt3 = this.data.getList("Rotation", 5); float rotationYaw = listnbt3.getFloat(0); float rotationPitch = listnbt3.getFloat(1); return new Vector3d(rotationPitch, rotationYaw, 0); }

Target:
private Vector3d getRotation() { final ListNBT listnbt3 = this.data.getList("Rotation", 5); float rotationYaw = listnbt3.getFloat(0); float rotationPitch = listnbt3.getFloat(1); return new Vector3d(rotationPitch, rotationYaw, 0); }
Source:
public void onClick(DialogInterface dialog, int which) { if (which == POSITIVE_BUTTON) { Intent intent = new Intent(ExternalStorageFormatter.FORMAT_ONLY); intent.setComponent(ExternalStorageFormatter.COMPONENT_NAME); intent.putExtras(getIntent()); startService(intent); } finish(); }

Target:
public void onClick(DialogInterface dialog, int which) { if (which == POSITIVE_BUTTON) { Intent intent = new Intent(ExternalStorageFormatter.FORMAT_ONLY); intent.setComponent(ExternalStorageFormatter.COMPONENT_NAME); final StorageVolume storageVolume = getIntent().getParcelableExtra( StorageVolume.EXTRA_STORAGE_VOLUME); intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, storageVolume); startService(intent); } finish(); }
Source:
public IAutoCompleter getFieldRelationshipAutoCompleter(String fieldName) { if (UPTIME.equals(fieldName) || CREATIONDATE.equals(fieldName)) { return BiggerOrSmallerRelationAutoCompleter.INSTANCE; } else if (CPU_USAGE.equals(fieldName) || MEM_USAGE.equals(fieldName) || MEM_USAGE.equals(fieldName) || NETWORK_USAGE.equals(fieldName)) { return NumericConditionRelationAutoCompleter.INSTANCE; } else if (TAG.equals(fieldName)) { return StringOnlyEqualConditionRelationAutoCompleter.INSTANCE; } else { return StringConditionRelationAutoCompleter.INSTANCE; } }

Target:
public IAutoCompleter getFieldRelationshipAutoCompleter(String fieldName) { if (UPTIME.equals(fieldName) || CREATIONDATE.equals(fieldName)) { return BiggerOrSmallerRelationAutoCompleter.INSTANCE; } else if (CPU_USAGE.equals(fieldName) || MEM_USAGE.equals(fieldName) || MEMORY.equals(fieldName) || NETWORK_USAGE.equals(fieldName)) { return NumericConditionRelationAutoCompleter.INSTANCE; } else if (TAG.equals(fieldName)) { return StringOnlyEqualConditionRelationAutoCompleter.INSTANCE; } else { return StringConditionRelationAutoCompleter.INSTANCE; } }
Source:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); SolrSearchSinkUtility.validateSolrConnectionString(config); SolrSearchSinkUtility.verifySolrConfiguration(config); if (inputSchema != null) { SolrSearchSinkUtility.validateIdField(inputSchema, config); SolrSearchSinkUtility.validateInputFieldsDataType(inputSchema); } }

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); config.validateSolrConnectionString(); if (inputSchema != null) { config.validateIdField(inputSchema); config.validateInputFieldsDataType(inputSchema); } }
Source:
public void testUsingSubqueryWithLimit() throws Exception { testQuery( "SELECT COUNT(*) AS cnt FROM ( SELECT * FROM druid.foo LIMIT 10 ) tmpA", ImmutableList.of(), ImmutableList.of() ); }

Target:
public void testUsingSubqueryWithLimit() throws Exception { expectedException.expect(CannotBuildQueryException.class); expectedException.expectMessage("Subquery could not be converted to GroupBy query"); testQuery( "SELECT COUNT(*) AS cnt FROM ( SELECT * FROM druid.foo LIMIT 10 ) tmpA", ImmutableList.of(), ImmutableList.of() ); }
Source:
protected void configure() { if (desiredCapabilities == null) { throw new IllegalStateException(); } if (recordingMode != VncRecordingMode.SKIP) { if (getNetwork() == null) { withNetwork(Network.SHARED); } vncRecordingContainer = new VncRecordingContainer(this) .withVncPassword(DEFAULT_PASSWORD) .withVncPort(VNC_PORT); } if (!customImageNameIsSet) { super.setDockerImageName(getImageForCapabilities(desiredCapabilities)); } String timeZone = System.getProperty("user.timezone"); if (timeZone == null || timeZone.isEmpty()) { timeZone = "Etc/UTC"; } addExposedPorts(SELENIUM_PORT, VNC_PORT); addEnv("TZ", timeZone); if (!getEnvMap().containsKey("no_proxy")) { addEnv("no_proxy", "localhost"); } setCommand("/opt/bin/entry_point.sh"); setStartupAttempts(3); }

Target:
protected void configure() { String seleniumVersion = SeleniumUtils.determineClasspathSeleniumVersion(); if (capabilities == null) { if (seleniumVersion.startsWith("2.")) { logger().info("No capabilities provided, falling back to DesiredCapabilities.chrome()"); capabilities = DesiredCapabilities.chrome(); } else { logger().info("No capabilities provided, falling back to ChromeOptions"); capabilities = new ChromeOptions(); } } if (recordingMode != VncRecordingMode.SKIP) { if (getNetwork() == null) { withNetwork(Network.SHARED); } vncRecordingContainer = new VncRecordingContainer(this) .withVncPassword(DEFAULT_PASSWORD) .withVncPort(VNC_PORT); } if (!customImageNameIsSet) { super.setDockerImageName(getImageForCapabilities(capabilities, seleniumVersion)); } String timeZone = System.getProperty("user.timezone"); if (timeZone == null || timeZone.isEmpty()) { timeZone = "Etc/UTC"; } addExposedPorts(SELENIUM_PORT, VNC_PORT); addEnv("TZ", timeZone); if (!getEnvMap().containsKey(NO_PROXY_KEY)) { addEnv(NO_PROXY_KEY, "localhost"); } setCommand("/opt/bin/entry_point.sh"); setStartupAttempts(3); }
Source:
public BaseStreamTest(boolean tx) { this.tx = tx; }

Target:
public BaseStreamTest(boolean tx) { this.transactional = tx; }
Source:
protected QosValidator<CpuQos> getQosValidator(CpuQos qos) { return new QosValidator<CpuQos>(qos) { @Override protected QosDao<CpuQos> getQosDao() { return AddCpuQosCommand.this.getQosDao(); } @Override public ValidationResult allValuesPresent() { return ValidationResult.VALID; } }; }

Target:
protected QosValidator<CpuQos> getQosValidator(CpuQos qos) { return new CpuQosValidator(qos); }
Source:
protected static void updateAllDiskImageSnapshotsStatusWithCompensation(final Guid diskId, final ImageStatus status, ImageStatus statusForCompensation, final CompensationContext compensationContext) { if (compensationContext != null) { List<DiskImage> diskSnapshots = DbFacade.getInstance().getDiskImageDao().getAllSnapshotsForImageGroup(diskId); for (DiskImage diskSnapshot : diskSnapshots) { diskSnapshot.setImageStatus(statusForCompensation); compensationContext.snapshotEntityStatus(diskSnapshot.getImage()); } TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { DbFacade.getInstance().getImageDao().updateStatusOfImagesByImageGroupId(diskId, status); compensationContext.stateChanged(); return null; } }); } else { DbFacade.getInstance().getImageDao().updateStatusOfImagesByImageGroupId(diskId, status); } }

Target:
protected static void updateAllDiskImageSnapshotsStatusWithCompensation(final Guid diskId, final ImageStatus status, ImageStatus statusForCompensation, final CompensationContext compensationContext) { if (compensationContext != null) { List<DiskImage> diskSnapshots = DbFacade.getInstance().getDiskImageDao().getAllSnapshotsForImageGroup(diskId); for (DiskImage diskSnapshot : diskSnapshots) { diskSnapshot.setImageStatus(statusForCompensation); compensationContext.snapshotEntityStatus(diskSnapshot.getImage()); } TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { DbFacade.getInstance().getImageDao().updateStatusOfImagesByImageGroupId(diskId, status); compensationContext.stateChanged(); return null; } }); } else { updateAllDiskImageSnapshotsStatus(diskId, status); } }
Source:
public void testGetDefaultDataTypes() { final List<DataType> expectedDataTypes = new ArrayList<>(); when(dataTypeUtils.defaultDataTypes()).thenReturn(expectedDataTypes); final List<DataType> actualDataTypes = dataTypeSelect.getDefaultDataTypes(); assertEquals(actualDataTypes, expectedDataTypes); }

Target:
public void testGetDefaultDataTypes() { final List<DataType> expectedDataTypes = new ArrayList<DataType>() {{ add(mock(DataType.class)); }}; when(dataTypeUtils.defaultDataTypes()).thenReturn(expectedDataTypes); final List<DataType> actualDataTypes = dataTypeSelect.getDefaultDataTypes(); assertEquals(actualDataTypes, expectedDataTypes); }
Source:
public String format(String value) { Map<String, String> map = Map.of(StandardEntryType.Article.getDisplayName(), "article", StandardEntryType.Book.getDisplayName(), "book", StandardEntryType.Conference.getDisplayName(), "paper-conference", StandardEntryType.Report.getDisplayName(), "report", StandardEntryType.Thesis.getDisplayName(), "thesis", StandardEntryType.MastersThesis.getDisplayName(), "thesis", StandardEntryType.PhdThesis.getDisplayName(), "thesis", StandardEntryType.WWW.getDisplayName(), "webpage", StandardEntryType.TechReport.getDisplayName(), "report", StandardEntryType.Online.getDisplayName(), "webpage"); return map.getOrDefault(value, "no-type"); }

Target:
public String format(String value) { return switch (StandardEntryType.valueOf(value)) { case Article -> "article"; case Book -> "book"; case Conference -> "paper-conference"; case Report, TechReport -> "report"; case Thesis, MastersThesis, PhdThesis -> "thesis"; case WWW, Online -> "webpage"; default -> "no-type"; }; }
Source:
public static Stream<Constraint> pmapToStream(@Nullable PMap<Class<? extends Constraint>, Constraint> pmap) { if(pmap == null) { return Stream.empty(); } Stream.Builder<Constraint> result = Stream.builder(); pmap.forEach((d, c) -> result.add(c)); return result.build(); }

Target:
static Stream<Constraint> pmapToStream(@Nullable PMap<Class<? extends Constraint>, Constraint> pmap) { if(pmap == null) { return Stream.empty(); } Stream.Builder<Constraint> result = Stream.builder(); pmap.forEach((d, c) -> result.add(c)); return result.build(); }
Source:
protected void doProcessMessage(HandshakeMessage message) throws HandshakeException, GeneralSecurityException { switch (message.getMessageType()) { case HELLO_VERIFY_REQUEST: receivedHelloVerifyRequest((HelloVerifyRequest) message); break; case SERVER_HELLO: receivedServerHello((ServerHello) message); break; case CERTIFICATE: receivedServerCertificate((CertificateMessage) message); break; case SERVER_KEY_EXCHANGE: switch (getKeyExchangeAlgorithm()) { case EC_DIFFIE_HELLMAN: receivedServerKeyExchange((ECDHServerKeyExchange) message); break; case PSK: break; case ECDHE_PSK: receivedServerKeyExchange((EcdhPskServerKeyExchange) message); break; case NULL: LOGGER.info("Received unexpected ServerKeyExchange message in NULL key exchange mode."); break; default: throw new HandshakeException( String.format("Unsupported key exchange algorithm %s", getKeyExchangeAlgorithm().name()), new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE, message.getPeer())); } handshakeMessages.add(message); break; case CERTIFICATE_REQUEST: certificateRequest = (CertificateRequest) message; handshakeMessages.add(message); break; case SERVER_HELLO_DONE: receivedServerHelloDone((ServerHelloDone) message); expectChangeCipherSpecMessage(); break; case FINISHED: receivedServerFinished((Finished) message); break; default: throw new HandshakeException( String.format("Received unexpected handshake message [%s] from peer %s", message.getMessageType(), message.getPeer()), new AlertMessage(AlertLevel.FATAL, AlertDescription.UNEXPECTED_MESSAGE, message.getPeer())); } }

Target:
protected void doProcessMessage(HandshakeMessage message) throws HandshakeException, GeneralSecurityException { switch (message.getMessageType()) { case HELLO_VERIFY_REQUEST: receivedHelloVerifyRequest((HelloVerifyRequest) message); break; case SERVER_HELLO: receivedServerHello((ServerHello) message); break; case CERTIFICATE: receivedServerCertificate((CertificateMessage) message); break; case SERVER_KEY_EXCHANGE: switch (getKeyExchangeAlgorithm()) { case EC_DIFFIE_HELLMAN: receivedServerKeyExchange((ECDHServerKeyExchange) message); break; case PSK: break; case ECDHE_PSK: receivedServerKeyExchange((EcdhPskServerKeyExchange) message); break; case NULL: LOGGER.info("Received unexpected ServerKeyExchange message in NULL key exchange mode."); break; default: throw new HandshakeException( String.format("Unsupported key exchange algorithm %s", getKeyExchangeAlgorithm().name()), new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE, message.getPeer())); } break; case CERTIFICATE_REQUEST: certificateRequest = (CertificateRequest) message; break; case SERVER_HELLO_DONE: receivedServerHelloDone((ServerHelloDone) message); expectChangeCipherSpecMessage(); break; case FINISHED: receivedServerFinished((Finished) message); break; default: throw new HandshakeException( String.format("Received unexpected handshake message [%s] from peer %s", message.getMessageType(), message.getPeer()), new AlertMessage(AlertLevel.FATAL, AlertDescription.UNEXPECTED_MESSAGE, message.getPeer())); } }
Source:
public String getVersion() { try { return applications.iterator().next() .getInstances().iterator().next().getAttributes().get("skipper.release.version"); } catch (Throwable t) { } return "no apps"; }

Target:
public String getVersion() { try { if (applications.iterator().hasNext()) { CollectionModel<AppInstanceStatusResource> instances = applications.iterator().next().getInstances(); if (instances != null && instances.iterator().hasNext()) { AppInstanceStatusResource instance = instances.iterator().next(); if (instance != null && instance.getAttributes() != null && instance.getAttributes().containsKey(StreamRuntimePropertyKeys.ATTRIBUTE_SKIPPER_RELEASE_VERSION)) { String releaseVersion = instance.getAttributes().get(StreamRuntimePropertyKeys.ATTRIBUTE_SKIPPER_RELEASE_VERSION); if (releaseVersion != null) { return releaseVersion; } } } } } catch (Throwable t) { } return NO_APPS; }
Source:
public Optional<List<DataType>> inferInputTypes(CallContext callContext, boolean throwOnFailure) { List<DataType> argumentDataTypes = callContext.getArgumentDataTypes(); for (int i = 0; i < argumentDataTypes.size() - 1; i++) { LogicalType firstLogicalType = argumentDataTypes.get(i).getLogicalType(); LogicalType secondLogicalType = argumentDataTypes.get(i + 1).getLogicalType(); if (!areComparable(firstLogicalType, secondLogicalType)) { if (throwOnFailure) { throw callContext.newValidationError( "All types in EQUALS should support %s comparison with each other. Can not compare %s with %s", requiredComparision == StructuredComparision.EQUALS ? "'EQUALS'" : "both 'EQUALS' and 'ORDER'", firstLogicalType, secondLogicalType ); } return Optional.empty(); } } return Optional.of(argumentDataTypes); }

Target:
public Optional<List<DataType>> inferInputTypes(CallContext callContext, boolean throwOnFailure) { List<DataType> argumentDataTypes = callContext.getArgumentDataTypes(); for (int i = 0; i < argumentDataTypes.size() - 1; i++) { LogicalType firstType = argumentDataTypes.get(i).getLogicalType(); LogicalType secondType = argumentDataTypes.get(i + 1).getLogicalType(); if (!areComparable(firstType.copy(true), secondType.copy(true))) { if (throwOnFailure) { throw callContext.newValidationError( "All types in a comparison should support %s comparison with each other. Can not compare" + " %s with %s", requiredComparision == StructuredComparision.EQUALS ? "'EQUALS'" : "both 'EQUALS' and 'ORDER'", firstType, secondType ); } return Optional.empty(); } } return Optional.of(argumentDataTypes); }
Source:
public void testPublisher() { List<Publisher> publishers = api().listPublishers(); System.out.println(publishers.size()); assertTrue(publishers.size() > 0); }

Target:
public void testPublisher() { List<Publisher> publishers = api().listPublishers(); assertTrue(publishers.size() > 0); }
Source:
private void parseRestStoreAttributes(XMLExtendedStreamReader reader, RestStoreConfigurationBuilder builder) throws XMLStreamException { for (int i = 0; i < reader.getAttributeCount(); i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); String value = reader.getAttributeValue(i); String attributeName = reader.getAttributeLocalName(i); Attribute attribute = Attribute.forName(attributeName); switch (attribute) { case CACHE_NAME: { builder.cacheName(value); break; } case KEY_TO_STRING_MAPPER: { builder.key2StringMapper(value); break; } case RAW_VALUES: { builder.rawValues(Boolean.parseBoolean(value)); break; } case MAX_CONTENT_LENGTH: { builder.maxContentLength(Integer.parseInt(value)); break; } default: { Parser.parseStoreAttribute(reader, i, builder); break; } } } }

Target:
private void parseRestStoreAttributes(XMLExtendedStreamReader reader, RestStoreConfigurationBuilder builder) throws XMLStreamException { boolean restStoreV2 = reader.getSchema().since(10, 1); boolean appendCacheName = false; String path = null; String cacheNameValue = null; for (int i = 0; i < reader.getAttributeCount(); i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); String value = reader.getAttributeValue(i); String attributeName = reader.getAttributeLocalName(i); Attribute attribute = Attribute.forName(attributeName); switch (attribute) { case APPEND_CACHE_NAME_TO_PATH: { if (restStoreV2) throw ParseUtils.unexpectedAttribute(reader, i); appendCacheName = Boolean.parseBoolean(value); break; } case PATH: { if (restStoreV2) throw ParseUtils.unexpectedAttribute(reader, i); path = value; break; } case CACHE_NAME: { cacheNameValue = value; break; } case KEY_TO_STRING_MAPPER: { builder.key2StringMapper(value); break; } case RAW_VALUES: { builder.rawValues(Boolean.parseBoolean(value)); break; } case MAX_CONTENT_LENGTH: { builder.maxContentLength(Integer.parseInt(value)); break; } default: { Parser.parseStoreAttribute(reader, i, builder); break; } } } String cacheName = restStoreV2 ? cacheNameValue : getCacheNameFromLegacy(appendCacheName, path); builder.cacheName(cacheName); }
Source:
public UserTuneElement parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { UserTuneElementBuilder builder = new UserTuneElementBuilder(); outerloop: while (true) { int tag = parser.next(); String name = parser.getName(); String namespace = parser.getNamespace(); switch (tag) { case START_TAG: if (!UserTuneElement.NAMESPACE.equals(namespace)) { LOGGER.log(Level.FINE,"Foreign namespace " + namespace + " detected."); continue outerloop; } try { builder.setArtist(parser.nextText()); parser.next(); builder.setLength(Integer.parseInt(parser.nextText())); parser.next(); builder.setRating(Integer.parseInt(parser.nextText())); parser.next(); builder.setSource(parser.nextText()); parser.next(); builder.setTitle(parser.nextText()); parser.next(); builder.setTrack(Integer.parseInt(parser.nextText())); parser.next(); URI uri = null; uri = new URI(parser.nextText()); builder.setUri(uri); continue outerloop; } catch (IllegalArgumentException e) { throw new XmlPullParserException("Unknown tune value: " + name + " encountered."); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URI"); } case END_TAG: if (UserTuneElement.ELEMENT.equals(name)) { return builder.build(); } } } }

Target:
public UserTuneElement parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { UserTuneElement.Builder builder = UserTuneElement.getBuilder(); XmlPullParser.TagEvent tag = parser.nextTag(); outerloop: while (true) { switch (tag) { case START_ELEMENT: String name = parser.getName(); String namespace = parser.getNamespace(); if (!UserTuneElement.NAMESPACE.equals(namespace)) { continue outerloop; } while (tag == XmlPullParser.TagEvent.START_ELEMENT) { switch (name) { case "artist": builder.setArtist(parser.nextText()); break; case "length": builder.setLength(ParserUtils.getIntegerFromNextText(parser)); break; case "rating": builder.setRating(ParserUtils.getIntegerFromNextText(parser)); break; case "source": builder.setSource(parser.nextText()); break; case "title": builder.setTitle(parser.nextText()); break; case "track": builder.setTrack(parser.nextText()); break; case "uri": URI uri = ParserUtils.getUriFromNextText(parser); builder.setUri(uri); break; } tag = parser.nextTag(); name = parser.getName(); } break; case END_ELEMENT: if (parser.getDepth() == initialDepth) { break outerloop; } break; } } return builder.build(); }
Source:
public void invokeOnPartitionOwner(ClientInvocation invocation, int partitionId) throws IOException { final Address owner = partitionService.getPartitionOwner(partitionId); if (owner == null) { partitionService.firstArrangement(); throw new IOException("Partition does not have an owner. partitionId: " + partitionId); } if (!isMember(owner)) { partitionService.firstArrangement(); throw new TargetNotMemberException("Partition owner '" + owner + "' is not a member."); } invocation.getClientMessage().setPartitionId(partitionId); Connection connection = getConnection(owner); send0(invocation, (ClientConnection) connection); }

Target:
public void invokeOnPartitionOwner(ClientInvocation invocation, int partitionId) throws IOException { Address partitionOwner = partitionService.getPartitionOwner(partitionId); if (partitionOwner == null) { if (invocationLogger.isFinestEnabled()) { invocationLogger.finest("Partition owner is not assigned yet, Retrying on random target"); } invokeOnRandomTarget(invocation); return; } invokeOnTarget(invocation, partitionOwner); }
Source:
public void then_Iterator() { Iterator<String> iterator = Arrays.asList("1").iterator(); then(iterator).toIterable().contains("1"); }

Target:
public void then_Iterator() { Iterator<String> iterator = Collections.singletonList("1").iterator(); then(iterator).hasNext(); }
Source:
public void testCleanupExpiredPools() { long ct = System.currentTimeMillis(); Date activeStart = new Date(ct + 3600000); Date activeEnd = new Date(ct + 7200000); Date expiredStart = new Date(ct - 7200000); Date expiredEnd = new Date(ct - 3600000); Owner owner = this.createOwner(); Product product1 = this.createProduct(owner, "test-product-1", "Test Product 1"); Product product2 = this.createProduct(owner, "test-product-2", "Test Product 2"); Pool activePool = this.createPool(owner, product1, 1L, activeStart, activeEnd); Pool expiredPool = this.createPool(owner, product2, 1L, expiredStart, expiredEnd); try { this.beginTransaction(); this.poolManager.cleanupExpiredPools(); this.commitTransaction(); } catch (RuntimeException e) { this.rollbackTransaction(); throw e; } assertNotNull(this.poolCurator.find(activePool.getId())); assertNull(this.poolCurator.find(expiredPool.getId())); }

Target:
public void testCleanupExpiredPools() { long ct = System.currentTimeMillis(); Date activeStart = new Date(ct + 3600000); Date activeEnd = new Date(ct + 7200000); Date expiredStart = new Date(ct - 7200000); Date expiredEnd = new Date(ct - 3600000); Owner owner = this.createOwner(); Product product1 = this.createProduct("test-product-1", "Test Product 1", owner); Product product2 = this.createProduct("test-product-2", "Test Product 2", owner); Pool activePool = this.createPool(owner, product1, 1L, activeStart, activeEnd); Pool expiredPool = this.createPool(owner, product2, 1L, expiredStart, expiredEnd); this.poolManager.cleanupExpiredPools(); assertNotNull(this.poolCurator.find(activePool.getId())); assertNull(this.poolCurator.find(expiredPool.getId())); }
Source:
public ParquetThriftBytesOutputFormat(TProtocolFactory protocolFactory, Class<? extends TBase<?, ?>> thriftClass, boolean buffered, FieldIgnoredHandler errorHandler) { this(null, protocolFactory, thriftClass, buffered, errorHandler); }

Target:
public ParquetThriftBytesOutputFormat(TProtocolFactory protocolFactory, Class<? extends TBase<?, ?>> thriftClass, boolean buffered, FieldIgnoredHandler errorHandler) { this(new Configuration(), protocolFactory, thriftClass, buffered, errorHandler); }
Source:
public void onError(Throwable e) { try { onTerminate.run(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); downstream.onError(ex); return; } downstream.onError(e); }

Target:
public void onError(Throwable e) { try { onTerminate.run(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); e = new CompositeException(e, ex); } downstream.onError(e); }
Source:
protected boolean isSearchEnabled() { return false; }

Target:
protected boolean isSearchEnabled() { return environment.getConfig().getDiscoveryConfig().getDegreeDiscoveryConfig().isSearchEnabled(); }
Source:
private String resolveJsModuleFile(String moduleAddress) { if (resolutionMode == ResolutionMode.LEGACY) { if (moduleAddress.endsWith(".js")) { return locate(moduleAddress); } else { return locate(moduleAddress + ".js"); } } else if (resolutionMode == ResolutionMode.BROWSER) { return locate(moduleAddress); } for (int i = 0; i < fileExtensionsToSearch.length; i++) { String loadAddress = locate(moduleAddress + fileExtensionsToSearch[i]); if (loadAddress != null) { return loadAddress; } } return null; }

Target:
private String resolveJsModuleFile(String moduleAddress) { if (resolutionMode == ResolutionMode.BROWSER) { return locate(moduleAddress); } for (int i = 0; i < fileExtensionsToSearch.length; i++) { String loadAddress = locate(moduleAddress + fileExtensionsToSearch[i]); if (loadAddress != null) { return loadAddress; } } return null; }
Source:
private void parseResourceColor(Element element, Map<TypeElement, BindingSet.Builder> builderMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); boolean isColorStateList = false; TypeMirror elementType = element.asType(); if (COLOR_STATE_LIST_TYPE.equals(elementType.toString())) { isColorStateList = true; } else if (elementType.getKind() != TypeKind.INT) { error(element, "@%s field type must be 'int' or 'ColorStateList'. (%s.%s)", BindColor.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } hasError |= isInaccessibleViaGeneratedCode(BindColor.class, "fields", element); hasError |= isBindingInWrongPackage(BindColor.class, element); if (hasError) { return; } String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindColor.class).value(); Id resourceId = elementToId(element, BindColor.class, id); BindingSet.Builder builder = getOrCreateBindingBuilder(builderMap, enclosingElement); builder.addResource(new FieldResourceBinding(resourceId, name, isColorStateList ? (useAndroidX ? FieldResourceBinding.Type.COLOR_STATE_LIST_ANDROIDX : FieldResourceBinding.Type.COLOR_STATE_LIST) : (useAndroidX ? FieldResourceBinding.Type.COLOR_ANDROIDX : FieldResourceBinding.Type.COLOR))); erasedTargetNames.add(enclosingElement); }

Target:
private void parseResourceColor(Element element, Map<TypeElement, BindingSet.Builder> builderMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); boolean isColorStateList = false; TypeMirror elementType = element.asType(); if (COLOR_STATE_LIST_TYPE.equals(elementType.toString())) { isColorStateList = true; } else if (elementType.getKind() != TypeKind.INT) { error(element, "@%s field type must be 'int' or 'ColorStateList'. (%s.%s)", BindColor.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } hasError |= isInaccessibleViaGeneratedCode(BindColor.class, "fields", element); hasError |= isBindingInWrongPackage(BindColor.class, element); if (hasError) { return; } String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindColor.class).value(); Id resourceId = elementToId(element, BindColor.class, id); BindingSet.Builder builder = getOrCreateBindingBuilder(builderMap, enclosingElement); FieldResourceBinding.Type colorStateList = useAndroidX ? FieldResourceBinding.Type.COLOR_STATE_LIST_ANDROIDX : FieldResourceBinding.Type.COLOR_STATE_LIST; FieldResourceBinding.Type color = useAndroidX ? FieldResourceBinding.Type.COLOR_ANDROIDX : FieldResourceBinding.Type.COLOR; builder.addResource(new FieldResourceBinding( resourceId, name, isColorStateList ? colorStateList : color)); erasedTargetNames.add(enclosingElement); }
Source:
private static ArrayList<TimeDistanceReport> calculateTimeDistanceResult( long userId, Collection<Long> deviceIds, Collection<Long> groupIds, Double latitude, Double longitude) { ArrayList<TimeDistanceReport> result = new ArrayList<>(); List<List<Double>> sourceLocations = new ArrayList<>(); ArrayList<Double> destinationLocation = new ArrayList<>(); destinationLocation.add(longitude); destinationLocation.add(latitude); for (long deviceId: ReportUtils.getDeviceList(deviceIds, groupIds)) { Context.getPermissionsManager().checkDevice(userId, deviceId); List<Double> deviceLocation = new ArrayList<>(); deviceLocation.add(Context.getIdentityManager().getLastPosition(deviceId).getLongitude()); deviceLocation.add(Context.getIdentityManager().getLastPosition(deviceId).getLatitude()); sourceLocations.add(deviceLocation); } TimeDistanceResponse timeDistanceResponse = Context.getMatrix().getTimeDistanceMatrix(sourceLocations, destinationLocation); int deviceIndex = 0; for (long deviceId: ReportUtils.getDeviceList(deviceIds, groupIds)) { Context.getPermissionsManager().checkDevice(userId, deviceId); TimeDistanceReport timeDistanceReport = new TimeDistanceReport(); timeDistanceReport.setDeviceId(deviceId); timeDistanceReport.setDeviceName(Context.getIdentityManager().getById(deviceId).getName()); timeDistanceReport.setDistance(timeDistanceResponse.getDistance(deviceIndex)); timeDistanceReport.setTime(timeDistanceResponse.getDuration(deviceIndex) * 1000); result.add(timeDistanceReport); deviceIndex++; } return result; }

Target:
private static ArrayList<TimeDistanceReport> calculateTimeDistanceResult( long userId, Collection<Long> deviceIds, Collection<Long> groupIds, Double latitude, Double longitude) { ArrayList<TimeDistanceReport> result = new ArrayList<>(); List<List<Double>> sourceLocations = new ArrayList<>(); List<Double> destinationLocation = new ArrayList<>(); destinationLocation.add(longitude); destinationLocation.add(latitude); List<Long> deviceList = new ArrayList<>(ReportUtils.getDeviceList(deviceIds, groupIds)); for (long deviceId: deviceList) { Context.getPermissionsManager().checkDevice(userId, deviceId); List<Double> deviceLocation = new ArrayList<>(); deviceLocation.add(Context.getIdentityManager().getLastPosition(deviceId).getLongitude()); deviceLocation.add(Context.getIdentityManager().getLastPosition(deviceId).getLatitude()); sourceLocations.add(deviceLocation); } TimeDistanceResponse timeDistanceResponse = Context .getTimeDistanceMatrix() .getTimeDistanceMatrix(sourceLocations, destinationLocation); for (int deviceIndex = 0; deviceIndex < deviceList.size(); deviceIndex++) { long deviceId = deviceList.get(deviceIndex); Context.getPermissionsManager().checkDevice(userId, deviceId); TimeDistanceReport timeDistanceReport = new TimeDistanceReport(); timeDistanceReport.setDeviceId(deviceId); timeDistanceReport.setDeviceName(Context.getIdentityManager().getById(deviceId).getName()); timeDistanceReport.setDistance(timeDistanceResponse.getDistance(deviceIndex)); timeDistanceReport.setTime(timeDistanceResponse.getDuration(deviceIndex) * 1000); result.add(timeDistanceReport); } return result; }
Source:
public void testGetAllDevicesWithSingleDevice() throws IOException, JSONException { String session_id = proxy.loginUser(newUser.get("username"), newUser.get("password")); int deviceNumber = 0; String name = "test"; String displayName = "test"; String deviceType = "deviceType"; String dataType = "json"; String sessionID = session_id; String value = "{\"interval\":0,\"data\":[2.23, 19.45, 20.2]}"; String dataStructure = createDataStructure(value); JSONObject sensor = proxy.createSensor(name, displayName, deviceType, dataType, dataStructure, sessionID); assertNotNull("Failed to create a sensor", sensor); String sensorId = sensor.get("sensor_id").toString(); assertEquals("The new sensorid returned from the server is empty",false, sensorId.isEmpty()); boolean result = proxy.addSensor(sensorId,"deviceType","uuid",sessionID); assertEquals("Failed to add the sensor to a device", true,result); deviceNumber++; JSONArray deviceList = proxy.getAllDevices(sessionID); assertNotNull("Failed to get the list of devices", deviceList); assertEquals("Incorrect device number", deviceNumber,deviceList.length()); }

Target:
public void testGetAllDevicesWithSingleDevice() throws IllegalArgumentException, IOException { String session_id = proxy.loginUser(newUser.get("username"), newUser.get("password")); int deviceNumber = 0; String name = "test"; String displayName = "test"; String deviceType = "deviceType"; String uuid = "uuid"; String dataType = "json"; String sessionID = session_id; String value = "{\"interval\":0,\"data\":[2.23, 19.45, 20.2]}"; String dataStructure = createDataStructure(value); JSONObject sensor = proxy.createSensor(name, displayName, deviceType, dataType, dataStructure, sessionID); assertNotNull("Failed to create a sensor", sensor); String sensorId; try { sensorId = sensor.get("sensor_id").toString(); }catch(JSONException js){ throw new RuntimeException("Failed to get the sensor id from sensor object"); } assertEquals("The new sensorid returned from the server is empty",false, sensorId.isEmpty()); JSONArray deviceList = proxy.getAllDevices(sessionID); assertEquals("No devices should be created", deviceNumber, deviceList.length()); boolean result = proxy.addSensorToDevice(sensorId, "deviceType", uuid, sessionID); assertEquals("Failed to add the sensor to a device", true,result); deviceNumber++; deviceList = proxy.getAllDevices(sessionID); assertNotNull("Failed to get the list of devices", deviceList); assertEquals("Incorrect device number", deviceNumber,deviceList.length()); String returnedDeviceType; String returnedUUID; try { returnedDeviceType = deviceList.getJSONObject(0).getString("type"); returnedUUID = deviceList.getJSONObject(0).getString("uuid"); }catch(JSONException js){ throw new RuntimeException("failed to get a sensor from the device list"); } assertEquals("Incorrect device Type",deviceType,returnedDeviceType); assertEquals("Incorrect UUID", uuid, returnedUUID); }
Source:
ArrayList<FieldValue> getFields(String name) { ArrayList<FieldValue> result = new ArrayList<FieldValue>(); for (FieldValue value : getValues()) { if (value.getField().getName().equals(name)) { result.add(value); } } return result; }

Target:
List<FieldValue> getFields(String name) { ArrayList<FieldValue> result = new ArrayList<FieldValue>(); for (FieldValue value : getValues()) { if (value.getField().getName().equals(name)) { result.add(value); } } return result; }
Source:
private OpenTracingField(String name, Map<String, Object> fields, String spanId, Long startTime, Long duration, String processName) { fOperationName = name; ITmfEventField[] array = fields.entrySet().stream() .map(entry -> new TmfEventField(entry.getKey(), entry.getValue(), null)) .toArray(ITmfEventField[]::new); fContent = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, fields, array); fSpanId = spanId; fStartTime = startTime; fDuration = duration; @SuppressWarnings("null") Map<@NonNull String, @NonNull Object> tags = fields.entrySet().stream() .filter(entry -> { return entry.getKey().startsWith(IOpenTracingConstants.TAGS + '/'); }) .collect(Collectors.toMap(entry -> entry.getKey().substring(5), Entry::getValue)); fTags = tags.isEmpty() ? null : tags; @SuppressWarnings("null") Map<@NonNull String, @NonNull Object> processTags = fields.entrySet().stream() .filter(entry -> { return entry.getKey().startsWith(IOpenTracingConstants.PROCESS_TAGS + "/"); }) .collect(Collectors.toMap(entry -> entry.getKey().substring(12), Entry::getValue)); fProcessTags = processTags.isEmpty() ? null : processTags; fProcessName = processName; }

Target:
private OpenTracingField(String name, Map<String, Object> fields, String spanId, Long startTime, Long duration, String processName) { fOperationName = name; ITmfEventField[] array = fields.entrySet().stream() .map(entry -> new TmfEventField(entry.getKey(), entry.getValue(), null)) .toArray(ITmfEventField[]::new); fContent = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, fields, array); fSpanId = spanId; fStartTime = startTime; fDuration = duration; @SuppressWarnings("null") Map<@NonNull String, @NonNull Object> tags = fields.entrySet().stream() .filter(entry -> { return entry.getKey().startsWith(IOpenTracingConstants.TAGS + '/'); }) .collect(Collectors.toMap(entry -> entry.getKey().substring(5), Entry::getValue)); fTags = tags.isEmpty() ? null : tags; @SuppressWarnings("null") Map<@NonNull String, @NonNull Object> processTags = fields.entrySet().stream() .filter(entry -> { return entry.getKey().startsWith(IOpenTracingConstants.PROCESS_TAGS + '/'); }) .collect(Collectors.toMap(entry -> entry.getKey().substring(12), Entry::getValue)); fProcessTags = processTags.isEmpty() ? null : processTags; fProcessName = processName; }
Source:
public void incrementValue(ITmfEvent event, int quark, long timestamp) throws StateValueTypeException, TimeRangeException, AttributeNotFoundException { ITmfStateSystemBuilder ss = fProvider.getAssignedStateSystem(); int increment = 0; if (fValue.getType() == ITmfStateValue.Type.INTEGER) { increment = fValue.unboxInt(); } else if (fValue.getType() == ITmfStateValue.Type.LONG) { increment = (int) fValue.unboxLong(); } else { Activator.logWarning("TmfXmlStateValue: The value increment is not a number type"); } int currentValue = ss.queryOngoingState(quark).unboxInt(); ITmfStateValue value = TmfStateValue.newValueInt(increment + currentValue); processValue(quark, timestamp, value); }

Target:
public void incrementValue(ITmfEvent event, int quark, long timestamp) throws StateValueTypeException, TimeRangeException, AttributeNotFoundException { ITmfStateSystemBuilder ss = fProvider.getAssignedStateSystem(); switch (fValue.getType()) { case LONG: { long incrementLong = fValue.unboxLong(); long currentValue = ss.queryOngoingState(quark).unboxLong(); ITmfStateValue value = TmfStateValue.newValueLong(incrementLong + currentValue); processValue(quark, timestamp, value); return; } case INTEGER: { int increment = fValue.unboxInt(); int currentValue = ss.queryOngoingState(quark).unboxInt(); ITmfStateValue value = TmfStateValue.newValueInt(increment + currentValue); processValue(quark, timestamp, value); break; } case DOUBLE: case NULL: case STRING: default: Activator.logWarning("TmfXmlStateValue: The increment value is not a number type"); break; } }
Source:
private void setupUI(boolean isOrientationChange) { if (this.getString(R.string.panes).equals("two") && !mNoDetailMode) { if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { setupLandscapeDualPaneView(); } else { setContentView(R.layout.entity_select_layout); restoreExistingSelection(isOrientationChange); } } else { setContentView(R.layout.entity_select_layout); } AdapterView visibleView; GridView gridView = (GridView)this.findViewById(R.id.screen_entity_select_grid); ListView listView = ((ListView)this.findViewById(R.id.screen_entity_select_list)); if (shortSelect.shouldBeLaidOutInGrid()) { visibleView = gridView; gridView.setVisibility(View.VISIBLE); gridView.setNumColumns(shortSelect.getNumEntitiesToDisplayPerRow()); listView.setVisibility(View.GONE); } else { visibleView = listView; listView.setVisibility(View.VISIBLE); gridView.setVisibility(View.GONE); EntitySelectViewSetup.setupDivider(this, listView, shortSelect.usesEntityTileView()); } visibleView.setOnItemClickListener(this); initUIComponents(); restoreLastQueryString(); persistAdapterState(visibleView); setupPreHoneycombFooter(attemptInitCallout()); setupMapNav(); }

Target:
private void setupUI(boolean isOrientationChange) { if (this.getString(R.string.panes).equals("two") && !mNoDetailMode) { if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { setupLandscapeDualPaneView(); } else { setContentView(R.layout.entity_select_layout); restoreExistingSelection(isOrientationChange); } } else { setContentView(R.layout.entity_select_layout); } AdapterView visibleView; GridView gridView = (GridView)this.findViewById(R.id.screen_entity_select_grid); ListView listView = ((ListView)this.findViewById(R.id.screen_entity_select_list)); if (shortSelect.shouldBeLaidOutInGrid()) { visibleView = gridView; gridView.setVisibility(View.VISIBLE); gridView.setNumColumns(shortSelect.getNumEntitiesToDisplayPerRow()); listView.setVisibility(View.GONE); } else { visibleView = listView; listView.setVisibility(View.VISIBLE); gridView.setVisibility(View.GONE); EntitySelectViewSetup.setupDivider(this, listView, shortSelect.usesEntityTileView()); } visibleView.setOnItemClickListener(this); initUIComponents(); restoreLastQueryString(); persistAdapterState(visibleView); attemptInitCallout(); setupPreHoneycombFooter(); setupMapNav(); }