### Install poster library for Python Source: https://context7.com/labkey/examples/llms.txt Installs the 'poster' library, a dependency for Python scripts interacting with LabKey Server's WebDAV and REST APIs. ```bash pip install poster ``` -------------------------------- ### Install Ontology Tools Dependencies Source: https://context7.com/labkey/examples/llms.txt Installs necessary Python packages for the ontology conversion tools. PySpark also requires a local Java installation (JDK 8+). ```bash pip install argparse pyspark pandas>=0.23.2 rdflib # PySpark also requires a local Java installation (JDK 8+) ``` -------------------------------- ### Access Current Container Information via LABKEY JavaScript API Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Get information about the current container or folder, including its ID, path, and name, using the LABKEY.container object. ```javascript // Access current container/folder information console.log('Container ID:', LABKEY.container.id); console.log('Container Path:', LABKEY.container.path); console.log('Container Name:', LABKEY.container.name); ``` -------------------------------- ### Scope JavaScript with wrapperDivId Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Use the wrapperDivId template variable to get the unique ID of the wrapper div for the view. This is useful for scoping JavaScript or CSS to a specific view instance. ```javascript var wrapper = document.getElementById('<%=wrapperDivId%>'); ``` -------------------------------- ### Deploying and Reloading Module Changes Source: https://context7.com/labkey/examples/llms.txt Instructions for deploying a file-based module to a local LabKey instance and notes on which changes trigger hot-reloading versus requiring a server restart. ```bash # Deploy to local LabKey instance (no restart needed for most changes) cp -r myModule/ /build/deploy/externalModules/myModule/ # Hot-reload rules: # ✅ HTML/JS view changes — browser refresh only # ✅ SQL query changes — browser refresh only # ✅ Report updates — browser refresh only # ⚠️ module.properties — server restart required # ⚠️ new resource types — may require server restart # Enable the module: # LabKey UI → Folder > Management → Folder Type tab # → Check your module → Update Folder ``` -------------------------------- ### Convert OWL/XML to LabKey Ontology Archive (NCI, GO, Generic) Source: https://context7.com/labkey/examples/llms.txt Uses `owl.py` to parse OWL XML and create a LabKey ontology archive. Supports presets for NCI and GO ontologies, and generic OWL files. Use `--verbose` for progress and `--keep` to retain intermediate files. ```bash # Generic OWL file python owl.py input.owl output.zip # NCI Thesaurus (Thesaurus.owl from https://bioportal.bioontology.org/ontologies/NCIT) # Uses NHC0 as code element, P97 as description, compact base64 path encoding python owl.py --type nci Thesaurus.owl nci_ontology.zip # Gene Ontology (go.owl from https://bioportal.bioontology.org/ontologies/GO) # Strips "GO_" prefix, uses base64 path encoding python owl.py --type go go.owl go_ontology.zip # Verbose output showing progress python owl.py --type nci --verbose Thesaurus.owl nci_ontology.zip # Output: # parsing Thesaurus.owl # computing paths # writing hierarchy.txt # writing concepts.txt # writing synonyms.txt # zipping nci_ontology.zip # Keep intermediate files for inspection python owl.py --type nci --keep Thesaurus.owl /output/nci_ontology.zip # Leaves concepts.txt, hierarchy.txt, synonyms.txt in /output/ alongside the zip # Internal classes used: # ImportConfig - base config (generic OWL) # NciThesaurusConfig - NCI-specific: reads NHC0 code tag, P97 description tag # GoConfig - GO-specific: strips GO_ prefix from codes # Concept - holds code, name, description, parent_codes, synonyms, paths ``` -------------------------------- ### Recommended module.properties Properties Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Includes recommended properties for module configuration, such as label, description, and version. ```properties ModuleClass: org.labkey.api.module.SimpleModule Name: myModule Label: My Custom Module Description: A file-based module for custom queries, reports, and views. Multi-line descriptions can span multiple lines using backslash continuation. Version: 1.0.0 Author: Your Name Organization: Your Organization OrganizationURL: https://example.com License: Apache 2.0 LicenseURL: https://www.apache.org/licenses/LICENSE-2.0 Maintainer: Your Name RequiredServerVersion: 23.11 ``` -------------------------------- ### Parse Basic OWL XML Files Source: https://github.com/labkey/examples/blob/main/ontology/README.md This script handles basic OWL XML files but does not support OWL extensions. It is recommended for NCI and GO ontologies. Run with no arguments for command-line options. ```python import sys from org.labkey.api.ontology import OntologyManager from org.labkey.api.util import FileUtil def main(argv): if len(argv) < 2: print('Usage: python owl.py ') sys.exit(1) ontology_file = argv[1] ontology_manager = OntologyManager() ontology_manager.parse_ontology(ontology_file) if __name__ == "__main__": main(sys.argv) ``` -------------------------------- ### Create Dashboard Web Part Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md This snippet shows how to create a dashboard web part that fetches and displays data. It parses web part configuration and uses LABKEY.Query.selectRows to query data, then renders it within a specified container. ```html

