auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testFacetWithSchema() throws Exception { var schemaByFacetName = Map.of(HAS_RELATED_TEXT, "relatedtext", COLD_STORAGE, "coldstorage"); for (Map.Entry<String, String> entry : schemaByFacetName.entrySet()) { CompositeType type = schemaManager.getFacet(entry.getKey()); JsonAssert json = jsonAssert(type); json.properties(3); json.has("entity-type").isEquals("facet"); json.has("name").isEquals(entry.getKey()); json = json.has("schemas").length(1).has(0); json.has("entity-type").isEquals("schema"); json.has("name").isEquals(entry.getValue()); } }

Target:
public void testFacetWithSchema() throws Exception { CompositeType type = schemaManager.getFacet("HasRelatedText"); JsonAssert json = jsonAssert(type); json.properties(3); json.has("entity-type").isEquals("facet"); json.has("name").isEquals("HasRelatedText"); json = json.has("schemas").length(1).has(0); json.has("entity-type").isEquals("schema"); json.has("name").isEquals("relatedtext"); }
Source:
public WMTSTileCacheInfo(final MapBounds bounds, final Rectangle paintArea, final double dpi) { super(bounds, paintArea, dpi, WMTSLayer.this.param); double diff = Double.POSITIVE_INFINITY; final double targetResolution = bounds.getScaleDenominator(paintArea, dpi).toResolution(bounds.getProjection(), dpi); for (Matrix m : WMTSLayer.this.param.matrices) { double delta = Math.abs(m.getResolution(this.bounds.getProjection()) - targetResolution); if (delta < diff) { diff = delta; this.matrix = m; } } if (this.matrix == null) { throw new IllegalArgumentException("Unable to find a matrix that at the resolution: " + targetResolution); } }

Target:
public WMTSTileCacheInfo(final MapBounds bounds, final Rectangle paintArea, final double dpi) { super(bounds, paintArea, dpi, WMTSLayer.this.param); double diff = Double.POSITIVE_INFINITY; final double targetResolution = bounds.getScaleDenominator(paintArea, dpi).toResolution(bounds.getProjection(), dpi); for (Matrix m : WMTSLayer.this.param.matrices) { double delta = Math.abs(m.getResolution(this.bounds.getProjection()) - targetResolution); if (delta < diff) { diff = delta; this.matrix = m; } } if (this.matrix == null) { throw new IllegalArgumentException("Unable to find a matrix for the resolution: " + targetResolution); } }
Source:
public void testFactionBorderTrackerAllPlanets() throws InterruptedException { FactionBorderTracker tracker = buildTestTracker(); tracker.setDefaultBorderSize(1, 1, 1); List<Planet> border = tracker.getBorderPlanets(factionUs, factionThem); assertEquals(tracker.getBorders(factionUs).getPlanets().size(), 1); assertEquals(tracker.getBorders(factionThem).getPlanets().size(), 12); assertEquals(border.size(), 2); for (Planet p : border) { assertEquals(Math.abs(p.getX()), 1, RegionPerimeter.EPSILON); assertEquals(p.getY(), 0, 0.001); } }

Target:
public void testFactionBorderTrackerAllPlanets() throws InterruptedException { FactionBorderTracker tracker = buildTestTracker(); tracker.setDefaultBorderSize(1, 1, 1); List<Planet> border = tracker.getBorderPlanets(factionUs, factionThem); assertEquals(tracker.getBorders(factionUs).getPlanets().size(), 1); assertEquals(tracker.getBorders(factionThem).getPlanets().size(), 12); assertEquals(border.size(), 2); for (Planet p : border) { assertEquals(Math.abs(p.getX()), 1, RegionPerimeter.EPSILON); assertEquals(p.getY(), 0, RegionPerimeter.EPSILON); } }
Source:
boolean updateNewAndRestoringTasks() { active.initializeNewTasks(); standby.initializeNewTasks(); final Collection<TopicPartition> restored = changelogReader.restore(active); if (!restored.isEmpty()) { active.updateRestored(restored); final Set<TopicPartition> needsRestoring = new HashSet<>(restoreConsumer.assignment()); needsRestoring.removeAll(restored); restoreConsumer.assign(needsRestoring); } if (active.allTasksRunning()) { final Set<TopicPartition> assignment = consumer.assignment(); log.trace("Resuming partitions {}", assignment); consumer.resume(assignment); assignStandbyPartitions(); return standby.allTasksRunning(); } return false; }

Target:
boolean updateNewAndRestoringTasks() { active.initializeNewTasks(); standby.initializeNewTasks(); final Collection<TopicPartition> restored = changelogReader.restore(active); active.updateRestored(restored); removeChangelogsFromRestoreConsumer(restored, false); if (active.allTasksRunning()) { final Set<TopicPartition> assignment = consumer.assignment(); log.trace("Resuming partitions {}", assignment); consumer.resume(assignment); assignStandbyPartitions(); return standby.allTasksRunning(); } return false; }
Source:
public void TestHmm() { final int offset = -3600*1000; Optional<SleepHmmWithInterpretation> hmm = sleepHmmDAO.getLatestModelForDate(0,0); assertTrue(hmm.isPresent()); AllSensorSampleList sensorSampleList = new AllSensorSampleList(); List<TrackerMotion> motionList = new ArrayList<TrackerMotion>(); for (int i = 0; i < 24; i++) { final long t = t0 + i*3600/3*1000; TrackerMotion m = new TrackerMotion(0,0,0L,t,500,offset,0L,1L,1L); motionList.add(m); } List<Sample> light = new ArrayList<Sample>(); for (int i = 1; i < 7*3600; i++) { Long t = t0 + i*60*1000; Sample s = new Sample(t,0.1f,offset); light.add(s); } sensorSampleList.add(Sensor.LIGHT,light); Optional<SleepHmmWithInterpretation.SleepHmmResult> res = hmm.get().getSleepEventsUsingHMM(sensorSampleList,motionList,t0,tf,tc1); Optional<SleepHmmWithInterpretation.SleepHmmResult> res2 = hmm.get().getSleepEventsUsingHMM(sensorSampleList,motionList,t0,tf,tc2); assertTrue(res.isPresent()); assertTrue(res2.isPresent()); assertTrue(res.get().fallAsleep.isPresent()); final int expectedLength1 = 6*60 / SleepHmmWithInterpretation.NUM_MINUTES_IN_WINDOW; final int expectedLength2 = 7*60 / SleepHmmWithInterpretation.NUM_MINUTES_IN_WINDOW; assertTrue(res.get().path.length == expectedLength1); assertTrue(res2.get().path.length == expectedLength2); }

