List of usage examples for com.google.common.collect Iterables isEmpty
public static boolean isEmpty(Iterable<?> iterable)
From source file:com.ydy.cf.solver.impl.AlternatingLeastSquaresSolver.java
private Vector solve(Iterable<Vector> featureVectors, Vector ratingVector, double lambda, int numFeatures) { Preconditions.checkNotNull(featureVectors, "Feature vectors cannot be null"); Preconditions.checkArgument(!Iterables.isEmpty(featureVectors)); Preconditions.checkNotNull(ratingVector, "rating vector cannot be null"); Preconditions.checkArgument(ratingVector.getNumNondefaultElements() > 0, "Rating vector cannot be empty"); Preconditions.checkArgument(Iterables.size(featureVectors) == ratingVector.getNumNondefaultElements()); int nui = ratingVector.getNumNondefaultElements(); Matrix MiIi = createMiIi(featureVectors, numFeatures); Matrix RiIiMaybeTransposed = createRiIiMaybeTransposed(ratingVector); /* compute Ai = MiIi * t(MiIi) + lambda * nui * E */ Matrix Ai = addLambdaTimesNuiTimesE(MiIi.times(MiIi.transpose()), lambda, nui); /* compute Vi = MiIi * t(R(i,Ii)) */ Matrix Vi = MiIi.times(RiIiMaybeTransposed); /* compute Ai * ui = Vi */ return solve(Ai, Vi); }
From source file:org.sonar.java.xml.XmlAnalyzer.java
public void scan(Iterable<File> files) { boolean hasChecks = !xmlChecks.isEmpty() || !pomChecks.isEmpty(); if (hasChecks && Iterables.isEmpty(files)) { LOG.warn("No 'xml' file have been indexed."); return;/* ww w . j a v a2 s. c o m*/ } ProgressReport progressReport = new ProgressReport("Report about progress of Xml analyzer", TimeUnit.SECONDS.toMillis(10)); progressReport.start(Lists.newArrayList(files)); boolean successfulyCompleted = false; try { for (File file : files) { simpleScan(file); progressReport.nextFile(); } successfulyCompleted = true; } finally { if (successfulyCompleted) { progressReport.stop(); } else { progressReport.cancel(); } } }
From source file:com.caiyunworks.crm.business.service.impl.HolidayServiceImpl.java
@Override public void create(Holiday record) throws UnsupportedOperationException, RecordAlreadyExistException { Iterable<Holiday> holiday = holidayRepository.findByNameOrDateRange(record.getName(), record.getStartDate(), record.getEndDate());//www. j a v a2s . c o m if (null == holiday || Iterables.isEmpty(holiday)) { holidayRepository.create(record); } else { if (logger.isWarnEnabled()) { logger.warn("try to create holiday {}, but it is already exist in DB.", record); } throw new RecordAlreadyExistException(); } }
From source file:com.google.devtools.build.android.resources.RSourceGenerator.java
private void writeSource(String packageName, Iterable<Entry<ResourceType, Map<String, FieldInitializer>>> initializersToWrite) throws IOException { String packageDir = packageName.replace('.', '/'); Path packagePath = outputBasePath.resolve(packageDir); Path rJavaPath = packagePath.resolve(SdkConstants.FN_RESOURCE_CLASS); Files.createDirectories(rJavaPath.getParent()); if (Iterables.isEmpty(initializersToWrite)) { return;/* w w w . j a v a2 s .c o m*/ } try (BufferedWriter writer = Files.newBufferedWriter(rJavaPath, UTF_8)) { writer.write("/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"); writer.write(" *\n"); writer.write(" * This class was automatically generated by the\n"); writer.write(" * bazel tool from the resource data it found. It\n"); writer.write(" * should not be modified by hand.\n"); writer.write(" */\n"); writer.write(String.format("package %s;\n", packageName)); writer.write("public final class R {\n"); for (Entry<ResourceType, Map<String, FieldInitializer>> entry : initializersToWrite) { writer.write(String.format(" public static final class %s {\n", entry.getKey().getName())); for (Entry<String, FieldInitializer> fieldEntry : entry.getValue().entrySet()) { fieldEntry.getValue().writeInitSource(fieldEntry.getKey(), writer, finalFields); } writer.write(" }\n"); } writer.write("}"); } }
From source file:com.b2international.snowowl.datastore.server.snomed.merge.rules.SnomedLanguageRefsetMembersMergeConflictRule.java
@Override public Collection<MergeConflict> validate(CDOTransaction transaction) { List<MergeConflict> conflicts = newArrayList(); Iterable<SnomedLanguageRefSetMember> newLanguageRefSetMembers = ComponentUtils2.getNewObjects(transaction, SnomedLanguageRefSetMember.class); if (!Iterables.isEmpty(newLanguageRefSetMembers)) { final IBranchPath branchPath = BranchPathUtils.createPath(transaction); final Set<String> synonymAndDescendantIds = SnomedRequests.prepareGetSynonyms() .build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath.getPath()) .execute(ApplicationContext.getServiceForClass(IEventBus.class)) .then(new Function<SnomedConcepts, Set<String>>() { @Override//from w ww.j a v a 2 s . c o m public Set<String> apply(SnomedConcepts input) { return FluentIterable.from(input).transform(IComponent.ID_FUNCTION).toSet(); } }).getSync(); final Set<SnomedLanguageRefSetMember> membersToRemove = newHashSet(); label: for (SnomedLanguageRefSetMember newLanguageRefSetMember : newLanguageRefSetMembers) { if (!newLanguageRefSetMember.isActive()) { continue; } Description description = (Description) newLanguageRefSetMember.eContainer(); if (!description.isActive()) { continue; } String descriptionTypeId = description.getType().getId(); String acceptabilityId = newLanguageRefSetMember.getAcceptabilityId(); String languageRefSetId = newLanguageRefSetMember.getRefSetIdentifierId(); Concept concept = description.getConcept(); for (Description conceptDescription : concept.getDescriptions()) { if (!conceptDescription.isActive()) { continue; } String conceptDescriptionTypeId = conceptDescription.getType().getId(); if (!descriptionTypeId.equals(conceptDescriptionTypeId) && !(synonymAndDescendantIds.contains(descriptionTypeId) && synonymAndDescendantIds.contains(conceptDescriptionTypeId))) { continue; } for (SnomedLanguageRefSetMember conceptDescriptionMember : conceptDescription .getLanguageRefSetMembers()) { if (!conceptDescriptionMember.isActive()) { continue; } if (!languageRefSetId.equals(conceptDescriptionMember.getRefSetIdentifierId())) { continue; } if (conceptDescriptionMember.equals(newLanguageRefSetMember)) { continue; } if (acceptabilityId.equals(conceptDescriptionMember.getAcceptabilityId())) { if (description.equals(conceptDescription)) { membersToRemove.add(newLanguageRefSetMember); continue label; } else if (Concepts.REFSET_DESCRIPTION_ACCEPTABILITY_PREFERRED .equals(acceptabilityId)) { // Two SNOMED CT Descriptions selected as preferred terms. conflicts.add(MergeConflictImpl.builder() .componentId(newLanguageRefSetMember.getUuid()) .componentType(newLanguageRefSetMember.eClass().getName()) .conflictingAttribute(ConflictingAttributeImpl.builder() .property("acceptabilityId") .value(newLanguageRefSetMember.getAcceptabilityId()).build()) .type(ConflictType.CONFLICTING_CHANGE).build()); } } else { if (description.equals(conceptDescription)) { // Different acceptability selected for the same description conflicts.add(MergeConflictImpl.builder() .componentId(newLanguageRefSetMember.getUuid()) .componentType(newLanguageRefSetMember.eClass().getName()) .conflictingAttribute(ConflictingAttributeImpl.builder() .property("acceptabilityId") .value(newLanguageRefSetMember.getAcceptabilityId()).build()) .type(ConflictType.CONFLICTING_CHANGE).build()); } } } } } for (SnomedLanguageRefSetMember memberToRemove : membersToRemove) { EcoreUtil.remove(memberToRemove); } } return conflicts; }
From source file:org.eclipse.elk.tree.intermediate.NeighborsProcessor.java
/** * Set the neighbors of each node in the current level and for their children. A neighbor is the * current node's nearest node, at the same level. A siblings is a neighbor with the same * parent./*w ww .j a v a2 s . c o m*/ * * @param currentLevel * the list of TNode at the same level, for which the neighbors and siblings should * be determined * @param progressMonitor * the current progress monitor */ private void setNeighbors(final Iterable<TNode> currentLevel, final IElkProgressMonitor progressMonitor) { /** only do something in filled levels */ if (!Iterables.isEmpty(currentLevel)) { /** create subtask for recursive descent */ IElkProgressMonitor sT = progressMonitor.subTask(Iterables.size(currentLevel) / numberOfNodes); sT.begin("Set neighbors in level", 1f); /** build empty iterator */ Iterable<TNode> nextLevel = new Iterable<TNode>() { public Iterator<TNode> iterator() { return Iterators.emptyIterator(); } }; TNode lN = null; /** * the left neighbor is the previous processed node the right neighbor of the left * neighbor is the current node */ for (TNode cN : currentLevel) { /** append the children of the current node to the next level */ nextLevel = Iterables.concat(nextLevel, cN.getChildren()); if (lN != null) { lN.setProperty(Properties.RIGHTNEIGHBOR, cN); cN.setProperty(Properties.LEFTNEIGHBOR, lN); if (cN.getParent() == lN.getParent()) { lN.setProperty(Properties.RIGHTSIBLING, cN); cN.setProperty(Properties.LEFTSIBLING, lN); } } lN = cN; } /** add amount of work units to the whole task */ sT.done(); /** determine neighbors by bfs and for the whole graph */ setNeighbors(nextLevel, progressMonitor); } }
From source file:com.google.devtools.build.lib.analysis.MergedConfiguredTarget.java
/** Creates an instance based on a configured target and a set of aspects. */ public static ConfiguredTarget of(ConfiguredTarget base, Iterable<ConfiguredAspect> aspects) throws DuplicateException { if (Iterables.isEmpty(aspects)) { // If there are no aspects, don't bother with creating a proxy object return base; }/*from w w w. j a v a 2 s . c o m*/ // Merge output group providers. OutputGroupProvider mergedOutputGroupProvider = OutputGroupProvider .merge(getAllProviders(base, aspects, OutputGroupProvider.class)); // Merge Skylark providers. ImmutableMap<String, Object> premergedProviders = mergedOutputGroupProvider == null ? ImmutableMap.<String, Object>of() : ImmutableMap.<String, Object>of(OutputGroupProvider.SKYLARK_NAME, mergedOutputGroupProvider); SkylarkProviders mergedSkylarkProviders = SkylarkProviders.merge(premergedProviders, getAllProviders(base, aspects, SkylarkProviders.class)); // Merge extra-actions provider. ExtraActionArtifactsProvider mergedExtraActionProviders = ExtraActionArtifactsProvider .merge(getAllProviders(base, aspects, ExtraActionArtifactsProvider.class)); TransitiveInfoProviderMap.Builder aspectProviders = TransitiveInfoProviderMap.builder(); if (mergedOutputGroupProvider != null) { aspectProviders.add(mergedOutputGroupProvider); } if (mergedSkylarkProviders != null) { aspectProviders.add(mergedSkylarkProviders); } if (mergedExtraActionProviders != null) { aspectProviders.add(mergedExtraActionProviders); } ImmutableList.Builder<AspectDescriptor> aspectDescriptors = ImmutableList.builder(); for (ConfiguredAspect aspect : aspects) { for (Map.Entry<Class<? extends TransitiveInfoProvider>, TransitiveInfoProvider> entry : aspect .getProviders().entrySet()) { Class<? extends TransitiveInfoProvider> providerClass = entry.getKey(); if (OutputGroupProvider.class.equals(providerClass) || SkylarkProviders.class.equals(providerClass) || ExtraActionArtifactsProvider.class.equals(providerClass)) { continue; } if (base.getProvider(providerClass) != null || aspectProviders.contains(providerClass)) { throw new IllegalStateException("Provider " + providerClass + " provided twice"); } aspectProviders.add(entry.getValue()); } aspectDescriptors.add(aspect.getDescriptor()); } return new MergedConfiguredTarget(base, aspectDescriptors.build(), aspectProviders.build()); }
From source file:com.palantir.atlasdb.table.description.IndexMetadata.java
public static IndexMetadata createDynamicIndex(String name, String javaName, Iterable<IndexComponent> rowComponents, Iterable<IndexComponent> colComponents, CachePriority cachePriority, PartitionStrategy partitionStrategy, ConflictHandler conflictHandler, boolean rangeScanAllowed, int explicitCompressionBlockSizeKB, boolean negativeLookups, IndexCondition indexCondition, IndexType indexType, SweepStrategy sweepStrategy, ExpirationStrategy expirationStrategy, boolean appendHeavyAndReadLight) { Validate.isTrue(!Iterables.isEmpty(rowComponents)); Validate.isTrue(!Iterables.isEmpty(colComponents)); return new IndexMetadata(name, javaName, rowComponents, colComponents, getColNameToAccessFrom(rowComponents, colComponents, indexCondition), cachePriority, partitionStrategy, conflictHandler, rangeScanAllowed, explicitCompressionBlockSizeKB, negativeLookups, indexCondition, indexType, sweepStrategy, expirationStrategy, appendHeavyAndReadLight);/*from w w w . ja va2s.com*/ }
From source file:com.eucalyptus.cloudformation.ws.CloudFormationRequestLoggingFilter.java
@Override public Collection<String> apply(final Collection<String> parametersOrBody) { if (Iterables.tryFind(ACTION_NVPS, Predicates.in(parametersOrBody)).isPresent()) { final Iterable<String> templateBodyNVPs = Iterables.filter(parametersOrBody, Predicates.contains(TEMPLATE_BODY_PARAMETER_REGEX)); final Iterable<String> parametersNVPs = Iterables.filter(parametersOrBody, Predicates.contains(PARAMETERS_PARAMETER_REGEX)); if (!Iterables.isEmpty(templateBodyNVPs) || !Iterables.isEmpty(parametersNVPs)) { final ArrayList<String> parametersCopy = Lists.newArrayList(parametersOrBody); redactParameters(parametersCopy, templateBodyNVPs, TEMPLATE_BODY_PARAMETER_REGEX); redactParameters(parametersCopy, parametersNVPs, PARAMETERS_PARAMETER_REGEX); return parametersCopy; }//from ww w .ja v a2 s. c o m } return parametersOrBody; }
From source file:gobblin.source.extractor.extract.AbstractSource.java
/** * Get a list of {@link WorkUnitState}s of previous {@link WorkUnit}s subject for retries. * * <p>// w w w .j a v a 2 s .c o m * We use two keys for configuring work unit retries. The first one specifies * whether work unit retries are enabled or not. This is for individual jobs * or a group of jobs that following the same rule for work unit retries. * The second one that is more advanced is for specifying a retry policy. * This one is particularly useful for being a global policy for a group of * jobs that have different job commit policies and want work unit retries only * for a specific job commit policy. The first one probably is sufficient for * most jobs that only need a way to enable/disable work unit retries. The * second one gives users more flexibilities. * </p> * * @param state Source state * @return list of {@link WorkUnitState}s of previous {@link WorkUnit}s subject for retries */ protected List<WorkUnitState> getPreviousWorkUnitStatesForRetry(SourceState state) { if (Iterables.isEmpty(state.getPreviousWorkUnitStates())) { return ImmutableList.of(); } // Determine a work unit retry policy WorkUnitRetryPolicy workUnitRetryPolicy; if (state.contains(ConfigurationKeys.WORK_UNIT_RETRY_POLICY_KEY)) { // Use the given work unit retry policy if specified workUnitRetryPolicy = WorkUnitRetryPolicy .forName(state.getProp(ConfigurationKeys.WORK_UNIT_RETRY_POLICY_KEY)); } else { // Otherwise set the retry policy based on if work unit retry is enabled boolean retryFailedWorkUnits = state.getPropAsBoolean(ConfigurationKeys.WORK_UNIT_RETRY_ENABLED_KEY, true); workUnitRetryPolicy = retryFailedWorkUnits ? WorkUnitRetryPolicy.ALWAYS : WorkUnitRetryPolicy.NEVER; } if (workUnitRetryPolicy == WorkUnitRetryPolicy.NEVER) { return ImmutableList.of(); } List<WorkUnitState> previousWorkUnitStates = Lists.newArrayList(); // Get previous work units that were not successfully committed (subject for retries) for (WorkUnitState workUnitState : state.getPreviousWorkUnitStates()) { if (workUnitState.getWorkingState() != WorkUnitState.WorkingState.COMMITTED) { if (state.getPropAsBoolean(ConfigurationKeys.OVERWRITE_CONFIGS_IN_STATESTORE, ConfigurationKeys.DEFAULT_OVERWRITE_CONFIGS_IN_STATESTORE)) { // We need to make a copy here since getPreviousWorkUnitStates returns ImmutableWorkUnitStates // for which addAll is not supported WorkUnitState workUnitStateCopy = new WorkUnitState(workUnitState.getWorkunit(), state); workUnitStateCopy.addAll(workUnitState); workUnitStateCopy.overrideWith(state); previousWorkUnitStates.add(workUnitStateCopy); } else { previousWorkUnitStates.add(workUnitState); } } } if (workUnitRetryPolicy == WorkUnitRetryPolicy.ALWAYS) { return previousWorkUnitStates; } JobCommitPolicy jobCommitPolicy = JobCommitPolicy.forName(state .getProp(ConfigurationKeys.JOB_COMMIT_POLICY_KEY, ConfigurationKeys.DEFAULT_JOB_COMMIT_POLICY)); if ((workUnitRetryPolicy == WorkUnitRetryPolicy.ON_COMMIT_ON_PARTIAL_SUCCESS && jobCommitPolicy == JobCommitPolicy.COMMIT_ON_PARTIAL_SUCCESS) || (workUnitRetryPolicy == WorkUnitRetryPolicy.ON_COMMIT_ON_FULL_SUCCESS && jobCommitPolicy == JobCommitPolicy.COMMIT_ON_FULL_SUCCESS)) { return previousWorkUnitStates; } // Return an empty list if job commit policy and work unit retry policy do not match return ImmutableList.of(); }