My Dashboard

Loading...
``` -------------------------------- ### Convert RDF/OWL to LabKey Ontology Archive (General Purpose) Source: https://context7.com/labkey/examples/llms.txt Uses `rdf.py` with `rdflib` for flexible RDF/XML parsing, suitable for ontologies with extensions or multilingual support. Supports language filtering. Codes are truncated to 44 characters. ```bash # Basic usage python rdf.py input.owl output.zip # Filter to English labels only (default) python rdf.py --language en input.owl output.zip # French labels python rdf.py --language fr input.owl output.zip # Verbose + keep temp files python rdf.py --verbose --keep input.owl /output/ontology.zip # Output: # writing hierarchy.txt # writing concepts.txt # writing synonyms.txt # zipping /output/ontology.zip # HGNC/Hugo-specific properties handled: # Hugo.owl#Approved_Symbol -> concept name (fallback) # Hugo.owl#Aliases -> synonyms # Hugo.owl#Approved_Name -> description # #prefLabel -> preferred label # #altLabel -> synonym # #subClassOf -> parent relationship # Note: codes are truncated to 44 characters (MAXCODE constant); ``` -------------------------------- ### Construct Container-Specific URLs with contextPath and containerPath Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Combine contextPath and containerPath template variables in JavaScript to create URLs that are specific to the current container or folder. ```javascript var containerUrl = '<%=contextPath%>' + '<%=containerPath%>'; ``` -------------------------------- ### Define a Basic SQL Query for Core Users Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md This SQL query selects user information (ID, DisplayName, Email, Active) from the core.Users table, filtering for active users and ordering by display name. ```sql SELECT UserId, DisplayName, Email, Active FROM core.Users WHERE Active = TRUE ORDER BY DisplayName ``` -------------------------------- ### Module Properties Configuration Source: https://context7.com/labkey/examples/llms.txt Defines the minimum required properties for a file-based LabKey module. Ensure 'RequiredServerVersion' matches your LabKey instance. ```properties ModuleClass: org.labkey.api.module.SimpleModule Name: myModule Label: My Custom Module Description: A file-based module for custom queries, reports, and views. Version: 1.0.0 Author: Your Name RequiredServerVersion: 23.11 ``` -------------------------------- ### Module properties configuration Source: https://context7.com/labkey/examples/llms.txt This is a required configuration file for LabKey modules. ```properties module.properties ``` -------------------------------- ### Provide Metadata for Core Users Query Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md This XML file defines metadata for the core.Users query, including descriptions for specific columns like UserId and DisplayName. ```xml Unique user identifier User's display name ``` -------------------------------- ### Web Part XML Configuration Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Provides the XML configuration for a LabKey web part, including its name and description. ```xml My Web Part Description of what this web part does body ``` -------------------------------- ### Validate LabKey ontology archive before upload Source: https://context7.com/labkey/examples/llms.txt Runs comprehensive consistency checks on a LabKey ontology ZIP archive using Apache Spark to catch potential issues before loading into LabKey. ```bash python validate.py my_ontology.zip ``` ```text SUCCESSS no problems found ``` ```text ERRORS Concept codes are not all unique. Some concepts were not found in hierarchies.txt. C12345 C67890 ... ``` ```text WARNINGS 15 concept codes do not have entries in aliases table. C99001 C99002 ... ``` -------------------------------- ### Download LabKey Study Archive (Python) Source: https://context7.com/labkey/examples/llms.txt Exports and downloads a LabKey Study archive as a ZIP file. It POSTs to the folder management export endpoint and streams the response. Requires the 'poster' library and a credentials file. ```bash # 1. Install dependency pip install poster # 2. Set credentials file (same format as above) export LABKEY_CREDENTIALS=~/.labkeycredentials.txt # 3. Edit variables inside download_study_archive.py: # labkey_url = 'https://mylabkey.example.com' # labkey_project = 'MyProject' # labkey_folder = 'ClinicalStudy' # 4. Run — download to current directory python download_study_archive.py # 5. Run — download to a specific directory python download_study_archive.py -d /data/archives/ # Expected output: download_study_archive.py is starting Download the study archive from https://mylabkey.example.com/admin/MyProject/ClinicalStudy/folderManagement.view?... -- Start-time: Mon Jan 15 09:22:01 2024 -- Completed at: Mon Jan 15 09:22:47 2024 The study archive has been successfully downloaded to /data/archives/ClinicalStudy_20240115.zip # Study components exported by default: # Missing value indicators, Study, Assay Datasets, Assay Schedule, # Categories, Cohort Settings, CRF Datasets, Custom Participant View, # Participant Comment Settings, Participant Groups, Protocol Documents, # QC State Settings, Specimen Settings, Specimens, Treatment Data, Visit Map ``` -------------------------------- ### Convert Ontology Files for i2b2 Import Source: https://github.com/labkey/examples/blob/main/ontology/README.md This script converts ontology files for importing into i2b2. Be aware that many files have poor handling of special character escaping. ```python import sys from org.labkey.api.ontology import OntologyManager from org.labkey.api.util import FileUtil def main(argv): if len(argv) < 2: print('Usage: python i2b2.py ') sys.exit(1) ontology_file = argv[1] ontology_manager = OntologyManager() ontology_manager.parse_ontology(ontology_file) if __name__ == "__main__": main(sys.argv) ``` -------------------------------- ### Module Directory Structure Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Defines the standard layout for a LabKey file-based module's resources and configuration files. ```text myModule/ ├── module.properties # Module configuration (REQUIRED) ├── README.md # Module documentation └── resources/ # All module resources go here ├── queries/ # SQL queries and query metadata │ └── [schema_name]/ # Organize by schema │ ├── [query_name].sql │ ├── [query_name].query.xml │ └── [query_name]/ # Query-specific views │ └── [view_name].html ├── reports/ # Report definitions │ └── schemas/ │ └── [schema_name]/ │ └── [query_name]/ │ ├── [report_name].r │ ├── [report_name].rhtml │ └── [report_name].report.xml ├── views/ # Custom views and web parts │ ├── [view_name].html │ └── [view_name].webpart.xml ├── schemas/ # Database schema definitions │ └── dbscripts/ │ ├── postgresql/ │ └── sqlserver/ ├── web/ # JavaScript, CSS, images │ └── [moduleName]/ │ ├── [moduleName].js │ └── [moduleName].css ├── assay/ # Assay type definitions ├── etls/ # ETL configurations ├── folderTypes/ # Custom folder type definitions └── pipeline/ # Pipeline task definitions ``` -------------------------------- ### LabKey Server Credentials File Format Source: https://context7.com/labkey/examples/llms.txt Specifies the format for the credentials file used by Python scripts for authentication. Set the LABKEY_CREDENTIALS environment variable to its path. ```text machine https://www.labkey.org login myusername@example.com password mySecretPassword ``` -------------------------------- ### Recommended module directory layout for file-based development Source: https://context7.com/labkey/examples/llms.txt This is a recommended directory structure for creating LabKey file-based modules. Place CLAUDE.md in the root of your module directory when using Claude Code. ```markdown # Recommended module directory layout myModule/ ├── module.properties # REQUIRED — module configuration ├── CLAUDE.md # Add this when using Claude Code ├── README.md └── resources/ ├── queries/[schema]/ # .sql + .query.xml ├── reports/schemas/ # .r, .rhtml, .report.xml ├── views/ # .html + .webpart.xml ├── schemas/dbscripts/ # postgresql/ and sqlserver/ ├── web/[moduleName]/ # .js and .css ├── assay/ ├── etls/ ├── folderTypes/ └── pipeline/ ``` -------------------------------- ### Content Security Policy (CSP) for Inline Scripts Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Demonstrates the correct way to include inline scripts in LabKey web parts to comply with Content Security Policy (CSP) by using the nonce attribute. ```html ``` -------------------------------- ### Validate LabKey Ontology Archive Source: https://github.com/labkey/examples/blob/main/ontology/README.md Run consistency checks on a LabKey ontology archive (.zip) before uploading. This tool flags potential problems that could lead to unexpected behavior. ```python import sys from org.labkey.api.ontology import OntologyManager from org.labkey.api.util import FileUtil def main(argv): if len(argv) < 2: print('Usage: python validate.py ') sys.exit(1) ontology_archive = argv[1] ontology_manager = OntologyManager() ontology_manager.validate_ontology_archive(ontology_archive) if __name__ == "__main__": main(sys.argv) ``` -------------------------------- ### Convert i2b2 flat files to LabKey ontology archive Source: https://context7.com/labkey/examples/llms.txt Processes i2b2-formatted pipe-delimited text files using Apache Spark. Handles poorly-escaped special characters and extracts concepts, hierarchy, and synonym tables. ```bash python i2b2.py snomed_i2b2.txt snomed_ontology.zip ``` ```bash python i2b2.py --strip snomed_i2b2.txt snomed_ontology.zip ``` ```bash python i2b2.py --keep snomed_i2b2.txt /output/snomed_ontology.zip ``` -------------------------------- ### Parse OWL Files with rdflib Source: https://github.com/labkey/examples/blob/main/ontology/README.md Use this script with rdflib to parse most OWL files, including those with schema extensions. It is recommended for ontologies other than GO and NCI. ```python import sys from org.labkey.api.ontology import OntologyManager from org.labkey.api.util import FileUtil def main(argv): if len(argv) < 2: print('Usage: python rdf.py ') sys.exit(1) ontology_file = argv[1] ontology_manager = OntologyManager() ontology_manager.parse_ontology(ontology_file) if __name__ == "__main__": main(sys.argv) ``` -------------------------------- ### Upload File to LabKey Server via WebDAV (Python) Source: https://context7.com/labkey/examples/llms.txt Uploads a file to a LabKey container's @files WebDAV endpoint using HTTP Basic Auth. Requires the 'poster' library and a credentials file. ```bash # 1. Install dependency pip install poster # 2. Set credentials export LABKEY_CREDENTIALS=~/.labkeycredentials.txt # ~/.labkeycredentials.txt contents: # machine https://mylabkey.example.com # login admin@example.com # password secret123 # 3. Edit variables inside upload_file.py: # labkey_url = 'https://mylabkey.example.com' # labkey_project = 'MyProject' # labkey_folder = 'Assay/Results' # 4. Run python upload_file.py -f /path/to/results.tsv # Expected output: # The file upload was successful. You can see the uploaded file at # https://mylabkey.example.com/_webdav/MyProject/Assay%2FResults/%40files/results.tsv ``` -------------------------------- ### Basic Web Part HTML Structure Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Defines the HTML content for a LabKey web part. Includes a script tag for client-side logic. ```html