Target:
public void TestHmm() { final int offset = -3600*1000; final Optional<SleepHmmWithInterpretation> hmm = sleepHmmDAO.getLatestModelForDate(0,0); assertTrue(hmm.isPresent()); final AllSensorSampleList sensorSampleList = new AllSensorSampleList(); final List<TrackerMotion> motionList = new ArrayList<TrackerMotion>(); for (int i = 0; i < 24; i++) { final long t = t0 + i*3600/3*1000; final TrackerMotion m = new TrackerMotion(0,0,0L,t,500,offset,0L,1L,1L); motionList.add(m); } List<Sample> light = new ArrayList<Sample>(); for (int i = 1; i < 7*3600; i++) { final Long t = t0 + i*60*1000; final Sample s = new Sample(t,0.1f,offset); light.add(s); } sensorSampleList.add(Sensor.LIGHT,light); Optional<SleepHmmWithInterpretation.SleepHmmResult> res = hmm.get().getSleepEventsUsingHMM(sensorSampleList,motionList,t0,tf,tc1); Optional<SleepHmmWithInterpretation.SleepHmmResult> res2 = hmm.get().getSleepEventsUsingHMM(sensorSampleList,motionList,t0,tf,tc2); assertTrue(res.isPresent()); assertTrue(res2.isPresent()); assertTrue(res.get().fallAsleep.isPresent()); final int expectedLength1 = 6*60 / SleepHmmWithInterpretation.NUM_MINUTES_IN_WINDOW; final int expectedLength2 = 7*60 / SleepHmmWithInterpretation.NUM_MINUTES_IN_WINDOW; assertTrue(res.get().path.size() == expectedLength1); assertTrue(res2.get().path.size() == expectedLength2); }
Source:
public void write( String destination, int requiredAlignment, byte[] data ) throws IOException { File fileName = new File( storeDir, destination ); fs.mkdirs( fileName.getParentFile() ); fileCopyMonitor.copyFile( fileName ); boolean isDefaultFileSystem = pageCache.getCachedFileSystem() instanceof DefaultFileSystemAbstraction; if ( !isDefaultFileSystem && StoreType.shouldBeManagedByPageCache( destination ) ) { WritableByteChannel channel = channels.get( destination ); if ( channel == null ) { int filePageSize = pageCache.pageSize() - pageCache.pageSize() % requiredAlignment; PagedFile pagedFile = pageCache.map( fileName, filePageSize, StandardOpenOption.CREATE ); channel = pagedFile.openWritableByteChannel(); pagedFiles.put( destination, pagedFile ); channels.put( destination, channel ); } ByteBuffer buffer = ByteBuffer.wrap( data ); while ( buffer.hasRemaining() ) { channel.write( buffer ); } } else { try ( OutputStream outputStream = fs.openAsOutputStream( fileName, true ) ) { outputStream.write( data ); } } }

Target:
public void write( String destination, int requiredAlignment, byte[] data ) throws IOException { File fileName = new File( storeDir, destination ); fs.mkdirs( fileName.getParentFile() ); fileCopyMonitor.copyFile( fileName ); if ( !pageCache.fileSystemSupportsFileOperations() && StoreType.canBeManagedByPageCache( destination ) ) { WritableByteChannel channel = channels.get( destination ); if ( channel == null ) { int filePageSize = pageCache.pageSize() - pageCache.pageSize() % requiredAlignment; PagedFile pagedFile = pageCache.map( fileName, filePageSize, StandardOpenOption.CREATE ); channel = pagedFile.openWritableByteChannel(); pagedFiles.put( destination, pagedFile ); channels.put( destination, channel ); } ByteBuffer buffer = ByteBuffer.wrap( data ); while ( buffer.hasRemaining() ) { channel.write( buffer ); } } else { try ( OutputStream outputStream = fs.openAsOutputStream( fileName, true ) ) { outputStream.write( data ); } } }
Source:
public void connect() throws Exception { super.connect(); if (_vds != null) { String actual = getHostFingerprint(); String expected = _vds.getSSHKeyFingerprint(); if (expected == null || expected.isEmpty()) { _vds.setSSHKeyFingerprint(getHostFingerprint()); DbFacade.getInstance().getVdsStaticDao().update(_vds.getStaticData()); } else if (!actual.equals(expected)) { throw new GeneralSecurityException( String.format( "Invalid fingerprint %s, expected %s", actual, expected ) ); } } }

Target:
public void connect() throws Exception { super.connect(); if (_vds != null) { String actual = getHostFingerprint(); String expected = _vds.getSSHKeyFingerprint(); if (expected == null || expected.isEmpty()) { _vds.setSSHKeyFingerprint(getHostFingerprint()); try { DbFacade.getInstance().getVdsStaticDao().update(_vds.getStaticData()); } catch (Exception e) { throw new SecurityException( String.format( "Couldn't store fingerprint to db for host %s: %s", _vds.getHostName(), e ) ); } } else if (!actual.equals(expected)) { throw new GeneralSecurityException( String.format( "Invalid fingerprint %s, expected %s", actual, expected ) ); } } }
Source:
public void createDraft() throws GitAPIException, IOException { PushOneCommit.Result r = createChange(); String changeId = r.getChangeId(); String revId = r.getCommit().getName(); ReviewInput.CommentInput comment = newCommentInfo( "file1", Comment.Side.REVISION, 1, "comment 1"); addDraft(changeId, revId, comment); Map<String, List<CommentInfo>> result = getDraftComments(changeId, revId); assertTrue(result.size() == 1); CommentInfo actual = Iterables.getOnlyElement(result.get(comment.path)); assertCommentInfo(comment, actual); }

Target:
public void createDraft() throws GitAPIException, IOException { PushOneCommit.Result r = createChange(); String changeId = r.getChangeId(); String revId = r.getCommit().getName(); ReviewInput.CommentInput comment = newCommentInfo( "file1", Comment.Side.REVISION, 1, "comment 1"); addDraft(changeId, revId, comment); Map<String, List<CommentInfo>> result = getDraftComments(changeId, revId); assertEquals(1, result.size()); CommentInfo actual = Iterables.getOnlyElement(result.get(comment.path)); assertCommentInfo(comment, actual); }
Source:
private long time(ITestResult o1) { return o1.getEndMillis() - o1.getStartMillis(); }

Target:
private static long time(ITestResult o1) { return o1.getEndMillis() - o1.getStartMillis(); }
Source:
private boolean hasProjects() { for (IResource fResource : fResources) { if (ReorgUtils.isProject(fResource)) { return true; } } for (IJavaElement fJavaElement : fJavaElements) { if (ReorgUtils.isProject(fJavaElement)) { return true; } } return false; }

