auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Visualization getVisualizationInternal(String identifier) { return visualizationCache.computeIfAbsent(identifier, (s) -> { StepEngineSettings.VisualizationSetting settings = visualizationSettingsMap.get(s); String visualizationClassName = settings.getVisualizationClassName(); return StreamSupport.stream(ServiceLoader.load(Visualization.Factory.class).spliterator(), false) .filter(factory -> visualizationClassName.equals(factory.getVisualizationClass().getName())) .findFirst().orElseThrow(() -> new RuntimeException("Failed: No Visualization.Factory found for " + s + " and " + visualizationClassName) ).create(settings); }); }

Target:
private Visualization getVisualizationInternal(String identifier) { return visualizationCache.computeIfAbsent(identifier, s -> { StepEngineSettings.VisualizationSetting settings = visualizationSettingsMap.get(s); String visualizationClassName = settings.getVisualizationClassName(); return getVisualizationFactory(identifier, visualizationClassName).create(settings); }); }
Source:
public Task<String> ensurePathExists(String path) { return exists(path).flatMap(stat -> { if (!stat.isPresent()) { Task<String> createAndIgnoreNodeExistsException = create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT) .recoverWith("recover from NodeExistsException", e -> { if (e instanceof KeeperException.NodeExistsException) { return Task.value(path); } else { return Task.failure(e); } }); String parent = path.substring(0, path.lastIndexOf('/')); if (parent.isEmpty()) { return createAndIgnoreNodeExistsException; } else { return ensurePathExists(parent).flatMap(unused -> createAndIgnoreNodeExistsException); } } else { return Task.value(path); } }); }

Target:
public Task<String> ensurePathExists(String path) { return exists(path).flatMap(stat -> { if (!stat.isPresent()) { Task<String> createIfAbsent = create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT) .recoverWith("recover from NodeExistsException", e -> { if (e instanceof KeeperException.NodeExistsException) { return Task.value(path); } else { return Task.failure(e); } }); String parent = path.substring(0, path.lastIndexOf('/')); if (parent.isEmpty()) { return createIfAbsent; } else { return ensurePathExists(parent).flatMap(unused -> createIfAbsent); } } else { return Task.value(path); } }); }
Source:
public static void initInternal(Context context) { SalesforceSDKUpgradeManager.getInstance().upgrade(); Encryptor.init(context); HttpAccess.init(context, INSTANCE.getUserAgent()); final RuntimeConfig runtimeConfig = RuntimeConfig.getRuntimeConfig(context); final String idpAppUrlScheme = runtimeConfig.getString(RuntimeConfig.ConfigKey.IDPAppURLScheme); if (!TextUtils.isEmpty(idpAppUrlScheme)) { INSTANCE.idpAppURIScheme = idpAppUrlScheme; } (new Thread(new Runnable() { @Override public void run() { final String loginServer = SalesforceSDKManager.getInstance().getLoginServerManager().getSelectedLoginServer().url; final AuthConfigUtil.SSOAuthConfig authConfig = AuthConfigUtil.getSSOAuthConfig(loginServer); boolean browserLoginEnabled = false; if (authConfig != null) { browserLoginEnabled = authConfig.isBrowserLoginEnabled(); } SalesforceSDKManager.getInstance().setBrowserLoginEnabled(browserLoginEnabled); } })).start(); }

Target:
public static void initInternal(Context context) { SalesforceSDKUpgradeManager.getInstance().upgrade(); Encryptor.init(context); HttpAccess.init(context, INSTANCE.getUserAgent()); final RuntimeConfig runtimeConfig = RuntimeConfig.getRuntimeConfig(context); final String idpAppUrlScheme = runtimeConfig.getString(RuntimeConfig.ConfigKey.IDPAppURLScheme); if (!TextUtils.isEmpty(idpAppUrlScheme)) { INSTANCE.idpAppURIScheme = idpAppUrlScheme; } }
Source:
public CacheConfiguration getCache() { return cache; }

Target:
public CacheConfiguration getCache() { if (cache != null && (cache.getSize() == 0 || cache.getTtl() == 0)) { return null; } return cache; }
Source:
CommandLineOptions build() { return new CommandLineOptions( this.files.build(), this.inPlace, this.lines.build(), this.offsets.build(), this.lengths.build(), this.aosp, this.version, this.help, this.stdin, this.fixImportsOnly, this.removeJavadocOnlyImports, this.validationMode ); }

Target:
CommandLineOptions build() { return new CommandLineOptions( this.files.build(), this.inPlace, this.lines.build(), this.offsets.build(), this.lengths.build(), this.aosp, this.version, this.help, this.stdin, this.fixImportsOnly, this.removeJavadocOnlyImports, this.sortImports, this.removeUnusedImports, this.dryRun, this.setExitIfChanged); }
Source:
public void update() { for (Integer rank = this.minRank; rank <= this.maxRank; rank++) { LOGGER.info(String.format("Starting rank %d", rank)); for (Map<String, Object> sector : getIndexSectors(rank)) for (UpdateRow place : getIndexSectorPlaces(rank, (Integer) sector.get("geometry_sector"))) { template.update("update placex set indexed_status = 0 where place_id = ?", place.getPlaceId()); final List<PhotonDoc> updatedDocs = exporter.getByPlaceId(place.getPlaceId()); for (PhotonDoc updatedDoc : updatedDocs) { switch (place.getIndexdStatus()) { case 1: if (updatedDoc.isUsefulForIndex()) updater.create(updatedDoc); break; case 2: if (!updatedDoc.isUsefulForIndex()) { updater.delete(place.getPlaceId()); break; } updater.updateOrCreate(updatedDoc); break; case 100: updater.delete(place.getPlaceId()); break; default: LOGGER.error(String.format("Unknown index status %d", place.getIndexdStatus())); break; } } } } updater.finish(); }

