/* (non-Javadoc)
@see org.opoo.press.RelatedPostsFinder#findRelatedPosts(org.opoo.press.Post, int)
507440
@Override
    public List<Post> findRelatedPosts(Post post, int size) {
        if (size <= 0 || (post.getCategories().isEmpty() && post.getTags().isEmpty())) {
            return null;
        }

        // n = n(a, b);
        // x = n / (sqrt(a.count) * sqrt(b.count))
        Map<Post, Integer> categoriesCountMap = calculatePostsCount(post, post.getCategories());
        Map<Post, Integer> tagsCountMap = calculatePostsCount(post, post.getTags());

        Map<Post, Double> scoreMap = new HashMap<Post, Double>();
        //categories
        for (Map.Entry<Post, Integer> en : categoriesCountMap.entrySet()) {
            double score = calculate(en.getValue(), post.getCategories().size(), en.getKey().getCategories().size());
            score = score * categoriesFactor;
            scoreMap.put(en.getKey(), score);
        }

        //tags
        for (Map.Entry<Post, Integer> en : tagsCountMap.entrySet()) {
            double score = calculate(en.getValue(), post.getTags().size(), en.getKey().getTags().size());
            Double val = scoreMap.get(en.getKey());
            if (val == null) {
                val = 0.0;
            }
            score = score * tagsFactor + val.doubleValue();
            scoreMap.put(en.getKey(), score);
        }

        final long time = post.getDate().getTime();
        List<Entry<Post, Double>> list = new ArrayList<Entry<Post, Double>>(scoreMap.entrySet());
        Collections.sort(list, new Comparator<Entry<Post, Double>>() {
            @Override
            public int compare(Entry<Post, Double> o1, Entry<Post, Double> o2) {
                double x = o1.getValue().doubleValue() - o2.getValue().doubleValue();
                int compare = (int) (x * 100000000.0);
                if (x == 0) {
                    //most near
                    long a = Math.abs(o1.getKey().getDate().getTime() - time);
                    long b = Math.abs(o2.getKey().getDate().getTime() - time);
                    return (a < b ? 1 : (a == b ? 0 : -1));
                    //most recent
                    //return o1.getKey().compareTo(o2.getKey());
                }
                return compare;
            }
        });

        Collections.reverse(list);

        if (size > list.size()) {
            size = list.size();
        }

        List<Entry<Post, Double>> subList = list.subList(0, size);

        ArrayList<Post> result = new ArrayList<Post>();
        for (Entry<Post, Double> en : subList) {
            result.add(en.getKey());
        }

        return result;
    }
978741
private void publishRelations(JsonSimple response, String oid) throws TransactionException {
		log.debug("Publishing Children of '{}'", oid);

		JsonSimple data = getDataFromStorage(oid);
		if (data == null) {
			log.error("Error accessing item data! '{}'", oid);
			emailObjectLink(response, oid,
					"An error occured publishing the related objects for this"
							+ " record. Please check the system logs.");
			return;
		}

		JSONArray relations = data.writeArray("relationships");
		for (Object relation : relations) {
			JsonSimple json = new JsonSimple((JsonObject) relation);
			String broker = json.getString(null, "broker");
			boolean localRecord = broker.equals(brokerUrl);
			String relatedId = json.getString(null, "identifier");

			// We need to find OIDs to match IDs (only for local records)
			String relatedOid = json.getString(null, "oid");
			if (relatedOid == null && localRecord) {
				String identifier = json.getString(null, "identifier");
				if (identifier == null) {
					log.error("NULL identifer provided!");
				}
				relatedOid = idToOid(identifier);
				if (relatedOid == null) {
					log.error("Cannot resolve identifer: '{}'", identifier);
				}
			}

			// We only publish downstream relations (ie. we are their authority)
			boolean authority = json.getBoolean(false, "authority");
			boolean relationPublishRequested = json.getBoolean(false, "relationPublishedRequested");
			if (authority && !relationPublishRequested) {
				// Is this relationship using a curated ID?
				boolean isCurated = json.getBoolean(false, "isCurated");
				if (isCurated) {
					log.debug(" * Publishing '{}'", relatedId);
					// It is a local object
					if (localRecord) {
						createTask(response, relatedOid, "publish");

						// Or remote
					} else {
						JsonObject task = createTask(response, broker,
								relatedOid, "publish");
						// We won't know OIDs for remote systems
						task.remove("oid");
						task.put("identifier", relatedId);
					}
					log.debug(" * Writing relationPublishedRequested for '{}'", relatedId);
					json.getJsonObject().put("relationPublishedRequested",true);
					saveObjectData(data, oid);
				} else {
					log.debug(" * Ignoring non-curated relationship '{}'",
							relatedId);
				}
			}
		}
	}
631222
private RelationType getRelationType(int index)
   {
      if (index < 0 || index > RELATION_TYPES.length)
      {
         index = 0;
      }

      return RELATION_TYPES[index];
   }
265595
public Set<Sense> getRelatedSenses(@NonNull Sense sense, @NonNull WordNetRelation relation) {
        return db
                   .getRelations(sense)
                   .entrySet()
                   .stream()
                   .filter(entry -> entry.getValue() == relation)
                   .map(Map.Entry::getKey)
                   .collect(Collectors.toSet());
    }
552031
@Override
    protected Result<Object> fetchRelated(RegistryEntry entry, Serializable relationId, QueryAdapter queryAdapter) {

        ResultFactory resultFactory = context.getResultFactory();

        String uid = getUID(entry, relationId);
        Object relatedResource = resourceMap.get(uid);
        if (relatedResource != null) {
            return resultFactory.just(relatedResource);
        }
        ResourceInformation resourceInformation = entry.getResourceInformation();
        Class<?> resourceClass = resourceInformation.getResourceClass();
        return resultFactory.just(proxyFactory.createResourceProxy(resourceClass, relationId));
    }
861584
public List<ExtendedRelation> getRelatedTableRelations(String relatedTable)
			throws SQLException {
		return queryForEq(ExtendedRelation.COLUMN_RELATED_TABLE_NAME,
				relatedTable);
	}
551999
public List<ExtendedRelation> getRelations(String baseTable,
			String relatedTable) throws SQLException {
		return getRelations(baseTable, null, relatedTable, null, null, null);
	}
847725
public List<TopicRelationship> getTopicRelationships() {
        ArrayList<TopicRelationship> relationships = new ArrayList<TopicRelationship>(topicRelationships);
        for (final TargetRelationship relationship : topicTargetRelationships) {
            relationships.add(new TopicRelationship(relationship.getPrimaryRelationship(), (SpecTopic) relationship.getSecondaryRelationship(),
                    relationship.getType()));
        }
        return relationships;
    }
1085464
public function get_related_data( $post_id ) {
		if ( ! isset( $this->_related_data[ $post_id ] ) ) {
			$table = $this->get_related_table_name();
			$data  = $this->app->db->select_row( $table, [
				'post_id' => $post_id,
			] );
			if ( empty( $data ) ) {
				$data = false;
			} else {
				$post = get_post( $post_id );
				if ( empty( $post ) || $post->post_type != $this->get_post_type() ) {
					$data = false;
				} else {
					$data = $this->filter_item( $this->set_post_data( $data, $post ) );
				}
			}

			$this->_related_data[ $post_id ] = $data;
		}

		return $this->_related_data[ $post_id ];
	}
579735
public void sortRelations(CmsObject cms, CmsResourceStatusBean resStatus) {

        final List<CmsSite> sites = OpenCms.getSiteManager().getAvailableSites(
            cms,
            false,
            false,
            cms.getRequestContext().getOuFqn());
        Collections.sort(resStatus.getOtherSiteRelationSources(), new Comparator<CmsResourceStatusRelationBean>() {

            private Map<String, Integer> m_rankCache = Maps.newHashMap();

            public int compare(CmsResourceStatusRelationBean o1, CmsResourceStatusRelationBean o2) {

                return ComparisonChain.start().compare(rank(o1), rank(o2)).compare(
                    o1.getSitePath(),
                    o2.getSitePath()).result();

            }

            public int rank(CmsResourceStatusRelationBean r) {

                if (m_rankCache.containsKey(r.getSiteRoot())) {
                    return m_rankCache.get(r.getSiteRoot()).intValue();
                }

                int j = 0;
                int result = Integer.MAX_VALUE;
                for (CmsSite site : sites) {
                    if (site.getSiteRoot().equals(r.getSiteRoot())) {
                        result = j;
                        break;
                    }
                    j += 1;
                }

                m_rankCache.put(r.getSiteRoot(), new Integer(result));
                return result;
            }
        });
        // sort relation sources by path, make sure all resources within .detailContainer folders show last
        Collections.sort(resStatus.getRelationSources(), new Comparator<CmsResourceStatusRelationBean>() {

            public int compare(CmsResourceStatusRelationBean arg0, CmsResourceStatusRelationBean arg1) {

                if (arg0.getSitePath().matches(DETAIL_CONTAINER_PATTERN)) {
                    if (!arg1.getSitePath().matches(DETAIL_CONTAINER_PATTERN)) {
                        return 1;
                    }
                } else if (arg1.getSitePath().matches(DETAIL_CONTAINER_PATTERN)) {
                    return -1;
                }
                return arg0.getSitePath().compareTo(arg1.getSitePath());
            }

        });
    }
971149
public static function hasPosts($postType, $categoriesID)
    {
        if(DB::table(categoriesRelationTable($postType))->where('categoryID', $categoriesID)->count()
        ) {
            return true;
        }else{
            return false;
        }
    }
863840
public ResourceMap getPublishRelatedResources() {

        ResourceMap related = computeRelatedResources();
        ResourceMap reachable = computeReachability(related);
        ResourceMap publishRelatedResources = getChangedResourcesReachableFromOriginalResources(reachable);
        removeNestedItemsFromTopLevel(publishRelatedResources);
        //addParentFolders(publishRelatedResources);
        removeUnchangedTopLevelResources(publishRelatedResources, reachable);
        return publishRelatedResources;
    }
1298737
public RelationshipTuple[] getRelationships(Context context,
                                                String pid,
                                                String relationship)
            throws ServerException {
        return worker.getRelationships(context, pid, relationship);
    }
1080637
public void setPublishRelatedResourcesMode(String publishRelatedResourcesMode) {

        m_publishRelatedResourcesMode = CmsPublishRelatedResourcesMode.valueOf(publishRelatedResourcesMode);
        if ((m_publishRelatedResourcesMode != null) && CmsLog.INIT.isInfoEnabled()) {
            CmsLog.INIT.info(
                Messages.get().getBundle().key(
                    Messages.INIT_PUBLISH_RELATED_RESOURCES_MODE_1,
                    m_publishRelatedResourcesMode.toString()));
        }
    }
774163
private void readRelationships()
   {
      for (MapRow row : getTable("CONTAB"))
      {
         Task task1 = m_projectFile.getTaskByUniqueID(row.getInteger("TASK_ID_1"));
         Task task2 = m_projectFile.getTaskByUniqueID(row.getInteger("TASK_ID_2"));

         if (task1 != null && task2 != null)
         {
            RelationType type = row.getRelationType("TYPE");
            Duration lag = row.getDuration("LAG");
            Relation relation = task2.addPredecessor(task1, type, lag);
            m_eventManager.fireRelationReadEvent(relation);
         }
      }
   }
1077978
@Override
	public ObjectList getObjectRelationships(String repositoryId, String objectId, Boolean includeSubRelationshipTypes, RelationshipDirection relationshipDirection, String typeId, String filter, Boolean includeAllowableActions, BigInteger maxItems, BigInteger skipCount, ExtensionsData extension) {
		return relationshipService.getObjectRelationships(repositoryId, objectId, includeSubRelationshipTypes, relationshipDirection, typeId, filter, includeAllowableActions, maxItems, skipCount, extension);
	}
347620
public List<Post> getPosts() {
        Gson gson = gsonParser();
        JsonObject object = (JsonObject) response;
        List<Post> l = gson.fromJson(object.get("posts"), new TypeToken<List<Post>>() {}.getType());
        for (Post e : l) { e.setClient(client); }
        return l;
    }