Target:
private boolean hasProjects() { for (IResource resource : fResources) { if (ReorgUtils.isProject(resource)) { return true; } } for (IJavaElement javaElement : fJavaElements) { if (ReorgUtils.isProject(javaElement)) { return true; } } return false; }
Source:
public String[] getSupportedExtensions() { return new String[] { "oga", "ogg", "oga", "spx", "opus", }; }

Target:
public String[] getSupportedExtensions() { return new String[] { "oga", "ogg", "spx", "opus", }; }
Source:
public void testIndividualProcTimeout() throws IOException, ProcCallException, InterruptedException { m_username="adminUser"; m_password="password"; if (isValgrind() || isDebug()) { return; } Client client; m_username = "adminUser"; m_password = "password"; client = getClient(); checkIndividualProcTimeout(client, true); m_username = "userWithAllProc"; m_password = "password"; client = getClient(); checkIndividualProcTimeout(client, false); }

Target:
public void testIndividualProcTimeout() throws IOException, ProcCallException, InterruptedException { m_username="adminUser"; m_password="password"; if (isValgrind() || isDebug()) { return; } Client client; client = getClient(); checkIndividualProcTimeout(client, true); m_username = "userWithAllProc"; m_password = "password"; client = getClient(); checkIndividualProcTimeout(client, false); }
Source:
protected void doCheck(Object key, boolean isWrite, long flagBitSet) { if (trace) log.tracef("Checking availability for key=%s, status=%s", key, availabilityMode); if (availabilityMode == AvailabilityMode.AVAILABLE) return; LocalizedCacheTopology cacheTopology = distributionManager.getCacheTopology(); Collection<Address> owners = cacheTopology.getDistribution(key).writeOwners(); List<Address> actualMembers = cacheTopology.getActualMembers(); boolean operationAllowed = isOperationAllowed(isWrite, flagBitSet); if (!actualMembers.containsAll(owners) && !operationAllowed) { if (trace) log.tracef("Partition is in %s mode, PartitionHandling is set to to %s, access is not allowed for key %s", availabilityMode, partitionHandling, key); throw log.degradedModeKeyUnavailable(key); } else { if (trace) log.tracef("Key %s is available.", key); System.err.println(String.format("Key %s is available.", key)); } }

Target:
protected void doCheck(Object key, boolean isWrite, long flagBitSet) { if (trace) log.tracef("Checking availability for key=%s, status=%s", key, availabilityMode); if (availabilityMode == AvailabilityMode.AVAILABLE) return; LocalizedCacheTopology cacheTopology = distributionManager.getCacheTopology(); Collection<Address> owners = cacheTopology.getDistribution(key).writeOwners(); List<Address> actualMembers = cacheTopology.getActualMembers(); boolean operationAllowed = isOperationAllowed(isWrite, flagBitSet); if (!actualMembers.containsAll(owners) && !operationAllowed) { if (trace) log.tracef("Partition is in %s mode, PartitionHandling is set to to %s, access is not allowed for key %s", availabilityMode, partitionHandling, key); throw log.degradedModeKeyUnavailable(key); } else { if (trace) log.tracef("Key %s is available.", key); } }
Source:
protected void processParentChangedBlobs(Runnable counter) { mango.select(MongoBlob.class).eq(MongoBlob.PARENT_CHANGED, true).limit(256).iterateAll(blob -> { invokeParentChangedHandlers(blob); mongo.update() .set(MongoBlob.PARENT_CHANGED, false) .where(MongoBlob.ID, blob.getId()) .executeFor(MongoBlob.class); counter.run(); }); }

Target:
protected void processParentChangedBlobs(Runnable counter) { mango.select(MongoBlob.class).eq(MongoBlob.PARENT_CHANGED, true).limit(CURSOR_LIMIT).iterateAll(blob -> { invokeParentChangedHandlers(blob); mongo.update() .set(MongoBlob.PARENT_CHANGED, false) .where(MongoBlob.ID, blob.getId()) .executeFor(MongoBlob.class); counter.run(); }); }
Source:
private int getRowCount(UUID oldShardUuid) { try (OrcDataSource dataSource = orcStorageManager.openShard(fileSystem, oldShardUuid, defaultReaderAttributes)) { OrcReader reader = new OrcReader( dataSource, ORC, defaultReaderAttributes.getMaxMergeDistance(), defaultReaderAttributes.getTinyStripeThreshold(), HUGE_MAX_READ_BLOCK_SIZE, orcFileTailSource, new StorageStripeMetadataSource()); if (reader.getFooter().getNumberOfRows() >= Integer.MAX_VALUE) { throw new IOException("File has too many rows"); } return toIntExact(reader.getFooter().getNumberOfRows()); } catch (Exception e) { throw new PrestoException(RAPTOR_ERROR, "Failed to read file: " + oldShardUuid, e); } }

Target:
private int getRowCount(UUID oldShardUuid) { try (OrcDataSource dataSource = orcStorageManager.openShard(fileSystem, oldShardUuid, defaultReaderAttributes)) { OrcReader reader = new OrcReader(dataSource, ORC, defaultReaderAttributes.getMaxMergeDistance(), defaultReaderAttributes.getTinyStripeThreshold(), HUGE_MAX_READ_BLOCK_SIZE, orcFileTailSource); if (reader.getFooter().getNumberOfRows() >= Integer.MAX_VALUE) { throw new IOException("File has too many rows"); } return toIntExact(reader.getFooter().getNumberOfRows()); } catch (Exception e) { throw new PrestoException(RAPTOR_ERROR, "Failed to read file: " + oldShardUuid, e); } }
Source:
private void updatePartitionDataFromKafka() { Map<String, List<PartitionInfo>> topics; try { synchronized (consumerLock) { topics = consumer.listTopics(); } if (!topics.containsKey(ioConfig.getTopic())) { log.warn("No such topic [%s] found, list of discovered topics [%s]", ioConfig.getTopic(), topics.keySet()); } } catch (Exception e) { log.warn( e, "Unable to get partition data from Kafka for brokers [%s], are the brokers up?", ioConfig.getConsumerProperties().get(KafkaSupervisorIOConfig.BOOTSTRAP_SERVERS_KEY) ); return; } List<PartitionInfo> partitions = topics.get(ioConfig.getTopic()); int numPartitions = (partitions != null ? partitions.size() : 0); log.debug("Found [%d] Kafka partitions for topic [%s]", numPartitions, ioConfig.getTopic()); for (int partition = 0; partition < numPartitions; partition++) { int taskGroupId = getTaskGroupIdForPartition(partition); partitionGroups.putIfAbsent(taskGroupId, new ConcurrentHashMap<Integer, Long>()); ConcurrentHashMap<Integer, Long> partitionMap = partitionGroups.get(taskGroupId); if (partitionMap.putIfAbsent(partition, NOT_SET) == null) { log.info( "New partition [%d] discovered for topic [%s], added to task group [%d]", partition, ioConfig.getTopic(), taskGroupId ); } } }