Target:
public void update() { for (Integer rank = this.minRank; rank <= this.maxRank; rank++) { LOGGER.info(String.format("Starting rank %d", rank)); for (Map<String, Object> sector : getIndexSectors(rank)) for (UpdateRow place : getIndexSectorPlaces(rank, (Integer) sector.get("geometry_sector"))) { template.update("update placex set indexed_status = 0 where place_id = ?", place.getPlaceId()); if (place.getIndexdStatus() == 100) { updater.delete(place.getPlaceId()); continue; } final List<PhotonDoc> updatedDocs = exporter.getByPlaceId(place.getPlaceId()); for (PhotonDoc updatedDoc : updatedDocs) { switch (place.getIndexdStatus()) { case 1: if (updatedDoc.isUsefulForIndex()) updater.create(updatedDoc); break; case 2: if (!updatedDoc.isUsefulForIndex()) { updater.delete(place.getPlaceId()); break; } updater.updateOrCreate(updatedDoc); break; default: LOGGER.error(String.format("Unknown index status %d", place.getIndexdStatus())); break; } } } } updater.finish(); }
Source:
private String sendAvroMessage(SpecificRecord message) throws ProducerException { try { GenericRecord avroRecord = addForkliftPropertiesToAvroObject(message); ProducerRecord record = new ProducerRecord<String, GenericRecord>(topic, null, avroRecord); try { RecordMetadata result = (RecordMetadata)kafkaProducer.send(record).get(); return result.topic() + "-" + result.partition() + "-" + result.offset(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ProducerException("Error sending Kafka Message", e); } catch (ExecutionException e) { throw new ProducerException("Error creating Kafka Message", e); } } catch (IOException e) { throw new ProducerException("Error creating Kafka Message", e); } }

Target:
private String sendAvroMessage(SpecificRecord message) throws ProducerException { try { ProducerRecord record = null; if(this.properties.size() > 0){ GenericRecord avroRecord = addForkliftPropertiesToAvroObject(message); record = new ProducerRecord<String, GenericRecord>(topic, null, avroRecord); } else{ record = new ProducerRecord<String, SpecificRecord>(topic, null, message); } try { RecordMetadata result = (RecordMetadata)kafkaProducer.send(record).get(); return result.topic() + "-" + result.partition() + "-" + result.offset(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ProducerException("Error sending Kafka Message", e); } catch (ExecutionException e) { throw new ProducerException("Error sending Kafka Message", e); } } catch (IOException e) { throw new ProducerException("Error creating Kafka Message", e); } }
Source:
protected void rebuild() { try (FlowScopeLog parentLogger = new FlowScopeLogBuilder(LOGGER, Level.FINE, "TimeGraphView:Rebuilding").setCategory(getViewId()).build()) { setStartTime(fTrace.getStartTime().toNanos()); setEndTime(fTrace.getEndTime().toNanos()); refresh(); ITmfTrace viewTrace = fTrace; if (viewTrace == null) { return; } resetView(viewTrace); List<IMarkerEventSource> markerEventSources = new ArrayList<>(); synchronized (fBuildJobMap) { for (ITmfTrace trace : getTracesToBuild(viewTrace)) { if (trace == null) { break; } List<@NonNull IMarkerEventSource> adapters = TmfTraceAdapterManager.getAdapters(trace, IMarkerEventSource.class); markerEventSources.addAll(adapters); Job buildJob = new Job(getTitle() + Messages.AbstractTimeGraphView_BuildJob) { @Override protected IStatus run(IProgressMonitor monitor) { new BuildRunnable(trace, viewTrace, parentLogger).run(monitor); monitor.done(); return Status.OK_STATUS; } }; fBuildJobMap.put(trace, buildJob); buildJob.schedule(); } } fMarkerEventSourcesMap.put(viewTrace, markerEventSources); } }

Target:
protected void rebuild() { try (FlowScopeLog parentLogger = new FlowScopeLogBuilder(LOGGER, Level.FINE, "TimeGraphView:Rebuilding").setCategory(getViewId()).build()) { setTimeBoundsAndRefresh(); ITmfTrace viewTrace = fTrace; if (viewTrace == null) { return; } resetView(viewTrace); List<IMarkerEventSource> markerEventSources = new ArrayList<>(); synchronized (fBuildJobMap) { for (ITmfTrace trace : getTracesToBuild(viewTrace)) { if (trace == null) { break; } List<@NonNull IMarkerEventSource> adapters = TmfTraceAdapterManager.getAdapters(trace, IMarkerEventSource.class); markerEventSources.addAll(adapters); Job buildJob = new Job(getTitle() + Messages.AbstractTimeGraphView_BuildJob) { @Override protected IStatus run(IProgressMonitor monitor) { new BuildRunnable(trace, viewTrace, parentLogger).run(monitor); monitor.done(); return Status.OK_STATUS; } }; fBuildJobMap.put(trace, buildJob); buildJob.schedule(); } } fMarkerEventSourcesMap.put(viewTrace, markerEventSources); } }
Source:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ImplementNetworkVspCommand)) return false; if (!super.equals(o)) return false; ImplementNetworkVspCommand that = (ImplementNetworkVspCommand) o; if (_dhcpOption != null ? !_dhcpOption.equals(that._dhcpOption) : that._dhcpOption != null) return false; if (_network != null ? !_network.equals(that._network) : that._network != null) return false; return true; }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ImplementNetworkVspCommand)) { return false; } ImplementNetworkVspCommand that = (ImplementNetworkVspCommand) o; return super.equals(that) && Objects.equals(_dhcpOption, that._dhcpOption) && Objects.equals(_network, that._network); }
Source:
static String getRequireBundleValue(File manifestFile) { String bundleValue; try (FileInputStream manifestStream = new FileInputStream(manifestFile)) { Manifest manifest = new Manifest(manifestStream); bundleValue = manifest.getMainAttributes().getValue(REQUIRE_BUNDLE_KEY); } catch (IOException e) { throw new GradleException( "Unable to determine the bundle dependencies defined in manifest: " + manifestFile.getAbsolutePath(), e); } return bundleValue; }

Target:
private static String getRequireBundleValue(File manifestFile) { String bundleValue; try (FileInputStream manifestStream = new FileInputStream(manifestFile)) { Manifest manifest = new Manifest(manifestStream); bundleValue = manifest.getMainAttributes().getValue(REQUIRE_BUNDLE_KEY); } catch (IOException e) { throw new GradleException( "Unable to determine the bundle dependencies defined in manifest: " + manifestFile.getAbsolutePath(), e); } return bundleValue; }
Source:
public void testMetadataUpdaterBinary() throws Exception { context.getRouteDefinition("FcrepoSerializationBinaryUpdater").adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { replaceFromWith("direct:start"); mockEndpointsAndSkip("*"); } }); context.start(); getMockEndpoint("mock:file:mock:direct:binary_file").expectedMessageCount(0); final String body = IOUtils.toString(ObjectHelper.loadResourceAsStream("binary.rdf"), "UTF-8"); final Map<String, Object> headers = ImmutableMap.of( BASE_URL, baseURL, IDENTIFIER, "foo"); template.sendBodyAndHeaders(body, headers); assertMockEndpointsSatisfied(); }

