### JavaScript Example: es5.js Source: https://github.com/extremeheat/jspybridge/blob/master/README.md A JavaScript example of an ES5-style class constructor. ```javascript function MyClass(num) { this.getNum = () => num } module.exports = { MyClass } ``` -------------------------------- ### JavaScript Example: time.js Source: https://github.com/extremeheat/jspybridge/blob/master/README.md A simple JavaScript module exporting a function to get the current time as a locale-string. ```javascript function whatTimeIsIt() { return (new Date()).toLocaleString() } module.exports = { whatTimeIsIt } ``` -------------------------------- ### JavaScript Example: emitter.js Source: https://github.com/extremeheat/jspybridge/blob/master/README.md A JavaScript class extending EventEmitter, demonstrating how to emit custom events. ```javascript const { EventEmitter } = require('events') class MyEmitter extends EventEmitter { counter = 0 inc() { this.emit('increment', ++this.counter) } } module.exports = { MyEmitter } ``` -------------------------------- ### Python: Install npm Package Source: https://github.com/extremeheat/jspybridge/blob/master/docs/python.md Installs an npm package into the internal node_modules folder. This command is passed directly to `npm install`. You can specify packages from git repositories. ```python python3 -m javascript --install ``` -------------------------------- ### JavaScript Example: items.js Source: https://github.com/extremeheat/jspybridge/blob/master/README.md A JavaScript module exporting an array of numbers for iteration. ```javascript module.exports = { items: [5, 6, 7, 8] } ``` -------------------------------- ### JavaScript Example: callback.js Source: https://github.com/extremeheat/jspybridge/blob/master/README.md A JavaScript function that accepts a callback and a salt value, then invokes the callback with a computed result. ```javascript export function method(cb, salt) { cb(42 + salt) } ``` -------------------------------- ### Mineflayer Bot with Pathfinder in Python Source: https://context7.com/extremeheat/jspybridge/llms.txt This example demonstrates how to create a Mineflayer Minecraft bot using Python. It includes setting up the bot, loading the pathfinder plugin, and handling chat messages to navigate the player to the sender's location. Requires 'mineflayer' and 'mineflayer-pathfinder' npm packages. ```python from javascript import require, On mineflayer = require('mineflayer') pathfinder = require('mineflayer-pathfinder') RANGE_GOAL = 1 BOT_USERNAME = 'python' bot = mineflayer.createBot({ 'host': '127.0.0.1', 'port': 25565, 'username': BOT_USERNAME }) bot.loadPlugin(pathfinder.pathfinder) @On(bot, 'spawn') def handle(*args): print("I spawned!") mcData = require('minecraft-data')(bot.version) movements = pathfinder.Movements(bot, mcData) @On(bot, 'chat') def handleMsg(this, sender, message, *args): print("Got message", sender, message) if sender and (sender != BOT_USERNAME): bot.chat('Hi, you said ' + message) if 'come' in message: player = bot.players[sender] target = player.entity if not target: bot.chat("I don't see you!") return pos = target.position bot.pathfinder.setMovements(movements) bot.pathfinder.setGoal(pathfinder.goals.GoalNear(pos.x, pos.y, pos.z, RANGE_GOAL)) @On(bot, "end") def handleEnd(*args): print("Bot ended!", args) ``` -------------------------------- ### Manage Pythonia Dependencies with CLI Commands Source: https://context7.com/extremeheat/jspybridge/llms.txt Provides essential command-line interface (CLI) commands for managing Pythonia's internal dependencies. These commands include cleaning the node_modules cache, updating specific npm packages, and installing new packages, including those from Git repositories. ```bash # Clear internal node_modules cache python3 -m javascript --clean # Update an internal npm package python3 -m javascript --update chalk # Install a package (supports git URLs) python3 -m javascript --install PrismarineJS/vec3 python3 -m javascript --install lodash@4.17.21 ``` -------------------------------- ### Import Python Module in JavaScript Source: https://github.com/extremeheat/jspybridge/blob/master/README.md Demonstrates how to import Python modules and call their functions from JavaScript using JSPyBridge. Requires Python to be installed and accessible. ```javascript const python = require('python') // Example: Calling a Python function async function callPython() { const math = python.import('math') const result = await math.sqrt(16) console.log(`Square root of 16 is: ${result}`) } callPython() // Example: Using keyword arguments async function callPythonWithKwargs() { const os = python.import('os') await os.system$('echo "Hello from JavaScript!"') // Note the '$' for kwargs } callPythonWithKwargs() // Exit the Python process when done // python.exit() // process.exit() ``` -------------------------------- ### Python: AsyncTask Decorator for Threads Source: https://github.com/extremeheat/jspybridge/blob/master/docs/python.md Wraps a Python function to run in a separate thread. The `start` parameter controls automatic thread initiation. TaskState provides control over thread lifecycle. ```python from javascript import AsyncTask, start, stop, abort from javascript.task import TaskState # Example with automatic start @AsyncTask(start=True) def routine(task: TaskState): # ... thread logic ... pass # Example without automatic start @AsyncTask(start=False) def another_routine(task: TaskState): # ... thread logic ... pass # Function signatures def start(fn: Function): pass def stop(fn: Function): pass def abort(fn: Function, killAfterSeconds: Optional[Int]): pass class TaskState: sleeping: bool def wait(self, seconds: Int): pass sleep = wait ``` -------------------------------- ### Control NodeJS Process: Terminate and Initialize (Python) Source: https://github.com/extremeheat/jspybridge/blob/master/docs/python.md Shows how to manually control the NodeJS process spawned by JSPyBridge. The `terminate()` function stops the current process, and `init()` starts a new one. This is useful for clearing memory or recovering from crashes. ```python import javascript javascript.eval_js('console.log("Hello from 1st NodeJS process!")') javascript.terminate() javascript.init() javascript.eval_js('console.log("Hello from 2nd NodeJS process!")') javascript.terminate() ``` -------------------------------- ### Access Python from JavaScript using JSPyBridge Source: https://github.com/extremeheat/jspybridge/blob/master/README.md This example shows how to import and use Python modules, specifically 'tkinter', from a Node.js environment using the 'pythonia' package. It includes creating a GUI label and running the Tkinter event loop. ```javascript import { python } from 'pythonia' // Import tkinter const tk = await python('tkinter') // All Python API access must be prefixed with await const root = await tk.Tk() // A function call with a $ suffix will treat the last argument as a kwarg dict const a = await tk.Label$(root, { text: 'Hello World' }) await a.pack() await root.mainloop() python.exit() // Make sure to exit Python in the end to allow node to exit. You can also use process.exit. ``` -------------------------------- ### Python: Managing AsyncTask Threads Source: https://github.com/extremeheat/jspybridge/blob/master/docs/python.md Provides functions to programmatically start, stop, or abort threads created with the AsyncTask decorator. `stop` sends a signal, while `abort` forcefully kills the thread after a timeout. ```python import time from javascript import AsyncTask, start, stop, abort from javascript.task import TaskState @AsyncTask(start=False) def routine(task: TaskState): while not task.stopping: # Perform task task.sleep(1) # Use task.sleep to yield and check for stopping flag # Start the thread start(routine) # Wait for a bit time.sleep(1) # Request the thread to stop stop(routine) # Forcefully kill the thread if it doesn't stop within 5 seconds # abort(routine, 5) ``` -------------------------------- ### Build a Calculator GUI with Tkinter in JavaScript Source: https://context7.com/extremeheat/jspybridge/llms.txt Presents a complete tkinter calculator GUI implemented in JavaScript, which calls Python functions for its operations. This example showcases how to create interactive graphical interfaces by bridging JavaScript and Python's tkinter library. ```javascript import { python } from 'pythonia' const tk = await python('tkinter') let expression = '' let equation async function press(num) { if (num === '=') { try { const total = eval(expression) await equation.set(total) } catch (e) { await equation.set(' error ') expression = '' } } else if (num === 'Clear') { expression = '' await equation.set('') } else { expression += num await equation.set(expression) } } const gui = await tk.Tk() await gui.configure({ background: 'light green' }) await gui.title('Simple Calculator') await gui.geometry('270x150') equation = await tk.StringVar() const inputField = await tk.Entry$(gui, { textvariable: equation }) await inputField.grid$({ columnspan: 4, ipadx: 70 }) const buttons = [1, 2, 3, null, 4, 5, 6, null, 7, 8, 9, null, 0, '+', '-', null, '*', '/', '=', 'Clear'] let row = 1, col = 0 for (const btn of buttons) { if (btn === null) { row += 2; col = 0; continue } const button = await tk.Button$(gui, { text: ` ${btn} `, fg: 'black', bg: 'red', command: () => press(btn), height: 1, width: 7 }) await button.grid({ row, column: col++ }) } await gui.mainloop$({ $timeout: Infinity }) python.exit() ``` -------------------------------- ### Python: Require JavaScript Module Source: https://github.com/extremeheat/jspybridge/blob/master/docs/python.md Imports a JavaScript module or package. Dependencies are managed automatically. If a version is not specified, it attempts to load from local/global npm registries, then installs if not found. ```python from typing import Optional, Any Void = None def require(package_name: str, package_version: Optional[str] = None) -> Void: """ Requires a JavaScript package. Args: package_name: The name of the npm package to import. Relative paths are supported. package_version: The version of the npm package to install. Ignored for relative imports. """ pass ``` -------------------------------- ### Define and Use a Python Class in JavaScript Source: https://github.com/extremeheat/jspybridge/blob/master/docs/javascript.md This example shows how to define a Python class in JavaScript by extending `PyClass`. It covers initializing the class with Python superclasses and arguments, defining methods in JavaScript that can call Python superclass methods, and accessing class variables from both sides. The `calc.py` file defines the Python base class, and `calc.js` extends it. ```python import math class Calc: def __init__(self, degrees, integers=False): self.degrees = degrees self.integers = integers def add(self, a, b): return a + b def div(self, a, b): if self.integers: return round(a / b) else: return a / b def tan(self, val): if self.degrees: # We need to round here because floating points are imprecise return round(math.tan(math.radians(val))) return math.tan(val) ``` ```javascript import { python, PyClass } from 'pythonia' const calc = await python('./calc.py') class MyCalculator extends PyClass { constructor() { // The second is an array of positional ... `true` maps to degrees. A third arg allows us to specify named arguments. // we could also do `super(calc.Calc, null, { degrees: true, integers: false })` super(calc.Calc, [true], { integers: false }) } async mul (a, b) { // Multiply the cool way let res = a for (let i = 1; i < b; i++) { res = await this.add(res, b) } return res } async div(a, b) { // Call the superclass's div() const superExample = this.parent.div(a, b) return superExample } } const calculator = await MyCalculator.init() console.log('3 * 3 = ', await calculator.mul(3, 3)) // 9 ! console.log('tan(360deg) = ', await calculator.tan(360)) // 0 ! console.log('6 / 3 = ', await calculator.div(6, 3)) // 2 ! python.exit() ``` -------------------------------- ### Import JavaScript Modules in Python using JSPyBridge Source: https://context7.com/extremeheat/jspybridge/llms.txt The `require` function in JSPyBridge allows importing JavaScript modules and npm packages. It handles automatic dependency installation for npm packages and can import local JavaScript files. `globalThis` provides access to built-in JavaScript objects. ```python from javascript import require, globalThis # Import npm packages (auto-installed if not present) chalk = require("chalk") fs = require("fs") # Import a specific version lodash = require("lodash", "^4.17.0") # Import local JavaScript files myModule = require("./myModule.js") # Use globalThis for built-in JS objects print("Hello", chalk.red("world!"), "it's", globalThis.Date().toLocaleString()) fs.writeFileSync("HelloWorld.txt", "Hello from Python!") ``` -------------------------------- ### Evaluate Python Expression in JavaScript using py Template Literal Source: https://github.com/extremeheat/jspybridge/blob/master/docs/javascript.md This snippet demonstrates how to evaluate a Python expression directly within JavaScript using the `py` template literal provided by JSPyBridge. It showcases the ability to seamlessly integrate Python operations, such as matrix addition with NumPy, into JavaScript code. Ensure the 'numpy' library is installed in your Python environment. ```javascript const np = await python('numpy') const A = await np.array(([1,2],[3,4])) const B = await np.array(([2,2],[2,2])) const r = await py`${A} + ${B} + ${np.array(([10,10],[10,10]))}` ``` -------------------------------- ### Manage Async JavaScript Operations in Python using JSPyBridge AsyncTask Source: https://context7.com/extremeheat/jspybridge/llms.txt The `AsyncTask` decorator in JSPyBridge allows running long-running JavaScript operations in background threads from Python, preventing blocking. Thread control is managed via `start()`, `stop()`, and `abort()`. The `task.sleep()` method provides non-blocking sleep within the async task. ```python import time from javascript import require, AsyncTask, start, stop, abort @AsyncTask(start=False) def pollServer(task): api = require('./api.js') while not task.stopping: result = api.fetchData() print("Got data:", result) task.sleep(5) # Sleep without blocking, auto-exits on stop # Start the background task start(pollServer) time.sleep(20) stop(pollServer) # Graceful stop request # Force kill if needed (not recommended) # abort(pollServer, killAfterSeconds=2) ``` -------------------------------- ### JavaScript to Python: py.with for Context Managers Source: https://context7.com/extremeheat/jspybridge/llms.txt Demonstrates how to manage Python 'with' statements in JavaScript using 'py.with()' from 'pythonia'. This ensures proper resource management for operations like file handling or disabling gradient calculations in PyTorch. ```javascript import { python, py } from 'pythonia' // File handling with context manager await py.with(await python('builtins').open('output.txt', 'w'), async (f) => { await f.write('Hello from JavaScript!\n') await f.write('Using Python context manager.') }) // torch.no_grad() context const torch = await python('torch') await py.with(torch.no_grad(), async () => { const tensor = await torch.randn([3, 3]) const result = await tensor.sum() console.log('Sum:', await result.item()) }) python.exit() ``` -------------------------------- ### Extend Python Classes in JavaScript with PyClass Source: https://context7.com/extremeheat/jspybridge/llms.txt Demonstrates how to create JavaScript classes that inherit from Python classes using `PyClass`. Initialization requires `await MyClass.init()` instead of the standard `new` keyword. This allows for seamless integration of Python's object-oriented features into JavaScript. ```javascript import { python, PyClass } from 'pythonia' const nn = await python('torch.nn') const F = await python('torch.nn.functional') class Net extends PyClass { constructor() { // Extend nn.Module with no positional args super(nn.Module) } async init() { // Called after Python __init__ this.conv1 = await nn.Conv2d(1, 32, 3, 1) this.conv2 = await nn.Conv2d(32, 64, 3, 1) this.fc1 = await nn.Linear(9216, 128) this.fc2 = await nn.Linear(128, 10) } async forward(x) { x = await this.conv1(x) x = await F.relu(x) x = await this.conv2(x) x = await F.relu(x) x = await F.max_pool2d(x, 2) x = await this.fc1(await x.view(-1, 9216)) x = await F.relu(x) x = await this.fc2(x) return await F.log_softmax$(x, { dim: 1 }) } } // Initialize with await .init(), not new const model = await Net.init() console.log('Model created:', await model.toString()) python.exit() ``` -------------------------------- ### Accessing Global Objects After Re-initialization (Python) Source: https://github.com/extremeheat/jspybridge/blob/master/docs/python.md Illustrates the recommended way to access global JavaScript objects like `globalThis` and `console` after re-initializing the NodeJS process with `javascript.init()`. It emphasizes using the full module import to ensure a reference to the most recent NodeJS process. ```python import javascript # instead of `from javascript import globalThis` # ... now = javascript.globalThis.Date() # instead of `now = globalThis.Date()` ``` -------------------------------- ### Configure Pythonia Environment Variables Source: https://context7.com/extremeheat/jspybridge/llms.txt Details the environment variables that can be set to customize Pythonia's behavior. This includes specifying custom paths for Node.js and Python binaries, enabling debug logging for IPC communication, and adjusting the function call timeout. ```bash # Custom binary paths export NODE_BIN=/usr/local/bin/node export PYTHON_BIN=/usr/bin/python3.10 # Debug IPC communication export DEBUG=jspybridge # Adjust function call timeout (default: 100000ms, 0 = disabled) export REQ_TIMEOUT=200000 ``` -------------------------------- ### JavaScript to Python: Keyword Arguments with $ Suffix Source: https://context7.com/extremeheat/jspybridge/llms.txt Shows how to call Python functions that accept keyword arguments from JavaScript using the '$' suffix with 'pythonia'. The last argument is treated as a kwargs dictionary, enabling flexible parameter passing. ```javascript import { python } from 'pythonia' const tk = await python('tkinter') const root = await tk.Tk() // Call with keyword arguments using $ suffix const label = await tk.Label$(root, { text: 'Hello World', fg: 'blue' }) await label.pack$({ side: 'top', padx: 10, pady: 10 }) // Grid with keyword arguments const button = await tk.Button$(root, { text: 'Click Me', command: () => console.log('Clicked!') }) await button.grid$({ row: 0, column: 0, sticky: 'nsew' }) // Mainloop with timeout await root.mainloop$({ $timeout: Infinity }) python.exit() ``` -------------------------------- ### Iterate Python Generator in JavaScript Source: https://github.com/extremeheat/jspybridge/blob/master/README.md Shows how to iterate over a Python generator function using a `for await` loop in JavaScript. This requires a Python file defining a generator function and the JavaScript code to consume it. ```python import os def get_files(): for f in os.listdir(): yield f ``` ```js const iter = await python('./iter.py') const files = await iter.get_files() for await (const file of files) { console.log(file) } ``` -------------------------------- ### Import Python Modules in JavaScript Source: https://context7.com/extremeheat/jspybridge/llms.txt Demonstrates how to import and use Python modules within a JavaScript environment using the 'pythonia' library. All Python API calls must be awaited. Use 'python.exit()' to terminate the Python process. ```javascript import { python } from 'pythonia' // Import Python standard library const os = await python('os') const datetime = await python('datetime') // Import local Python files const myModule = await python('./myModule.py') // All calls are async const cwd = await os.getcwd() console.log("Current dir:", cwd) const now = await datetime.datetime.now() console.log("Time:", await now.isoformat()) // Always exit when done python.exit() ``` -------------------------------- ### Import JavaScript Module in Python Source: https://github.com/extremeheat/jspybridge/blob/master/README.md Shows how to import JavaScript modules and call their functions from Python using JSPyBridge. Handles dependency management and versioning. ```python from javascript import require # Basic import time = require('./time.js') print(time.whatTimeIsIt()) # Event emitter example from javascript import require, On, off MyEmitter = require('./emitter.js') myEmitter = MyEmitter() @On(myEmitter, 'increment') def handleIncrement(this, counter): print("Incremented", counter) off(myEmitter, 'increment', handleIncrement) myEmitter.inc() # ES5 class example MyClass = require('./es5.js').MyClass myClass = MyClass.new(3) print(myClass.getNum()) # Iteration example items = require('./items.js') for item in items: print(item) # Callback example method = require('./callback').method method(lambda v: print(v), 2) # Prints 44 ``` -------------------------------- ### JavaScript to Python: py.enumerate for Iteration with Index Source: https://context7.com/extremeheat/jspybridge/llms.txt Explains how to use 'py.enumerate()' with 'for await' loops in JavaScript to iterate over Python iterables while accessing both the index and the item. Also shows standard iteration without an index. ```javascript import { python, py } from 'pythonia' const os = await python('os') const files = await os.listdir('.') // Enumerate with index for await (const [index, filename] of await py.enumerate(files)) { console.log(`${index}: ${filename}`) } // Standard iteration (without index) for await (const file of files) { console.log(file) } python.exit() ``` -------------------------------- ### Import and Call Python Function from JavaScript Source: https://github.com/extremeheat/jspybridge/blob/master/README.md Demonstrates how to import a Python module and call a function from JavaScript using jspybridge. It requires a Python file with a function and imports the 'python' object from 'pythonia'. ```python import datetime def what_time_is_it(): return str(datetime.datetime.now()) ``` ```js import { python } from 'pythonia' const time = await python('./time.py') console.log("It's", await time.what_time_is_it()) python.exit() ``` -------------------------------- ### Inline JavaScript Evaluation (Swift) Source: https://github.com/extremeheat/jspybridge/blob/master/docs/python.md Demonstrates inline JavaScript expression evaluation using `eval_js`. This is a concise way to evaluate simple JS expressions that return a value. ```swift x_or_z = eval_js(''' obj.x ?? obj.z ''') ``` -------------------------------- ### Instantiate JavaScript Classes (ES5/ES6) in Python using JSPyBridge Source: https://context7.com/extremeheat/jspybridge/llms.txt JSPyBridge allows instantiation of both ES5 and ES6 JavaScript classes from Python. ES5 classes (function constructors) require the `.new` pseudo-method for instantiation, while ES6 classes can be constructed directly. This enables seamless object creation across the language boundary. ```python from javascript import require # ES5 class (function constructor) # es5.js: function MyClass(num) { this.getNum = () => num } MyClass = require('./es5.js').MyClass instance = MyClass.new(42) # Use .new for ES5 classes print(instance.getNum()) # Output: 42 # ES6 class - construct directly # es6.js: class Calculator { constructor(x) { this.x = x } } Calculator = require('./es6.js').Calculator calc = Calculator(10) # No .new needed for ES6 print(calc.x) # Output: 10 ``` -------------------------------- ### Access JavaScript from Python using JSPyBridge Source: https://github.com/extremeheat/jspybridge/blob/master/README.md This snippet demonstrates how to use the 'javascript' package to access Node.js modules like 'chalk' and 'fs' from within a Python script. It shows basic string manipulation and file writing operations. ```python from javascript import require, globalThis chalk, fs = require("chalk"), require("fs") print("Hello", chalk.red("world!"), "it's", globalThis.Date().toLocaleString()) fs.writeFileSync("HelloWorld.txt", "hi!") ``` -------------------------------- ### Data Transfer between Python and JavaScript Source: https://context7.com/extremeheat/jspybridge/llms.txt Explains how to transfer data between Python and JavaScript using `.valueOf()` for JSON-serializable objects and `.blobValueOf()` for binary data. `.valueOf()` is suitable for general data, while `.blobValueOf()` offers efficient transfer of large binary data like image buffers. ```javascript import { python } from 'pythonia' const np = await python('numpy') // valueOf() - JSON serialization (works for any serializable object) const array = await np.array([1, 2, 3, 4, 5]) const jsArray = await array.valueOf() console.log('JS Array:', jsArray) // [1, 2, 3, 4, 5] // blobValueOf() - Direct binary transfer (faster for large data) const pdfjs = await python('javascript').require('pdfjs-dist') const canvas = await python('javascript').require('canvas') // Render and transfer image buffer efficiently const canvasObj = await canvas.createCanvas(800, 600) const ctx = await canvasObj.getContext('2d') // ... render operations ... const buffer = await canvasObj.toBuffer('raw') const pyBuffer = await buffer.blobValueOf() // Fast binary transfer python.exit() ``` -------------------------------- ### Python: Clean npm Cache Source: https://github.com/extremeheat/jspybridge/blob/master/docs/python.md Clears the internal node_modules folder cache. This can resolve dependency issues. ```python python3 -m javascript --clean ``` -------------------------------- ### Python: Decorators for EventEmitter Source: https://github.com/extremeheat/jspybridge/blob/master/docs/python.md Wraps JavaScript EventEmitters for Python integration using decorators. `@On` and `@Once` are used to bind event handlers. `off` is used to unbind handlers. ```python from javascript import require, On, Once, off, once # Assume MyEmitter is a JavaScript class requiring './emitter.js' MyEmitter = require('./emitter.js') myEmitter = MyEmitter() @On(myEmitter, 'increment') def handleIncrement(this, counter): print(f"Incremented {counter}") # Stop listening to the event off(myEmitter, 'increment', handleIncrement) # Trigger the event myEmitter.inc() # Example using the top-level 'once' function # Note: This assumes a JS 'emitter' library with a default export # JS_Emitter = require('emitter') # Example if 'emitter' is an npm package # js_emitter_instance = JS_Emitter() # @Once(js_emitter_instance, 'data') # def handle_data(data): # print(f"Received data: {data}") ``` -------------------------------- ### Handle JavaScript Events in Python with JSPyBridge Decorators Source: https://context7.com/extremeheat/jspybridge/llms.txt JSPyBridge provides decorators (`@On`, `@Once`) for Python to subscribe to JavaScript EventEmitter events. `@On` creates persistent listeners, `@Once` handles events a single time, and `off()` can be used to remove listeners. These decorators offer a Python-native syntax for event handling. ```python from javascript import require, On, Once, off # Assuming emitter.js exports a class extending EventEmitter MyEmitter = require('./emitter.js') myEmitter = MyEmitter() @On(myEmitter, 'increment') def handleIncrement(this, counter): print("Incremented to:", counter) # Stop listening after handling off(myEmitter, 'increment', handleIncrement) @Once(myEmitter, 'ready') def handleReady(this): print("Emitter is ready (fires only once)") # Trigger events myEmitter.inc() ``` -------------------------------- ### Python: Update npm Package Source: https://github.com/extremeheat/jspybridge/blob/master/docs/python.md Updates an existing npm package in the internal node_modules folder. This command is passed directly to `npm update`. ```python python3 -m javascript --update ``` -------------------------------- ### Evaluate JavaScript Expressions in Python (Julia) Source: https://github.com/extremeheat/jspybridge/blob/master/docs/python.md Evaluates JavaScript code within the Python context using the `eval_js` function. It allows access to Python variables and requires `await` for JS function calls or property accesses on Python objects. Variables can be set without `await`. ```julia import javascript countUntil = 9 myArray = [1] myObject = { 'hello': '' } # Make sure you await everywhere you expect a JS call ! output = javascript.eval_js(''' myObject['world'] = 'hello' for (let x = 0; x < countUntil; x++) { await myArray.append(2) } return 'it worked' ''') # If we look at myArray and myObject, we should see it updated print(output, myArray, myObject) ``` -------------------------------- ### JavaScript to Python: py Template Function for Inline Evaluation Source: https://context7.com/extremeheat/jspybridge/llms.txt Utilizes the 'py' template function from 'pythonia' to evaluate Python expressions directly within JavaScript, including seamless variable interpolation. This is useful for operations like operator overloading that require Python-side execution. ```javascript import { python, py } from 'pythonia' const np = await python('numpy') // Create numpy arrays const A = await np.array([[1, 2], [3, 4]]) const B = await np.array([[2, 2], [2, 2]]) // Use py template for Python operators (matrix addition) const result = await py`${A} + ${B} + ${np.array([[10, 10], [10, 10]])}` console.log(await result.tolist()) // Output: [[13, 14], [15, 16]] // Create Python tuples and sets const myTuple = await py.tuple(1, 2, 3) const mySet = await py.set('a', 'b', 'c') ``` -------------------------------- ### Evaluate JavaScript Expressions from Python with JSPyBridge Source: https://context7.com/extremeheat/jspybridge/llms.txt JSPyBridge's `eval_js` function enables the execution of JavaScript code directly from Python. It allows Python variables to be accessed within the JavaScript scope, and `await` can be used for operations involving Python objects. This facilitates dynamic code execution and interaction. ```python import javascript countUntil = 9 myArray = [1] myObject = {'hello': ''} # Evaluate JS with Python variables output = javascript.eval_js(''' myObject['world'] = 'hello' for (let x = 0; x < countUntil; x++) { await myArray.append(2) } return 'it worked' ''') print(output, myArray, myObject) # Output: it worked [1, 2, 2, 2, 2, 2, 2, 2, 2, 2] {'hello': '', 'world': 'hello'} # Inline evaluation obj = {'x': None, 'z': 42} x_or_z = javascript.eval_js('obj.x ?? obj.z') # Returns 42 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.