Target:
private void updatePartitionDataFromKafka() { Map<String, List<PartitionInfo>> topics; try { synchronized (consumerLock) { topics = consumer.listTopics(); } } catch (Exception e) { log.warn( e, "Unable to get partition data from Kafka for brokers [%s], are the brokers up?", ioConfig.getConsumerProperties().get(KafkaSupervisorIOConfig.BOOTSTRAP_SERVERS_KEY) ); return; } List<PartitionInfo> partitions = topics.get(ioConfig.getTopic()); if (partitions == null) { log.warn("No such topic [%s] found, list of discovered topics [%s]", ioConfig.getTopic(), topics.keySet()); } int numPartitions = (partitions != null ? partitions.size() : 0); log.debug("Found [%d] Kafka partitions for topic [%s]", numPartitions, ioConfig.getTopic()); for (int partition = 0; partition < numPartitions; partition++) { int taskGroupId = getTaskGroupIdForPartition(partition); partitionGroups.putIfAbsent(taskGroupId, new ConcurrentHashMap<Integer, Long>()); ConcurrentHashMap<Integer, Long> partitionMap = partitionGroups.get(taskGroupId); if (partitionMap.putIfAbsent(partition, NOT_SET) == null) { log.info( "New partition [%d] discovered for topic [%s], added to task group [%d]", partition, ioConfig.getTopic(), taskGroupId ); } } }
Source:
public Response registerInstallation( @DefaultValue("") @HeaderParam("x-ag-old-token") final String oldToken, Installation entity, @Context HttpServletRequest request) { final Variant variant = loadVariantWhenAuthorized(request); if (variant == null) { return create401Response(request); } final String deviceToken = entity.getDeviceToken(); if (deviceToken == null || !DeviceTokenValidator.isValidDeviceTokenForVariant(deviceToken, variant.getType())) { logger.trace(String.format("Invalid device token was delivered: %s for variant type: %s", deviceToken, variant.getType())); return appendAllowOriginHeader(Response.status(Status.BAD_REQUEST), request); } logger.trace("Mobile Application on device was launched"); if (!oldToken.isEmpty() && !oldToken.equals(entity.getDeviceToken())) { clientInstallationService.removeInstallationForVariantByDeviceToken(variant.getVariantID(), oldToken); } clientInstallationService.addInstallation(variant, entity); return appendAllowOriginHeader(Response.ok(entity), request); }

Target:
public Response registerInstallation( @DefaultValue("") @HeaderParam("x-ag-old-token") final String oldToken, Installation entity, @Context HttpServletRequest request) { final Variant variant = loadVariantWhenAuthorized(request); if (variant == null) { return create401Response(request); } final String deviceToken = entity.getDeviceToken(); if (deviceToken == null || !DeviceTokenValidator.isValidDeviceTokenForVariant(deviceToken, variant.getType())) { logger.trace(String.format("Invalid device token was delivered: %s for variant type: %s", deviceToken, variant.getType())); return appendAllowOriginHeader(Response.status(Status.BAD_REQUEST), request); } logger.trace("Mobile Application on device was launched"); if (!oldToken.isEmpty() && !oldToken.equals(entity.getDeviceToken())) { logger.info(String.format("Deleting old device token %s", oldToken)); clientInstallationService.removeInstallationForVariantByDeviceToken(variant.getVariantID(), oldToken); } clientInstallationService.addInstallation(variant, entity); return appendAllowOriginHeader(Response.ok(entity), request); }
Source:
protected boolean validateInputs() { boolean result = super.validateInputs(); if (result) { VdcQueryReturnValue returnValue = getQueryReturnValue(); returnValue.setExceptionString(""); try { String hostName = getParameters().getVdsHostName(); if (StringUtils.isBlank(hostName)) { returnValue.setExceptionString("Cannot register Host - no Hostname address specified."); result = false; } else { List<VDS> vdssByUniqueId = getVdssByUniqueId(); if (vdssByUniqueId.size() > 1) { returnValue.setExceptionString("Cannot register Host - unique id is ambigious."); result = false; } else if (vdssByUniqueId.size() == 1) { VDS vds = vdssByUniqueId.get(0); if (!VdsHandler.isPendingOvirt(vds)) { returnValue.setExceptionString(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE.name()); result = false; } else { Long otp = getParameters().getOtp(); if (otp != null && !isValidOtp(vds, otp)) { returnValue.setExceptionString(String.format("Invalid OTP for host %s", hostName)); result = false; } } } } } catch (RuntimeException ex) { log.error("RegisterVdsQuery::CanDoAction: An exception has been thrown.", ex); returnValue.setExceptionString(String.format("Cannot register Host - An exception has been thrown: %1$s", ex.getMessage())); result = false; } } return result; }

Target:
protected boolean validateInputs() { if (!super.validateInputs()) { return false; } VdcQueryReturnValue returnValue = getQueryReturnValue(); returnValue.setExceptionString(""); try { String hostName = getParameters().getVdsHostName(); if (StringUtils.isBlank(hostName)) { returnValue.setExceptionString("Cannot register Host - no Hostname address specified."); return false; } List<VDS> vdssByUniqueId = getVdssByUniqueId(); if (vdssByUniqueId.size() > 1) { returnValue.setExceptionString("Cannot register Host - unique id is ambigious."); return false; } if (vdssByUniqueId.size() == 1) { VDS vds = vdssByUniqueId.get(0); if (!VdsHandler.isPendingOvirt(vds)) { returnValue.setExceptionString(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE.name()); return false; } Long otp = getParameters().getOtp(); if (otp != null && !isValidOtp(vds, otp)) { returnValue.setExceptionString(String.format("Invalid OTP for host %s", hostName)); return false; } } } catch (RuntimeException ex) { log.error("RegisterVdsQuery::CanDoAction: An exception has been thrown.", ex); returnValue.setExceptionString(String.format("Cannot register Host - An exception has been thrown: %1$s", ex.getMessage())); return false; } return true; }
Source:
public void addSmap(SmapFile smap) { if (!smap.getGeneratedFile().equals(path)) { throw new IllegalStateException("Invalid smap " + smap + " for this generated file " + path); } smapFiles.add(smap); }