Target:
public void testMetadataUpdaterBinary() throws Exception { context.getRouteDefinition("FcrepoSerializationBinaryUpdater").adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { replaceFromWith("direct:start"); mockEndpointsAndSkip("*"); } }); context.start(); getMockEndpoint("mock:file:binary_file").expectedMessageCount(0); final String body = IOUtils.toString(ObjectHelper.loadResourceAsStream("binary.rdf"), "UTF-8"); final Map<String, Object> headers = ImmutableMap.of( BASE_URL, baseURL, IDENTIFIER, "foo"); template.sendBodyAndHeaders(body, headers); assertMockEndpointsSatisfied(); }
Source:
public ObjectFilter withParameters(Map<String, Object> namedParameters) { if (namedParameters == null) { throw new IllegalArgumentException("namedParameters argument cannot be null"); } for (String paramName : getParameterNames()) { if (namedParameters.get(paramName) == null) { throw new IllegalArgumentException("Query parameter '" + paramName + "' was not set"); } } return new RejectObjectFilter<>(namedParameters, parsingResult); }

Target:
public ObjectFilter withParameters(Map<String, Object> namedParameters) { validateParameters(namedParameters); return new RejectObjectFilter<>(namedParameters, parsingResult); }
Source:
public String commitMessage(GitRepositoryManager repoManager, Provider<ReviewDb> db) throws IOException, OrmException { if (commitMessage == null) { PatchSet.Id psId = change(db).currentPatchSetId(); String sha1 = db.get().patchSets().get(psId).getRevision().get(); Project.NameKey name = change.getProject(); Repository repo = repoManager.openRepository(name); RevWalk walk = new RevWalk(repo); try { RevCommit c = walk.parseCommit(ObjectId.fromString(sha1)); commitMessage = c.getFullMessage(); } finally { walk.release(); repo.close(); } } return commitMessage; }

Target:
public String commitMessage(GitRepositoryManager repoManager, Provider<ReviewDb> db) throws IOException, OrmException { if (commitMessage == null) { PatchSet.Id psId = change(db).currentPatchSetId(); String sha1 = db.get().patchSets().get(psId).getRevision().get(); Project.NameKey name = change.getProject(); Repository repo = repoManager.openRepository(name); try { RevWalk walk = new RevWalk(repo); try { RevCommit c = walk.parseCommit(ObjectId.fromString(sha1)); commitMessage = c.getFullMessage(); } finally { walk.release(); } } finally { repo.close(); } } return commitMessage; }
Source:
private void createAndDispatchGDBFocusChangedEvent() { assert fCurrentThreadCtx != null; fCommandControl.getSession().dispatchEvent(new GDBFocusChangedEvent(fCurrentThreadCtx), fCommandControl.getProperties()); }

Target:
private void createAndDispatchGDBFocusChangedEvent() { assert fCurrentGDBFocus != null; fGdbcontrol.getSession().dispatchEvent(new GDBFocusChangedEvent(fCurrentGDBFocus), fGdbcontrol.getProperties()); }
Source:
public void init() { if (!init) { for (String mapName : store.getMapNames()) { if (mapName.startsWith(UNDO_LOG_NAME_PREFIX)) { if (mapName.equals(UNDO_LOG_NAME_PREFIX)) { if (!store.hasData(mapName) || store.isReadOnly()) { store.removeMap(mapName); } continue; } boolean committed = mapName.charAt(UNDO_LOG_NAME_PREFIX.length()) == UNDO_LOG_COMMITTED; if (store.hasData(mapName) || committed) { int transactionId = Integer.parseInt(mapName.substring(UNDO_LOG_NAME_PREFIX.length() + 1)); VersionedBitSet openTxBitSet = openTransactions.get(); if (!openTxBitSet.get(transactionId)) { Object[] data = preparedTransactions.get(transactionId); int status; String name; if (data == null) { status = Transaction.STATUS_OPEN; name = null; } else { status = (Integer) data[0]; name = (String) data[1]; } if (committed) { status = Transaction.STATUS_COMMITTED; } MVMap<Long, Object[]> undoLog = store.openMap(mapName, undoLogBuilder); undoLogs[transactionId] = undoLog; Long lastUndoKey = undoLog.lastKey(); assert committed || lastUndoKey != null; assert committed || getTransactionId(lastUndoKey) == transactionId; long logId = lastUndoKey == null ? 0 : getLogId(lastUndoKey) + 1; registerTransaction(transactionId, status, name, logId, timeoutMillis, 0, RollbackListener.NONE); } } } } init = true; } }

Target:
public void init() { if (!init) { for (String mapName : store.getMapNames()) { if (mapName.startsWith(UNDO_LOG_NAME_PREFIX)) { if (mapName.equals(UNDO_LOG_NAME_PREFIX)) { if (!store.hasData(mapName) && !store.isReadOnly()) { store.removeMap(mapName); } continue; } boolean committed = mapName.charAt(UNDO_LOG_NAME_PREFIX.length()) == UNDO_LOG_COMMITTED; if (store.hasData(mapName) || committed) { int transactionId = Integer.parseInt(mapName.substring(UNDO_LOG_NAME_PREFIX.length() + 1)); VersionedBitSet openTxBitSet = openTransactions.get(); if (!openTxBitSet.get(transactionId)) { Object[] data = preparedTransactions.get(transactionId); int status; String name; if (data == null) { status = Transaction.STATUS_OPEN; name = null; } else { status = (Integer) data[0]; name = (String) data[1]; } if (committed) { status = Transaction.STATUS_COMMITTED; } MVMap<Long, Object[]> undoLog = store.openMap(mapName, undoLogBuilder); undoLogs[transactionId] = undoLog; Long lastUndoKey = undoLog.lastKey(); assert committed || lastUndoKey != null; assert committed || getTransactionId(lastUndoKey) == transactionId; long logId = lastUndoKey == null ? 0 : getLogId(lastUndoKey) + 1; registerTransaction(transactionId, status, name, logId, timeoutMillis, 0, RollbackListener.NONE); } } } } init = true; } }
Source:
public void testDateTimeChannelCalendarDefaultTimeZoneUpdate() { Configuration configuration = new Configuration(); initialize(configuration, NtpBindingConstants.CHANNEL_DATE_TIME, ACCEPTED_ITEM_TYPE_DATE_TIME, null, null); ZoneOffset timeZoneIdFromItemRegistry = ((DateTimeType) getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME)) .getZonedDateTime().getOffset(); assertThat("The dateTime channel calendar was not updated with the right timezone", timeZoneIdFromItemRegistry, is(equalTo(ZoneOffset.of("+03:00")))); }