My Web Part

Content goes here

``` -------------------------------- ### Build URLs with contextPath in JavaScript Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Utilize the contextPath template variable to construct URLs for server resources within your JavaScript code. This ensures correct path resolution. ```javascript var url = '<%=contextPath%>' + '/someResource.js'; ``` -------------------------------- ### Parse Web Part Configuration with webpartContext Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Access detailed web part configuration, including its ID, wrapper div ID, and custom properties, by parsing the webpartContext JSON string. ```javascript var config = JSON.parse('<%=webpartContext%>'); console.log('Web part ID:', config.id); console.log('Properties:', config.properties); ``` -------------------------------- ### Nightly PostgreSQL Backup Script for Windows Source: https://context7.com/labkey/examples/llms.txt This batch script automates nightly backups of PostgreSQL databases on Windows using pg_dump. It supports custom formats, compression, and logs output to a dated file. Ensure the BACKUP_DIR exists and PGPASSFILE is correctly configured to avoid password prompts. ```batch REM ---- Configuration (edit these variables at the top of the script) ---- SET BACKUP_DIR=C:\labkey\backup\database SET POSTGRES_HOME="C:\Program Files\PostgreSQL\9.2" SET POSTGRES_USER=postgres SET POSTGRES_HOST=localhost SET POSTGRES_PORT=5432 SET PGPASSFILE=C:\DIR\PG_BACKUP\PGPASSFILE\pgpass.conf SET LOGFILE=%BACKUP_DIR%\labkey-database-backup.log REM ---- Run the script ---- REM labkey-database-backup-sample-script.bat REM ---- What it does ---- REM 1. Validates that %BACKUP_DIR% exists (exits with error if not) REM 2. Runs pg_dump for 'postgres' DB: REM pg_dump --format=c --compress=9 -h localhost -p 5432 -U postgres REM -f C:\labkey\backup\database\postgresql-backup-postgres_20240115.bak postgres REM 3. Runs pg_dump for 'labkey' DB: REM pg_dump --format=c --compress=9 -h localhost -p 5432 -U postgres REM -f C:\labkey\backup\database\postgresql-backup-labkey_20240115.bak labkey REM 4. Verifies both .bak files exist; logs ERROR if either is missing REM 5. Writes timestamped completion entry to %LOGFILE% REM ---- Sample log output (success) ---- REM [20240115 09:00:01] ============== Start the PostgreSQL backup of all databases REM [20240115 09:00:01] ======= Start the backup of postgres database REM [20240115 09:00:08] ======= Start the backup of labkey database REM [20240115 09:00:45] ============== Verify the database backup files have been created REM [20240115 09:00:45] ============== PostgreSQL backup has completed REM ---- pgpass.conf format (avoids password prompts) ---- REM localhost:5432:*:postgres:myPostgresPassword ``` -------------------------------- ### SQL Query for Active Users Source: https://context7.com/labkey/examples/llms.txt A SQL query to select active users from the core.Users table, ordered by display name. This can be used in LabKey schemas. ```sql -- resources/queries/core/ActiveUsers.sql SELECT UserId, DisplayName, Email FROM core.Users WHERE Active = TRUE ORDER BY DisplayName ``` -------------------------------- ### Web Part XML Definition Source: https://context7.com/labkey/examples/llms.txt Defines the metadata for a LabKey web part, including its name, description, and location within the UI. ```xml My Dashboard Displays active users in the current container body ``` -------------------------------- ### Query Data with LABKEY.Query.selectRows Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Execute a query to select rows from a specified schema and query name. Handles success and failure callbacks for asynchronous data retrieval. ```javascript LABKEY.Query.selectRows({ schemaName: 'lists', queryName: 'MyList', success: function(data) { console.log('Rows:', data.rows); }, failure: function(error) { console.error('Query failed:', error); } }); ``` -------------------------------- ### Required module.properties Properties Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Specifies the essential properties for a LabKey module's configuration. ```properties ModuleClass: org.labkey.api.module.SimpleModule Name: myModule ``` -------------------------------- ### Add Custom Button Actions Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md This snippet demonstrates how to add custom button actions to a web part. It attaches an event listener to a button that triggers a LABKEY.Utils.alert when clicked. ```html
``` -------------------------------- ### Web Part with LabKey JS API Source: https://context7.com/labkey/examples/llms.txt An HTML-based web part that uses the LabKey JavaScript API to fetch and display user data. Ensure 'nonce' is included for CSP compliance and scope DOM access using 'wrapperDivId'. ```html

My Dashboard

Loading...
``` -------------------------------- ### Use scriptNonce for CSP Compliance in HTML Views Source: https://github.com/labkey/examples/blob/main/module-development/file-based/CLAUDE.md Include the scriptNonce template variable in script tags to ensure compliance with Content Security Policy. This is required for all inline scripts. ```html