Target:
public void addSmap(SmapFile smap) { if (!smap.getGeneratedFile().equals(path)) { LOG.warn("Invalid smap for {}.", smap, path); return; } smapFiles.add(smap); }
Source:
private TreeItem thisOrFirstItem(TreeItem item) { return item != null ? item : getFirstItemInTree(); }

Target:
private TreeItem thisOrFirstItem(TreeItem item) { if (item != null) { return item; } return getFirstItemInTree(); }
Source:
private Map<String, Element> getMetaPropertyField( TypeElement classElement, PropertyMetaTypes type ) { final Messager messager = processingEnv.getMessager(); Map<String, Element> result = new LinkedHashMap<>(); while ( !classElement.toString().equals( Object.class.getName() ) ) { List<VariableElement> variableElements = ElementFilter.fieldsIn( classElement.getEnclosedElements() ); for ( VariableElement variableElement : variableElements ) { final Property metaProperty = variableElement.getAnnotation( Property.class ); if ( null != metaProperty ) { final TypeMirror fieldReturnType = variableElement.asType(); final TypeElement t = ( TypeElement ) ( ( DeclaredType ) fieldReturnType ).asElement(); final String fieldName = variableElement.getSimpleName().toString(); result.put( fieldName, t ); messager.printMessage( Diagnostic.Kind.WARNING, "Discovered meta property value " + "for class [" + classElement.getSimpleName() + "] " + "at field [" + fieldName + "] " + "of return type [" + fieldReturnType + "]" ); } } classElement = getParent( classElement ); } return result; }

Target:
private Map<String, Element> getMetaPropertyField( TypeElement classElement, PropertyMetaTypes type ) { final Messager messager = processingEnv.getMessager(); Map<String, Element> result = new LinkedHashMap<>(); while ( !classElement.toString().equals( Object.class.getName() ) ) { List<VariableElement> variableElements = ElementFilter.fieldsIn( classElement.getEnclosedElements() ); for ( VariableElement variableElement : variableElements ) { final Property metaProperty = variableElement.getAnnotation( Property.class ); if ( null != metaProperty ) { final TypeMirror fieldReturnType = variableElement.asType(); final TypeElement t = ( TypeElement ) ( ( DeclaredType ) fieldReturnType ).asElement(); final String fieldName = variableElement.getSimpleName().toString(); result.put( fieldName, t ); messager.printMessage( Diagnostic.Kind.NOTE, "Discovered meta property value " + "for class [" + classElement.getSimpleName() + "] " + "at field [" + fieldName + "] " + "of return type [" + fieldReturnType + "]" ); } } classElement = getParent( classElement ); } return result; }
Source:
public Filter toFilter() { ExtractionFn extractionFn = getExtractionFn(); String dimension = getDimension(); String value = getValue(); if (extractionFn == null) { return new NoBitmapSelectorFilter(dimension, value); } else { final String valueOrNull = StringUtils.emptyToNullNonDruidDataString(value); final DruidPredicateFactory predicateFactory = new DruidPredicateFactory() { @Override public Predicate<String> makeStringPredicate() { return input -> Objects.equals(valueOrNull, input); } @Override public DruidLongPredicate makeLongPredicate() { return input -> Objects.equals(valueOrNull, String.valueOf(input)); } @Override public DruidFloatPredicate makeFloatPredicate() { return input -> Objects.equals(valueOrNull, String.valueOf(input)); } @Override public DruidDoublePredicate makeDoublePredicate() { return input -> Objects.equals(valueOrNull, String.valueOf(input)); } }; return new NoBitmapDimensionPredicateFilter(dimension, predicateFactory, extractionFn); } }

Target:
public Filter toFilter() { ExtractionFn extractionFn = getExtractionFn(); String dimension = getDimension(); String value = getValue(); if (extractionFn == null) { return new NoBitmapSelectorFilter(dimension, value); } else { final String valueOrNull = NullHandling.emptyToNullIfNeeded(value); final DruidPredicateFactory predicateFactory = new DruidPredicateFactory() { @Override public Predicate<String> makeStringPredicate() { return input -> Objects.equals(valueOrNull, input); } @Override public DruidLongPredicate makeLongPredicate() { return input -> Objects.equals(valueOrNull, String.valueOf(input)); } @Override public DruidFloatPredicate makeFloatPredicate() { return input -> Objects.equals(valueOrNull, String.valueOf(input)); } @Override public DruidDoublePredicate makeDoublePredicate() { return input -> Objects.equals(valueOrNull, String.valueOf(input)); } }; return new NoBitmapDimensionPredicateFilter(dimension, predicateFactory, extractionFn); } }
Source:
public String findTitle() { List<WebElement> elements = post.findElements(By.className("post-content__body")); return elements.isEmpty() ? "" : elements.get(0).getText(); }

Target:
public String findTitle() { List<WebElement> elements = post.findElements(By.className("post-content__title")); return elements.isEmpty() ? "" : elements.get(0).getText(); }
Source:
protected Optional<ExampleProjectError> getError(OrganizationalUnit ou, ImportProject importProject) { if (this.projectImportService.exist(ou, importProject)) { String errorPattern = "Already exist project <{1}> in space <{0}> "; String errorMessage = MessageFormat.format(errorPattern, ou.getSpace().getName(), importProject.getName()); return Optional.of(new ExampleProjectError(NameAlreadyExistValidator.class.getCanonicalName(), errorMessage)); } else { return Optional.empty(); } }

Target:
protected Optional<ExampleProjectError> getError(OrganizationalUnit ou, ImportProject importProject) { if (this.projectImportService.exist(ou, importProject)) { String errorPattern = "Project <{1}> already exists in space <{0}>"; return Optional.of(new ExampleProjectError(NameAlreadyExistValidator.class.getCanonicalName(), errorPattern, ou.getSpace().getName(), importProject.getName())); } else { return Optional.empty(); } }
Source:
public boolean processInvalidUrl(final WebView view, String url) { final String methodName = ".processInvalidUrl"; if (isBrokerRequest(getIntent()) && url.startsWith(AuthenticationConstants.Broker.REDIRECT_PREFIX)) { Logger.e(TAG + methodName, String.format( "The RedirectUri is not as expected. Received %s and expected %s", url, mRedirectUrl), "", ADALError.DEVELOPER_REDIRECTURI_INVALID); returnError(ADALError.DEVELOPER_REDIRECTURI_INVALID, String.format( "The RedirectUri is not as expected. Received %s and expected %s", url, mRedirectUrl)); view.stopLoading(); return true; } if(!url.toLowerCase(Locale.US).startsWith(AuthenticationConstants.Broker.REDIRECT_SSL_PREFIX)) { Logger.e(TAG + methodName, "The webview was redirected to an unsafe URL.", "", ADALError.WEBVIEW_REDIRECTURL_NOT_SSL_PROTECTED); returnError(ADALError.WEBVIEW_REDIRECTURL_NOT_SSL_PROTECTED, "The webview was redirected to an unsafe URL."); view.stopLoading(); return true; } return false; }