Target:
public void testDateTimeChannelCalendarDefaultTimeZoneUpdate() { Configuration configuration = new Configuration(); initialize(configuration, NtpBindingConstants.CHANNEL_DATE_TIME, ACCEPTED_ITEM_TYPE_DATE_TIME, null, null); ZonedDateTime timeZoneIdFromItemRegistry = ((DateTimeType) getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME)) .getZonedDateTime(); ZoneOffset expectedOffset; if (timeZoneIdFromItemRegistry.getZone().getRules().isDaylightSavings(timeZoneIdFromItemRegistry.toInstant())) { expectedOffset = ZoneOffset.of("+03:00"); } else { expectedOffset = ZoneOffset.of("+02:00"); } assertThat("The dateTime channel calendar was not updated with the right timezone", timeZoneIdFromItemRegistry.getOffset(), is(equalTo(expectedOffset))); }
Source:
public void mergeWith(UnweightedDoubleReservoirSample other) { checkArgument(samples.length == other.samples.length, "Max samples must be equal"); if (other.count < other.samples.length) { other.stream().forEach(o -> add(o)); return; } if (count < samples.length) { final UnweightedDoubleReservoirSample target = ((UnweightedDoubleReservoirSample) other.clone()); stream().forEach(o -> target.add(o)); count = target.count; samples = target.samples; return; } shuffleArray(samples); shuffleArray(other.samples); int nextIndex = 0; int otherNextIndex = 0; double[] merged = new double[samples.length]; for (int i = 0; i < samples.length; ++i) { if (ThreadLocalRandom.current().nextLong(0, count + other.count) < count) { merged[i] = samples[nextIndex++]; } else { merged[i] = other.samples[otherNextIndex++]; } } count += other.count; samples = merged; }

Target:
public void mergeWith(UnweightedDoubleReservoirSample other) { checkArgument( samples.length == other.samples.length, format("Maximum number of samples %s must be equal to that of other %s", samples.length, other.samples.length)); if (other.seenCount < other.samples.length) { for (int i = 0; i < other.seenCount; i++) { add(other.samples[i]); } return; } if (seenCount < samples.length) { UnweightedDoubleReservoirSample target = ((UnweightedDoubleReservoirSample) other.clone()); for (int i = 0; i < seenCount; i++) { target.add(samples[i]); } seenCount = target.seenCount; samples = target.samples; return; } shuffleArray(samples); shuffleArray(other.samples); int nextIndex = 0; int otherNextIndex = 0; double[] merged = new double[samples.length]; for (int i = 0; i < samples.length; i++) { if (ThreadLocalRandom.current().nextLong(0, seenCount + other.seenCount) < seenCount) { merged[i] = samples[nextIndex++]; } else { merged[i] = other.samples[otherNextIndex++]; } } seenCount += other.seenCount; samples = merged; }
Source:
public OperationAction createOperationAction() { OperationActionImpl operationAction = new OperationActionImpl(); return operationAction; }

Target:
public OperationAction createOperationAction() { OperationActionImpl operationAction = new OperationActionImpl(); ContainerViewVariable containerViewVariable = this.createContainerViewVariable(); containerViewVariable.setName("views"); InitialOperation initalOperation = this.createInitialOperation(); operationAction.setView(containerViewVariable); operationAction.setInitialOperation(initalOperation); return operationAction; }
Source:
protected void writeItem(@NonNull final File rootFolder, @NonNull final AssetItem item, @NonNull WaitableExecutor executor) throws IOException { if (item.isTouched()) { executor.execute(new Callable() { @Override public Object call() throws Exception { AssetFile assetFile = item.getSource(); File fromFile = assetFile.getFile(); File toFile = new File(rootFolder, item.getKey().replaceAll("/", File.separator)); toFile.getParentFile().mkdirs(); Files.copy(fromFile, toFile); return null; } }); } }

Target:
protected void writeItem(@NonNull final File rootFolder, @NonNull final AssetItem item, @NonNull WaitableExecutor executor) throws IOException { if (item.isTouched()) { executor.execute(new Callable() { @Override public Object call() throws Exception { AssetFile assetFile = item.getSource(); File fromFile = assetFile.getFile(); File toFile = new File(rootFolder, item.getKey().replace('/', File.separatorChar)); toFile.getParentFile().mkdirs(); Files.copy(fromFile, toFile); return null; } }); } }
Source:
private boolean getValue(FutureVDSCall<VDSReturnValue> task, Guid hostId) { try { VDSReturnValue vdsReturnValue = task.get(Config.<Integer> getValue(ConfigValues.SetupNetworksPollingTimeout), TimeUnit.SECONDS); return vdsReturnValue.getSucceeded(); } catch (TimeoutException e) { return false; } catch (VDSRecoveringException e) { LOGGER.trace("Failed to poll host - it's in recovery mode.", hostId, e); return false; } }

Target:
private boolean getValue(FutureVDSCall<VDSReturnValue> task, Guid hostId) { try { VDSReturnValue vdsReturnValue = task.get(Config.<Integer> getValue(ConfigValues.SetupNetworksPollingTimeout), TimeUnit.SECONDS); return vdsReturnValue.getSucceeded(); } catch (TimeoutException e) { return false; } catch (VDSRecoveringException e) { LOGGER.debug("Failed to poll host - it's in recovery mode.", hostId, e); return false; } }
Source:
public List<String> getURLsFromPage(Document page) { Elements elements = page.select("#post-list .thumb a,#pool-show .thumb a"); List<String> res = new ArrayList<String>(elements.size()); if (page.getElementById("pool-show") != null) { int index = 0; Element e = page.getElementById("paginator"); if (e != null && (e = e.getElementsByClass("current").first()) != null) index = (Integer.parseInt(e.text()) - 1) * POOL_IMAGES_PER_PAGE; for (Element e_ : elements) res.add(e_.absUrl("href") + "#" + ++index); } else { for (Element e : elements) res.add(e.absUrl("href") + "#" + e.child(0).attr("id").substring(1)); } return res; }

