### Initialize Application GUI and Load Data Source: https://context7.com/nikola034/edgerank/llms.txt This snippet demonstrates the initialization of the main application window and the loading of serialized data. It relies on the PyQt5 framework to manage the application lifecycle and data persistence. ```python G = LoadSerializedGraph() comments, reactions, shares, statuses = LoadSerializedData() main_window.show() sys.exit(app.exec()) ``` -------------------------------- ### PyQt5 GUI Components Source: https://context7.com/nikola034/edgerank/llms.txt GUI components for user authentication and the main application dashboard. Includes login handling and integration with search and feed features. ```python from PyQt5.QtWidgets import QApplication from gui import LoginWindow, MainWindow import sys app = QApplication(sys.argv) login_window = LoginWindow() def on_login(username): main_window = MainWindow(username) main_window.show() login_window.loginSignal.connect(on_login) login_window.show() sys.exit(app.exec()) ``` -------------------------------- ### Trie Prefix Tree for Search Source: https://context7.com/nikola034/edgerank/llms.txt A prefix tree implementation for efficient word storage and retrieval. It supports exact word matching and prefix-based autocomplete suggestions. ```python from trie import Trie trie = Trie() words = ["hello", "help", "helper", "world", "word"] for word in words: trie.insert(word.lower()) # Prefix search for autocomplete suggestions = [word for word, count in trie.prefix("hel")] ``` -------------------------------- ### Implement KMP Algorithm for Phrase Search Source: https://context7.com/nikola034/edgerank/llms.txt The KMP algorithm is utilized within the MainWindow class to perform exact phrase matching when search queries are enclosed in quotes. It involves generating a failure table and searching text to rank results via a MaxHeap. ```python from gui import MainWindow # Example usage (internal to MainWindow): # main_window._generate_table(pattern) # Generate failure table # main_window.kmp(text, pattern) # Find all occurrences ``` -------------------------------- ### MaxHeap for Priority Ranking Source: https://context7.com/nikola034/edgerank/llms.txt A max-heap implementation used to manage and retrieve ranked items based on priority scores. Ideal for feed generation and relevance sorting. ```python from heap import MaxHeap data = [(85.5, "status_id_1"), (120.3, "status_id_2")] heap = MaxHeap(data) # Pop items in descending priority top_item = heap.pop() ``` -------------------------------- ### Serialize Social Media Data for Fast Loading (Python) Source: https://context7.com/nikola034/edgerank/llms.txt Serializes loaded data dictionaries to binary files using Python's pickle module for faster subsequent loads. This is crucial for large datasets that require significant parsing time from CSV. ```python from main import LoadOriginalData, SerializeData, MakeSerializedGraph # First load the original data LoadOriginalData() # Generate and serialize the friendship graph G = generate_graph_from_friends(friends) MakeSerializedGraph() # Saves to: serialized_data/serial_friends.csv # Serialize all data dictionaries comments, reactions, shares, statuses = SerializeData() # Saves to: serialized_data/serial_comments.csv, serial_reactions.csv, # serial_shares.csv, serial_statuses.csv ``` -------------------------------- ### Ranking Algorithm API Source: https://context7.com/nikola034/edgerank/llms.txt Endpoints for calculating user affinity and post popularity scores based on the EdgeRank algorithm. ```APIDOC ## POST /rank/affinity ### Description Calculates the relationship strength between two users based on interaction history and time decay. ### Method POST ### Endpoint /rank/affinity ### Request Body - **user_a** (string) - Required - ID of the first user. - **user_b** (string) - Required - ID of the second user. ### Request Example { "user_a": "John Smith", "user_b": "Jane Doe" } ### Response #### Success Response (200) - **affinity_score** (float) - The calculated weighted relationship strength. --- ## POST /rank/popularity ### Description Calculates the popularity score of a post based on weighted engagement metrics (likes, comments, shares). ### Method POST ### Endpoint /rank/popularity ### Request Body - **status** (object) - Required - The status object containing engagement counts. ### Request Example { "status": { "num_shares": 10, "num_comments": 25, "num_likes": 100 } } ### Response #### Success Response (200) - **popularity_score** (float) - The calculated engagement score. ``` -------------------------------- ### Generate User Relationship Graph with NetworkX Source: https://context7.com/nikola034/edgerank/llms.txt Creates a directed graph representing user relationships with affinity scores as edge weights. It considers direct friendships and implicit connections through interactions like shares, comments, and reactions. The graph is built using the NetworkX library. ```python from main import generate_graph_from_friends, LoadData import networkx as nx # Load data first LoadData() # Generate the friendship/affinity graph G = generate_graph_from_friends(friends) # Graph structure: # - Nodes: All users in the friends dictionary # - Edges: Weighted by affinity scores # - Direct friends: full affinity weight # - Share interactions: affinity * 0.9 # - Comment interactions: affinity * 0.8 # - Reaction interactions: affinity * 0.7 # Check if connection exists if ("User A", "User B") in G.edges: weight = G["User A"]["User B"]["weight"] print(f"Affinity: {weight}") # Get all neighbors neighbors = list(G.neighbors("User A")) ``` -------------------------------- ### Load Social Media Data from CSV Files (Python) Source: https://context7.com/nikola034/edgerank/llms.txt Loads social media data including friends, comments, reactions, shares, and statuses from CSV files. It populates global dictionaries for feed generation and search. It also supports loading pre-serialized data for faster startup. ```python from main import LoadData, LoadSerializedData, LoadOriginalData # Load test data from CSV files LoadData() # Loads from: dataset/friends.csv, dataset/test_comments.csv, # dataset/test_reactions.csv, dataset/test_shares.csv, dataset/test_statuses.csv # Or load original (full) dataset LoadOriginalData() # Loads from: dataset/friends.csv, dataset/original_comments.csv, # dataset/original_reactions.csv, dataset/original_shares.csv, dataset/original_statuses.csv # For faster startup, load pre-serialized data comments, reactions, shares, statuses = LoadSerializedData() # Returns: (dict, dict, dict, dict) - All social data dictionaries ``` -------------------------------- ### Generate Personalized User Feed with MaxHeap Source: https://context7.com/nikola034/edgerank/llms.txt Generates a personalized feed for a user by calculating relevance scores for all posts from connected users. It utilizes a MaxHeap for efficient retrieval of the top-ranked posts. Relevance is determined by affinity, popularity, and time decay. ```python from main import generate_feed, LoadSerializedData, LoadSerializedGraph # Load serialized data G = LoadSerializedGraph() comments, reactions, shares, statuses = LoadSerializedData() # Generate feed for a user user = "Sarina Hudgens" feed_heap = generate_feed(user) # Relevance calculation per post: # relevance = (affinity_weight * 5) + (popularity * 3) # relevance *= time_weight # Get top 10 posts for i in range(min(10, len(feed_heap))): relevance, status_id = feed_heap.pop() status = statuses[status_id] print(f"Author: {status['author']}") print(f"Message: {status['status_message']}") print(f"Relevance: {relevance}") print("---") ``` -------------------------------- ### Search Posts by Author or Message using Trie Source: https://context7.com/nikola034/edgerank/llms.txt Searches for posts matching search terms by author name or status message content. It employs a Trie data structure for efficient prefix matching and returns results ranked by relevance, considering factors like affinity, popularity, time decay, and word match. ```python from main import search, LoadSerializedData, LoadSerializedGraph G = LoadSerializedGraph() comments, reactions, shares, statuses = LoadSerializedData() user = "Sarina Hudgens" # Search by author name author_results = search(user, "author", "John") # Search by status message message_results = search(user, "status_message", "florida vacation") # Relevance calculation includes: # - Affinity to post author # - Post popularity # - Time decay # - Word match ratio (full match = 1000000x multiplier) # Process results for i in range(min(10, len(message_results))): relevance, status_id = message_results.pop() print(f"Found: {statuses[status_id]['status_message'][:50]}...") ``` -------------------------------- ### Parse Social Media Data Files Source: https://context7.com/nikola034/edgerank/llms.txt Functions to load reaction and share data from CSV files into structured Python dictionaries. These utilities facilitate data ingestion for social graph analysis. ```python from parse_files import load_reactions, load_shares # Load reactions keyed by reactor reactions = load_reactions("dataset/test_reactions.csv") # Load shares keyed by sharer shares = load_shares("dataset/test_shares.csv") ``` -------------------------------- ### Data Management API Source: https://context7.com/nikola034/edgerank/llms.txt Endpoints for loading raw social media data from CSV files and serializing data for optimized performance. ```APIDOC ## POST /data/load ### Description Loads social media data (friends, comments, reactions, shares, statuses) into the application memory. ### Method POST ### Endpoint /data/load ### Parameters #### Query Parameters - **mode** (string) - Optional - Use 'original' to load full dataset or 'test' for sample data. ### Request Example { "mode": "test" } ### Response #### Success Response (200) - **status** (string) - Confirmation of successful data load. --- ## POST /data/serialize ### Description Serializes current data dictionaries into binary files using pickle to enable faster application startup. ### Method POST ### Endpoint /data/serialize ### Response #### Success Response (200) - **message** (string) - Confirmation that serialized files have been saved to the disk. ``` -------------------------------- ### Calculate Post Engagement Popularity Score (Python) Source: https://context7.com/nikola034/edgerank/llms.txt Calculates the popularity score of a status post by aggregating its engagement metrics like shares, comments, and various reaction types. Each metric is assigned a specific weight to reflect its contribution to the overall popularity. ```python from main import calculate_popularity # Example status dictionary structure status = { "status_id": "123456_789", "status_message": "Hello world!", "author": "John Smith", "status_published": datetime.datetime(2023, 6, 15, 10, 30, 0), "num_shares": 10, "num_comments": 25, "num_likes": 100, "num_loves": 20, "num_wows": 5, "num_hahas": 8, "num_sads": 2, "num_angrys": 1, "num_reactions": 136 } popularity_score = calculate_popularity(status) # Calculation: shares*1 + comments*0.8 + likes*0.3 + loves*0.4 + # wows*0.4 + hahas*0.3 + angrys*0.1 + sads*0.1 # Result: 10*1 + 25*0.8 + 100*0.3 + 20*0.4 + 5*0.4 + 8*0.3 + 2*0.1 + 1*0.1 = 72.7 ``` -------------------------------- ### Apply Time Decay Weight to Content Recency (Python) Source: https://context7.com/nikola034/edgerank/llms.txt Applies a time decay weight to content based on the elapsed time since its interaction or publication. This function ensures that more recent content receives a higher weight in the ranking algorithm. ```python from main import calculate_time_weight # Time thresholds and their weights: time_elapsed_seconds = 43200 # 12 hours weight = calculate_time_weight(time_elapsed_seconds) # Time decay schedule: ``` -------------------------------- ### Parse Comments CSV Data Source: https://context7.com/nikola034/edgerank/llms.txt Loads user comments on status posts from a CSV file, with support for multi-line comment text. The function returns a dictionary keyed by the author of the comments, with each value being a list of comment objects. ```python from parse_files import load_comments comments = load_comments("dataset/test_comments.csv") # Result structure (keyed by author): # { # "Jane Doe": [ # { # "comment_id": "abc123", ``` -------------------------------- ### Parse Friends CSV Data Source: https://context7.com/nikola034/edgerank/llms.txt Loads social graph friendship data from a CSV file. The CSV format is expected to be 'person_name, friend_count, friend1, friend2, ...'. The function returns a dictionary where keys are user names and values are lists of their friends. ```python from parse_files import load_friends # CSV format: person_name, friend_count, friend1, friend2, ... friends = load_friends("dataset/friends.csv") # Result structure: # { # "John Smith": ["Jane Doe", "Bob Wilson", ...], # "Jane Doe": ["John Smith", "Alice Brown", ...], # ... # } # Access friends list user_friends = friends["John Smith"] print(f"John has {len(user_friends)} friends") ``` -------------------------------- ### Calculate User Relationship Affinity Score (Python) Source: https://context7.com/nikola034/edgerank/llms.txt Calculates the affinity score between two users based on their interactions such as shares, comments, and reactions. The score is weighted by interaction type and incorporates time decay, prioritizing recent and significant interactions. ```python from main import calculate_affinity # Calculate affinity between two users user = "John Smith" other_user = "Jane Doe" affinity_score = calculate_affinity(user, other_user) # Interaction weights used internally: # weights = { # 'reaction': { # 'likes': 0.5, 'loves': 0.6, 'wows': 0.6, # 'hahas': 0.5, 'angrys': 0.1, 'sads': 0.2, 'special': 0.2 # }, # 'comment': 1.0, # 'share': 1.5 # } # Result: float - Weighted sum of interactions with time decay applied ``` -------------------------------- ### Parse Status Posts CSV Data Source: https://context7.com/nikola034/edgerank/llms.txt Parses status posts from CSV files, correctly handling multi-line messages that may contain escaped quotes. The function returns a dictionary where keys are status IDs and values are dictionaries containing all status details. ```python from parse_files import load_statuses statuses = load_statuses("dataset/test_statuses.csv") # Result structure: # { # "644891892279936_12345": { # "status_id": "644891892279936_12345", # "status_message": "Post content here...", # "status_type": "photo", # "status_link": "http://...", # "status_published": datetime.datetime(2023, 6, 15, 10, 30, 0), # "author": "John Smith", # "num_reactions": 150, # "num_comments": 25, # "num_shares": 10, # "num_likes": 100, # "num_loves": 20, # "num_wows": 15, # "num_hahas": 10, # "num_sads": 3, # "num_angrys": 2, # "num_special": 0 # }, # ... # } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.