Target:
public boolean processInvalidUrl(final WebView view, String url) { final String methodName = ":processInvalidUrl"; if (isBrokerRequest(getIntent()) && url.startsWith(AuthenticationConstants.Broker.REDIRECT_PREFIX)) { Logger.e(TAG + methodName, String.format( "The RedirectUri is not as expected. Received %s and expected %s", url, mRedirectUrl), "", ADALError.DEVELOPER_REDIRECTURI_INVALID); returnError(ADALError.DEVELOPER_REDIRECTURI_INVALID, String.format( "The RedirectUri is not as expected. Received %s and expected %s", url, mRedirectUrl)); view.stopLoading(); return true; } if(!url.toLowerCase(Locale.US).startsWith(AuthenticationConstants.Broker.REDIRECT_SSL_PREFIX)) { Logger.e(TAG + methodName, "The webview was redirected to an unsafe URL.", "", ADALError.WEBVIEW_REDIRECTURL_NOT_SSL_PROTECTED); returnError(ADALError.WEBVIEW_REDIRECTURL_NOT_SSL_PROTECTED, "The webview was redirected to an unsafe URL."); view.stopLoading(); return true; } return false; }
Source:
public List<List<WebElement>> getColumns() { List<WebElement> firstRow = getWrappedElement().findElements( By.cssSelector("tr:nth-of-type(1) > td")); return IntStream.range(0, firstRow.size()) .mapToObj(i -> getWrappedElement().findElements( By.cssSelector("tr > td:nth-of-type(" + i + ")"))) .collect(toList()); }

Target:
public List<List<WebElement>> getColumns() { List<List<WebElement>> columns = new ArrayList<>(); List<List<WebElement>> rows = getRows(); if (rows.isEmpty()) { return columns; } int columnCount = rows.get(0).size(); for (int i = 0; i < columnCount; i++) { List<WebElement> column = new ArrayList<>(); for (List<WebElement> row : rows) { column.add(row.get(i)); } columns.add(column); } return columns; }
Source:
public DevicesResource<WatchDog, WatchDogs> getWatchdogsResource() { return inject(new BackendWatchdogsResource(guid, VdcQueryType.GetWatchdog, new IdQueryParameters(guid))); }

Target:
public WatchdogsResource getWatchdogsResource() { return inject(new BackendWatchdogsResource(guid, VdcQueryType.GetWatchdog, new IdQueryParameters(guid))); }
Source:
public void onComplete() { T v = value; value = null; if (v != null) { actual.onSuccess(v); } else { actual.onComplete(); } }

Target:
public void onComplete() { if (done) { return; } done = true; T v = value; value = null; if (v != null) { actual.onSuccess(v); } else { actual.onComplete(); } }
Source:
WildFlyLogContextSelectorImpl(final LogContextSelector defaultLogContextSelector) { final LogContextSelector dft; if (defaultLogContextSelector instanceof WildFlyLogContextSelector) { dft = ((WildFlyLogContextSelectorImpl) defaultLogContextSelector).defaultLogContextSelector; } else { dft = defaultLogContextSelector; } this.defaultLogContextSelector = dft; counter = new AtomicInteger(0); contextSelector = new ClassLoaderLogContextSelector(dft, true); threadLocalContextSelector = new ThreadLocalLogContextSelector(contextSelector); }

Target:
WildFlyLogContextSelectorImpl(final LogContextSelector defaultLogContextSelector) { final LogContextSelector dft; if (defaultLogContextSelector instanceof WildFlyLogContextSelectorImpl) { dft = ((WildFlyLogContextSelectorImpl) defaultLogContextSelector).defaultLogContextSelector; } else { dft = defaultLogContextSelector; } this.defaultLogContextSelector = dft; counter = new AtomicInteger(0); contextSelector = new ClassLoaderLogContextSelector(dft, true); threadLocalContextSelector = new ThreadLocalLogContextSelector(contextSelector); }
Source:
private List<Record> getRecordsForXLS(InputStream xls) throws IOException { List<Record> records = new ArrayList<>(); HSSFWorkbook wb = new HSSFWorkbook(xls); HSSFSheet sheet = wb.getSheetAt(0); for (int j = 0; j <= sheet.getLastRowNum(); j++) { HSSFRow row = sheet.getRow(j); if (row != null) { for (int i = 0; i < row.getLastCellNum(); i++) { HSSFCell cell = row.getCell(i); if (cell != null) { cell.setCellType(HSSFCell.CELL_TYPE_STRING); Record record = changeCellTypeToString(cell, i, j); if (record != null) { records.add(record); } } } } } return records; }

Target:
private List<Record> getRecordsForXLS(InputStream xls) throws IOException { List<Record> records = new ArrayList<>(); HSSFWorkbook wb = new HSSFWorkbook(xls); HSSFSheet sheet = wb.getSheetAt(0); for (int j = 0; j <= sheet.getLastRowNum(); j++) { HSSFRow row = sheet.getRow(j); if (Objects.nonNull(row)) { for (int i = 0; i < row.getLastCellNum(); i++) { HSSFCell cell = row.getCell(i); if (Objects.nonNull(cell)) { cell.setCellType(HSSFCell.CELL_TYPE_STRING); Record record = changeCellTypeToString(cell, i, j); if (Objects.nonNull(record)) { records.add(record); } } } } } return records; }
Source:
public KObjectMarshaller(String typeName) { this.typeName = typeName; this.mainAttributes = Arrays.asList(MetaObject.META_OBJECT_ID, MetaObject.META_OBJECT_TYPE, CLUSTER_ID, SEGMENT_ID, MetaObject.META_OBJECT_KEY, MetaObject.META_OBJECT_FULL_TEXT); }

Target:
public KObjectMarshaller(String typeName) { this.typeName = typeName; }
Source:
void setUp() { Locale.setDefault(Locale.ENGLISH); }