Target:
public List<String> getURLsFromPage(Document page) { Elements elements = page.select("#post-list .thumb a,#pool-show .thumb a"); List<String> res = new ArrayList<String>(elements.size()); if (page.getElementById("pool-show") != null) { int index = 0; Element e = page.getElementById("paginator"); if (e != null) { e = e.getElementsByClass("current").first(); if (e != null) { index = (Integer.parseInt(e.text()) - 1) * POOL_IMAGES_PER_PAGE; } } for (Element e_ : elements) { res.add(e_.absUrl("href") + "#" + ++index); } } else { for (Element e : elements) { res.add(e.absUrl("href") + "#" + e.child(0).attr("id").substring(1)); } } return res; }
Source:
public void testExecuteAndPostProcess() throws Exception{ InstructorAttributes instructor = dataBundle.instructors.get("teammates.test.instructor2"); String instructorId = instructor.googleId; gaeSimulation.loginAsInstructor(instructorId); ______TS("Successful case"); InstructorFeedbackEditCopyPageAction a = getAction(); AjaxResult r = getAjaxResult(a); assertFalse(r.isError); InstructorFeedbackEditCopyPageData pageData = (InstructorFeedbackEditCopyPageData) r.data; assertEquals(4, pageData.courses.size()); }

Target:
public void testExecuteAndPostProcess() throws Exception{ InstructorAttributes instructor = dataBundle.instructors.get("teammates.test.instructor2"); String instructorId = instructor.googleId; gaeSimulation.loginAsInstructor(instructorId); ______TS("Successful case"); InstructorFeedbackEditCopyPageAction a = getAction(); AjaxResult r = getAjaxResult(a); assertFalse(r.isError); InstructorFeedbackEditCopyPageData pageData = (InstructorFeedbackEditCopyPageData) r.data; assertEquals(4, pageData.courses.size()); List<String> idOfCourses = new ArrayList<String>(); for (CourseAttributes course: pageData.courses) { idOfCourses.add(course.id); } assertFalse(idOfCourses.contains("FeedbackEditCopy.CS1101")); assertFalse(idOfCourses.contains("FeedbackEditCopy.CS2107")); assertTrue(idOfCourses.contains("FeedbackEditCopy.CS2102")); assertTrue(idOfCourses.contains("FeedbackEditCopy.CS2103")); assertTrue(idOfCourses.contains("FeedbackEditCopy.CS2103R")); assertTrue(idOfCourses.contains("FeedbackEditCopy.CS2104")); }
Source:
protected static String propertyValue(String propertyFile, String propertyName) throws ParserConfigurationException, SAXException, IOException, URISyntaxException{ String configLocation = System.getenv("HADOOP_CONF_DIR"); File file = new File(configLocation+"/"+propertyFile); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(file); document.getDocumentElement().normalize(); Element docElement = document.getDocumentElement(); NodeList nodeList = docElement.getElementsByTagName("property"); ArrayList<String> names = new ArrayList<String>(); ArrayList<String> values = new ArrayList<String>(); if (nodeList != null) { int length = nodeList.getLength(); for (int i = 0; i < length; i++) { if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) nodeList.item(i); if (element.getNodeName().contains("property")) { names.add( element.getElementsByTagName("name").item(0).getTextContent()); values.add( element.getElementsByTagName("value").item(0).getTextContent()); } } } } String[] nameslist = names.toArray(new String[names.size()]); String[] valueslist = values.toArray(new String[values.size()]); int valuePosition = Arrays.asList(nameslist).indexOf(propertyName); String propertyValue = valueslist[valuePosition].toString(); return propertyValue; }

Target:
static String propertyValue(String propertyFile, String propertyName) throws ParserConfigurationException, SAXException, IOException, URISyntaxException { String configLocation = System.getenv("HADOOP_CONF_DIR"); File file = new File(configLocation + "/" + propertyFile); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory .newDocumentBuilder(); Document document = documentBuilder.parse(file); document.getDocumentElement().normalize(); Element docElement = document.getDocumentElement(); NodeList nodeList = docElement.getElementsByTagName("property"); ArrayList<String> names = new ArrayList<String>(); ArrayList<String> values = new ArrayList<String>(); if (nodeList != null) { int length = nodeList.getLength(); for (int i = 0; i < length; i++) { if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) nodeList.item(i); if (element.getNodeName().contains("property")) { names.add(element.getElementsByTagName("name").item(0) .getTextContent()); values.add(element.getElementsByTagName("value") .item(0).getTextContent()); } } } } String[] nameslist = names.toArray(new String[names.size()]); String[] valueslist = values.toArray(new String[values.size()]); int valuePosition = Arrays.asList(nameslist).indexOf(propertyName); String propertyValue = valueslist[valuePosition].toString(); return propertyValue; }
Source:
public ConstraintEventsIterator(String dumpDirectory, HiveConf hiveConf) throws IOException { Path path = new Path(dumpDirectory); fs = path.getFileSystem(hiveConf); dbDirs = fs.listStatus(new Path(dumpDirectory), EximUtil.getDirectoryFilter(fs)); currentDbIndex = 0; if (dbDirs.length != 0) { currentConstraintIndex = 0; constraintFiles = listConstraintFilesInDBDir(fs, dbDirs[0].getPath()); } }

Target:
public ConstraintEventsIterator(String dumpDirectory, HiveConf hiveConf) throws IOException { path = new Path(dumpDirectory); fs = path.getFileSystem(hiveConf); }
Source:
private void setUpAudioPlayer() { audioPlayer = ExoPlayerFactory.newSimpleInstance( getApplicationContext(), new DefaultTrackSelector(), new DefaultLoadControl()); audioPlayer.addListener(this); audioPlayer.setPlayWhenReady(true); audioPlayer.setVolume(1.0f); }

