### Initialize Actions for Menu Example (Python) Source: https://docs.cerebrohq.com/en/home/api/client/examples/capi-example-menu This Python snippet demonstrates how to initialize actions for the menu adding example in Cerebro. It imports necessary modules and calls the main function from the examples.action module. Ensure the examples module is correctly set up. ```python import cerebro import examples def init_actions(): examples.action.main() ``` -------------------------------- ### Example Task Filtering Setup for Maya (JSON) Source: https://docs.cerebrohq.com/en/home/helpcenter/tentaculo/tentaculo-setting/configuration-settings A comprehensive example showing how to configure 'status_filter', 'activity_filter', and 'tree_hide_list' specifically for the Maya application within the 'filters' section. ```json "filters": { "maya": { "status_filter": ["No Status", "ready to start", "in progress"], "activity_filter": ["No Activity", "animation", "compose"], "tree_hide_list": ["/Project 1/{*}/Shot{?}{?}/animation", "/{*}/Task {?}/Work"] } } ``` -------------------------------- ### PyQt Menu Creation Example Source: https://docs.cerebrohq.com/en/home/api/client/examples/capi-example-pyside This Python code demonstrates how to add custom menu items to Cerebro's main menu using the PyQt5 package. It creates a 'Python Qt' submenu with actions to show a Qt dialog and a Qt window. The module requires PyQt5 to be installed and accessible within Cerebro's environment. ```python # -*- coding: utf-8 -*- """ The sample shows the usage of PyQt5 package (http://www.riverbankcomputing.com/software/pyqt/). The package is included in Cerebro distribution pack, located in the "py-site-packages" folder. Functions: create_menu() - adding menu items calling Qt windows. show_dialog() - is called on activation of a custom 'Qt dialog' menu item show_window() - is called on activation of a custom 'Qt window' menu item """ import cerebro def create_menu(): # Adding menu items calling Qt windows. # Adding the items to the main menu main_menu = cerebro.actions.MainMenu() # getting the main menu my_menu = main_menu.insert_menu(main_menu.size() - 2, 'Python Qt') # inserting the submenu into the penultimate position my_menu.add_action('examples.pyqt.show_dialog', 'Qt dialog') # adding the menu item my_menu.add_action('examples.pyqt.show_window', 'Qt window') # adding the menu item ``` -------------------------------- ### Cerebro Attachment Initialization Examples (Python) Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/aclasses Provides examples of how to get the current attachment or a list of attachments from a message using Cerebro's core functionalities. ```python attach = cerebro.core.current_attachment() attachs = message.attachments() ``` -------------------------------- ### PyQt Dialog Display Example Source: https://docs.cerebrohq.com/en/home/api/client/examples/capi-example-pyside This Python code defines a function `show_dialog` that displays a simple modal Qt dialog using PyQt5. The dialog blocks the main application interface until it is closed. Ensure PyQt5 is installed and available in the Cerebro environment. ```python from PyQt5 import QtWidgets, QtCore class MyDialog(QtWidgets.QDialog): # dialog class def __init__(self, parent=None): super(MyDialog, self).__init__(parent) label = QtWidgets.QLabel('Qt dialog') label.setAlignment(QtCore.Qt.AlignCenter) mainLayout = QtWidgets.QGridLayout() mainLayout.addWidget(label, 0, 0) self.setLayout(mainLayout) def show_dialog(): # A 'Qt Dialog' main menu item activation. # Displays a dialog. The main interface is blocked at the moment. dialog = MyDialog() dialog.setFixedSize(300, 200) dialog.exec_() # main application interface remains blocked until the dialog window is closed ``` -------------------------------- ### Cerebro Configuration File Example (JSON) Source: https://docs.cerebrohq.com/en/home/helpcenter/tentaculo/tentaculo-setting/examples-of-configuration This JSON structure defines configuration settings for Cerebro, including network protocols, project directory paths, and file path rules for publishing and versioning. It supports dynamic variable substitution for creating flexible file paths based on task details and software. ```json { "protocol": { "cerebro": ["ftp:ftp://ftp.example.com", "network"], "maya": "network" }, "project_path": [ { "project_name": "", "task_activity": "", "paths": [ "//s2/front/connector.files", "/Volumes/front/connector.files", "/s2/front/connector.files", "/ftp2/front/connector.files" ] } ], "file_path": [ { "folder_path": "", "task_activity": "", "name": "$(task_name)", "publish": "$(url[0])/$(url[1])/$(url[2])", "version": "$(url[0])/$(url[1])/$(url[2])/versions", "ver_prefix": "_v", "ver_padding": "3" }, { "folder_path": "/$(url[0])/Environment", "task_activity": "texturing", "name": "$(task_name)", "publish": "$(url[0])/$(url[1])/$(url[2])/$(soft_folder)/", "version": "$(url[0])/$(url[1])/$(url[2])/$(soft_folder)/versions", "ver_prefix": "_v", "ver_padding": "2" } ], "soft_folder": { "maya": "3D" } } ``` -------------------------------- ### Configure PyQt Menu in Cerebro Source: https://docs.cerebrohq.com/en/home/api/client/examples/capi-example-pyside This code snippet shows how to import necessary modules and uncomment a function call in `menu.py` to enable PyQt menu integration in Cerebro. It requires renaming `menu.py.template` to `menu.py` and assumes the `examples` module is available. ```python import cerebro import examples def init_menu(): examples.pyqt.create_menu() ``` -------------------------------- ### PyQt Window Display Example Source: https://docs.cerebrohq.com/en/home/api/client/examples/capi-example-pyside This Python code defines a function `show_window` that displays a non-modal Qt window using PyQt5. The window does not block the main application interface. It creates a new window on the first call and reuses the existing window on subsequent calls. Requires PyQt5. ```python from PyQt5 import QtWidgets, QtCore window = None def show_window(): # A 'Qt Window' main menu item activation. # The window doesn't cause the main interface to block. global window if window == None: # if a window object is not created yet, creating it window = QtWidgets.QLabel() window.setAlignment(QtCore.Qt.AlignCenter) window.setFixedSize(300, 200) window.setWindowTitle('Qt window') window.setText('Displaying the window for the first time') else: window.setText('Displaying the window for the next time') window.show() ``` -------------------------------- ### Git Protocol Connection String Format Source: https://docs.cerebrohq.com/en/home/helpcenter/tentaculo/tentaculo-setting/configuration-settings This example illustrates the format for configuring the Git protocol, including connection parameters for remote repositories. It specifies the address, group, repository name, working branch, and file working mode. The Git client must be installed on the user's machine. ```plaintext "git:https://{remote git repository address}/{group name}/{repository name}:{working branch name}:{file working mode}" ``` -------------------------------- ### Python ProgressBox Example: Creating and Updating Progress Source: https://docs.cerebrohq.com/ru/home/api/client/cerebropackage/gui Demonstrates how to initialize a ProgressBox, set its label and show it, then update its value in a loop. It also shows how to check if the user has canceled the operation and how to close the box. This example is useful for displaying the progress of long-running tasks. ```python prgbar = cerebro.gui.ProgressBox('Окно прогресса', 0, 100) prgbar.set_label('Прогресс...') prgbar.show() for i in range(0,100): if prgbar.was_canceled() == True: # проверяем, не отменил ли пользователь операцию break prgbar.set_value(i) prgbar.close() ``` -------------------------------- ### Get Attachment Data and File Hash Example (Python) Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/aclasses Demonstrates how to access attachment data and verify the file hash using the Attachment class in Cerebro. It highlights the relationship between direct data access and specific methods like file_hash(). ```python attach = cerebro.core.current_attachment() attach.file_hash() == attach.data()[attach.DATA_FILE_HASH] attach.is_link() == (attach.data()[attach.DATA_IS_LINK] != 0) ``` -------------------------------- ### Multiple Directory Mappings Example Source: https://docs.cerebrohq.com/en/home/helpcenter/for-administrators/cerebro-installation/directory-mapping Illustrates how to configure multiple directory mappings within the viewers.conf file to support various network resources across different operating systems. ```xml ``` -------------------------------- ### Configure Maya Task Filters Example Source: https://docs.cerebrohq.com/ru/home/helpcenter/tentaculo/tentaculo-setting/configuration-settings This example demonstrates how to configure status, activity, and tree hide list filters specifically for the Maya application within the project settings. ```json "filters": { "maya": { "status_filter": ["No Status", "ready to start", "in progress"], "activity_filter": ["No Activity", "animation", "compose"], "tree_hide_list": ["/Project 1/{*}/Shot{?}{?}/animation", "/{*}/Task {?}/Work"] } } ``` -------------------------------- ### Example of $(date) Variable Output Source: https://docs.cerebrohq.com/ru/home/helpcenter/community/convenient-search-backgrounds-borders-new-keys-and-variables Illustrates the resulting file path after the $(date) variable is processed. This shows how the current date is dynamically inserted into the path, based on the specified format. ```plaintext /project/scenes/sc_01/2025-02-28 ``` -------------------------------- ### PyQt: Display PyQt QMessageBox Source: https://docs.cerebrohq.com/en/home/api/client/pyqt Example demonstrating how to display a PyQt QMessageBox. It highlights that a QApplication instance is already managed by Cerebro and should not be recreated. ```python def show_window(): #app = QtGui.QApplication(sys.argv) do not create!!! box = QtGui.QMessageBox() box.setText('Hello, World!') box.exec_() ``` -------------------------------- ### Python Logoff Handling Example for Cerebro Source: https://docs.cerebrohq.com/en/home/api/client/examples/capi-example-logonoff This Python code snippet illustrates how to handle user logoff events within the Cerebro platform. It imports necessary modules and defines a function to manage logoff actions. This is a placeholder for specific logoff logic. ```python import cerebro import examples def logoff(): return examples.logoff.logoff() ``` -------------------------------- ### Core Functions - Start Timer Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/core Starts a timer for a specified task. ```APIDOC ## POST /cerebro/core/start_timer ### Description Starts a timer for a specified task. ### Method POST ### Endpoint /cerebro/core/start_timer ### Parameters #### Request Body - **task_id** (int) - The ID of the task for which to start the timer. ### Request Example ```json { "task_id": 987 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of starting the timer. #### Response Example ```json { "status": "Timer started successfully." } ``` ``` -------------------------------- ### Task Start Time API Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/aclasses Provides methods to set and retrieve the start time of a task. The start time can be set as a specific date or reset to derive from predecessors and schedule. ```APIDOC ## POST /websites/cerebrohq/task/set_start ### Description Sets the task start time. The time is represented as the number of days from 01.01.2000 UTC. Setting the time to `None` resets it to derive from predecessors' start times and the working schedule. ### Method POST ### Endpoint `/websites/cerebrohq/task/set_start` ### Parameters #### Request Body - **time** (float) - Required - Time period from 01.01.2000, in days. ### Request Example ```json { "time": 4506.375 } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful update. #### Response Example ```json { "message": "Task start time updated successfully." } ``` ## GET /websites/cerebrohq/task/start ### Description Retrieves the task start time. ### Method GET ### Endpoint `/websites/cerebrohq/task/start` ### Response #### Success Response (200) - **start_time** (string) - Task start time in ISO format (e.g., "2012-05-03T09:00:00Z"). #### Response Example ```json { "start_time": "2012-05-03T09:00:00Z" } ``` ``` -------------------------------- ### Example Status Filter Configuration (JSON) Source: https://docs.cerebrohq.com/en/home/helpcenter/tentaculo/tentaculo-setting/configuration-settings An example demonstrating how to configure the 'status_filter' for tasks. This filter accepts an array of strings representing task statuses. 'No Status' can be used to filter tasks without a defined status. ```json "status_filter": ["No Status", "ready to start", "in progress"] ``` -------------------------------- ### Python Logon Handling Example for Cerebro Source: https://docs.cerebrohq.com/en/home/api/client/examples/capi-example-logonoff This Python code demonstrates how to handle user logon events in Cerebro. It sets a timer to periodically check for upcoming tasks and notifies the user. Dependencies include the 'cerebro' and 'datetime' modules. The function 'logon' initiates the timer, and 'check_start_tasks' retrieves and displays task notifications. ```python import cerebro import datetime def logon(): # Starting the timer to call the check_start_tasks function cerebro.core.start_timer('examples.logon.check_start_tasks', 1800000) # The check_start_tasks function will be called every 30 minutes def check_start_tasks(): # getting the current user's task list current_user = cerebro.core.user_profile() tasks = cerebro.core.to_do_task_list(current_user[cerebro.aclasses.Users.DATA_ID], False) for task in tasks: td = task.start() - datetime.datetime.now() seconds = td.total_seconds() if seconds >= 0 and seconds < 1800: # if the task has not started yet and it is less than 30 minutes till its start message = 'The task: ' + task.name() + ' is starting in ' + str(round(seconds/60)) + " minutes." cerebro.core.notify_user(message, task.id()) ``` -------------------------------- ### Python Processor Example for Opening a File Source: https://docs.cerebrohq.com/en/home/helpcenter/tentaculo/expanding-tentaculo-features/adding-processors Demonstrates a Python 'open_pre' processor that modifies the 'original_file_path' argument based on the task name. This allows for custom file opening behavior. ```python def open_pre(task_info, arg): if task_info['name'] == 'test': arg['original_file_path'] = 'C:/test_file.ma' return arg ``` -------------------------------- ### Example: before_event Function Source: https://docs.cerebrohq.com/en/home/api/client/event A specific example of the before_event function signature, indicating its role in handling actions immediately preceding data modification. This function is crucial for validation and pre-commit logic. ```python def before_event(event): ... ``` -------------------------------- ### AccountDialog: Execute and Retrieve Credentials Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/gui Demonstrates how to instantiate an AccountDialog, execute it to get user credentials, and retrieve the entered login and password. It also shows how to store the credentials for future use. ```python daccount = cerebro.gui.account_dialog('Example', 'Enter your login and password', 'store_key') res = daccount.execute() if res == True: print('Login and password entered by user:', daccount.login(), daccount.password()) daccount.store('store_key') # saving the password for future calls ``` -------------------------------- ### Example Activity Filter Configuration (JSON) Source: https://docs.cerebrohq.com/en/home/helpcenter/tentaculo/tentaculo-setting/configuration-settings An example illustrating the 'activity_filter' configuration. This filter accepts an array of strings to specify activity types for task filtering. 'No Activity' can be selected to filter tasks lacking an activity type. ```json "activity_filter": ["No Activity", "animation", "compose"] ``` -------------------------------- ### Example Tree Hide List Configuration (JSON) Source: https://docs.cerebrohq.com/en/home/helpcenter/tentaculo/tentaculo-setting/configuration-settings An example for configuring 'tree_hide_list' to hide specific tasks. This filter supports wildcard characters: '*' for any path element and '?' for any character except a path separator. It accepts an array of path patterns. ```json "tree_hide_list" : ["/Project 1/{*}/Shot{?}{?}/animation", "/{*}/Task {?}/Work"] ``` -------------------------------- ### Python Processor Example for Saving a Version Source: https://docs.cerebrohq.com/en/home/helpcenter/tentaculo/expanding-tentaculo-features/adding-processors Shows a Python 'version_post' processor that appends information to the report and adds a hashtag. It also demonstrates how to modify attachment paths and control version sending. ```python arg['report']['plain_text'] += ' Path to file ' + arg['version_file_path'] arg['report']['hashtags'] = ['version'] return arg ``` -------------------------------- ### Initialize Actions in Cerebro Source: https://docs.cerebrohq.com/en/home/api/client/action The `init_actions` function is called when the application starts or when Python modules are updated during debugging. It's responsible for initializing custom user-defined menu items. ```python def init_actions(): ... ``` -------------------------------- ### Python: Пример добавления пользовательского меню в Cerebro Source: https://docs.cerebrohq.com/ru/home/api/client/templates Этот пример демонстрирует, как добавить пользовательское меню в Cerebro, используя шаблон action.py.template. Необходимо переименовать файл шаблона в action.py и написать код в функции init_actions. Для этого требуется импортировать пакет examples и вызвать функцию examples.action.main(). ```python import examples # Import examples package def init_actions(): # Call function to adding user-defined menus examples.action.main() ``` -------------------------------- ### Get Current Task Information Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/core Retrieves the current task object that is active in the Cerebro GUI. The example demonstrates how to get the name of the current task. This is fundamental for any operation targeting the currently focused task. ```python def example_task_menu(): print('Call example_task_menu on clicking "My menu item"') # Getting current task task = cerebro.core.current_task() print('Current task:', task.name()) ``` -------------------------------- ### Stop Example Timer in Logoff Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/core This Python function, part of the logoff example, stops a timer that was previously started. It specifically targets a timer named 'example_timer' associated with the logon process and prints a confirmation message. ```python # examples/logoff.py file # examples package # logoff module import cerebro def logoff(): # Stopping the timer calling 'example_timer' function, started on login to Cerebro cerebro.core.stop_timer('examples.logon.example_timer') print('Timer calling example_timer stopped') ``` -------------------------------- ### Initialize and Connect to Cerebro Database (Python) Source: https://docs.cerebrohq.com/ru/home/api/server/components/database Demonstrates how to initialize the Database class and establish a connection to the Cerebro database. It shows preference for connecting via the running Cerebro client, with a fallback to direct connection using credentials if the client connection fails. This is essential for any database operations within Cerebro. ```python import pycerebro # Устанавливаем соединение с базой данных db = pycerebro.database.Database() if db.connect_from_cerebro_client() != 0: # Пробуем установить соединение с помощью запущенного клиента Cerebro. # Если не выходит, устанавливаем соединение с помощью логина и пароля db.connect('user', 'password') ``` -------------------------------- ### Greet Administrator using Cerebro Python API Source: https://docs.cerebrohq.com/en/home/api/client/examples/capi-example-menu This function retrieves the current user's profile and displays a personalized greeting message using the Cerebro GUI. It requires access to the `cerebro.core.user_profile` and `cerebro.gui.information_box` functions. ```python def hello_administrator(): # Приветствие администратора current_user = cerebro.core.user_profile() # получили профиль пользователя msg = 'Hello administrator' + current_user[cerebro.aclasses.Users.DATA_FULL_NAME] # сформировали сообщение cerebro.gui.information_box('Cerebro Python API', msg) # показали сообщение ``` -------------------------------- ### Directory Mapping Configuration XML Source: https://docs.cerebrohq.com/en/home/helpcenter/for-administrators/cerebro-installation/directory-mapping Example XML structure for defining directory mappings in the Cerebro viewers.conf file. This section enables and configures how network paths are translated for different operating systems. ```xml ``` -------------------------------- ### Iterate and Print Task Hashtags Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/aclasses This example shows how to retrieve a list of hashtags associated with a task and iterate through them to print each hashtag. It uses the `task.hashtags()` method. ```python for ht in task.hashtags(): print('Hashtag:', ht) ``` -------------------------------- ### Get Current Message Details Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/core Retrieves the current message object when a user's menu item is activated. The example shows how to access the plain text content of the message. This is useful for context-specific actions on messages. ```python def example_message_menu(): print('Calling example_message_menu by click on "My Forum menu item"') # Getting current message message = cerebro.core.current_message() if message: print('Текущее сообщение', message.text_as_plain()) ``` -------------------------------- ### Map Directories for Different OS Source: https://docs.cerebrohq.com/ru/home/helpcenter/for-administrators/cerebro-installation/cerebro-troubleshooting This XML snippet defines directory mappings for different operating systems. It allows administrators to specify server paths that Cerebrohq should use for projects on Windows, macOS, and Linux systems. This is crucial for ensuring consistent access to project files across different platforms. ```xml ``` -------------------------------- ### Get Current Attachment Information Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/core Retrieves the current attachment object when a user's menu item is activated. It includes an example of how to resolve the file name from a hash and download the file if it's missing. This function is related to `selected_attachments()`. ```python def example_attachment_menu(): # Downloading attachment attach = cerebro.core.current_attachment() # getting current attachment on which a user's menu was called file_name = cerebro.cargador.file_name_form_hash(attach.file_hash()) # resolving file name by its hash sum if not file_name or file_name == '': # if the file is absent, attempting to download it cerebro.cargador.download_file(attach.file_hash()) ``` -------------------------------- ### Инициализация действий модуля action Source: https://docs.cerebrohq.com/ru/home/api/client/action Функция init_actions() вызывается при старте программы и при обновлении Python-модулей во время отладки. Она отвечает за инициализацию пользовательских меню. ```python def init_actions(): ... ``` -------------------------------- ### Get New Task Value in Cerebro Events Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/events This Python code shows how to retrieve the new value of a task property that is about to change. It's useful for validating or processing the incoming data. The example specifically checks for activity type changes and prints previous and new values. ```python def before_event(event): if event.event_type() == event.EVENT_CHANGING_OF_TASKS_ACTIVITY: # activity type is being changed tasks = event.tasks() for task in tasks: print('Task name', task.name()) print('Previous activity type', task.activity()) print('New activity type', event.new_value()) ``` -------------------------------- ### Python API Module pycerebro Example Source: https://docs.cerebrohq.com/en/home/helpcenter/community/cerebro-de-cerca Demonstrates the usage of the new pycerebro server API module, which replaces older versions and supports Python 2.7 to 3.x. It uses a new protocol for connecting to Cerebro. ```python import pycerebro # Connect to Cerebro server server = pycerebro.connect("your_cerebro_server_address") # Example: Get tasks tasks = server.get_tasks() print(tasks) # Example: Submit a report server.submit_report(task_id=123, report_data="Report details") ``` -------------------------------- ### Task Start Time API Source: https://docs.cerebrohq.com/en/home/api/server/components/database Sets the starting time for a task, specified in days from 01.01.2000 UTC. Can also reset the start time. ```APIDOC ## POST /task_set_start ### Description Sets the start time for a task, represented as days from 01.01.2000 UTC. Setting `time` to `null` resets the start time. ### Method POST ### Endpoint `/task_set_start` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **task_id** (int or set/list of int) - Required - The ID(s) of the task(s) to update. - **time** (float or null) - Required - The start time in days from 01.01.2000 UTC. `null` resets the start time. ### Request Example ```json { "task_id": 123, "time": 4506.375 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Cerebro API File Structure Example Source: https://docs.cerebrohq.com/en/home/api/client/file Illustrates the typical directory layout for the Cerebro Python API, showing the main executable, frontend modules, and site-packages containing third-party libraries. This structure is crucial for understanding module import paths. ```tree Cerebro/ cerebro py-frontend/ examples/ ... cerebro/ ... event.py.template logoff.py.template logon.py.template menu.py.template py-site-packages/ linux32/ ... linux64/ ... mac/ ... psycopg2/ ... win/ ... html2text.py python32.zip xlrd3.zip xlwt3.zip ... ``` -------------------------------- ### Set Task Start Time (Python) Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/aclasses Sets the start time for a task, specified in days from 01.01.2000 UTC. Passing 'None' resets the start time, allowing it to be derived from predecessors and the working schedule. This is crucial for defining the task's timeline. ```python import datetime # Example 1: Setting a specific start time task.set_start(4506.375) # start time is May 03, 2012 9:00 UTC # Example 2: Setting task start time equal to the current time datetime_now = datetime.datetime.utcnow() datetime_2000 = datetime.datetime(2000, 1, 1) timedelta = datetime_now - datetime_2000 days = timedelta.total_seconds()/(24*60*60) task.set_start(days) ``` -------------------------------- ### Set Task Start Time Source: https://docs.cerebrohq.com/en/home/api/server/components/database Sets the starting time for a task, represented as days from 01.01.2000 UTC. If set to None, the start time is reset and recalculated based on task dependencies and schedules. Accepts a single task ID or an iterable of task IDs. ```python db.task_set_start({task_id, task_id1}, 4506.375) # starting point is May 03, 2012 9:00am UTC ``` ```python import datetime datetime_now = datetime.datetime.utcnow() datetime_2000 = datetime.datetime(2000, 1, 1) timedelta = datetime_now - datetime_2000 days = timedelta.total_seconds()/(24*60*60) db.task_set_start({task_id, task_id1}, days) ``` -------------------------------- ### before_event Exception Example in Python Source: https://docs.cerebrohq.com/ru/home/api/client/event Provides an example of raising an exception within the before_event function to prevent an action, such as creating a new message. ```python def before_event(event): ... raise Exception('Ouch') ... ``` -------------------------------- ### Define Directory Mapping Paths per OS Source: https://docs.cerebrohq.com/en/home/helpcenter/for-administrators/cerebro-installation/cerebro-troubleshooting This XML snippet defines the directory mapping paths for different operating systems (Windows, macOS, Linux). It specifies the network locations where project directories should be mapped, ensuring cross-platform compatibility. Ensure paths are correctly spelled and cased. ```xml ``` -------------------------------- ### Get Selected Tasks by ID Cerebrohq Python Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/aclasses Retrieves a collection of selected tasks, potentially filtered by a task ID, from the cerebro.core module. This function is useful for getting multiple related tasks. ```python tasks = cerebro.core.selected_tasks(task_id) ``` -------------------------------- ### Plugin Development for Cerebro Beta Qt6 with qtpy Source: https://docs.cerebrohq.com/en/home/helpcenter/community/sony-vegas-pro-and-tb-storyboard-pro-in-tentaculo-cerebro-beta-qt6-visual-web-update This snippet demonstrates how to import Qt GUI modules using the `qtpy` compatibility layer, which is essential for developing plugins compatible with the Cerebro Beta Qt6 version. Ensure your plugins are translated to use `qtpy` for broader compatibility. ```python from qtpy.QtGui import * ``` -------------------------------- ### Example: error_event Function Source: https://docs.cerebrohq.com/en/home/api/client/event An example showcasing the error_event function, which is called when a commit error occurs. This function is responsible for handling and reporting any issues encountered while saving data to the database. ```python def error_event(error, event): ... ``` -------------------------------- ### Creating and Managing Plugins in Cerebro (Python) Source: https://docs.cerebrohq.com/en/home/helpcenter/for-administrators/cerebro-administrator-panel/universes This section describes how to create, install, update, and revert plugin versions within the Cerebro Administrator Panel. It requires specifying plugin name, description, path to the Python package, and version details. Network plugins are also discussed, which are loaded remotely. ```Python def create_plugin(name, description, path, version, version_comment): # Logic to add a new plugin to the database pass def update_plugin(name, new_package_path, new_version, new_version_comment): # Logic to update an existing plugin to a new version pass def revert_plugin_version(name, target_version): # Logic to revert a plugin to a previous version pass # Example usage: # create_plugin('my_plugin', 'A sample plugin', '/path/to/my_plugin_package', '1.0.0', 'Initial release') # update_plugin('my_plugin', '/path/to/my_plugin_package_v2', '1.1.0', 'Added new feature') # revert_plugin_version('my_plugin', '1.0.0') ``` -------------------------------- ### Activate Directory Mapping Source: https://docs.cerebrohq.com/en/home/helpcenter/for-administrators/cerebro-installation/cerebro-troubleshooting This XML snippet shows how to activate the directory mapping feature in CerebroHQ. Setting the `enable` value to `1` turns on directory mapping, which is crucial for the functionality described in Situation 3. ```xml ``` -------------------------------- ### Task Starting Point Change Event Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/events Captures events related to modifications in a task's start time, whether through the table, Task Properties window, or Gantt chart. It allows for pre-change, post-change, and error handling callbacks. ```Python EVENT_CHANGING_OF_TASKS_START = 115 # Event objects for handlers: def before_event(BeforeEventChangingOfTasks): pass def after_event(AfterEventChangingOfTasks): pass def error_event(EventError, BeforeEventChangingOfTasks): pass ``` -------------------------------- ### Generating Thumbnails with FFmpeg Source: https://docs.cerebrohq.com/en/home/api/server/components/database This code example shows how to generate thumbnails from a video file using the FFmpeg command-line tool. It illustrates creating multiple thumbnails at specific time points (e.g., beginning, middle, end) of the video. The `subprocess.call` function is used to execute FFmpeg commands with options for input file, output size, seeking to specific times, and saving frames. ```python import subprocess filename = "input_video.mp4" thumbnails = [ "output_thumb1.jpg", "output_thumb2.jpg", "output_thumb3.jpg" ] # Generate first frame thumbnail subprocess.call(['ffmpeg', '-i', filename, '-s', '512x512', '-an', '-ss', '00:00:00', '-r', '1', '-vframes', '1', '-y', thumbnails[0]]) # Generate middle frame thumbnail (assuming 30-second video, middle is 15s) subprocess.call(['ffmpeg', '-i', filename, '-s', '512x512', '-an', '-ss', '00:00:15', '-r', '1', '-vframes', '1', '-y', thumbnails[1]]) # Generate last frame thumbnail (assuming 30-second video, last is 30s) subprocess.call(['ffmpeg', '-i', filename, '-s', '512x512', '-an', '-ss', '00:00:30', '-r', '1', '-vframes', '1', '-y', thumbnails[2]]) print("Thumbnails generated:", thumbnails) ``` -------------------------------- ### Get File Name from Hash using cerebro.cargador.file_name_form_hash Source: https://docs.cerebrohq.com/ru/home/api/client/cerebropackage/cargador This function retrieves the absolute path of a file given its hash. If the file does not exist in storage, it returns None. This is useful for checking if a file is already downloaded or for getting its local path. ```python attach = cerebro.core.current_attachment() # получаем текущее вложение file_name = cerebro.cargador.file_name_form_hash(attach.file_hash()) # пробуем получить имя файла по хешу print('Имя файла', file_name) ``` -------------------------------- ### Executing Mirada for Thumbnail Generation Source: https://docs.cerebrohq.com/en/home/api/server/components/database This Python snippet demonstrates how to execute the Mirada command-line tool to generate thumbnails. It uses the `subprocess.call` function and specifies arguments such as the input file, output directory, and hidden mode. It also includes error handling for non-zero exit statuses and code for searching the generated thumbnail files based on a pattern. ```python import subprocess import os import fnmatch mirada_path = "/path/to/mirada" filename = "/path/to/video.mov" gen_path = "/path/to/generate/thumbnails" es_code = subprocess.call([mirada_path, filename, '--temp', gen_path, '--hide', '--mode', 'thumbstandalone']) if es_code != 0: raise Exception("Mirada returned bad exit-status.\n" + mirada_path) thumbnails = list() for f in os.listdir(gen_path): if fnmatch.fnmatch(f, os.path.basename(filename) + '.thumb*.jpg'): thumbnails.append(gen_path + '/' + f) thumbnails.sort() print("Generated thumbnails:", thumbnails) ``` -------------------------------- ### POST /api/connect Source: https://docs.cerebrohq.com/en/home/api/server/components/database Establishes a connection to the database with provided user credentials. ```APIDOC ## POST /api/connect ### Description Establishes a connection to the database with provided user credentials. ### Method POST ### Endpoint /api/connect ### Parameters #### Query Parameters - **db_user** (string) - Required - Database username. - **db_password** (string) - Required - Database password. ### Request Example ```json { "db_user": "myuser", "db_password": "mypassword" } ``` ### Response #### Success Response (200) - **connection_status** (string) - Indicates the status of the connection (e.g., "connected"). #### Response Example ```json { "connection_status": "connected" } ``` ``` -------------------------------- ### Python: Обработка событий в CerebroHQ Source: https://docs.cerebrohq.com/ru/home/api/client/examples/capi-example-event Пример демонстрирует обработку событий создания сообщения, задачи и изменения прогресса. Включает проверку вложений, установку приоритета для задач, начинающихся сегодня, и запрос подтверждения при уменьшении прогресса. Требует наличия библиотеки cerebro и examples. Основные функции: before_event, after_event, error_event. ```python import cerebro import examples def before_event(event): examples.event.before_event(event) def after_event(event): examples.event.after_event(event) def error_event(error, event): examples.event.error_event(error, event) ``` ```python # -*- coding: utf-8 -*- """ Пример демонстрирует обработку события создания сообщения, создания задачи и изменения прогресса. Здесь мы: a) сделаем проверку на наличие приложенного файла при создании отчета; b) выставим высокий приоритет задаче при её создании, если она начинается сегодня; c) Переспросим пользователя при изменении прогресса в меньшую сторону. Функции: before_event() - действие перед изменением данных after_event() - действие после изменения данных error_event() - обработка ошибки изменения данных """ import cerebro import datetime def before_event(event): # Проверка на наличие вложения при создании отчета if event.event_type() == event.EVENT_CREATION_OF_MESSAGE: # если тип события - создание сообщения if event.type() == event.TYPE_REPORT: # если новое сообщение - "Отчет" attachs = event.new_attachments() # получаем все вложения отчета if len(attachs) == 0: # если вложений нет, генерируем исключение raise Exception('Приложите файл к отчету!') # Отчет не будет добавлен и пользователь увидит окно с этим текстом исключения. # Вопрос пользователю при уменьшении прогресса elif event.event_type() == event.EVENT_CHANGING_OF_TASKS_PROGRESS: # если тип события - изменение прогресса tasks = event.tasks() # получаем изменяемые задачи new_progress = event.new_value() # получаем выставленное пользователем значение прогресса for task in tasks: # смотрим, в какую сторону изменяется прогресс у каждой задачи if new_progress < task.progress(): # если новый прогресс меньше, чем тот, что был до этого, то: # переспрашиваем пользователя, действительно ли он хочет это сделать q = 'Вы уверены, что хотите изменить прогресс задачи "'+task.name()+'" в меньшую сторону?' if cerebro.gui.question_box('Изменение прогресса', q) == False: # если пользователь не уверен, то: raise Exception('') # Прогресс не будет изменен def after_event(event): # Выставление приоритета при создании задачи if event.event_type() == event.EVENT_CREATION_OF_TASK: # если тип события - создание задачи start = event.start() # получаем время начала задачи delta = start - datetime.datetime.now() if delta.days == 0 or delta.days == -1: # если задача начинается сегодня event.set_priority(event.PRIORITY_HIGHT) # устанавливаем высокий приоритет новой задаче def error_event(error, event): print('Ошибка события', event.type_str(), error) ``` -------------------------------- ### Start Timer to Call Function Periodically Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/core Starts a timer that repeatedly calls a specified function at a given interval. The function to be called is specified as a string, including its module path. This is useful for scheduling recurring actions or updates within Cerebro. Ensure the module path is accessible via `sys.path`. ```python # logon.py file # logon module import cerebro import examples # The function handling Cerebro logon def logon(): examples.logon.logon() # calling an example of logon handling ``` ```python # examples/logon.py file # examples package # logon module import cerebro def logon(): # Starting the timer to call 'example_timer' function cerebro.core.start_timer('examples.logon.example_timer', 1000) # restarting the timer each second def example_timer(): print('Calling example_timer by timer') ``` -------------------------------- ### Python PyQt Module Import Handling Source: https://docs.cerebrohq.com/en/home/helpcenter/community/adobe-substance-painter-in-tentaculo-mirada-referral-program This Python code snippet demonstrates how to handle imports for PyQt modules using the 'qtpy' proxy module. It allows for compatibility with different PyQt versions by trying to import from 'qtpy' first and falling back to 'PyQt5' if necessary. This is crucial for developers migrating to Qt6. ```python try: from qtpy.QtGui import * except ImportError: from PyQt5.QtGui import * ``` -------------------------------- ### catalogDownload(hash HASH, siteList STR, CommenceFlags INT, userName STR, url STR, retryCount INT) Source: https://docs.cerebrohq.com/en/home/api/server/xml Commands Cargador to download a file from remote Cargador(s). The operation is queued and does not wait for completion. ```APIDOC ## catalogDownload(hash HASH, siteList STR, CommenceFlags INT, userName STR, url STR, retryCount INT) ### Description Commands Cargador to download the specified file from remote Cargador(s). This method queues the task and returns immediately. Use `statusTables()` to monitor progress and `controlIO()` to manage operations. ### Method N/A (This appears to be a method call within a library, not a direct HTTP endpoint). ### Endpoint N/A ### Parameters #### Path Parameters - **hash** (HASH) - The hash of the file to download. - **siteList** (STR) - A string specifying the source Cargador systems. Format: `addr1:port1[?name1][;addr2:port2[?name2]]`. - `addr`: IP or DNS name of the remote Cargador. - `port`: 'Foreign' port (usually 45431). - `name`: Optional user-friendly Cargador server name. - **CommenceFlags** (INT) - Flags that modify the download behavior (specifics not detailed). - **userName** (STR) - Username of the operation creator (for informational purposes). - **url** (STR) - User-friendly file path (e.g., `example://task /sub-task/file.name`). - **retryCount** (INT) - Number of retries before the operation receives an error status. ### Response #### Success Response - **Returns**: VOID ``` -------------------------------- ### Set Task Finish Time in Python Source: https://docs.cerebrohq.com/en/home/api/server/components/database This example shows how to set a specific finish time for a task in the Cerebro system. The time is represented as the number of days since January 1, 2000 (UTC). It also provides an example of calculating this value dynamically using Python's datetime module. ```python db.task_set_finish(task_id, 4506.75) # the finish time is 03.05.2012 18:00 UTC ``` ```python import datetime datetime_now = datetime.datetime.utcnow() datetime_2000 = datetime.datetime(2000, 1, 1) timedelta = datetime_now - datetime_2000 days = timedelta.total_seconds()/(24*60*60) + 3 db.task_set_finish(task_id, days) ``` -------------------------------- ### Open File for Review in Cerebro Source: https://docs.cerebrohq.com/en/home/helpcenter/community/mobile-app-for-all-android-versions-new-features-in-tentaculo-desktop-update Illustrates how to trigger 'open_...' processors for safely opening files in Cerebro for review. A '"review": True' parameter is passed to the arguments to distinguish this mode from a file being taken into work. The configuration allows specifying the postfix name and path for these review files. ```python args = {"review": True} # When a file is opened in such a way, the open_… processors are triggered. # The same processors are called when a file is taken into work. ``` -------------------------------- ### Import Tasks from Excel using pycerebro Source: https://docs.cerebrohq.com/en/home/api/server/examples/import This Python script demonstrates how to import tasks and their properties from an Excel file into Cerebro. It utilizes the 'xlrd' library for reading Excel files and 'pytz' and 'tzlocal' for timezone handling. The script defines functions for importing, reading data, connecting to the database, and logging. It requires user credentials, a path to the target task in Cerebro, and the path to the Excel file. ```python # -*- coding: utf-8 -*- """ Пример импорта задач из Excel. Этот пример демонстрирует импорт задач и свойств задач из Excel. Для чтения файлов Excel используется сторонний пакет xlrd (https://pypi.python.org/pypi/xlrd) Для работы с временными зонами используются сторонние пакеты pytz (https://pypi.python.org/pypi/pytz/) и tzlocal (https://pypi.python.org/pypi/tzlocal) В модуле используются следующие функции: do_import - Функция импорта. Принимает параметры: Имя пользователя, Пароль пользователя, Путь до задачи, Путь к файлу Excel. read - Функция, которая записывает свойства задачи и всех вложенных задач из Excel в Cerebro. connect_db - Функция для соединения с базой данных Cerebro. write_info, write_error - Функции для логирования. Пример использования: do_import('Имя_пользователя', 'Пароль_пользователя', '/Путь/к/Задаче', 'C:/путь/к/файлу.xlsx') """ # Следующие два параметра, хост и порт - это наш главный сервер с базой данных. # У вас эти параметры могут быть иными, если вы используете свою базу данных host = 'db.cerebrohq.com' port = 45432 # Имена колонок Excel columns = {1: "Описание", 2: "Назначено", 3: "Начало", 4: "Окончание", 5: "Запланировано"} # Индекс колонки с именем задачи name_column = 0 # Пропуск 1 строки заголовка skeep_first_rows = 1 ``` -------------------------------- ### Get message ID (Python) Source: https://docs.cerebrohq.com/en/home/api/client/cerebropackage/aclasses Retrieves the unique identifier (ID) of the message. This is returned as an integer. ```Python # Assuming 'message' is a Message object message_id = message.id() print(f"Message ID: {message_id}") ```