Target:
void setUp() { LocaleContextHolder.setLocale(Locale.ENGLISH); }
Source:
private ContentEquivalenceUpdatingWorker( EquivalenceGraphStore graphStore, DirectAndExplicitEquivalenceMigrator equivMigrator, String metricPrefix, MetricRegistry metricRegistry ) { this.graphStore = checkNotNull(graphStore); this.equivMigrator = checkNotNull(equivMigrator); this.metricRegistry = metricRegistry; this.executionTimer = metricRegistry.timer(metricPrefix + "timer.execution"); this.messageReceivedMeter = metricRegistry.meter(metricPrefix + "meter.received"); this.failureMeter = metricRegistry.meter(metricPrefix + "meter.failure"); this.latencyTimer = metricRegistry.timer(metricPrefix + "latency.meter"); this.publisherMeterName = metricPrefix + "%s.meter.received"; }

Target:
private ContentEquivalenceUpdatingWorker( EquivalenceGraphStore graphStore, DirectAndExplicitEquivalenceMigrator equivMigrator, String metricPrefix, MetricRegistry metricRegistry ) { this.graphStore = checkNotNull(graphStore); this.equivMigrator = checkNotNull(equivMigrator); this.metricRegistry = metricRegistry; this.executionTimer = metricRegistry.timer(metricPrefix + "timer.execution"); this.messageReceivedMeter = metricRegistry.meter(metricPrefix + "meter.received"); this.failureMeter = metricRegistry.meter(metricPrefix + "meter.failure"); this.latencyTimer = metricRegistry.timer(metricPrefix + "timer.latency"); this.publisherMeterName = metricPrefix + "%s.meter.received"; }
Source:
public void testCreateFeedbackResponse() { FeedbackQuestionAttributes fq = dataBundle.feedbackQuestions.get("qn1InSession1InCourse1"); StudentAttributes student = dataBundle.students.get("student3InCourse1"); fq = BackDoor.getFeedbackQuestion(fq.courseId, fq.feedbackSessionName, fq.questionNumber); FeedbackResponseAttributes fr = FeedbackResponseAttributes.builder() .withFeedbackResponseId(fq.getId() + "%" + student.email + "%" + student.email) .withFeedbackSessionName(fq.feedbackSessionName) .withCourseId(fq.courseId) .withFeedbackQuestionId(fq.getId()) .withFeedbackQuestionType(fq.questionType) .withGiver(student.email) .withGiverSection(student.section) .withRecipient(student.email) .withRecipientSection(student.section) .withResponseMetaData(new Text("Student 3 self feedback")) .build(); BackDoor.deleteFeedbackResponse(fr.feedbackQuestionId, fr.giver, fr.recipient); verifyAbsentInDatastore(fr); BackDoor.createFeedbackResponse(fr); verifyPresentInDatastore(fr); BackDoor.deleteFeedbackResponse(fr.feedbackQuestionId, fr.giver, fr.recipient); verifyAbsentInDatastore(fr); }

Target:
public void testCreateFeedbackResponse() { FeedbackQuestionAttributes fq = dataBundle.feedbackQuestions.get("qn1InSession1InCourse1"); StudentAttributes student = dataBundle.students.get("student3InCourse1"); fq = BackDoor.getFeedbackQuestion(fq.courseId, fq.feedbackSessionName, fq.questionNumber); FeedbackResponseAttributes fr = FeedbackResponseAttributes.builder() .withFeedbackSessionName(fq.feedbackSessionName) .withCourseId(fq.courseId) .withFeedbackQuestionId(fq.getId()) .withFeedbackQuestionType(fq.questionType) .withGiver(student.email) .withGiverSection(student.section) .withRecipient(student.email) .withRecipientSection(student.section) .withResponseMetaData(new Text("Student 3 self feedback")) .build(); BackDoor.deleteFeedbackResponse(fr.feedbackQuestionId, fr.giver, fr.recipient); verifyAbsentInDatastore(fr); BackDoor.createFeedbackResponse(fr); verifyPresentInDatastore(fr); BackDoor.deleteFeedbackResponse(fr.feedbackQuestionId, fr.giver, fr.recipient); verifyAbsentInDatastore(fr); }
Source:
private List<String> getAllLemmas(final String word, final String postag) { List<String> lemmasList = new ArrayList<>(); final List<String> keys = this.getDictKeys(word, postag); final List<String> keyValues = this.dictMap.get(keys); if (!keyValues.isEmpty()) { for (String keyValue : keyValues) { lemmasList.add(keyValue); } } else { lemmasList.add("O"); } return lemmasList; }

Target:
private List<String> getAllLemmas(final String word, final String postag) { List<String> lemmasList = new ArrayList<>(); final List<String> keys = this.getDictKeys(word, postag); final List<String> keyValues = this.dictMap.get(keys); if (!keyValues.isEmpty()) { lemmasList.addAll(keyValues); } else { lemmasList.add("O"); } return lemmasList; }
Source:
public void sendInternalLarge(CoreMessage message, boolean direct) throws Exception { int headerSize = message.getHeadersAndPropertiesEncodeSize(); if (headerSize >= connection.getMinLargeMessageSize()) { throw BUNDLE.headerTooBig(); } StorageManager storageManager = ((ServerSessionImpl) session).getStorageManager(); long id = storageManager.generateID(); LargeServerMessage largeMessage = storageManager.createLargeMessage(id, message); byte[] bytes = new byte[message.getBodyBuffer().readableBytes()]; message.getBodyBuffer().readBytes(bytes); largeMessage.addBytes(bytes); largeMessage.releaseResources(); largeMessage.putLongProperty(Message.HDR_LARGE_BODY_SIZE, bytes.length); session.send(largeMessage, direct); largeMessage = null; }

Target:
public void sendInternalLarge(CoreMessage message, boolean direct) throws Exception { int headerSize = message.getHeadersAndPropertiesEncodeSize(); if (headerSize >= connection.getMinLargeMessageSize()) { throw BUNDLE.headerTooBig(); } StorageManager storageManager = ((ServerSessionImpl) session).getStorageManager(); long id = storageManager.generateID(); LargeServerMessage largeMessage = storageManager.createLargeMessage(id, message); ActiveMQBuffer body = message.getReadOnlyBodyBuffer(); byte[] bytes = new byte[body.readableBytes()]; body.readBytes(bytes); largeMessage.addBytes(bytes); largeMessage.releaseResources(); largeMessage.putLongProperty(Message.HDR_LARGE_BODY_SIZE, bytes.length); session.send(largeMessage, direct); largeMessage = null; }
Source:
public void open() { String execType = getProperty("zeppelin.pig.execType"); if (execType == null) { execType = "mapreduce"; } String includeJobStats = getProperty("zeppelin.pig.includeJobStats"); if (includeJobStats != null) { this.includeJobStats = Boolean.parseBoolean(includeJobStats); } try { pigServer = new PigServer(execType); } catch (IOException e) { throw new RuntimeException("Fail to launch PigServer", e); } }