Target:
private void setUpAudioPlayer() { audioPlayer = ExoPlayerFactory.newSimpleInstance(new DefaultRenderersFactory(this), new DefaultTrackSelector(), new DefaultLoadControl()); audioPlayer.addListener(this); audioPlayer.setPlayWhenReady(true); audioPlayer.setVolume(1.0f); }
Source:
private ClusterCacheStatus initCacheStatusIfAbsent(String cacheName) { return cacheStatusMap.computeIfAbsent(cacheName, (name) -> { Configuration cacheConfiguration = cacheManager.getCacheConfiguration(cacheName); AvailabilityStrategy availabilityStrategy; if (cacheConfiguration != null && cacheConfiguration.clustering().partitionHandling().enabled()) { availabilityStrategy = new PreferConsistencyStrategy(eventLogManager); } else { availabilityStrategy = new PreferAvailabilityStrategy(eventLogManager); } Optional<GlobalStateManager> globalStateManager = cacheManager.getGlobalComponentRegistry().getOptionalComponent(GlobalStateManager.class); Optional<ScopedPersistentState> persistedState = globalStateManager.flatMap(gsm -> { return gsm.readScopedState(cacheName); }); return new ClusterCacheStatus(cacheName, availabilityStrategy, this, transport, persistedState); }); }

Target:
private ClusterCacheStatus initCacheStatusIfAbsent(String cacheName) { return cacheStatusMap.computeIfAbsent(cacheName, (name) -> { Configuration cacheConfiguration = cacheManager.getCacheConfiguration(cacheName); AvailabilityStrategy availabilityStrategy; if (cacheConfiguration != null && cacheConfiguration.clustering().partitionHandling().enabled()) { availabilityStrategy = new PreferConsistencyStrategy(eventLogManager, persistentUUIDManager); } else { availabilityStrategy = new PreferAvailabilityStrategy(eventLogManager, persistentUUIDManager); } Optional<GlobalStateManager> globalStateManager = cacheManager.getGlobalComponentRegistry().getOptionalComponent(GlobalStateManager.class); Optional<ScopedPersistentState> persistedState = globalStateManager.flatMap(gsm -> { return gsm.readScopedState(cacheName); }); return new ClusterCacheStatus(cacheName, availabilityStrategy, this, transport, persistedState, persistentUUIDManager); }); }
Source:
public void sortingShouldIgnoreCase() { assertSortedLike("a", "b", "z"); assertSortedLike("a", "B"); }

Target:
public void sortingShouldIgnoreCase() { assertSortedLike("a", "b", "z"); assertSortedLike("a", "B", "c", "D"); }
Source:
private static void checkValidStep(long start, long stop, long step) { checkCondition( step != 0, INVALID_FUNCTION_ARGUMENT, "step must not be zero"); checkCondition( step > 0 ? stop >= start : stop <= start, INVALID_FUNCTION_ARGUMENT, "sequence stop value should be greater than or equal to start value if step is greater than zero otherwise stop should be less than or equal start"); }

Target:
private static void checkValidStep(long start, long stop, long step) { checkCondition( step != 0, INVALID_FUNCTION_ARGUMENT, "step must not be zero"); checkCondition( step > 0 ? stop >= start : stop <= start, INVALID_FUNCTION_ARGUMENT, "sequence stop value should be greater than or equal to start value if step is greater than zero otherwise stop should be less than or equal to start"); }
Source:
public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { Object returnValue = super.visitPutMapCommand(ctx, command); if (shouldUpdateOnWriteCommand(command)) { Set<Object> keys = command.getMap().keySet(); Set<Object> toInvalidate = new HashSet<Object>(keys.size()); for (Object k : keys) { if (cdl.localNodeIsPrimaryOwner(k)) { toInvalidate.add(k); } } if (!toInvalidate.isEmpty()) { getLog().tracef("Sending additional invalidation for requestors if necessary."); l1Manager.flushCache(toInvalidate, ctx.getOrigin(), true); } } return returnValue; }

Target:
public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { Object returnValue = invokeNextInterceptor(ctx, command); if (shouldUpdateOnWriteCommand(command)) { Set<Object> keys = command.getMap().keySet(); Set<Object> toInvalidate = new HashSet<Object>(keys.size()); for (Object k : keys) { if (cdl.localNodeIsPrimaryOwner(k)) { toInvalidate.add(k); } } if (!toInvalidate.isEmpty()) { if (trace) { log.trace("Sending additional invalidation for requestors if necessary."); } l1Manager.flushCache(toInvalidate, ctx.getOrigin(), true); } } return returnValue; }
Source:
private void initRenderingSupport() { dynamicFBM = new DynamicFBM(); staticFBM = new StaticFBM(); shadowMapResolutionDependentFBM = new ShadowMapResolutionDependentFBM(); context.put(DynamicFBM.class, dynamicFBM); context.put(StaticFBM.class, staticFBM); context.put(ShadowMapResolutionDependentFBM.class, shadowMapResolutionDependentFBM); postProcessor = new PostProcessor(dynamicFBM); context.put(PostProcessor.class, postProcessor); dynamicFBM.setPostProcessor(postProcessor); dynamicFBM.initialise(); staticFBM.initialise(); shadowMapResolutionDependentFBM.initialise(); shaderManager.initShaders(); initMaterials(); context.put(WorldRenderer.class, this); context.put(RenderQueuesHelper.class, renderQueues); context.put(RenderableWorld.class, renderableWorld); initRenderGraph(); }

Target:
private void initRenderingSupport() { screenGrabber = new ScreenGrabber(context); context.put(ScreenGrabber.class, screenGrabber); displayResolutionDependentFBOs = new DisplayResolutionDependentFBOs(context); immutableFBOs = new ImmutableFBOs(); shadowMapResolutionDependentFBOs = new ShadowMapResolutionDependentFBOs(); context.put(DisplayResolutionDependentFBOs.class, displayResolutionDependentFBOs); context.put(ImmutableFBOs.class, immutableFBOs); context.put(ShadowMapResolutionDependentFBOs.class, shadowMapResolutionDependentFBOs); shaderManager.initShaders(); initMaterials(); context.put(WorldRenderer.class, this); context.put(RenderQueuesHelper.class, renderQueues); context.put(RenderableWorld.class, renderableWorld); initRenderGraph(); }
Source:
private void writeCSV(){ try { for (int i = 0; i < this.usersIdArray.size()-1; i++) { Integer idUser = this.mapUsers.inverse().get(this.usersIdArray.get(i)); this.fileWriter.append(String.valueOf(idUser)); this.fileWriter.append(","); Integer idProduct = this.mapProducts.inverse().get(this.productsIdArray.get(i)); this.fileWriter.append(String.valueOf(idProduct)); this.fileWriter.append(","); this.fileWriter.append(String.valueOf(this.reviewsArray.get(i))); this.fileWriter.append('\n'); } } catch (IOException e) { e.printStackTrace(); } }

