### Start partitioned registry Source: https://elixir.hexdocs.pm/1.20.1/Registry.md This example shows how to start a registry with partitioning enabled, setting the number of partitions to the number of available schedulers. This is recommended for intensive workloads. ```elixir Registry.start_link( keys: :unique, name: MyApp.Registry, partitions: System.schedulers_online() ) ``` -------------------------------- ### Starting and Using the GenServer Calculator Source: https://elixir.hexdocs.pm/1.20.1/process-anti-patterns.md This example shows how to start the GenServer Calculator and interact with it using its defined functions. ```elixir iex> {:ok, pid} = GenServer.start_link(Calculator, :init) {:ok, #PID<0.132.0>} iex> Calculator.add(1, 5, pid) 6 iex> Calculator.subtract(2, 3, pid) -1 ``` -------------------------------- ### Starting and Interacting with KV Process Source: https://elixir.hexdocs.pm/1.20.1/processes.md Demonstrates how to start the KV process, send a 'get' message, and observe the initial 'nil' response. Requires the KV module to be defined. ```iex iex> {:ok, pid} = KV.start_link() {:ok, #PID<0.62.0>} iex> send(pid, {:get, :hello, self()}) {:get, :hello, #PID<0.41.0>} iex> flush() nil :ok ``` -------------------------------- ### Starting a Task.Supervisor Source: https://elixir.hexdocs.pm/1.20.1/Task.Supervisor.md Demonstrates how to start a Task.Supervisor under a main supervisor with a specific name. This is the initial setup for using Task.Supervisor. ```elixir children = [ {Task.Supervisor, name: MyApp.TaskSupervisor} ] Supervisor.start_link(children, strategy: :one_for_one) ``` -------------------------------- ### Starting Agent and Demonstrating Scattered Updates Source: https://elixir.hexdocs.pm/1.20.1/process-anti-patterns.md This example starts an Agent and shows how direct interaction from multiple modules can lead to mixed data formats in the agent's state. ```elixir # start an agent with initial state of an empty list iex> {:ok, agent} = Agent.start_link(fn -> [] end) {:ok, #PID<0.135.0>} # many data formats (for example, List, Map, Integer, Atom) are # combined through direct access spread across the entire system iex> A.update(agent) iex> B.update(agent) iex> C.update(agent) # state of shared information iex> D.get(agent) [:atom_value, %{a: 123}] ``` -------------------------------- ### Direct Registry and Supervisor Start (Not Recommended) Source: https://elixir.hexdocs.pm/1.20.1/supervisor-and-application.md This is an example of how NOT to start a registry and supervisor directly. Processes should typically be started within a supervision tree. ```elixir def start(_type, _args) do Registry.start_link(name: KV, keys: :unique) Supervisor.start_link([], strategy: :one_for_one) end ``` -------------------------------- ### Start duplicate-key registry with partitioning Source: https://elixir.hexdocs.pm/1.20.1/Registry.md This example shows how to start a registry that supports duplicate keys and is partitioned by key. This configuration optimizes key-based lookups for scenarios with many keys and few entries per key. ```elixir Registry.start_link( keys: {:duplicate, :key}, name: MyApp.TopicRegistry, partitions: System.schedulers_online() ) ``` -------------------------------- ### Interacting with KV Buckets in IEx Source: https://elixir.hexdocs.pm/1.20.1/supervisor-and-application.md This snippet demonstrates how to start a KV bucket and interact with it (put and get operations) after the registry has been started as part of the application. ```iex iex> name = {:via, Registry, {KV, "shopping"}} iex> KV.Bucket.start_link(name: name) {:ok, #PID<0.43.0>} iex> KV.Bucket.put(name, "milk", 1) :ok iex> KV.Bucket.get(name, "milk") 1 ``` -------------------------------- ### Starting Dynamic Children with start_child/2 Source: https://elixir.hexdocs.pm/1.20.1/DynamicSupervisor.md Use `start_child/2` with a child specification to start a GenServer dynamically. This example shows starting two Counter servers and incrementing them. ```elixir {:ok, counter1} = DynamicSupervisor.start_child(MyApp.DynamicSupervisor, {Counter, 0}) Counter.inc(counter1) #=> 0 {:ok, counter2} = DynamicSupervisor.start_child(MyApp.DynamicSupervisor, {Counter, 10}) Counter.inc(counter2) #=> 10 DynamicSupervisor.count_children(MyApp.DynamicSupervisor) #=> %{active: 2, specs: 2, supervisors: 0, workers: 2} ``` -------------------------------- ### Starting a GenServer under a Supervisor Source: https://elixir.hexdocs.pm/1.20.1/GenServer.md This example shows how to define children for a supervisor to start a `Stack` GenServer with initial data. The `children` list specifies the module and its initial argument. ```elixir children = [ {Stack, "hello,world"} ] Supervisor.start_link(children, strategy: :one_for_all) ``` -------------------------------- ### Example Command Sequence Source: https://elixir.hexdocs.pm/1.20.1/docs-tests-and-with.md This sequence demonstrates the expected input and output for various commands like CREATE, PUT, GET, and DELETE. ```text CREATE shopping OK PUT shopping milk 1 OK PUT shopping eggs 3 OK GET shopping milk 1 OK DELETE shopping eggs OK ``` -------------------------------- ### Example of starting a PartitionSupervisor as a child Source: https://elixir.hexdocs.pm/1.20.1/PartitionSupervisor.md Demonstrates how to include a PartitionSupervisor in a list of children for another supervisor, specifying its child spec and name. ```elixir children = [ {PartitionSupervisor, child_spec: SomeChild, name: MyPartitionSupervisor} ] ``` -------------------------------- ### Example session interacting with named KV buckets Source: https://elixir.hexdocs.pm/1.20.1/supervisor-and-application.md A text-based example session demonstrating interaction with named KV buckets, including creation, putting a value, and getting a value. ```text CREATE shopping OK PUT shopping milk 1 OK GET shopping milk 1 OK ``` -------------------------------- ### Start registry in a supervisor Source: https://elixir.hexdocs.pm/1.20.1/Registry.md This example demonstrates how to include a Registry in a supervisor's children list for supervised startup. It uses the `:one_for_one` strategy. ```elixir Supervisor.start_link([ {Registry, keys: :unique, name: MyApp.Registry} ], strategy: :one_for_one) ``` -------------------------------- ### Agent start example Source: https://elixir.hexdocs.pm/1.20.1/Agent.md Starts an agent process without linking it to the current process. The provided function is executed to initialize the agent's state. ```elixir iex> {:ok, pid} = Agent.start(fn -> 42 end) iex> Agent.get(pid, fn state -> state end) 42 ``` -------------------------------- ### Implementing the Application Behaviour Source: https://elixir.hexdocs.pm/1.20.1/Application.md This example shows a basic implementation of the `Application` behaviour, including the required `c:start/2` callback. This callback is responsible for starting the application's supervision tree. ```elixir defmodule MyApp do use Application def start(_type, _args) do children = [] Supervisor.start_link(children, strategy: :one_for_one) end end ``` -------------------------------- ### Starting and Interacting with Counter GenServer Source: https://elixir.hexdocs.pm/1.20.1/GenServer.md Shows how to start the Counter GenServer and interact with it. Includes an example of how the GenServer will eventually stop due to inactivity timeout. ```elixir {:ok, counter_pid} = GenServer.start(Counter, 50) GenServer.call(counter_pid, :increment) #=> 51 # After 5 seconds Process.alive?(counter_pid) #=> false ``` -------------------------------- ### Start Application with Dependencies Source: https://elixir.hexdocs.pm/1.20.1/supervisor-and-application.md Shows how to start an application and ensure all its dependencies are also started. This is useful when an application cannot start due to missing dependencies. ```elixir iex> Application.ensure_all_started(:kv) {:ok, [:logger, :kv]} ``` -------------------------------- ### Start, Update, and Get Agent State Source: https://elixir.hexdocs.pm/1.20.1/Agent.md Shows how to start an Agent with an initial state, update its state using a function, and retrieve the current state. ```elixir iex> {:ok, pid} = Agent.start_link(fn -> 42 end) iex> Agent.update(pid, Kernel, :+, [12]) :ok iex> Agent.get(pid, fn state -> state end) 54 ``` -------------------------------- ### Start, Update, Get, and Stop an Agent Source: https://elixir.hexdocs.pm/1.20.1/agents.md Demonstrates the basic lifecycle of an Agent: starting with an initial state, updating the state, retrieving the state, and stopping the agent. ```elixir iex> {:ok, agent} = Agent.start_link(fn -> [] end) {:ok, #PID<0.57.0>} iex> Agent.update(agent, fn list -> ["eggs" | list] end) :ok iex> Agent.get(agent, fn list -> list end) ["eggs"] iex> Agent.stop(agent) :ok ``` -------------------------------- ### Agent start_link example Source: https://elixir.hexdocs.pm/1.20.1/Agent.md Starts an agent process and links it to the current process. The provided function is executed to initialize the agent's state. This is commonly used when starting agents as part of a supervision tree. ```elixir iex> {:ok, pid} = Agent.start_link(fn -> 42 end) iex> Agent.get(pid, fn state -> state end) 42 ``` -------------------------------- ### Start an Application Source: https://elixir.hexdocs.pm/1.20.1/supervisor-and-application.md Demonstrates starting an application. This command will return an error if the application is already started. ```elixir iex> Application.start(:kv) {:error, {:already_started, :kv}} ``` -------------------------------- ### Sample GenServer for Dynamic Children Source: https://elixir.hexdocs.pm/1.20.1/DynamicSupervisor.md This GenServer is used as an example for starting dynamic children. It implements `start_link/1`, `inc/1`, `init/1`, and `handle_call/3`. ```elixir defmodule Counter do use GenServer def start_link(initial) do GenServer.start_link(__MODULE__, initial) end def inc(pid) do GenServer.call(pid, :inc) end def init(initial) do {:ok, initial} end def handle_call(:inc, _, count) do {:reply, count, count + 1} end end ``` -------------------------------- ### GenServer start_link Example Source: https://elixir.hexdocs.pm/1.20.1/GenServer.md Starts a GenServer process linked to the current process, typically used within a supervision tree. Ensures synchronized startup and handles various initialization outcomes. ```elixir GenServer.start_link(YourServer, :init_arg, name: :your_server) ``` -------------------------------- ### Starting and using a KV Bucket with an atom name Source: https://elixir.hexdocs.pm/1.20.1/supervisor-and-application.md Shows a basic example of starting a KV Bucket with an atom as its name and performing basic operations. This method is discouraged for dynamic process naming due to the risk of atom exhaustion. ```elixir iex> KV.Bucket.start_link(name: :shopping) {:ok, #PID<0.43.0>} iex> KV.Bucket.put(:shopping, "milk", 1) :ok iex> KV.Bucket.get(:shopping, "milk") 1 ``` -------------------------------- ### DynamicSupervisor init function example Source: https://elixir.hexdocs.pm/1.20.1/DynamicSupervisor.md Example of initializing a dynamic supervisor with a maximum number of children. ```elixir def init(_arg) do DynamicSupervisor.init(max_children: 1000) end ``` -------------------------------- ### Supervise Agent with Initial Value Source: https://elixir.hexdocs.pm/1.20.1/Agent.md Shows how to start an Agent (specifically the Counter example) as a child in a supervision tree with a specific initial value. ```Elixir children = [ {Counter, 0} ] Supervisor.start_link(children, strategy: :one_for_all) ``` -------------------------------- ### Agent start_link with error handling example Source: https://elixir.hexdocs.pm/1.20.1/Agent.md Demonstrates starting an agent with a function that raises an error. The start_link function will return an error tuple containing the exception and stacktrace. ```elixir iex> {:error, {exception, _stacktrace}} = Agent.start(fn -> raise "oops" end) iex> exception %RuntimeError{message: "oops"} ``` -------------------------------- ### Starting Children with Supervisor Source: https://elixir.hexdocs.pm/1.20.1/dynamic-supervisor.md This snippet shows a basic way to start children using a standard Supervisor. It is limited to starting a fixed set of children. ```elixir children = [ {Registry, name: KV, keys: :unique} {KV.Bucket, name: {:via, Registry, {KV, "shopping"}}} ] ``` -------------------------------- ### Application Start Callback Source: https://elixir.hexdocs.pm/1.20.1/Application.md Callback invoked when an application is started. It should start the top-level supervisor and return `{:ok, pid}` or `{:ok, pid, state}`. The `start_type` argument specifies the startup context. ```elixir @callback start(start_type(), start_args :: term()) :: {:ok, pid()} | {:ok, pid(), state()} | {:error, reason :: term()} ``` -------------------------------- ### start Source: https://elixir.hexdocs.pm/1.20.1/Application.md Callback called when an application is started. It should start the top-level process of the application, typically a supervisor. ```APIDOC ## start ### Description Called when an application is started. This function is called when an application is started using `Application.start/2` (and functions on top of that, such as `Application.ensure_started/2`). This function should start the top-level process of the application (which should be the top supervisor of the application's supervision tree if the application follows the OTP design principles around supervision). `start_type` defines how the application is started: * `:normal` - used if the startup is a normal startup or if the application is distributed and is started on the current node because of a failover from another node and the application specification key `:start_phases` is `:undefined`. * `{:takeover, node}` - used if the application is distributed and is started on the current node because of a failover on the node `node`. * `{:failover, node}` - used if the application is distributed and is started on the current node because of a failover on node `node`, and the application specification key `:start_phases` is not `:undefined`. `start_args` are the arguments passed to the application in the `:mod` specification key (for example, `mod: {MyApp, [:my_args]}`). This function should either return `{:ok, pid}` or `{:ok, pid, state}` if startup is successful. `pid` should be the PID of the top supervisor. `state` can be an arbitrary term, and if omitted will default to `[]`; if the application is later stopped, `state` is passed to the `stop/1` callback (see the documentation for the `c:stop/1` callback for more information). `use Application` provides no default implementation for the `start/2` callback. ### Callback Signature ```elixir @callback start(start_type(), start_args :: term()) :: {:ok, pid()} | {:ok, pid(), state()} | {:error, reason :: term()} ``` ``` -------------------------------- ### start_link (module-based) Source: https://elixir.hexdocs.pm/1.20.1/DynamicSupervisor.md Starts a module-based supervisor process with a given module and initialization argument. The `c:init/1` callback in the specified module is invoked to get the supervisor specification. ```APIDOC ## `start_link` (module-based) ### Description Starts a module-based supervisor process with the given `module` and `init_arg`. The `c:init/1` callback in the `module` is invoked with `init_arg` to return a supervisor specification. ### Function Signature ```elixir @spec start_link(module(), term(), [GenServer.option()]) :: Supervisor.on_start() ``` ### Options * `:name` - Can be given to register a supervisor name. Supported values are described in the "Name registration" section in the `GenServer` module docs. * Any regular [`GenServer` options](`t:GenServer.option/0`). ### Returns * `{:ok, pid}` - If the supervisor is successfully spawned. * `{:error, {:already_started, pid}}` - If a process with the specified name already exists. * `:ignore` - If the `c:init/1` callback returns `:ignore`. * `{:error, term}` - If the `c:init/1` callback fails or returns an incorrect value. ``` -------------------------------- ### Start KV Server with Task Source: https://elixir.hexdocs.pm/1.20.1/task-and-gen-tcp.md Adds KV.Server.accept/1 as a task to the supervision tree, allowing it to start automatically with the application. ```elixir def start(_type, _args) do children = [ {Registry, name: KV, keys: :unique}, {DynamicSupervisor, name: KV.BucketSupervisor, strategy: :one_for_one}, {Task, fn -> KV.Server.accept(4040) end} ] Supervisor.start_link(children, strategy: :one_for_one) end ``` -------------------------------- ### Starting and using a KV Bucket with a named Registry Source: https://elixir.hexdocs.pm/1.20.1/supervisor-and-application.md Demonstrates how to start a Registry, define a process name using the 'via' tuple, and then start and use a KV Bucket with this named registry. This approach avoids the pitfalls of using atoms for dynamic process names. ```elixir iex> Registry.start_link(name: KV, keys: :unique) iex> name = {:via, Registry, {KV, "shopping"}} iex> KV.Bucket.start_link(name: name) {:ok, #PID<0.43.0>} iex> KV.Bucket.put(name, "milk", 1) :ok iex> KV.Bucket.get(name, "milk") 1 ``` -------------------------------- ### Starting a Task with Task.Supervisor.async Source: https://elixir.hexdocs.pm/1.20.1/Task.Supervisor.md Shows how to start a task directly under a named Task.Supervisor. This task is linked to the caller. ```elixir task = Task.Supervisor.async(MyApp.TaskSupervisor, fn -> :do_some_work end) ``` -------------------------------- ### Supervisor Initialization Options Example Source: https://elixir.hexdocs.pm/1.20.1/Supervisor.md Options that can be passed to `start_link/2` and `init/2` for configuring supervisor behavior. Includes strategy, restart limits, and shutdown settings. ```elixir @type init_option() :: {:strategy, strategy()} | {:max_restarts, non_neg_integer()} | {:max_seconds, pos_integer()} | {:auto_shutdown, auto_shutdown()} ``` -------------------------------- ### start_link Source: https://elixir.hexdocs.pm/1.20.1/Registry.md Starts the registry as a supervisor process. Manually it can be started as: Registry.start_link(keys: :unique, name: MyApp.Registry). ```APIDOC ## start_link ### Description Starts the registry as a supervisor process. This function can be used to manually start the registry or as part of a supervisor tree. ### Function Signature `@spec start_link([start_option()]) :: {:ok, pid()} | {:error, term()} ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```elixir Registry.start_link(keys: :unique, name: MyApp.Registry) ``` ### Response #### Success Response (200) - `{:ok, pid()}`: The process identifier of the started registry. #### Response Example ```elixir {:ok, #PID<0.123.456>} ``` ``` -------------------------------- ### Get Beginning of Week (Custom Start) Source: https://elixir.hexdocs.pm/1.20.1/Date.md Calculates the first day of the week for a given date, specifying a custom starting day for the week (e.g., Sunday or Saturday). ```elixir iex> Date.beginning_of_week(~D[2020-07-11], :sunday) ~D[2020-07-05] ``` ```elixir iex> Date.beginning_of_week(~D[2020-07-11], :saturday) ~D[2020-07-11] ``` -------------------------------- ### Ensuring Application Start Source: https://elixir.hexdocs.pm/1.20.1/Application.md This code shows how to manually start an application and its dependencies using `Application.ensure_all_started/1`. This is typically handled by build tools like Mix. ```elixir {:ok, _} = Application.ensure_all_started(:some_app) ``` -------------------------------- ### Example: Open a compressed file for reading Source: https://elixir.hexdocs.pm/1.20.1/File.md Demonstrates opening a compressed tar.gz file for reading using File.open/2. The file is then read line by line using IO.read/2 and explicitly closed. ```elixir {:ok, file} = File.open("foo.tar.gz", [:read, :compressed]) IO.read(file, :line) File.close(file) ``` -------------------------------- ### Get Environment Stacktrace Source: https://elixir.hexdocs.pm/1.20.1/Macro.Env.md Example of retrieving the environment's stacktrace using Macro.Env.stacktrace. ```elixir Macro.Env.stacktrace(__ENV__) ``` -------------------------------- ### KV.Bucket.start_link/1 Source: https://elixir.hexdocs.pm/1.20.1/genservers.md Starts a new KV.Bucket GenServer process. It initializes the bucket with an empty map and accepts options for server configuration. ```APIDOC ## KV.Bucket.start_link/1 ### Description Starts a new GenServer process for the KV bucket. This function initializes the bucket with an empty map and accepts a list of options for server configuration. ### Function Signature `start_link(opts)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```elixir KV.Bucket.start_link(name: :my_bucket) ``` ### Response #### Success Response Returns `{:ok, pid}` where `pid` is the process identifier of the started GenServer. #### Response Example ```elixir {:ok, #PID<0.123.0>} ``` ``` -------------------------------- ### Stream.take_every/2 Example (nth=2) Source: https://elixir.hexdocs.pm/1.20.1/Stream.md Takes every second element from an enumerable, starting with the first element. ```elixir iex> stream = Stream.take_every(1..10, 2) iex> Enum.to_list(stream) [1, 3, 5, 7, 9] ``` -------------------------------- ### Enum.chunk_by Example Source: https://elixir.hexdocs.pm/1.20.1/Enum.md Splits an enumerable into chunks based on a function that determines when a new chunk should start. ```elixir iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1)) [[1], [2, 2], [3], [4, 4, 6], [7, 7]] ``` -------------------------------- ### Starting DynamicSupervisor Directly Source: https://elixir.hexdocs.pm/1.20.1/PartitionSupervisor.md This is the standard way to start a single `DynamicSupervisor` within a supervision tree. It's presented as a baseline before introducing the `PartitionSupervisor` for managing multiple `DynamicSupervisor` instances. ```elixir children = [ {DynamicSupervisor, name: MyApp.DynamicSupervisor} ] Supervisor.start_link(children, strategy: :one_for_one) ``` -------------------------------- ### Get Variables from Environment Source: https://elixir.hexdocs.pm/1.20.1/Macro.Env.md Example of retrieving a list of variables from the current environment using Macro.Env.vars. ```elixir Macro.Env.vars(__ENV__) ``` -------------------------------- ### Starting and Using a Supervised KV.Bucket Source: https://elixir.hexdocs.pm/1.20.1/dynamic-supervisor.md Starts a KV.Bucket process under a supervisor and demonstrates basic put/get operations. This shows how to integrate a dynamic child into a supervision tree. ```elixir iex> children = [{KV.Bucket, name: :shopping}] iex> Supervisor.start_link(children, strategy: :one_for_one) iex> KV.Bucket.put(:shopping, "milk", 1) :ok iex> KV.Bucket.get(:shopping, "milk") 1 ``` -------------------------------- ### Get Compiler Option Example Source: https://elixir.hexdocs.pm/1.20.1/Code.md Retrieves the value of a specific compiler option. Use this to inspect build-time configurations. ```elixir Code.get_compiler_option(:debug_info) ``` -------------------------------- ### Start Module-Based Supervisor Source: https://elixir.hexdocs.pm/1.20.1/DynamicSupervisor.md Starts a module-based supervisor with a given module and initialization argument. The `c:init/1` callback in the specified module is invoked to get the supervisor specification. It handles `:ignore` returns and errors from the `c:init/1` callback. ```elixir @spec start_link(module(), term(), [GenServer.option()]) :: Supervisor.on_start() ``` -------------------------------- ### start/1 Source: https://elixir.hexdocs.pm/1.20.1/Application.md Starts the given application. If the application is not loaded, it will be loaded first. Dependencies must be started explicitly before this function is called. ```APIDOC ## start/1 ### Description Starts the given `app` with `t:restart_type/0`. If the `app` is not loaded, the application will first be loaded using `load/1`. Any included application, defined in the `:included_applications` key of the `.app` file will also be loaded, but they won't be started. Furthermore, all applications listed in the `:applications` key must be explicitly started before this application is. If not, `{:error, {:not_started, app}}` is returned, where `app` is the name of the missing application. In case you want to automatically load **and start** all of `app`'s dependencies, see `ensure_all_started/2`. ### Method Elixir Function Call ### Parameters #### Path Parameters - **app** (app()) - The application to start. - **restart_type** (restart_type()) - The type of restart strategy. ### Response #### Success Response - **:ok** - Indicates the application started successfully. - **{:error, term()}** - Indicates an error occurred during startup. #### Response Example ```elixir Application.start(:my_app, :permanent) # Returns :ok or {:error, {:not_started, :some_dependency}} ``` ``` -------------------------------- ### Stream.scan/3 Example Source: https://elixir.hexdocs.pm/1.20.1/Stream.md Applies a function to each element, emitting the result and using it as the next accumulator. Starts with a given initial accumulator. ```elixir iex> stream = Stream.scan(1..5, 0, &(&1 + &2)) iex> Enum.to_list(stream) [1, 3, 6, 10, 15] ``` -------------------------------- ### Starting Task.Supervisor directly Source: https://elixir.hexdocs.pm/1.20.1/Task.Supervisor.md Shows how to start Task.Supervisor directly using start_link/1. This method is generally recommended only for scripting and should be avoided in production. ```elixir Task.Supervisor.start_link(name: MyApp.TaskSupervisor) ``` -------------------------------- ### Importing only sigils from a module Source: https://elixir.hexdocs.pm/1.20.1/Kernel.SpecialForms.md This example shows how to import only sigils from the `Kernel` module. Sigils are special operators that start with a backtick. ```elixir import Kernel, only: :sigils ``` -------------------------------- ### Interactive Elixir (IEx) Examples Source: https://elixir.hexdocs.pm/1.20.1/introduction.md Evaluate basic Elixir expressions in the interactive shell. Start IEx by typing 'iex' in your terminal. ```elixir Erlang/OTP 26 [64-bit] [smp:2:2] [...] Interactive Elixir - press Ctrl+C to exit iex(1)> 40 + 2 42 iex(2)> "hello" <> " world" "hello world" ``` -------------------------------- ### start_link (with options) Source: https://elixir.hexdocs.pm/1.20.1/DynamicSupervisor.md Starts a supervisor with a list of initialization options. This is typically used when embedding a DynamicSupervisor as a child in another supervisor. It supports various options for naming, restart strategy, and child limits. ```APIDOC ## `start_link` (with options) ### Description Starts a supervisor with the given options. This function is typically not invoked directly but rather when using a `DynamicSupervisor` as a child of another supervisor. ### Function Signature ```elixir @spec start_link([init_option() | GenServer.option()]) :: Supervisor.on_start() ``` ### Options * `:name` - Registers the supervisor under the given name. * `:strategy` - The restart strategy option. Only `:one_for_one` is supported. * `:max_restarts` - The maximum number of restarts allowed in a time frame. Defaults to `3`. * `:max_seconds` - The time frame in which `:max_restarts` applies. Defaults to `5`. * `:max_children` - The maximum amount of children to be running under this supervisor at the same time. Defaults to `:infinity`. * `:extra_arguments` - Arguments that are prepended to the arguments specified in the child spec given to `start_child/2`. Defaults to an empty list. * Any of the standard [GenServer options](`t:GenServer.option/0`) ### Returns * `{:ok, pid}` - If the supervisor is successfully spawned. * `{:error, {:already_started, pid}}` - If a process with the specified name already exists. ``` -------------------------------- ### Example: Fetch Documentation for an Existing Module Source: https://elixir.hexdocs.pm/1.20.1/Code.md Demonstrates how to fetch and access the documentation for an existing Elixir module, specifically extracting the first line of the module's documentation. ```elixir iex> {:docs_v1, _, :elixir, _, %{"en" => module_doc}, _, _} = Code.fetch_docs(Atom) iex> module_doc |> String.split("\n") |> Enum.at(0) "Atoms are constants whose values are their own name." ``` -------------------------------- ### Telnet Connection Example (Second Client) Source: https://elixir.hexdocs.pm/1.20.1/task-and-gen-tcp.md Illustrates connecting a second telnet client, highlighting potential concurrency issues. ```console $ telnet 127.0.0.1 4040 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. hello hello? HELLOOOOOO? ``` -------------------------------- ### start_link (children, options) Source: https://elixir.hexdocs.pm/1.20.1/Supervisor.md Starts a supervisor with a list of child specifications and options. A strategy must be provided via the :strategy option. Options can also be used for name registration. ```APIDOC ## start_link (children, options) ### Description Starts a supervisor with the given children and options. A strategy is required via the :strategy option. Name registration is also supported. ### Method `start_link/2` ### Parameters #### Path Parameters - `children` (list of child_spec() | module_spec() | :supervisor.child_spec()) - Required - A list of child specifications, module specifications, or old Erlang-style child specifications. - `options` (list of option() | init_option()) - Required - A list of options for the supervisor, including the required :strategy. ### Response #### Success Response - `{:ok, pid()}` - If the supervisor and all child processes are successfully spawned. - `{:error, {:already_started, pid()} | {:shutdown, term()} | term()}` - If the supervisor is given a name and a process with the specified name already exists, or if a child process fails to start. ### Response Example ```elixir {:ok, } {:error, {:already_started, }} {:error, {:shutdown, {:failed_to_start_child, id, reason}}} ``` ``` -------------------------------- ### Elixir Stream Unfold Example: Exponential Growth Source: https://elixir.hexdocs.pm/1.20.1/Stream.md Generates an infinite stream where each subsequent element is double the previous one, starting from 1. ```elixir iex> Stream.unfold(1, fn ...> n -> {n, n * 2} ...> end) |> Enum.take(10) [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] ``` -------------------------------- ### Starting Children on a Partitioned DynamicSupervisor Source: https://elixir.hexdocs.pm/1.20.1/PartitionSupervisor.md Illustrates how to start a child process on one of the `DynamicSupervisor` instances managed by a `PartitionSupervisor`. It uses the `{:via, PartitionSupervisor, {name, key}}` format to route the request, with `self()` as the key to assign the child to a dynamic supervisor based on the calling process. ```elixir DynamicSupervisor.start_child( {:via, PartitionSupervisor, {MyApp.DynamicSupervisors, self()}}, {Agent, fn -> %{} end} ) ``` -------------------------------- ### Stream.from_index/0, /1, and /1 with function Examples Source: https://elixir.hexdocs.pm/1.20.1/Stream.md Builds a stream from an index, starting from an offset or using a provided function. Useful for generating sequences. ```elixir iex> Stream.from_index() |> Enum.take(3) [0, 1, 2] ``` ```elixir iex> Stream.from_index(1) |> Enum.take(3) [1, 2, 3] ``` ```elixir iex> Stream.from_index(fn x -> x * 10 end) |> Enum.take(3) [0, 10, 20] ``` -------------------------------- ### Start DynamicSupervisor with Options Source: https://elixir.hexdocs.pm/1.20.1/DynamicSupervisor.md Starts a DynamicSupervisor with specified options. This is typically used when DynamicSupervisor is a child of another supervisor. It returns `{:ok, pid}` on success or `{:error, {:already_started, pid}}` if a process with the same name already exists. ```elixir @spec start_link([init_option() | GenServer.option()]) :: Supervisor.on_start() ``` -------------------------------- ### Get module information Source: https://elixir.hexdocs.pm/1.20.1/Module.md This example shows how to retrieve the module itself using module_info(:module). It also verifies the presence of a specific function export. ```elixir iex> URI.module_info(:module) URI iex> {:decode_www_form, 1} in URI.module_info(:exports) true ``` -------------------------------- ### Get callbacks for a behaviour Source: https://elixir.hexdocs.pm/1.20.1/Module.md This example demonstrates how to retrieve a list of callbacks defined for a behaviour using behaviour_info/1. The output is sorted for consistent display. ```elixir iex> Enum.sort(GenServer.behaviour_info(:callbacks)) [ code_change: 3, format_status: 1, format_status: 2, handle_call: 3, handle_cast: 2, handle_continue: 2, handle_info: 2, init: 1, terminate: 2 ] ``` -------------------------------- ### Example: Fetch Documentation for a Non-existent Module Source: https://elixir.hexdocs.pm/1.20.1/Code.md Shows the expected output when attempting to fetch documentation for a module that does not exist. ```elixir iex> Code.fetch_docs(ModuleNotGood) {:error, :module_not_found} ``` -------------------------------- ### Get File Extension Source: https://elixir.hexdocs.pm/1.20.1/Path.md Returns the extension of the last component of a path. For filenames starting with a dot and without an extension, it returns an empty string. ```elixir Path.extname("foo.erl") #=> ".erl" ``` ```elixir Path.extname("~/foo/bar") #=> "" ``` ```elixir Path.extname(".gitignore") #=> "" ``` -------------------------------- ### Starting Children on a Single DynamicSupervisor Source: https://elixir.hexdocs.pm/1.20.1/PartitionSupervisor.md Shows how to start a child process, in this case an `Agent`, on a directly named `DynamicSupervisor`. This is the typical usage pattern when only one `DynamicSupervisor` is in use. ```elixir DynamicSupervisor.start_child(MyApp.DynamicSupervisor, {Agent, fn -> %{} end}) ``` -------------------------------- ### Elixir Stream WithIndex Example: Custom Offset Source: https://elixir.hexdocs.pm/1.20.1/Stream.md Creates a stream where elements are paired with their index, starting from a specified integer offset instead of zero. ```elixir iex> stream = Stream.with_index([1, 2, 3], 3) iex> Enum.to_list(stream) [{1, 3}, {2, 4}, {3, 5}] ``` -------------------------------- ### Get Beginning of Week (Default) Source: https://elixir.hexdocs.pm/1.20.1/Date.md Calculates the first day of the week for a given date using the default starting day (Monday for ISO calendar). ```elixir iex> Date.beginning_of_week(~D[2020-07-11]) ~D[2020-07-06] ``` ```elixir iex> Date.beginning_of_week(~D[2020-07-06]) ~D[2020-07-06] ``` ```elixir iex> Date.beginning_of_week(~N[2020-07-11 01:23:45]) ~D[2020-07-06] ``` -------------------------------- ### Starting a Task Source: https://elixir.hexdocs.pm/1.20.1/processes.md Shows how to use `Task.start/1` to spawn a process that provides better error reporting and introspection. It returns `{:ok, pid}`. ```elixir iex> Task.start(fn -> raise "oops" end) {:ok, #PID<0.55.0>} 15:22:33.046 [error] Task #PID<0.55.0> started from #PID<0.53.0> terminating ** (RuntimeError) oops (stdlib) erl_eval.erl:668: :erl_eval.do_apply/6 (elixir) lib/task/supervised.ex:85: Task.Supervised.do_apply/2 (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3 Function: #Function<20.99386804/0 in :erl_eval.expr/5> Args: [] ``` -------------------------------- ### Elixir Counter Module using Agent Source: https://elixir.hexdocs.pm/1.20.1/process-anti-patterns.md Defines a Counter module that uses Agent to maintain state. This is an example of a process that can be started outside a supervision tree. ```elixir defmodule Counter do @moduledoc "" """Global counter implemented as an Agent. """ use Agent @doc "Starts a counter process." def start_link(opts \ []) do initial_state = Keyword.get(opts, :initial_value, 0) name = Keyword.get(opts, :name, __MODULE__) Agent.start_link(fn -> initial_state end, name: name) end @doc "Gets the current value of the given counter." def get(name \ __MODULE__) do Agent.get(name, fn state -> state end) end @doc "Bumps the value of the given counter." def bump(name \ __MODULE__, value) do Agent.get_and_update(fn state -> {state, value + state} end) end end ``` -------------------------------- ### Telnet Connection Example Source: https://elixir.hexdocs.pm/1.20.1/task-and-gen-tcp.md Demonstrates making a telnet connection to a server running on localhost:4040. ```console $ telnet 127.0.0.1 4040 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. say you say you say me say me ``` -------------------------------- ### Initial Server Implementation (Before `with`) Source: https://elixir.hexdocs.pm/1.20.1/docs-tests-and-with.md The initial server definition in `lib/kv/server.ex` before implementing `with`. It includes basic read, write, and serve functions. ```elixir defp serve(socket) do socket |> read_line() |> write_line(socket) serve(socket) end defp read_line(socket) do {:ok, data} = :gen_tcp.recv(socket, 0) data end defp write_line(line, socket) do :gen_tcp.send(socket, line) end ``` -------------------------------- ### Stream.interval/1 Example Source: https://elixir.hexdocs.pm/1.20.1/Stream.md Creates a stream that emits a value after a given period in milliseconds. Emitted values are an increasing counter starting at 0. This operation blocks the caller. ```elixir iex> Stream.interval(10) |> Enum.take(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` -------------------------------- ### Starting Release Nodes with Environment Variables Source: https://elixir.hexdocs.pm/1.20.1/releases.md Starts two instances of the release with specified NODES, PORT, and RELEASE_NODE environment variables for distributed operation. Ensure `@computer-name` is replaced with your actual computer name. ```console $ NODES="foo@computer-name,bar@computer-name" PORT=4040 RELEASE_NODE="foo" bin/kv start_iex ``` ```console $ NODES="foo@computer-name,bar@computer-name" PORT=4041 RELEASE_NODE="bar" bin/kv start_iex ``` -------------------------------- ### Supervisor Child Specification Example Source: https://elixir.hexdocs.pm/1.20.1/Supervisor.md Defines how a supervisor should start, stop, and restart its children. Includes options for restart strategy, shutdown behavior, and process type. ```elixir @type child_spec() :: %{ :id => atom() | term(), :start => {module(), function_name :: atom(), args :: [term()]}, optional(:restart) => restart(), optional(:shutdown) => shutdown(), optional(:type) => type(), optional(:modules) => [module()] | :dynamic, optional(:significant) => boolean() } ``` -------------------------------- ### Using Foo.Bucket for Agent Interaction Source: https://elixir.hexdocs.pm/1.20.1/process-anti-patterns.md Demonstrates how to start an Agent via `Foo.Bucket`, add shared values, and retrieve them. This pattern centralizes process interaction. ```elixir # start an agent through `Foo.Bucket` iex> {:ok, bucket} = Foo.Bucket.start_link(%{}) {:ok, #PID<0.114.0>} # add shared values to the keys `milk` and `beer` iex> Foo.Bucket.put(bucket, "milk", 3) iex> Foo.Bucket.put(bucket, "beer", 7) # access shared data of specific keys iex> Foo.Bucket.get(bucket, "beer") 7 iex> Foo.Bucket.get(bucket, "milk") 3 ``` -------------------------------- ### Enum.split examples Source: https://elixir.hexdocs.pm/1.20.1/Enum.md Shows how Enum.split divides an enumerable into two lists based on a count. A negative count starts from the end, but may require two enumerations. ```elixir Enum.split([1, 2, 3], 2) ``` ```elixir Enum.split([1, 2, 3], 10) ``` ```elixir Enum.split([1, 2, 3], 0) ``` ```elixir Enum.split([1, 2, 3], -1) ``` ```elixir Enum.split([1, 2, 3], -5) ``` -------------------------------- ### Start partitioned registry in a supervisor Source: https://elixir.hexdocs.pm/1.20.1/Registry.md This snippet demonstrates starting a partitioned registry within a supervisor's configuration. It specifies the registry and its partitioning options. ```elixir Supervisor.start_link([ {Registry, keys: :unique, name: MyApp.Registry, partitions: System.schedulers_online()} ], strategy: :one_for_one) ``` -------------------------------- ### Child Specification as Tuple Source: https://elixir.hexdocs.pm/1.20.1/Supervisor.md A shorthand for defining a child specification using a module and its start argument. The supervisor calls `module.child_spec(arg)` to get the full specification. ```elixir children = [ {Counter, 0} ] ``` -------------------------------- ### Initial Command Parser with Doctest Source: https://elixir.hexdocs.pm/1.20.1/docs-tests-and-with.md Defines the initial KV.Command module with a placeholder parse function and a doctest example for the CREATE command. This serves as the starting point for testing. ```elixir defmodule KV.Command do @doc ~S""" Parses the given `line` into a command. ## Examples iex> KV.Command.parse("CREATE shopping\r\n") {:ok, {:create, "shopping"}} """ def parse(_line) do :not_implemented end end ``` -------------------------------- ### Example: Open a file and process its content Source: https://elixir.hexdocs.pm/1.20.1/File.md Shows how to open a file for both reading and writing using File.open/3, passing a function to process the file content. The file is automatically closed after the function executes. ```elixir File.open("file.txt", [:read, :write], fn file -> IO.read(file, :line) end) #=> {:ok, "file content"} ``` -------------------------------- ### Implement Application Start Callback Source: https://elixir.hexdocs.pm/1.20.1/supervisor-and-application.md Implements the start/2 callback for the Application behaviour, which is responsible for starting the application's supervision tree. ```elixir defmodule KV do use Application @impl true def start(_type, _args) do Supervisor.start_link([], strategy: :one_for_one) end end ``` -------------------------------- ### Select all entries from a registry Source: https://elixir.hexdocs.pm/1.20.1/Registry.md This example demonstrates how to retrieve all registered entries from a registry using a full match spec. Ensure the registry is started and populated before calling select. ```elixir iex> Registry.start_link(keys: :unique, name: Registry.SelectAllTest) iex> {:ok, _} = Registry.register(Registry.SelectAllTest, "hello", :value) iex> {:ok, _} = Registry.register(Registry.SelectAllTest, "world", :value) iex> Registry.select(Registry.SelectAllTest, [{{:"$1", :"$2", :"$3"}, [], [{{:"$1", :"$2", :"$3"}}]}] ) |> Enum.sort() [{"hello", self(), :value}, {"world", self(), :value}] ``` -------------------------------- ### Example: Setting Child ID with `child_spec` Source: https://elixir.hexdocs.pm/1.20.1/Supervisor.md Demonstrates how to use `Supervisor.child_spec/2` to set a unique `:id` for a child specification, particularly useful when starting the same module multiple times. ```elixir Supervisor.child_spec({Agent, fn -> :ok end}, id: {Agent, 1}) #=> %{id: {Agent, 1}, #=> start: {Agent, :start_link, [fn -> :ok end]}} ``` -------------------------------- ### Example of building a custom environment Source: https://elixir.hexdocs.pm/1.20.1/Macro.Env.md Demonstrates how to build a custom environment by importing modules and aliasing them. This is an example of high-level constructs for environment manipulation. ```elixir def make_custom_env do import SomeModule, only: [some_function: 2], warn: false alias A.B.C, warn: false __ENV__ end ``` -------------------------------- ### DynamicSupervisor with Naming and Registry Source: https://elixir.hexdocs.pm/1.20.1/dynamic-supervisor.md Shows how to start a DynamicSupervisor with a name and use it to start children that are also named using a registry. This avoids passing PIDs around. ```elixir iex> DynamicSupervisor.start_link(strategy: :one_for_one, name: :dyn_sup) iex> name = {:via, Registry, {KV, "yet_another_list"}} iex> DynamicSupervisor.start_child(:dyn_sup, {KV.Bucket, name: name}) iex> KV.Bucket.put(name, "milk", 1) :ok iex> KV.Bucket.get(name, "milk") 1 ``` -------------------------------- ### Elixir Agent for State Management Source: https://elixir.hexdocs.pm/1.20.1/processes.md Illustrates using Elixir's Agent to manage state, providing a higher-level abstraction for starting, updating, and getting state from a process. ```iex iex> {:ok, pid} = Agent.start_link(fn -> %{} end) {:ok, #PID<0.72.0>} iex> Agent.update(pid, fn map -> Map.put(map, :hello, :world) end) :ok iex> Agent.get(pid, fn map -> Map.get(map, :hello) end) :world ``` -------------------------------- ### Starting Supervisor with :one_for_one Strategy Source: https://elixir.hexdocs.pm/1.20.1/Supervisor.md Initializes a supervisor with a list of child specifications and specifies the `:one_for_one` supervision strategy. This is the default strategy if none is provided. ```elixir children = [ {Counter, 0} ] Supervisor.start_link(children, strategy: :one_for_one) ``` -------------------------------- ### Get Monotonic Time (Specified Unit) Source: https://elixir.hexdocs.pm/1.20.1/System.md Returns the current monotonic time, converted to the specified time unit. The time starts at an unspecified point and is monotonically increasing. ```elixir @spec monotonic_time(time_unit() | :native) :: integer() ``` -------------------------------- ### Select keys from a registry Source: https://elixir.hexdocs.pm/1.20.1/Registry.md This example shows how to extract only the keys from a registry using a match spec that selects the first element of the entry tuple. The registry must be started and populated. ```elixir iex> Registry.start_link(keys: :unique, name: Registry.SelectKeysTest) iex> {:ok, _} = Registry.register(Registry.SelectKeysTest, "hello", :value) iex> {:ok, _} = Registry.register(Registry.SelectKeysTest, "world", :value) iex> Registry.select(Registry.SelectKeysTest, [{{:"$1", :_, :_}, [], [:"$1"]}] ) |> Enum.sort() ["hello", "world"] ```