Target:
public void open() { String execType = getProperty("zeppelin.pig.execType"); if (execType == null) { execType = "mapreduce"; } String includeJobStats = getProperty("zeppelin.pig.includeJobStats"); if (includeJobStats != null) { this.includeJobStats = Boolean.parseBoolean(includeJobStats); } try { pigServer = new PigServer(execType); } catch (IOException e) { LOGGER.error("Fail to initialize PigServer", e); throw new RuntimeException("Fail to initialize PigServer", e); } }
Source:
private void testGetForDeletedBlobWithoutIncludeDeleteOption(List<BlobId> blobIds) { try { store.get(blobIds, EnumSet.noneOf(StoreGetOptions.class)); assertTrue( "get should fail for a deleted blob, if StoreGetOptions.Store_Include_Deleted is not set in get options", false); } catch (StoreException e) { assertTrue( "get for deleted blob with with Store_Include_Deleted not set in get options should throw exception with " + StoreErrorCodes.ID_Deleted + " error code.", e.getErrorCode().equals(StoreErrorCodes.ID_Deleted)); } }

Target:
private void testGetForDeletedBlobWithoutIncludeDeleteOption(List<BlobId> blobIds) { try { store.get(blobIds, EnumSet.noneOf(StoreGetOptions.class)); fail("get should fail for a deleted blob, if StoreGetOptions.Store_Include_Deleted is not set in get options"); } catch (StoreException e) { assertEquals( "get for deleted blob with with Store_Include_Deleted not set in get options should throw exception with " + StoreErrorCodes.ID_Deleted + " error code.", e.getErrorCode(), StoreErrorCodes.ID_Deleted); } }
Source:
public String getMessage(FormApiException exception) { if (exception.getType() == FormApiException.Type.UNKNOWN_HOST) { return resources.getString(R.string.unknown_host_error, exception.getServerUrl()); } return resources.getString(R.string.generic_network_error); }

Target:
public String getMessage(FormApiException exception) { if (exception.getType() == FormApiException.Type.UNKNOWN_HOST) { return resources.getString(R.string.unknown_host_error, exception.getServerUrl()) + " " + resources.getString(R.string.report_to_project_lead); } return resources.getString(R.string.report_to_project_lead); }
Source:
public void run() { HTInterval currentInterval = intervalQueue.blockingPeek(); while (currentInterval.getStartTime() != -1) { getSHT().insertInterval(currentInterval); intervalQueue.take(); currentInterval = intervalQueue.blockingPeek(); } if (currentInterval.getAttribute() != -1) { throw new IllegalStateException(); } getSHT().closeTree(currentInterval.getEndTime()); return; }

Target:
public void run() { HTInterval currentInterval = intervalQueue.blockingPeek(); while (currentInterval.getStartTime() != -1) { getSHT().insertInterval(currentInterval); intervalQueue.take(); currentInterval = intervalQueue.blockingPeek(); } if (currentInterval.getAttribute() != -1) { throw new IllegalStateException(); } getSHT().closeTree(currentInterval.getEndTime()); }
Source:
public static int getIntegerValueFromDatabase(Connection dbConnection, String sqlStmt, Object... params) throws UserStoreException { int value = -1; try (PreparedStatement prepStmt = dbConnection.prepareStatement(sqlStmt)){ if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param == null) { throw new UserStoreException("Null data provided."); } else if (param instanceof String) { prepStmt.setString(i + 1, (String) param); } else if (param instanceof Integer) { prepStmt.setInt(i + 1, (Integer) param); } } } try(ResultSet rs = prepStmt.executeQuery()) { if (rs.next()) { value = rs.getInt(1); } return value; } } catch (SQLException e) { String errorMessage = "Using sql : " + sqlStmt + " " + e.getMessage(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } }

Target:
public static int getIntegerValueFromDatabase(Connection dbConnection, String sqlStmt, Object... params) throws UserStoreException { int value = -1; try (PreparedStatement prepStmt = dbConnection.prepareStatement(sqlStmt)){ if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param == null) { throw new UserStoreException("Null data provided."); } else if (param instanceof String) { prepStmt.setString(i + 1, (String) param); } else if (param instanceof Integer) { prepStmt.setInt(i + 1, (Integer) param); } } } try(ResultSet rs = prepStmt.executeQuery()) { if (rs.next()) { value = rs.getInt(1); } return value; } } catch (SQLException e) { String errorMessage = "Using sql : " + sqlStmt + " " + e.getMessage(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); }finally { close(dbConnection); } }
Source:
protected void updateData(long start, long end, int nb, @Nullable IProgressMonitor monitor) { double x[] = getXAxis(start, end, nb); setXAxis(x); final double y[] = new double[nb]; final long yLong[] = new long[nb]; Arrays.fill(y, 0.0); for (ITmfTrace trace : TmfTraceManager.getTraceSet(getTrace())) { final TmfStatisticsModule statsMod = TmfTraceUtils.getAnalysisModuleOfClass(trace, TmfStatisticsModule.class, TmfStatisticsModule.ID); if (statsMod == null) { continue; } statsMod.waitForInitialization(); final ITmfStatistics stats = Objects.requireNonNull(statsMod.getStatistics()); List<Long> values = stats.histogramQuery(start, end, nb); for (int i = 0; i < nb; i++) { yLong[i] += values.get(i); } } for (int i = 0; i < nb; i++) { y[i] += yLong[i]; } setSeries("Number of events", y); updateDisplay(); }

Target:
protected void updateData(long start, long end, int nb, @Nullable IProgressMonitor monitor) { double[] x = getXAxis(start, end, nb); setXAxis(x); final double[] y = new double[nb]; final long[] yLong = new long[nb]; for (ITmfTrace trace : TmfTraceManager.getTraceSet(getTrace())) { final TmfStatisticsModule statsMod = TmfTraceUtils.getAnalysisModuleOfClass(trace, TmfStatisticsModule.class, TmfStatisticsModule.ID); if (statsMod == null) { continue; } statsMod.waitForInitialization(); final ITmfStatistics stats = Objects.requireNonNull(statsMod.getStatistics()); List<Long> values = stats.histogramQuery(start, end, nb); for (int i = 0; i < nb; i++) { yLong[i] += values.get(i); } } for (int i = 0; i < nb; i++) { y[i] = yLong[i]; } setSeries("Number of events", y); updateDisplay(); }