Target:
private void writeCSV(){ try { String lineToAppend; for (int i = 0; i < this.usersIdArray.size()-1; i++) { Integer idUser = this.mapUsers.inverse().get(this.usersIdArray.get(i)); Integer idProduct = this.mapProducts.inverse().get(this.productsIdArray.get(i)); lineToAppend = idUser + "," + idProduct + "," + this.reviewsArray.get(i) + "\n"; this.fileWriter.append(lineToAppend); } } catch (IOException e) { e.printStackTrace(); } }
Source:
List<String> registerProvidedLocalResources() { checkNotNull(localResources); final ArrayList<String> classPaths = new ArrayList<>(); providedSharedLibs.forEach( (fileName, fileStatus) -> { final Path filePath = fileStatus.getPath(); LOG.debug("Using remote file to register local resource", filePath); final YarnLocalResourceDescriptor descriptor = YarnLocalResourceDescriptor .fromFileStatus(fileName, fileStatus, LocalResourceVisibility.PUBLIC); localResources.put(fileName, descriptor.toLocalResource()); remotePaths.add(filePath); envShipResourceList.add(descriptor); if (!isFlinkDistJar(fileName) && !isPlugin(fileStatus.getPath())) { classPaths.add(fileName); } else if (isFlinkDistJar(fileName)) { flinkDist = descriptor; } }); return classPaths; }

Target:
List<String> registerProvidedLocalResources() { checkNotNull(localResources); final ArrayList<String> classPaths = new ArrayList<>(); providedSharedLibs.forEach( (fileName, fileStatus) -> { final Path filePath = fileStatus.getPath(); LOG.debug("Using remote file to register local resource", filePath); final YarnLocalResourceDescriptor descriptor = YarnLocalResourceDescriptor .fromFileStatus(fileName, fileStatus, LocalResourceVisibility.PUBLIC); localResources.put(fileName, descriptor.toLocalResource()); remotePaths.add(filePath); envShipResourceList.add(descriptor); if (!isFlinkDistJar(filePath.getName()) && !isPlugin(filePath)) { classPaths.add(fileName); } else if (isFlinkDistJar(filePath.getName())) { flinkDist = descriptor; } }); return classPaths; }
Source:
private Group addDomainToUserMembers(Group group, String userStoreDomain) throws CharonException { List<String> membersId = group.getMembers(); if (StringUtils.isBlank(userStoreDomain) || membersId == null || membersId.isEmpty()) { return group; } List<String> membersDisplayNamesWithoutDomain = group.getMembersWithDisplayName(); List<String> membersDisplayNamesWithDomain = new ArrayList<String>(); for (String memberId : membersId) { group.removeMember(memberId); } if (membersDisplayNamesWithoutDomain != null) { for (String memberDisplayNameWithoutDomain : membersDisplayNamesWithoutDomain) { membersDisplayNamesWithDomain .add(UserCoreUtil.addDomainToName(memberDisplayNameWithoutDomain, userStoreDomain)); } } for (int i = 0; i < membersId.size(); i++) { group.setMember(membersId.get(i), membersDisplayNamesWithDomain.get(i)); } return group; }

Target:
private Group addDomainToUserMembers(Group group, String userStoreDomain) throws CharonException { List<String> membersId = group.getMembers(); if (StringUtils.isBlank(userStoreDomain) || membersId == null || membersId.isEmpty()) { return group; } Map<String, String> userMembers = mergeSCIMIDsWithDisplayNames(group); for (String memberId : membersId) { group.removeMember(memberId); } for (Map.Entry<String, String> entry : userMembers.entrySet()) { group.setMember(entry.getKey(), UserCoreUtil.addDomainToName(entry.getValue(), userStoreDomain)); } return group; }
Source:
private boolean isProjectInternalDependency(VirtualFile jar) { Path jarPath = Paths.get(jar.getPath()); Optional<Path> bloopJarsPath = bloopJarsPath(project); Optional<Path> sourcesJarPath = sourcesJarPath(project); return jarPath.startsWith(bloopJarsPath.get()) || jarPath.startsWith(sourcesJarPath.get()); }

Target:
private boolean isProjectInternalDependency(VirtualFile jar) { Path jarPath = Paths.get(jar.getPath()); return isBloopJarPath(jarPath) || isSourcesJarPath(jarPath); }
Source:
public ImmutableColumn(String name, ColumnType type, Table table, int columnNumber, Integer columnSize, String nativeType, Boolean nullable, String remarks, boolean indexed, String quote, boolean primaryKey) { this.name = name; this.type = type; this.table = table; this.columnNumber = columnNumber; this.columnSize = columnSize; this.decimalDigits = null; this.nativeType = nativeType; this.nullable = nullable; this.remarks = remarks; this.indexed = indexed; this.quote = quote; this.primaryKey = primaryKey; }

Target:
public ImmutableColumn(String name, ColumnType type, Table table, int columnNumber, Integer columnSize, String nativeType, Boolean nullable, String remarks, boolean indexed, String quote, boolean primaryKey) { this(name, type, table, columnNumber, columnSize, null, nativeType, nullable, remarks, indexed, quote, primaryKey); }
Source:
public void appendCompacted(List<LogData> entries) { try { if (entries.isEmpty()) { return; } if (containsAny(entries, true)) { log.debug("appendCompacted: Overwritten exception, entries: {}", entries); throw new OverwriteException(OverwriteCause.SAME_DATA); } Map<Long, AddressMetaData> addressMetaData = writeRecords(entries); knownAddresses.putAll(addressMetaData); compactionMetaData.updateTotalPayloadSize(entries); log.trace("appendCompacted: Written entries to disk: {}", entries); } catch (IOException ioe) { log.error("appendCompacted: IOException when writing entries: {}", entries, ioe); throw new RuntimeException(ioe); } }

