### Starting the Python Bridge Application in Smalltalk Source: https://book.gtoolkit.com/getting-started-with-the-python-bridge-4bh6zrt8nhuwf3p2x3vvbw5ke This Smalltalk command initiates the Python Bridge. The first time it's executed, it may take a significant amount of time (tens of seconds) as it performs necessary installations and setup processes. ```Smalltalk PBApplication start ``` -------------------------------- ### Install and Start GemStone Server Source: https://book.gtoolkit.com/loading-gt-server-code-into-a-non-rowan-st-cvdib7y69u7ow8uo6x5zvu5ah Provides commands to unpack, install, and initialize the GemStone server. This includes setting necessary permissions for network components and starting the netldi and stone processes. ```bash cd $GEMSTONE/.. unzip GemStone64Bit3.7.0-x86_64.Linux.zip cd GemStone64Bit3.7.0-x86_64.Linux/install ./installgs sudo chmod ug+s $GEMSTONE/sys/netldid sudo chown root $GEMSTONE/sys/netldid cd - startnetldi startstone ``` -------------------------------- ### Configure and Start PharoLink Client Application Source: https://book.gtoolkit.com/pharolink--start-manual-server-and-client-4lsasvmsw9es7f227ws9vybqa Configures a PharoLink client application to connect to a local server at `localhost:7001`, using a manual process class. The application is then started in a forked process, which is useful for debugging the startup sequence without blocking the UI. ```Smalltalk settings := LanguageLinkSettings pharoDefaultSettings. settings serverProcessClass: LanguageLinkManualProcess; serverSocketAddress: (LanguageLinkSocketAddress from: 'localhost:7001'). app := PharoLinkApplication newWith: settings."To facilitate debugging while starting, fork the start process."[ app start ] fork. ``` -------------------------------- ### Start PharoLink Server in-image Source: https://book.gtoolkit.com/pharolink--start-manual-server-and-client-4lsasvmsw9es7f227ws9vybqa Initializes and starts a PharoLink server instance within the Pharo image, configuring it to listen on port 7001. This sets up the backend for inter-process communication. ```Smalltalk PharoLinkServer new listenPort: 7001; start ``` -------------------------------- ### Pharo: Instantiating a GtImage Source: https://book.gtoolkit.com/a-single-starting-point-for-scripting--lin-2sslgxkw1agkq7liw4heoqycp This snippet demonstrates a basic Pharo code example for creating an instance of the `GtImage` class. It illustrates how Lepiter integrates Pharo code directly into its notebooks, allowing for live execution and interaction. ```Pharo GtImage instance ``` -------------------------------- ### Demonstrating Logging Method Wrapper Source: https://book.gtoolkit.com/method-wrappers-4ubz1k70ucugtd4iaw6gnx1uz A comprehensive example showing the lifecycle of a `LoggingMethodWrapper`. It covers creating the wrapper, running the original method, installing the wrapper, running the method with logging, uninstalling, and verifying invocation counts. ```Smalltalk "Create the logging method wrapper."logger := LoggingMethodWrapper on: Integer >> #slowFactorial."We run the method without the wrapper."logger invocationCount.4 slowFactorial.self assert: logger invocationCount equals: 0."We install the wrapper to log the invocations and uninstall it when we are done."logger install.[ 5 slowFactorial ] ensure: [ logger uninstall ].self assert: logger invocationCount equals: 6."Again without the wrapper."logger invocationCount: 0.10 slowFactorial.logger invocationCount.self assert: logger invocationCount equals: 0.logger. ``` -------------------------------- ### Example Subclass of GtHomeMultiCardSection Source: https://book.gtoolkit.com/how-to-set-up-a-home-section-7gj04bclw6nw29h8299pylw4t This Smalltalk snippet demonstrates how to create a concrete subclass, `GtHomeMultiCardGetStartedSection`, from `GtHomeMultiCardSection`. This pattern is used to define specific home sections, such as a 'Get Started' section, without adding new instance variables. ```Smalltalk GtHomeMultiCardSection subclass: #GtHomeMultiCardGetStartedSection instanceVariableNames: '' classVariableNames: '' package: 'GToolkit-World-Sections' ``` -------------------------------- ### Verify Python Bridge Application Instance (Smalltalk) Source: https://book.gtoolkit.com/python-debugger-setup---example-6h3icwf26fev4i7s74u6jghm8 Retrieves the unique instance of the Python Bridge application in Smalltalk. This command is used to confirm that the application has successfully started and is accessible. ```Smalltalk PBApplication uniqueInstance ``` -------------------------------- ### Initialize gToolkit Examples Explorer Source: https://book.gtoolkit.com/how-to-browse-examples-3yg0hfqe84nbqtmmzt7eykt5l This snippet initializes an explorer object in gToolkit, providing a convenient interface to browse and interact with various examples available in the current image. ```Smalltalk GtRlGToolkitExamplesExplorer buildForGToolkitProject ``` -------------------------------- ### Smalltalk Example Method: chooseMatchingPair Source: https://book.gtoolkit.com/moldable-object-9jkob03k21sbjujct0kh60016 This Smalltalk example method, chooseMatchingPair, demonstrates a specific scenario for GtMemoryGame. Marked with , it sets up a game, performs card selections, asserts game state, and returns the game instance. Example methods are a way to get a live, pre-configured instance for inspection. ```Smalltalk chooseMatchingPair | game | game := self fixedGame. game chooseCard: (game availableCards at: 6). game chooseCard: (game availableCards at: 11). self assert: game visibleCards size equals: 14. self assert: game isOver not. ^ game ``` -------------------------------- ### Smalltalk: Prototyping a Basic UI Element Source: https://book.gtoolkit.com/a-single-starting-point-for-scripting--lin-2sslgxkw1agkq7liw4heoqycp This simple Smalltalk code creates a new `BlElement` (Block element) and sets its background color to red. It serves as an example of how Lepiter can be used for rapid prototyping of user interface components, demonstrating immediate visual feedback. ```Smalltalk BlElement new background: Color red ``` -------------------------------- ### Smalltalk Example: Inspecting BrToggleExamples Group Source: https://book.gtoolkit.com/example-driven-development-by-example-wmr9ggp9fan2j19g4z4crz0m Illustrates how to inspect another set of examples, `BrToggleExamples`, from the Bloc framework. This demonstrates the flexibility of the example system for different contexts and how various example groups can be analyzed. ```Smalltalk GtExampleGroup withAll: BrToggleExamples gtExamples ``` -------------------------------- ### Example of a generated `start` method in PetitParser class Source: https://book.gtoolkit.com/parsing-with-petitparser2-bovgk7k60j179f0wcw8cfw3be This Pharo Smalltalk snippet shows the typical implementation of the `start` method, which is automatically generated in an extracted PetitParser class. This method acts as the entry point for the parser, returning the final production of the grammar (e.g., `expression`). ```Smalltalk start ^ expression ``` -------------------------------- ### Install and Initialize GemStone Server on Linux Source: https://book.gtoolkit.com/loading-gt-server-code-into-a-rowan-stone-gmpnoytigqv2tzrnz78szvi2 This bash script provides a sequence of commands to install and prepare a GemStone server instance. It covers unzipping the distribution, running the installation script, adjusting file permissions for `netldid`, cleaning and copying a base extent file, and finally starting the GemStone network daemon and the stone itself. ```bash cd $GEMSTONE/.. unzip GemStone64Bit3.7.0-x86_64.Linux.zip cd GemStone64Bit3.7.0-x86_64.Linux/install sudo ./installgs sudo chmod ug+s $GEMSTONE/sys/netldid sudo chown root $GEMSTONE/sys/netldid cd ../data rm *.dbf *.log cp /path/to/extent0.rowan.dbf ./extent0.dbf chmod 644 extent0.dbf cd - startnetldi startstone ``` -------------------------------- ### Verify Pure Git CLI Platform Status Source: https://book.gtoolkit.com/how-to-use-the-pure-git-tool-b7orhscgmczdqyatb6u3wgae This Pharo example checks and returns the current instance of `IceGitCliPlatform`, ensuring the Pure Git CLI setup is correctly initialized and available for use within the environment. ```Pharo currentIceGitCliPlatform ^ IceGitCliPlatform current ``` -------------------------------- ### Smalltalk: Fetching and Parsing GitHub API Data Source: https://book.gtoolkit.com/a-single-starting-point-for-scripting--lin-2sslgxkw1agkq7liw4heoqycp This code shows how to make an HTTP GET request to the GitHub API using the `ZnClient` library in Smalltalk. It then parses the received JSON response into a Smalltalk dictionary using `STON fromString:`. This snippet exemplifies starting an exploration of external APIs directly within the Lepiter environment. ```Smalltalk json := ZnClient new get: 'https://api.github.com/orgs/feenkcom'. dictionary := STON fromString: json. ``` -------------------------------- ### Create File on Disk using GtExample in Smalltalk Source: https://book.gtoolkit.com/example-driven-development-by-example-wmr9ggp9fan2j19g4z4crz0m This GtExample method illustrates how to create a file directly on the disk, using `FileSystem workingDirectory`. It writes predefined file contents to the specified path. This example highlights the potential for side effects when examples interact with the file system, necessitating cleanup mechanisms. ```Smalltalk "protocol: #examples"GtExamplesTutorial >> createFileOnDisk ^ self directoryOnDisk / self fileName writeStreamDo: [ :stream | stream nextPutAll: self fileContents ]; yourself"protocol: #examples"GtExamplesTutorial >> directoryOnDisk ^ FileSystem workingDirectory ``` -------------------------------- ### Locate tfactorial.py Source File (Smalltalk) Source: https://book.gtoolkit.com/python-debugger-setup---example-6h3icwf26fev4i7s74u6jghm8 Provides the Smalltalk code snippet to programmatically locate the `tfactorial.py` source file within the GToolkit resource structure. This is helpful for inspecting the implementation of the external factorial example. ```Smalltalk GtResourcesUtility default resourceAtPath: Path * 'feenkcom'/ 'PythonBridge' / 'PyPI' / 'src' / 'gtoolkit_bridge' / 'PythonBridge' / 'tfactorial.py' ``` -------------------------------- ### Smalltalk Example: Inspecting GtExampleGroup Dependencies Source: https://book.gtoolkit.com/example-driven-development-by-example-wmr9ggp9fan2j19g4z4crz0m Shows how to inspect the dependencies and structure of examples within a GtExampleGroup by querying all examples from `GtExamplesTutorial`. This helps visualize how examples relate to each other and understand their execution flow. ```Smalltalk GtExampleGroup withAll: GtExamplesTutorial gtExamples ``` -------------------------------- ### Collect All Glamorous Toolkit Examples Source: https://book.gtoolkit.com/creating-a-dataset-for-fine-tuning-5mxkpdy0fqi3yjgzqp34wclhu This Smalltalk code collects all currently defined examples within Glamorous Toolkit and converts them into a group of cached examples with their results. This forms the initial dataset for fine-tuning. ```Smalltalk aCollection := Smalltalk gtExamplesContained collect: [ :eachExample | eachExample asCachedExampleWithResult ].aGroup := GtExampleGroup withAll: aCollection ``` -------------------------------- ### Manage SSH Agent Service on Windows Source: https://book.gtoolkit.com/using-libgit-cli-as-an-alternative-to-libg-7mfe0ftw0eakhrjuf13m3hdd6 PowerShell commands to set the ssh-agent service startup type to manual and start the service, often required for initial setup on Windows. ```PowerShell Get-Service -Name ssh-agent | Set-Service -StartupType Manual Start-Service ssh-agent ``` -------------------------------- ### Verify Python and Pipenv Command Line Tools Source: https://book.gtoolkit.com/getting-started-with-the-python-bridge-4bh6zrt8nhuwf3p2x3vvbw5ke These shell commands are used to confirm that Python and Pipenv are correctly installed and accessible from the command line, displaying their respective version numbers. ```Bash $ python3 --version Python 3.11.7 ``` ```Bash $ pipenv --version pipenv, version 2023.11.15 ``` -------------------------------- ### Example Smalltalk Startup Script for GToolkit Source: https://book.gtoolkit.com/how-to-use-a-startup-script-95rw0drel0wsiu3gb4nce9sy8 This script demonstrates how to configure a GToolkit instance on startup. It includes examples for showing explicit references in a compact form, scaling the UI, and conditionally loading a Metacello baseline repository if it's not already present. This `startup.st` file should be placed in the same directory as your GT image. ```Smalltalk "This is a sample startup script. It will be run whenever you start up a GT image. Put whatever you like in here." "Show explicit references in compact form." LePageToolContentTreeElement showIncomingReferencesInlined. "Scale up the UI." BlSpace userScale: 1.2. "Load my startup repo, if it's not already loaded." Smalltalk globals at: #BaselineClassName ifAbsent: [ Metacello new repository: ''. Smalltalk saveSession ]. ``` -------------------------------- ### Example for Implementing Price Addition (Smalltalk) Source: https://book.gtoolkit.com/modeling-a-concrete-price-4zfv1b6ujzwv1ukvjxkb2yep5 This snippet provides a starting point for developing addition functionality for Price objects. It illustrates a simple addition operation between two Price instances, guiding the implementation of the + method. ```Smalltalk 100 euros asPrice + 15 euros asPrice. ``` -------------------------------- ### Instantiate Gemini API Client from Clipboard Source: https://book.gtoolkit.com/working-with-the-gemini-api-client-6rkv2am15mvctqf9bmpanfvmg This snippet provides an alternative method for initializing the Gemini API client. It illustrates how to load the API key directly from the system clipboard, useful for quick setup without a file. ```Smalltalk client := GtGeminiClient withApiKeyFromClipboard ``` -------------------------------- ### Initialize and Start a Game Instance Source: https://book.gtoolkit.com/playing-the-memory-game-53lj10f3wdz11q2uyhiqfcjkv Demonstrates how to initialize a new game instance with numbers and create a `GameElement` to display it, making the game playable. ```Smalltalk | aGame | aGame := Game numbers. GameElement new game: aGame ``` -------------------------------- ### Get Current Working Directory (JavaScript) Source: https://book.gtoolkit.com/javascript-debugger-setup---example-9y7jowdtdfxenw1klw6t4n39s This JavaScript code retrieves and displays the current working directory of the Node.js process. It uses `process.cwd()` to obtain the path, which is useful for verifying the execution context of JavaScript scripts. ```JavaScript var cwd = process.cwd(); cwd; ``` -------------------------------- ### Execute Remote Command via PharoLink Source: https://book.gtoolkit.com/pharolink--start-manual-server-and-client-4lsasvmsw9es7f227ws9vybqa Demonstrates sending a command from the client application to the connected PharoLink server to retrieve its process ID. This illustrates a basic example of remote evaluation and command execution across the link. ```Smalltalk serverPid := app newCommandFactory << 'GtOsSystemInfo current currentProcessId'; sendAndWait. ``` -------------------------------- ### Directly Execute GToolkit Examples via Handler Source: https://book.gtoolkit.com/how-to-debug-the-examples-command-line-run-n3u261phzkdmva6yh47tv1kl Provides a more granular approach to running examples by directly instantiating the GtExamplesCommandLineHandler. This allows bypassing some of the default activation logic to explicitly set command-line arguments, identify packages, and run examples, offering greater control for debugging. ```Smalltalk handler := GtExamplesCommandLineHandler new commandLine: commandLine.packages := handler sortedPackageNamesToRun.examplesReportResult := handler basicRunExamplesInPackages: packages ``` -------------------------------- ### Instantiate OpenAI Client from API Key File (Smalltalk) Source: https://book.gtoolkit.com/working-with-the-openai-api-client-5lw2wjefqnw6qokwfgjghsecb Demonstrates how to create an instance of the GtOpenAIClient by loading the API key from a file. This is the default and recommended method for client initialization. ```Smalltalk client := GtOpenAIClient withApiKeyFromFile ``` -------------------------------- ### Smalltalk: Invoking an Extracted Example Method Source: https://book.gtoolkit.com/modeling-a-concrete-price-4zfv1b6ujzwv1ukvjxkb2yep5 This snippet demonstrates how to invoke an example method, 'hundredEuros', from the 'PriceExamples' class. This is the final form of the snippet after applying the 'Extract example' refactoring, showcasing how to run predefined examples. ```Smalltalk PriceExamples new hundredEuros. ``` -------------------------------- ### Run Hello World SPL Program Demo Source: https://book.gtoolkit.com/spl-facade-oevv51bh05vtux6sygbde0i5 A simple demonstration of running a 'hello world' type program using `SPL hello`. This showcases a common introductory program within the SPL context. ```Smalltalk SPL hello. ``` -------------------------------- ### Retrieve Python Kernel Installation Log Source: https://book.gtoolkit.com/working-with-python-source-files-1f5nlu7ul60puw4d8lvtsrkij Fetches the installation log for the Python kernel, which can be useful for debugging setup issues or understanding the installation process. ```Smalltalk PBApplication uniqueInstance processHandler process installLog ``` -------------------------------- ### Smalltalk Example Method for Text Editor Selection Source: https://book.gtoolkit.com/example-89mq4s0mtsnhcc85fx3pjmw6d This Smalltalk code snippet demonstrates an example method (``) within Glamorous Toolkit. It simulates user interaction with a text editor, moving the cursor and selecting text, then asserts the correctness of the selection and the selected content. This method serves as a test case for editor functionality. ```Smalltalk select_moveOneRight_at_6 | anEditor | anEditor := self editorOnMultilineText. anEditor editor moveCursorTo: 6. anEditor selecter moveOneToRight; select. self assert: anEditor selection equals: (BlCompositeSelection new select: 6 to: 7). self assert: anEditor editor selectedText asString equals: 'e'. self assert: anEditor cursors equals: (BrTextEditorCursor atAll: #(7)). ^ anEditor ``` -------------------------------- ### Start PBApplication Instance (Smalltalk) Source: https://book.gtoolkit.com/running-the-pythonbridge-in-another-direct-1omx4omgaapqeyrlfumam1vfi This Smalltalk command starts the configured `PBApplication` instance. Upon starting, a new PythonBridge installation will be performed in the specified custom working directory. ```Smalltalk pbApplication start ``` -------------------------------- ### Instantiate Gemini API Client from File Source: https://book.gtoolkit.com/working-with-the-gemini-api-client-6rkv2am15mvctqf9bmpanfvmg This snippet demonstrates the default method for initializing the Gemini API client. It shows how to load the API key from a local file, establishing the connection to the Gemini API. ```Smalltalk client := GtGeminiClient withApiKeyFromFile ``` -------------------------------- ### Calculate net words from embedded examples Source: https://book.gtoolkit.com/how-to-measure-the-size-of-the-current-kno-agukn9aiomo47o0nzkk5gnese This Smalltalk code calculates the number of words in the definition of the example snippets themselves (excluding the actual example method source code). It then subtracts this from the total words found in example methods to get the net word count contributed by the embedded example source code. ```Smalltalk examplesDefinitionWords := allExampleSnippets sumNumbers: [ :each | (each contentAsString piecesCutWhere: [ :a :b | a isSeparator ]) size ].examplesTotalWords := examplesWords - examplesDefinitionWords. ``` -------------------------------- ### Smalltalk: Player A Lands on First Unoccupied Goal Square Source: https://book.gtoolkit.com/testing-the-ludo-corner-cases-7fp6z0jub1kmadpjhfy3riv9b This example demonstrates player A's token 'a' landing precisely on the first goal square. It starts from the 'arrives close to goal' setup, then simulates a roll of 3, moving the token from position 38 to the goal state. It asserts that the token is now in the goal state. ```Smalltalk playerAlandsOnFirstGoalSquare "Example for 6. Landing on the first goal square, unoccupied." | game | game := self playerAarrivesCloseToGoal. self assert: game currentPlayer name equals: 'A'. self assert: (game positionOfTokenNamed: 'a') equals: 38. game roll: 3. game moveTokenNamed: 'a'. self assert: (game tokenNamed: 'a') isInGoalState. ^ game ``` -------------------------------- ### Initiate OpenAI Fine-Tuning Job Source: https://book.gtoolkit.com/creating-a-dataset-for-fine-tuning-5mxkpdy0fqi3yjgzqp34wclhu This Smalltalk code initializes an OpenAI client, uploads the prepared fine-tuning file to OpenAI, and then creates a fine-tuning job using the uploaded file and the specified model. This starts the actual fine-tuning process. ```Smalltalk client := GtOpenAIClient withApiKeyFromFile.openAiFile := client uploadFile: file withPurpose: 'fine-tune'.fineTuningJob := client createFineTuningJobOnModel: file model withFile: openAiFile id ``` -------------------------------- ### Smalltalk: Player A Lands on Second Unoccupied Goal Square Source: https://book.gtoolkit.com/testing-the-ludo-corner-cases-7fp6z0jub1kmadpjhfy3riv9b This example shows player A's token 'a' landing on the second unoccupied goal square. Starting from the 'arrives close to goal' setup, it simulates a roll of 4, moving the token from position 38 to the goal state. It verifies the token's final state. ```Smalltalk playerAlandsOnSecondGoalSquare "Example for 7. Landing on the unoccupied second goal square." | game | game := self playerAarrivesCloseToGoal. self assert: game currentPlayer name equals: 'A'. self assert: (game positionOfTokenNamed: 'a') equals: 38. game roll: 4. game moveTokenNamed: 'a'. self assert: (game tokenNamed: 'a') isInGoalState. ^ game ``` -------------------------------- ### Debug External Python Factorial Example (Python) Source: https://book.gtoolkit.com/python-debugger-setup---example-6h3icwf26fev4i7s74u6jghm8 Demonstrates debugging an external Python file (`tfactorial.py`) by importing it, resetting signals, and calling a function with a breakpoint. This example showcases how to debug code that relies on separate modules. ```Python import gtoolkit_bridge gtoolkit_bridge.reset_signals() import gtoolkit_bridge.PythonBridge.tfactorial as tfactorial pbbreak() tfactorial.factorial(5,1) ``` -------------------------------- ### GToolkit Smalltalk Example: Create 42 Euros Money Object Source: https://book.gtoolkit.com/warmup--understanding-the-money-classes-3zfbohxxqjqy3v6oiyg77dub8 Demonstrates an example method in GToolkit using the `` pragma. It creates a `GtTCurrencyMoney` object representing 42 euros and includes assertions for testing. Example methods also serve as tests and can be inspected. ```Smalltalk fortyTwoEuros | money | money := 42 euros. self assert: money isZero not. self assert: money equals: 42 euros. ^ money ``` -------------------------------- ### Define GtExamplesTutorial Class and createFileInMemory Method Source: https://book.gtoolkit.com/example-driven-development-by-example-wmr9ggp9fan2j19g4z4crz0m Defines the `GtExamplesTutorial` class and adds a `createFileInMemory` instance method. This method creates a file named 'sample.txt' in the in-memory file system with 'Sample contents' and is marked as a GtExample using the `` pragma. ```Smalltalk Object subclass: #GtExamplesTutorial instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'GToolkitExamplesTutorial'.GtExamplesTutorial class instanceVariableNames: ''"protocol: #examples"GtExamplesTutorial >> createFileInMemory ^ FileSystem memory workingDirectory / 'sample.txt' writeStreamDo: [ :stream | stream nextPutAll: 'Sample contents' ]; yourself ``` -------------------------------- ### Python Debugger Setup and Example in GT Source: https://book.gtoolkit.com/setting-different-behavior-for-cursor-word-92fulbdphhonsxzxyxig75thp Instructions and example code for configuring and using the Python debugger within Glamorous Toolkit, facilitating interactive debugging of Python code. ```Python import pdb def my_function(): a = 1 b = 2 pdb.set_trace() # Python debugger breakpoint c = a + b return c my_function() ``` -------------------------------- ### JavaScript Debugger Setup and Example in GT Source: https://book.gtoolkit.com/setting-different-behavior-for-cursor-word-92fulbdphhonsxzxyxig75thp Instructions and example code for configuring and using the JavaScript debugger within Glamorous Toolkit, facilitating interactive debugging of JS code. ```JavaScript // Setup for JavaScript debugger in GT // This is a conceptual example, actual setup might involve specific GT APIs. function debugMe() { let x = 10; let y = 20; debugger; // This keyword triggers a debugger breakpoint let sum = x + y; return sum; } debugMe(); ``` -------------------------------- ### Smalltalk: Running 'PriceExamples' Methods Source: https://book.gtoolkit.com/modeling-discounted-prices-4zfv1bcyj6if9010meqvdsfmq Shows how to invoke an example method, specifically 'discountedPriceByAmount', from the 'PriceExamples' class. This snippet is used both after example extraction and to verify functionality post-refactoring. ```Smalltalk PriceExamples new discountedPriceByAmount. ``` -------------------------------- ### Execute GtExamplesTutorial createFileInMemory Method Directly Source: https://book.gtoolkit.com/example-driven-development-by-example-wmr9ggp9fan2j19g4z4crz0m Demonstrates how to execute the `createFileInMemory` method directly on a new instance of `GtExamplesTutorial` to obtain its returned object. ```Smalltalk GtExamplesTutorial new createFileInMemory ``` -------------------------------- ### Smalltalk: Simulate player A rolling a 6 in Ludo Source: https://book.gtoolkit.com/example-object-dyquv1b6xptl2c0ayhgb376bw This Smalltalk example, `playerArolls6`, demonstrates composition by starting from the `emptyGame` example. It simulates player A rolling a 6, then asserts the updated game state, including the current player and tokens available for movement. It returns the modified game instance. ```Smalltalk GtLudoGameExamples>>#playerArolls6 | game | game := self emptyGame. game roll: 6. self assert: game currentPlayer name equals: 'A'. self assert: game playerToRoll not. self assert: game playerToMove. self assert: (game tokensToMove collect: #name) asSet equals: {'A'. 'a'} asSet. ^ game ``` -------------------------------- ### PetitParser2 Parsing Examples Source: https://book.gtoolkit.com/parsing-with-petitparser2-bovgk7k60j179f0wcw8cfw3be Examples demonstrating how to use the defined parsers to process various input strings. ```Smalltalk identifier parse: 'howdy' ``` ```Smalltalk number parse: '42'. ``` ```Smalltalk start parse: '1 + 2 * 3'. ``` ```Smalltalk start parse: '(1 + 2) * 3'. ``` -------------------------------- ### PharoLink Get Image Directory Example Source: https://book.gtoolkit.com/pharolink-snippet-66e1y89n1t9njhkc1d8c9g9ng An example showing how to retrieve the full path of the current Pharo image directory using `FileLocator`. This is useful for understanding the environment of the remote Pharo image. ```Pharo FileLocator imageDirectory fullName ``` -------------------------------- ### Execute GToolkit Smalltalk Example Method Source: https://book.gtoolkit.com/introducing-test-examples-and-code-cleanin-4wxxpyxj2ow5qoyg5ntecmlmh This snippet demonstrates how to run a defined example method in GToolkit Smalltalk. By sending the `defaultExample` message to a new `Jumble` instance, the example method's assertions are executed and its result is produced. ```Smalltalk Jumble new defaultExample ``` -------------------------------- ### Instantiate Anthropic Client with API Key from File Source: https://book.gtoolkit.com/working-with-the-anthropic-api-client-1ncbmunmfwhpw1wry1mj91cm7 Demonstrates how to create an instance of the `GtAnthropicClient` by loading the API key from a file. This is the default and recommended method for client initialization. ```Smalltalk client := GtAnthropicClient withApiKeyFromFile ``` -------------------------------- ### Execute SPL Program with run: Method Source: https://book.gtoolkit.com/spl-facade-oevv51bh05vtux6sygbde0i5 Demonstrates how to execute a simple 'Hello world!' SPL program using the `SPL>>#run:` method. This will parse, interpret, and print the output of the program. ```Smalltalk SPL run: 'print "Hello world!";' ``` -------------------------------- ### Query for Example Methods in GToolkit Source: https://book.gtoolkit.com/implementing-a-moldable-stack-machine-2taosk42d3purmvmwfdg5y5x Shows a Smalltalk query to find methods marked with the `#gtExample` pragma within the `GtLudoGame` package. This helps in discovering existing example method patterns for `StackMachineExamples`. ```Smalltalk #gtExample gtPragmas & GtLudoGame package gtPackageMatches ``` -------------------------------- ### Smalltalk: Player A Lands on Occupied Goal Square Source: https://book.gtoolkit.com/testing-the-ludo-corner-cases-7fp6z0jub1kmadpjhfy3riv9b This example demonstrates player A's token (capital 'A') landing on an occupied goal square. Starting from the 'second token close to goal' setup, where token 'a' is on the first goal square, a roll of 4 causes token 'A' to land on 'a', resulting in 'A' moving to the next available goal square (the second one). It asserts that token 'A' is now in the goal state. ```Smalltalk playerAlandsOnOccupiedGoalSquare "Example for 9. Landing on the first occupied goal square. (Land on next goal square.)" | game | game := self playerAsecondTokenCloseToGoal. self assert: game currentPlayer name equals: 'A'. self assert: (game positionOfTokenNamed: 'A') equals: 37. game roll: 4. game moveTokenNamed: 'A'. self assert: (game tokenNamed: 'A') isInGoalState. ^ game ``` -------------------------------- ### Instantiate OpenAI Client from API Key in Clipboard (Smalltalk) Source: https://book.gtoolkit.com/working-with-the-openai-api-client-5lw2wjefqnw6qokwfgjghsecb Shows an alternative way to initialize the GtOpenAIClient by retrieving the API key directly from the system clipboard. This method is useful for quick testing or temporary setups. ```Smalltalk client := GtOpenAIClient withApiKeyFromClipboard ``` -------------------------------- ### Initialize PythonBridge Application and Install Pandas Module Source: https://book.gtoolkit.com/pythonbridge-custom-views-for-pandas-dataf-defuf5iv1o49xfbvy5b5s4312 Ensures the `PBApplication` is running, starting it if necessary, and then installs the 'pandas' module within the PythonBridge environment to make it available for use in subsequent operations. ```Smalltalk PBApplication isRunning ifFalse: [ PBApplication start ]. PBApplication uniqueInstance installModule: 'pandas'. ``` -------------------------------- ### Install gtoolkit-mapper using Metacello Source: https://book.gtoolkit.com/geolife-gps-trajectory-dataset-example-4s7idmjcl3mt7z5lr313r36dl This code snippet installs the 'gtoolkit-mapper' package, which is required for some views of the Geolife GPS trajectory dataset demo in Glamorous Toolkit. It uses Metacello to load the baseline from a GitHub repository. ```Smalltalk Metacello new baseline: 'GToolkitMapperWithoutGT'; repository: 'github://feenkcom/gtoolkit-mapper:master/src'; load ``` -------------------------------- ### Install Yarn lockfile module in JSLinkApplication (Pharo) Source: https://book.gtoolkit.com/visualizing-yarn-lock-files-using-javascri-9y7jowgda5bkjzwesvsdg8aew Before parsing the `yarn.lock` file with JavaScript, this Pharo code snippet starts the `JSLinkApplication` and installs the `@yarnpkg/lockfile` module into the remote JavaScript server, making it available for use. ```Pharo JSLinkApplication start.JSLinkApplication uniqueInstance installModule: '@yarnpkg/lockfile' ``` -------------------------------- ### Load Pure Git Repository for 'gtoolkit' Source: https://book.gtoolkit.com/how-to-use-the-pure-git-tool-b7orhscgmczdqyatb6u3wgae This Pharo example shows how to load an existing 'gtoolkit' repository using `PureGitRepository`. It obtains the system repository by name and then initializes Pure Git on its location, verifying its presence to ensure it's ready for operations. ```Pharo exampleGToolkit | systemRepository repository | systemRepository := IceRepository repositoryNamed: 'gtoolkit'. self assert: systemRepository notNil. repository := PureGitRepository on: systemRepository location. self assert: repository exists. ^ repository ``` -------------------------------- ### Display GToolkit Installer Help Source: https://book.gtoolkit.com/how-to-use-gt-installer-caskangdjwh15y6a0m8dry56h This command shows all available arguments and options for the `gt-installer release-build` command. It's useful for understanding the various functionalities and parameters supported by the GToolkit installer. ```Shell ./gt-installer release-build --help ``` -------------------------------- ### Install Glamorous Toolkit with Nix (Stable Channel with Unstable Overlay) Source: https://book.gtoolkit.com/how-to-install-glamorous-toolkit-with-nix-bfbaaxjyp9t1ktuetlgm8okxb This Nix configuration demonstrates how to install Glamorous Toolkit from the unstable channel even when your system is configured for the stable channel. It achieves this by importing the unstable channel as an overlay and referencing the `glamoroustoolkit` package from it. ```Nix { config, pkgs, ... }: let # Define the unstable channel, reusing the current config unstable = import (builtins.fetchTarball https://github.com/nixos/nixpkgs/tarball/nixpkgs-unstable) { config = config.nixpkgs.config; }; in { environment.systemPackages = with pkgs; [ # ... unstable.glamoroustoolkit # ... ]; } ``` -------------------------------- ### Simple JavaScript Expression Inspection Source: https://book.gtoolkit.com/javascript-debugger-setup---example-9y7jowdtdfxenw1klw6t4n39s This JavaScript snippet demonstrates a basic variable assignment and an arithmetic expression. It is provided as a simple example for inspection, allowing users to observe variable values and the result of the expression evaluation. ```JavaScript let aVariable = 1;aVariable + 40 + 1 ``` -------------------------------- ### Visualize GtLudoBoardElement with Example Data Source: https://book.gtoolkit.com/creating-the-ludo-board-view-7fp6z0igdtj9xayx8owjpt6cd This snippet demonstrates how to instantiate and visualize the `GtLudoBoardElement` using example data. It creates a new `GtLudoBoardExamples` instance and uses its `boardWith2PlayingPlayers` method to provide the board state for the visualization. ```Smalltalk GtLudoBoardElement for: GtLudoBoardExamples new boardWith2PlayingPlayers ``` -------------------------------- ### Ludo Game: Player B Lands on Opponent's Token, Sends Back to Start Source: https://book.gtoolkit.com/testing-the-ludo-corner-cases-7fp6z0jub1kmadpjhfy3riv9b Illustrates a Ludo game scenario where player B's token lands on player A's token at position 12. As a result, player A's token is sent back to its starting state. This example confirms B's final position and A's return to start. ```Smalltalk bEntersAndPlaysWithAahead "Example for 4. Landing on another player's token. (Send other token to start.)" | game | game := self playerBentersWithTokenAahead. game roll: 6. game moveTokenNamed: 'B'. game roll: 1. game moveTokenNamed: 'B'. self assert: (game positionOfTokenNamed: 'B') equals: 12. self assert: game currentPlayer name equals: 'C'. self assert: (game tokenNamed: 'A') isInStartState. ^ game ``` -------------------------------- ### Define GToolkit Smalltalk Alternative Example Method Source: https://book.gtoolkit.com/introducing-test-examples-and-code-cleanin-4wxxpyxj2ow5qoyg5ntecmlmh This Smalltalk example method, `altExample`, illustrates instantiating the `Jumble` class from an alternative word list URL. It uses `Jumble class>>#from:` and asserts different unscrambling results, showcasing the flexibility of the `Jumble` class with varied data sources. ```Smalltalk "protocol: #example"Jumble >> altExample | jumble | jumble := Jumble from: Jumble altUrl. self assert: (jumble unJumble: 'gameses') size = 1. self assert: (jumble unJumble: 'gameses') first = 'message'. self assert: (jumble unJumble: 'xyz') isEmpty. ^ jumble ``` -------------------------------- ### Define GtExample Dependencies for In-Memory File Creation Source: https://book.gtoolkit.com/example-driven-development-by-example-wmr9ggp9fan2j19g4z4crz0m This snippet defines several GtExample methods that serve as dependencies for creating a file in memory. It includes methods for retrieving a memory-based directory, defining file contents, and specifying a file name. These components can be composed to form more complex examples, illustrating dependency chaining. ```Smalltalk "protocol: #examples"GtExamplesTutorial >> directoryInMemory ^ FileSystem memory workingDirectory"protocol: #examples"GtExamplesTutorial >> fileContents ^ 'Sample contents'"protocol: #examples"GtExamplesTutorial >> fileName ^ 'sample.txt'"protocol: #examples"GtExamplesTutorial >> createFileInMemory ^ self directoryInMemory / self fileName writeStreamDo: [ :stream | stream nextPutAll: self fileContents ]; yourself ``` -------------------------------- ### Run GtExamplesTutorial createFileInMemory as a GtExample Source: https://book.gtoolkit.com/example-driven-development-by-example-wmr9ggp9fan2j19g4z4crz0m Shows how to execute the `createFileInMemory` method specifically as a `GtExample`, accessing its return value through the `gtExample run returnValue` mechanism. ```Smalltalk (GtExamplesTutorial>>#createFileInMemory) gtExample run returnValue ``` -------------------------------- ### Manually Start GT Python Bridge (Shell) Source: https://book.gtoolkit.com/python-bridge-troubleshooting-4bh6zrwgxadl6bccu380jvs3t This shell command demonstrates how to manually start the gtoolkit_bridge using `pipenv`. It specifies the communication ports for the bridge and Pharo, the messaging method (msgpack), and enables logging for debugging purposes. This is useful for testing the bridge startup independently. ```Shell pipenv run python -m gtoolkit_bridge --port 7007 --pharo 7006 --method msgpack --log ``` -------------------------------- ### List Available OpenAI Models (Smalltalk) Source: https://book.gtoolkit.com/working-with-the-openai-api-client-5lw2wjefqnw6qokwfgjghsecb Illustrates how to use the initialized OpenAI client to fetch and display a list of all available models from the OpenAI API. ```Smalltalk client listModels ``` -------------------------------- ### Start GtRemoteRunner Worker via Command Line Source: https://book.gtoolkit.com/remote-runner--start-manual-runner-and-wor-bliie6oqqvw3frin9ugcff9as This Bash command line example shows how to launch a GtRemoteRunner worker directly from the terminal. It specifies the server address, enables logging, and configures various operational flags like `changesSync` and `detachChangesFromFileSystem`. ```Bash bin/GlamorousToolkit-cli GlamorousToolkit.image clap remoteRunnerWorker --log --serverSocketAddress 7042 --changesSync --detachChangesFromFileSystem --noLepiterReload --noGtImageUpdate ``` -------------------------------- ### Sending Unary Message to a Class (Date) Source: https://book.gtoolkit.com/understanding-smalltalk-message-syntax-w9fc37am75ozp0rrdb5xftjo Example of sending a unary message `today` to the `Date` class, showing how to get the current date. ```Smalltalk Date today ``` -------------------------------- ### Instantiating PriceExample for Initial Inspection (Smalltalk) Source: https://book.gtoolkit.com/modeling-a-concrete-price-4zfv1b6ujzwv1ukvjxkb2yep5 This snippet shows how to create a new instance of PriceExamples and call the hundredEuros method. It serves as an initial setup for inspecting object behavior before implementing custom equality. ```Smalltalk PriceExamples new hundredEuros. ``` -------------------------------- ### Load Pure Git Repository for 'gt4git' Source: https://book.gtoolkit.com/how-to-use-the-pure-git-tool-b7orhscgmczdqyatb6u3wgae This Pharo example demonstrates how to load an existing 'gt4git' repository using `PureGitRepository`. It first retrieves the system repository by name and then initializes Pure Git on its location, asserting its existence to confirm successful loading. ```Pharo exampleGt4Git | systemRepository repository | systemRepository := IceRepository repositoryNamed: 'gt4git'. self assert: systemRepository notNil. repository := PureGitRepository on: systemRepository location. self assert: repository exists. ^ repository ``` -------------------------------- ### Get Remote gt4gemstone Version (Direct) Source: https://book.gtoolkit.com/checking-the-loaded-gt4gemstone-version-in-cdv36qads5tcwm0303t5hfzrv This snippet attempts to directly retrieve the version string of the `gt4gemstone` release installed in the remote GemStone extent. This method is applicable only if `gt4gemstone` is already installed remotely and is compatible with the current Glamorous Toolkit client's connection. ```Smalltalk GtGsRelease versionString ``` -------------------------------- ### Debug JavaScript Code with External Module and Breakpoint Source: https://book.gtoolkit.com/javascript-debugger-setup---example-9y7jowdtdfxenw1klw6t4n39s This JavaScript example demonstrates debugging a script that relies on an external module. It imports `TestClass` from a relative path, creates an instance, and then uses a `debugger;` statement to pause execution before calling a method on the object, facilitating inspection of module interactions. ```JavaScript let TestClass = require('../gtoolkit/testclass'); let testObject = new TestClass(); debugger; testObject.factorial(3); ``` -------------------------------- ### Implement Stack Machine Example Methods in Smalltalk Source: https://book.gtoolkit.com/implementing-a-stack-machine-64llyut36jrc7chozc64fs9mb Defines various example methods ('pushed1', 'push1andPop', 'pushed1and2', 'add1and2') that demonstrate the usage and testing of the 'StackMachine' operations. These methods are marked with the '' pragma, indicating they are intended for testing or demonstration within a GToolkit environment. ```Smalltalk "protocol: #accessing"StackMachine >> pushed1 | result | result := self empty. result push: 1. self assert: result size equals: 1. self assert: result top equals: 1. ^ result ``` ```Smalltalk "protocol: #accessing"StackMachine >> push1andPop | result popped | result := self pushed1. popped := result pop. self assert: popped equals: 1. self assert: result isEmpty. ^ result ``` ```Smalltalk "protocol: #accessing"StackMachine >> pushed1and2 | result | result := self pushed1. result push: 2. self assert: result value size equals: 2. self assert: result top equals: 2. ^ result ``` ```Smalltalk "protocol: #accessing"StackMachine >> add1and2 | result | result := self pushed1and2. result add. self assert: result value size equals: 1. self assert: result top equals: 3. ^ result ``` -------------------------------- ### Glamorous Toolkit Command-Line Tools Source: https://book.gtoolkit.com/how-to-install-glamorous-toolkit-with-nix-bfbaaxjyp9t1ktuetlgm8okxb Overview of the command-line tools available after installing Glamorous Toolkit via Nix, including scripts for image management and launching the GUI/CLI applications. ```APIDOC GlamorousToolkit-GetImage: Description: A simple script to install the latest image into the current working directory. GlamorousToolkit: Description: The GUI version of Glamorous Toolkit. GlamorousToolkit-cli: Description: The CLI version of Glamorous Toolkit. ``` -------------------------------- ### Define GtMyExampleBeaconStartSignal Class in Smalltalk Source: https://book.gtoolkit.com/an-example-of-moldable-logging-using-beaco-9iy8ihtv3046fcttg153ybg0y Defines GtMyExampleBeaconStartSignal, a concrete signal class subclassing GtMyExampleBeaconSignal, specifically for marking the start of an event in logging examples. ```Smalltalk GtMyExampleBeaconSignal subclass: #GtMyExampleBeaconStartSignal instanceVariableNames: '' classVariableNames: '' package: 'GToolkit-Utility-Logging-Examples' ``` -------------------------------- ### Smalltalk: Querying API References within the Image Source: https://book.gtoolkit.com/a-single-starting-point-for-scripting--lin-2sslgxkw1agkq7liw4heoqycp This Smalltalk snippet demonstrates how to query for references to `ZnClient` within the current Smalltalk image. It further refines the search to include only those references found within the 'GToolkit' or 'Lepiter' packages, showcasing an in-image search and filtering capability. ```Smalltalk ZnClient gtReferences & ('GToolkit' gtPackageMatches | 'Lepiter' gtPackageMatches) ``` -------------------------------- ### Ludo Game Setup: Tokens B and A Positioned for Chained Movement Source: https://book.gtoolkit.com/testing-the-ludo-corner-cases-7fp6z0jub1kmadpjhfy3riv9b Prepares a Ludo game state with token B at position 17 and token A at position 18. This setup is for a complex scenario involving a player landing on their own token, which then moves to a square occupied by an opponent's token, sending the opponent's token back to start. ```Smalltalk playerBtoPlayWithTokensBandAahead "Setup for 5. Landing on a square with the same play's token, followed by a square with a token of another player. (Land on next square, sending the token there to start.)" | game | game := self playerAentersTokenA. game roll: 6. game moveTokenNamed: 'A'. game roll: 6. game moveTokenNamed: 'A'. game roll: 5. game moveTokenNamed: 'A'. self assert: (game positionOfTokenNamed: 'A') equals: 18. self assert: game currentPlayer name equals: 'B'. game roll: 6. game moveTokenNamed: 'B'. game roll: 6. game moveTokenNamed: 'b'. game roll: 6. game moveTokenNamed: 'B'. self assert: (game positionOfTokenNamed: 'B') equals: 17. ^ game ``` -------------------------------- ### Example Smalltalk Game Initialization with Characters Source: https://book.gtoolkit.com/implementing-the-memory-game-model-53lj109284d474rzn4qlisx0e Shows an example of creating a new `Game` instance and initializing it with a set of capital letters as symbols. ```Smalltalk aGame := Game new.aGame initializeForSymbols: 'ABCDEFGH' ``` -------------------------------- ### Stop All Python Bridge Instances (Smalltalk) Source: https://book.gtoolkit.com/python-debugger-setup---example-6h3icwf26fev4i7s74u6jghm8 Invokes a Smalltalk method to terminate all active instances of the Python Bridge application. This is useful for resetting the environment or resolving issues. ```Smalltalk PBApplication stopAllInstances ``` -------------------------------- ### Smalltalk: Ludo Token Collision on Opponent's Start Square Setup Source: https://book.gtoolkit.com/testing-the-ludo-corner-cases-7fp6z0jub1kmadpjhfy3riv9b This Smalltalk code sets up a Ludo game state where player A's token is strategically placed on player B's start square. It simulates a sequence of moves and dice rolls to achieve this specific pre-collision scenario, verifying token position and current player. ```Smalltalk bToPlayWithAonStartSquare "Setup for 1. Entering play when there is a token of another player on the start square. (Send other token to start state.)" | game | game := self playerAentersTokenA. game roll: 6. game moveTokenNamed: 'A'. game roll: 4. game moveTokenNamed: 'A'. self assert: (game positionOfTokenNamed: 'A') equals: 11. self assert: game currentPlayer name equals: 'B'. ^ game ``` -------------------------------- ### Inspect PharoLink Application Object Source: https://book.gtoolkit.com/pharolink--start-manual-server-and-client-4lsasvmsw9es7f227ws9vybqa Allows for interactive inspection of the `app` object, which represents the running PharoLink client application. This is a standard Pharo debugging technique to explore an object's state and methods. ```Smalltalk "Inspect the app"app ``` -------------------------------- ### Initialize Ludo Board Example Source: https://book.gtoolkit.com/creating-the-ludo-board-view-7fp6z0igdtj9xayx8owjpt6cd This snippet initializes a new Ludo board example with two playing players and creates a `GtLudoBoardElement` instance for it. This sets up the basic board structure ready for interaction. ```Smalltalk example := GtLudoBoardExamples new boardWith2PlayingPlayers .board := GtLudoBoardElement for: example ``` -------------------------------- ### Capture Signals with MemoryLogger (Smalltalk) Source: https://book.gtoolkit.com/logging-with-beacon-53lj10cumhck8flzo567i0cuu This Smalltalk example illustrates how to use MemoryLogger to capture BeaconSignal objects. The start and stop methods define a recording scope, within which any emitted signals, such as ContextStackSignal, are collected for later analysis. ```Smalltalk MemoryLogger start.ContextStackSignal emit.MemoryLogger stop. ``` -------------------------------- ### Smalltalk: Initialize and Play Game Source: https://book.gtoolkit.com/playing-the-memory-game-53lj10f3wdz11q2uyhiqfcjkv This Smalltalk snippet demonstrates how to initialize a new game instance and associate it with a `GameElement`. This is typically the final step to set up and make the game playable after defining its logic and UI components. ```Smalltalk aGame := Game numbers.GameElement new game: aGame ```