Target:
public void appendCompacted(List<LogData> entries) { try { if (entries.isEmpty()) { return; } Map<Long, AddressMetaData> addressMetaData = writeRecords(entries); knownAddresses.putAll(addressMetaData); compactionMetaData.updateTotalPayloadSize(entries); log.trace("appendCompacted: Written entries to disk: {}", entries); } catch (IOException ioe) { log.error("appendCompacted: IOException when writing entries: {}", entries, ioe); throw new RuntimeException(ioe); } }
Source:
public void destroy() { super.destroy(); this.subscribers.forEach(Subscriber::onComplete); this.disposables.values().forEach(Disposable::dispose); }

Target:
public void destroy() { this.subscribedSignal.onNext(false); this.processor.onComplete(); super.destroy(); }
Source:
public Order discontinueOrder(Order orderToDiscontinue, String reasonNonCoded, Date discontinueDate) { discontinueOrder(orderToDiscontinue, discontinueDate); Order newOrder = orderToDiscontinue.cloneForDiscontinuing(); newOrder.setDiscontinuedReasonNonCoded(reasonNonCoded); return saveOrder(newOrder); }

Target:
public Order discontinueOrder(Order orderToDiscontinue, String reasonNonCoded, Date discontinueDate) { discontinue(orderToDiscontinue, discontinueDate); Order newOrder = orderToDiscontinue.cloneForDiscontinuing(); newOrder.setDiscontinuedReasonNonCoded(reasonNonCoded); return saveOrder(newOrder); }
Source:
protected SleepTask createRunnable(HttpAction action) { String interval = action.request.getParameter("interval"); int sleepMilli = 5000; if ( interval != null ) { try { sleepMilli = Integer.parseInt(interval); } catch (NumberFormatException ex) { ServletOps.errorBadRequest("Bad format for 'interval': integer required"); return null; } } if ( sleepMilli < 0 ) { ServletOps.errorBadRequest("Negative sleep interval"); return null; } if ( sleepMilli > MaxSleepMillis ) { ServletOps.errorBadRequest("Sleep internal greater than maximum allowed"); return null; } return new SleepTask(action, sleepMilli, AsyncPool.get()); }

Target:
protected SleepTask createRunnable(HttpAction action) { String interval = action.request.getParameter("interval"); int sleepMilli = 5000; if ( interval != null ) { try { sleepMilli = Integer.parseInt(interval); } catch (NumberFormatException ex) { ServletOps.errorBadRequest("Bad value for 'interval': integer required"); return null; } } if ( sleepMilli < 0 ) { ServletOps.errorBadRequest("Bad value for 'interval': negative sleep interval"); return null; } if ( sleepMilli > MaxSleepMillis ) { ServletOps.errorBadRequest("Bad value for 'interval': sleep internal greater than maximum allowed"); return null; } return new SleepTask(action, sleepMilli, AsyncPool.get()); }
Source:
public void shouldBeAbleToDeserializeADogWithoutRootAndParameterNameEqualsJsonProperty() throws Exception { InputStream stream = asStream("{'name':'Brutus','age':7}"); when(deserializeeInstance.get()).thenReturn(new Deserializee()); when(container.instanceFor(WithoutRoot.class)).thenReturn(new WithoutRoot()); Object[] deserialized = deserializer.deserialize(stream, dogParameterNameEqualsJsonPropertyWithoutRoot); assertThat(deserialized.length, is(1)); assertThat(deserialized[0], is(instanceOf(Dog.class))); Dog dog = (Dog) deserialized[0]; assertThat(dog.name, is("Brutus")); assertThat(dog.age, is(7)); }

Target:
public void shouldBeAbleToDeserializeADogWithoutRootAndParameterNameEqualsJsonProperty() throws Exception { InputStream stream = asStream("{'name':'Brutus','age':7}"); Object[] deserialized = deserializer.deserialize(stream, dogParameterNameEqualsJsonPropertyWithoutRoot); assertThat(deserialized.length, is(1)); assertThat(deserialized[0], is(instanceOf(Dog.class))); Dog dog = (Dog) deserialized[0]; assertThat(dog.name, is("Brutus")); assertThat(dog.age, is(7)); }
Source:
public void testImport() { mode = LanguageMode.ECMASCRIPT6; parse("import 'someModule'"); parse("import d from './someModule'"); parse("import from './someModule'"); parse("import {x, y} from './someModule'"); parse("import {x as x1, y as y1} from './someModule'"); parse("import {x as x1, y as y1, } from './someModule'"); parse("import {default as d} from './someModule'"); parse("import d, {x as x1, y as y1} from './someModule'"); parse("import * as sm from './someModule'"); parseError("import class from './someModule'", "cannot use keyword 'class' here."); parseError("import * as class from './someModule'", "'identifier' expected"); parseError("import {a as class} from './someModule'", "'identifier' expected"); parseError("import {class} from './someModule'", "'as' expected"); }

Target:
public void testImport() { mode = LanguageMode.ECMASCRIPT6; parse("import 'someModule'"); parse("import d from './someModule'"); parse("import from './someModule'"); parse("import {x, y} from './someModule'"); parse("import {x as x1, y as y1} from './someModule'"); parse("import {x as x1, y as y1, } from './someModule'"); parse("import {default as d, class as c} from './someModule'"); parse("import d, {x as x1, y as y1} from './someModule'"); parse("import * as sm from './someModule'"); parseError("import class from './someModule'", "cannot use keyword 'class' here."); parseError("import * as class from './someModule'", "'identifier' expected"); parseError("import {a as class} from './someModule'", "'identifier' expected"); parseError("import {class} from './someModule'", "'as' expected"); }
Source:
public void post_generated_events_to_event_bus() { final Command cmd = Given.Command.startProject(); handler.handle(cmd); final int postedEventCount = 2; final ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class); verify(eventBus, times(postedEventCount)).post(eventCaptor.capture()); final List<Event> events = eventCaptor.getAllValues(); assertEquals(postedEventCount, events.size()); assertEquals(ProjectStarted.class, Events.getMessage(events.get(0)) .getClass()); assertEquals(StringValue.class, Events.getMessage(events.get(1)) .getClass()); }

Target:
public void post_generated_events_to_event_bus() { final Command cmd = Given.Command.startProject(); handler.handle(cmd); final ImmutableList<Message> expectedMessages = handler.getEventsOnStartProjectCmd(); final List<Event> actualEvents = verifyPostedEvents(expectedMessages.size()); for (int i = 0; i < expectedMessages.size(); i++) { final Message expected = expectedMessages.get(i); final Message actual = Events.getMessage(actualEvents.get(i)); assertEquals(expected, actual); } }