### Example Key-Value Store Commands Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/introduction-to-mix.md Demonstrates basic commands for a distributed key-value store, including creating buckets, putting and getting key-value pairs, and deleting entries. ```text CREATE shopping OK PUT shopping milk 1 OK PUT shopping eggs 3 OK GET shopping milk 1 OK DELETE shopping eggs OK ``` -------------------------------- ### Elixir GenServer Process Linking Example Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/genservers.md Demonstrates starting a process with spawn_link and its behavior when the spawned process completes successfully. ```elixir iex> self() #PID<0.115.0> iex> spawn_link(fn -> :nothing_bad_will_happen end) #PID<0.116.0> iex> self() #PID<0.115.0> ``` -------------------------------- ### Interacting with a Supervised Registry in IEx Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/supervisor-and-application.md Demonstrates how to interact with a process (KV.Bucket) that has been started as part of an application's supervision tree. This example assumes the registry and bucket are already supervised. ```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 ``` -------------------------------- ### Start Distributed Elixir Nodes Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/config-and-distribution.md Example commands to start two Elixir nodes with specific names and ports, demonstrating how to set the NODES environment variable for inter-node communication. ```bash $ NODES="foo@computer-name,bar@computer-name" PORT=4040 iex --sname foo -S mix $ NODES="foo@computer-name,bar@computer-name" PORT=4041 iex --sname bar -S mix ``` -------------------------------- ### Start DynamicSupervisor and Child Processes Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/dynamic-supervisor.md Demonstrates starting a DynamicSupervisor and then dynamically starting a child process, followed by interacting with it. ```elixir iex> {:ok, sup_pid} = DynamicSupervisor.start_link(strategy: :one_for_one) iex> DynamicSupervisor.start_child(sup_pid, {KV.Bucket, name: :another_list}) iex> KV.Bucket.put(:another_list, "milk", 1) iex> KV.Bucket.get(:another_list, "milk") ``` -------------------------------- ### Example Usage of Centralized Agent Module Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/anti-patterns/process-anti-patterns.md Demonstrates how to start an Agent via `Foo.Bucket`, add shared values, and access them using the module's functions. ```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 ``` -------------------------------- ### Supervised Process Application Setup Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/anti-patterns/process-anti-patterns.md Refactors the Counter process to be started within a supervision tree using `Supervisor.start_link/2`. This ensures proper lifecycle management and ordered startup/shutdown. ```elixir defmodule SupervisedProcess.Application do use Application @impl true def start(_type, _args) do children = [ # With the default values for counter and name Counter, # With custom values for counter, name, and a custom ID Supervisor.child_spec( {Counter, name: :other_counter, initial_value: 15}, id: :other_counter ) ] Supervisor.start_link(children, strategy: :one_for_one, name: App.Supervisor) end end ``` -------------------------------- ### Start and use KV.Bucket with named processes Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/supervisor-and-application.md Demonstrates starting a KV.Bucket with a name registered via Registry and performing basic operations. ```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 ``` ```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 ``` -------------------------------- ### Start KV Server with Task Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/task-and-gen-tcp.md Integrates `KV.Server.accept/1` as a task within the application's supervision tree to start it automatically on boot. ```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 ``` -------------------------------- ### Start Link with Keyword List Options Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/references/typespecs.md Demonstrates starting a GenServer link with a list of options, splitting them into module-specific and GenServer options. Ensures only defined options are passed. ```elixir @type option :: {:my_option, String.t()} | GenServer.option() @spec start_link([option()]) :: GenServer.on_start() def start_link(opts) do {my_opts, gen_server_opts} = Keyword.split(opts, [:my_option]) GenServer.start_link(__MODULE__, my_opts, gen_server_opts) end ``` -------------------------------- ### Start Named DynamicSupervisor and Child Processes Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/dynamic-supervisor.md Shows how to start a DynamicSupervisor with a name and then dynamically start a child process using the supervisor's name. ```elixir iex> DynamicSupervisor.start_link(strategy: :one_for_one, name: :dyn_sup) iex> name = {:via, Registry, {"yet_another_list"}} iex> DynamicSupervisor.start_child(:dyn_sup, {KV.Bucket, name: name}) iex> KV.Bucket.put(name, "milk", 1) iex> KV.Bucket.get(name, "milk") ``` -------------------------------- ### Implement Application Start Callback Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/supervisor-and-application.md Implements the `start/2` callback for an application. This function 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 ``` -------------------------------- ### Starting and interacting with a supervised KV.Bucket Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/dynamic-supervisor.md Starts a KV.Bucket as a supervised child and demonstrates basic put/get operations. ```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 ``` -------------------------------- ### Ensure Application and Dependencies are Started Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/supervisor-and-application.md Ensures that an application and all its dependencies are started. This is useful when an application fails to start due to missing dependencies. ```elixir iex> Application.ensure_all_started(:kv) {:ok, [:logger, :kv]} ``` -------------------------------- ### Start two release nodes with IEx Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/releases.md Starts two instances of a release, each with a different node name and port, and connects them to IEx. Adjust `@computer-name` to your actual computer name. ```bash $ NODES="foo@computer-name,bar@computer-name" PORT=4040 RELEASE_NODE="foo" bin/kv start_iex ``` ```bash $ NODES="foo@computer-name,bar@computer-name" PORT=4041 RELEASE_NODE="bar" bin/kv start_iex ``` -------------------------------- ### Start IEx with Project Dependencies Source: https://github.com/elixir-lang/elixir/wiki/FAQ Use this command to launch an interactive Elixir shell (IEx) with your project and its dependencies loaded and started. Navigate to your project's directory first. ```bash iex -S mix ``` -------------------------------- ### Start an Elixir Application Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/supervisor-and-application.md Demonstrates starting an Elixir application. If the application is already running, it returns an error. ```elixir iex> Application.start(:kv) {:error, {:already_started, :kv}} ``` -------------------------------- ### Interacting with the KV Process Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/getting-started/processes.md Demonstrates starting the KV process, sending messages to get and put data, and flushing the inbox to retrieve results. Shows initial nil return and subsequent data retrieval. ```elixir 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 ``` ```elixir iex> send(pid, {:put, :hello, :world}) {:put, :hello, :world} iex> send(pid, {:get, :hello, self()}) {:get, :hello, #PID<0.41.0>} iex> flush() :world :ok ``` -------------------------------- ### Starting Processes with a Supervisor in Elixir Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/supervisor-and-application.md This is the recommended way to start processes in Elixir. Child specifications are provided to the supervisor, which then manages their lifecycle. ```elixir def start(_type, _args) do children = [ {Registry, name: KV, keys: :unique} ] Supervisor.start_link(children, strategy: :one_for_one) end ``` -------------------------------- ### GenServer init Callback Example Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/genservers.md Initializes the GenServer state. It receives initial arguments and returns an {:ok, state} tuple. ```elixir def init(bucket) do state = %{ bucket: bucket } {:ok, state} end ``` -------------------------------- ### Add Comprehensive Doctests for Parsing Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/docs-tests-and-with.md Expands the documentation string with more doctest examples covering various commands (CREATE, PUT, GET, DELETE) and edge cases like extra whitespace and unknown commands. This ensures robust testing of the parsing logic. ```elixir @doc ~S""" Parses the given `line` into a command. ## Examples iex> KV.Command.parse "CREATE shopping\r\n" {:ok, {:create, "shopping"}} iex> KV.Command.parse "CREATE shopping \r\n" {:ok, {:create, "shopping"}} iex> KV.Command.parse "PUT shopping milk 1\r\n" {:ok, {:put, "shopping", "milk", "1"}} iex> KV.Command.parse "GET shopping milk\r\n" {:ok, {:get, "shopping", "milk"}} iex> KV.Command.parse "DELETE shopping eggs\r\n" {:ok, {:delete, "shopping", "eggs"}} Unknown commands or commands with the wrong number of arguments return an error: iex> KV.Command.parse "UNKNOWN shopping eggs\r\n" {:error, :unknown_command} iex> KV.Command.parse "GET shopping\r\n" {:error, :unknown_command} """ ``` -------------------------------- ### Install Neofetch on WSL Source: https://github.com/elixir-lang/elixir/wiki/Windows These commands are used within the WSL bash environment to add a PPA, update package lists, and install the neofetch utility. ```bash $ sudo add-apt-repository ppa:dawidd0811/neofetch && sudo apt update && sudo apt install neofetch -y $ neofetch ``` -------------------------------- ### Telnet Client Interaction Example Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/task-and-gen-tcp.md Demonstrates connecting to a server via telnet to test functionality and observe behavior under load. ```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 ``` ```console $ telnet 127.0.0.1 4040 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. hello hello? HELLOOOOOO? ``` -------------------------------- ### Starting Counter Agent Outside Supervision Tree Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/anti-patterns/process-anti-patterns.md Demonstrates how to start and interact with the Counter Agent when it is not managed by a supervision tree. Note that this approach lacks robust lifecycle management. ```elixir iex> Counter.start_link() {:ok, #PID<0.115.0>} iex> Counter.bump(13) 0 iex> Counter.get() 13 ``` -------------------------------- ### Start ExUnit test framework Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/introduction-to-mix.md This line starts the ExUnit test framework. It's typically placed in test/test_helper.exs and required by Mix before running tests. ```elixir ExUnit.start() ``` -------------------------------- ### Start KV.Bucket with a name Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/agents.md Starts a KV.Bucket agent with a specific name, allowing interaction via the name instead of PID. Useful for testing. ```elixir test "stores values by key on a named process" do {:ok, _} = KV.Bucket.start_link(name: :shopping_list) assert KV.Bucket.get(:shopping_list, "milk") == nil KV.Bucket.put(:shopping_list, "milk", 3) assert KV.Bucket.get(:shopping_list, "milk") == 3 end ``` -------------------------------- ### Starting Elixir Nodes Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/config-and-distribution.md Start two separate Elixir nodes with distinct names for distributed testing. ```console $ PORT=4100 iex --sname foo -S mix ``` ```console $ PORT=4101 iex --sname bar -S mix ``` -------------------------------- ### KV Application with DynamicSupervisor Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/dynamic-supervisor.md Defines the KV application's start callback to include a Registry and a DynamicSupervisor for managing buckets. ```elixir defmodule KV do use Application @impl true def start(_type, _args) do children = [ {Registry, name: KV, keys: :unique}, {DynamicSupervisor, name: KV.BucketSupervisor, strategy: :one_for_one} ] Supervisor.start_link(children, strategy: :one_for_one) end @doc """ Creates a bucket with the given name. """ def create_bucket(name) do DynamicSupervisor.start_child(KV.BucketSupervisor, {KV.Bucket, name: via(name)}) end @doc """ Looks up the given bucket. """ def lookup_bucket(name) do GenServer.whereis(via(name)) end defp via(name), do: {:via, Registry, {KV, name}} end ``` -------------------------------- ### Create a named bucket Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/dynamic-supervisor.md Example of creating a named bucket, which will spawn a new process that can be observed in the Observer tool. ```elixir iex> KV.create_bucket("shopping") #PID<0.89.0> ``` -------------------------------- ### Elixir Map module functions Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/getting-started/keywords-and-maps.md Provides examples of using convenience functions from the `Map` module, such as `get`, `put`, and `to_list`, for map manipulation. ```elixir iex> Map.get(%{:a => 1, 2 => :b}, :a) 1 iex> Map.put(%{:a => 1, 2 => :b}, :c, 3) %{2 => :b, :a => 1, :c => 3} iex> Map.to_list(%{:a => 1, 2 => :b}) [{2, :b}, {:a, 1}] ``` -------------------------------- ### GenServer KV.Bucket Implementation Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/genservers.md Defines a GenServer module for a key-value bucket. Includes functions for starting the bucket and performing get, put, and delete operations. ```elixir defmodule KV.Bucket do use GenServer @doc """ Starts a new bucket. """ def start_link(opts) do GenServer.start_link(__MODULE__, %{}, opts) end @doc """ Gets a value from the `bucket` by `key`. """ def get(bucket, key) do GenServer.call(bucket, {:get, key}) end @doc """ Puts the `value` for the given `key` in the `bucket`. """ def put(bucket, key, value) do GenServer.call(bucket, {:put, key, value}) end @doc """ Deletes `key` from `bucket`. Returns the current value of `key`, if `key` exists. """ def delete(bucket, key) do GenServer.call(bucket, {:delete, key}) end ### Callbacks @impl true def init(bucket) do state = %{ bucket: bucket } {:ok, state} end @impl true def handle_call({:get, key}, _from, state) do value = get_in(state.bucket[key]) {:reply, value, state} end def handle_call({:put, key, value}, _from, state) do state = put_in(state.bucket[key], value) {:reply, :ok, state} end def handle_call({:delete, key}, _from, state) do {value, state} = pop_in(state.bucket[key]) {:reply, value, state} end end ``` -------------------------------- ### KV.Bucket Module Implementation Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/agents.md Implements the KV.Bucket module using Elixir's Agent, providing functions to start, get, and put key-value pairs. ```elixir defmodule KV.Bucket do use Agent @doc """ Starts a new bucket. All options are forwarded to `Agent.start_link/2`. """ def start_link(opts) do Agent.start_link(fn -> %{} end, opts) end @doc """ Gets a value from the `bucket` by `key`. """ def get(bucket, key) do Agent.get(bucket, &Map.get(&1, key)) end @doc """ Puts the `value` for the given `key` in the `bucket`. """ def put(bucket, key, value) do Agent.update(bucket, &Map.put(&1, key, value)) end end ``` -------------------------------- ### Elixir Counter Agent Implementation Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/anti-patterns/process-anti-patterns.md Defines a Counter module using Agent to maintain a numerical 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 ``` -------------------------------- ### GenServer handle_call Callback Example Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/genservers.md Handles synchronous calls to the GenServer. It processes requests for getting, putting, or deleting key-value pairs from the server's state. ```elixir def handle_call({:get, key}, _from, state) do value = get_in(state.bucket[key]) {:reply, value, state} end def handle_call({:put, key, value}, _from, state) do state = put_in(state.bucket[key], value) {:reply, :ok, state} end def handle_call({:delete, key}, _from, state) do {value, state} = pop_in(state.bucket[key]) {:reply, value, state} end ``` -------------------------------- ### Initialize release configuration files Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/releases.md Generates template files for release configuration, including `vm.args.eex`, `remote.vm.args.eex`, `env.sh.eex`, and `env.bat.eex`. ```bash $ mix release.init ``` -------------------------------- ### Elixir Key-Value Store Process Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/getting-started/processes.md Defines a module that starts a process to act as a key-value store. The process loops, receiving messages to get or put data into an internal map. ```elixir defmodule KV do def start_link do Task.start_link(fn -> loop(%{}) end) end defp loop(map) do receive do {:get, key, caller} -> send(caller, Map.get(map, key)) loop(map) {:put, key, value} -> loop(Map.put(map, key, value)) end end end ``` -------------------------------- ### Process files in directories using multiple generators Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/getting-started/comprehensions.md Comprehensions can handle multiple generators and intermediate variable assignments. This example gets the size of regular files in specified directories. ```elixir dirs = ["/home/mikey", "/home/james"] for dir <- dirs, file <- File.ls!(dir), path = Path.join(dir, file), File.regular?(path) do File.stat!(path).size end ``` -------------------------------- ### Initial Server Implementation Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/docs-tests-and-with.md The initial implementation of the server's serve, read_line, and write_line functions before using `with`. ```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 ``` -------------------------------- ### Start supervised processes in tests Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/dynamic-supervisor.md Use `start_supervised` to start processes within a test-specific supervision tree. This ensures that any started process is shut down at the end of the test. ```elixir defmodule KV.BucketTest do use ExUnit.Case, async: true test "stores values by key" do {:ok, bucket} = start_supervised(KV.Bucket) assert KV.Bucket.get(bucket, "milk") == nil KV.Bucket.put(bucket, "milk", 3) assert KV.Bucket.get(bucket, "milk") == 3 end test "stores values by key on a named process", config do {:ok, _} = start_supervised({KV.Bucket, name: config.test}) assert KV.Bucket.get(config.test, "milk") == nil KV.Bucket.put(config.test, "milk", 3) assert KV.Bucket.get(config.test, "milk") == 3 end end ``` -------------------------------- ### Atom Identifier Start Characters Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/references/unicode-syntax.md Shows that atoms additionally include the underscore character '_' in their starting set. ```elixir _ (005F) ``` -------------------------------- ### Basic Agent Operations in IEx Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/agents.md Demonstrates starting an agent with an initial state, updating its state, retrieving the state, and stopping the agent. ```elixir iex> {:ok, agent} = Agent.start_link(fn -> [] end) iex> Agent.update(agent, fn list -> ["eggs" | list] end) iex> Agent.get(agent, fn list -> list end) iex> Agent.stop(agent) ``` -------------------------------- ### Elixir Match Operator Example Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/references/patterns-and-guards.md An example showing the basic usage of the match operator (`=`) for assignment, noting that it does not support guards. ```elixir {:ok, binary} = File.read("some/file") ``` -------------------------------- ### Assemble a Production Release Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/releases.md Use `mix release` with `MIX_ENV=prod` to create a production-ready release. The output indicates the release path and provides commands to start, stop, and connect to the running system. ```bash MIX_ENV=prod mix release Compiling 4 files (.ex) Generated kv app * assembling kv-0.1.0 on MIX_ENV=prod * using config/runtime.exs to configure the release at runtime Release created at _build/prod/rel/kv # To start your system _build/prod/rel/kv/bin/kv start Once the release is running: # To connect to it remotely _build/prod/rel/kv/bin/kv remote # To stop it gracefully (you may also send SIGINT/SIGTERM) _build/prod/rel/kv/bin/kv stop To list all commands: _build/prod/rel/kv/bin/kv ``` -------------------------------- ### Unicode Categories for Identifier Start Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/references/unicode-syntax.md Specifies the Unicode General Categories and specific code points that constitute the start of an Elixir identifier. ```regex [\p{L}\p{Nl}\p{Other_ID_Start}-\p{Pattern_Syntax}-\p{Pattern_White_Space}] ``` -------------------------------- ### Build Elixir Documentation with ExDoc Source: https://github.com/elixir-lang/elixir/blob/main/CONTRIBUTING.md Installs ExDoc and compiles Elixir alongside it to generate HTML and EPUB documentation. Ensure Elixir is cloned and compiled before running. ```shell elixir_dir=$(pwd) cd .. && git clone https://github.com/elixir-lang/ex_doc.git cd ex_doc && "${elixir_dir}/bin/elixir" "${elixir_dir}/bin/mix" do deps.get + compile # Now we will go back to Elixir's root directory, cd "${elixir_dir}" # and generate HTML and EPUB documents: make docs ``` -------------------------------- ### Starting a Task with Task.start/1 Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/getting-started/processes.md Introduces `Task.start/1` for creating processes with better error reporting and introspection than basic `spawn/1`. It returns `{:ok, pid}` and provides enhanced error messages upon failure. ```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: [] ``` -------------------------------- ### Rounding and Truncating Floats in Elixir Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/getting-started/basic-types.md Demonstrates using `round` to get the closest integer and `trunc` to get the integer part of a float. ```elixir iex> round(3.58) 4 iex> trunc(3.58) 3 ``` -------------------------------- ### Starting the Observer Tool Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/getting-started/debugging.md Launch the Erlang Observer tool from IEx to inspect the virtual machine, processes, and applications. Ensure the `:observer` application is available. ```elixir iex> :observer.start() ``` -------------------------------- ### Variable Identifier Start Characters Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/references/unicode-syntax.md Illustrates the specific Unicode categories and characters allowed at the start of Elixir variables, excluding uppercase and titlecase letters. ```regex [\u{005F}\p{Ll}\p{Lm}\p{Lo}\p{Nl}\p{Other_ID_Start}-\p{Pattern_Syntax}-\p{Pattern_White_Space}] ``` -------------------------------- ### Elixir Directives: alias, require, import, use Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/getting-started/alias-require-and-import.md Demonstrates the basic syntax for alias, require, import, and use directives in Elixir. ```elixir # Alias the module so it can be called as Bar instead of Foo.Bar alias Foo.Bar, as: Bar # Require the module in order to use its macros require Foo # Import functions from Foo so they can be called without the `Foo.` prefix import Foo # Invokes the custom code defined in Foo as an extension point use Foo ``` -------------------------------- ### Elixir IEx Examples for Refactored Functions Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/anti-patterns/design-anti-patterns.md These examples demonstrate the usage of the refactored `AlternativeInteger.parse/1` and `AlternativeInteger.parse_discard_rest/1` functions, showing their distinct and predictable return types. ```elixir iex> AlternativeInteger.parse("13") {13, ""} iex> AlternativeInteger.parse_discard_rest("13") 13 ``` -------------------------------- ### Creating and Comparing Bitstrings Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/getting-started/binaries-strings-and-charlists.md Demonstrates the creation of bitstrings with default 8-bit size and explicit bit sizes. Shows how values are truncated if they exceed the provisioned bits. ```elixir iex> <<42>> == <<42::8>> true ``` ```elixir iex> <<3::4>> <<3::size(4)>> ``` ```elixir iex> <<0::1, 0::1, 1::1, 1::1>> == <<3::4>> true ``` ```elixir iex> <<1>> == <<257>> true ``` -------------------------------- ### Elixir IEx Examples for Alternative Return Types Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/anti-patterns/design-anti-patterns.md These examples show how the `AlternativeInteger.parse/2` function behaves with different options, illustrating the alternative return types. ```elixir iex> AlternativeInteger.parse("13") {13, ""} iex> AlternativeInteger.parse("13", discard_rest: false) {13, ""} iex> AlternativeInteger.parse("13", discard_rest: true) 13 ``` -------------------------------- ### Start the Observer tool Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/dynamic-supervisor.md Launch the Observer tool, which ships with Erlang, to inspect running applications, supervision trees, and processes. Ensure the `:observer` application is available. ```elixir iex> :observer.start() ``` ```elixir iex> Mix.ensure_application!(:observer) iex> :observer.start() ``` -------------------------------- ### Module with Documentation and Function Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/getting-started/module-attributes.md This example demonstrates defining module documentation using a heredoc and documenting a function with @doc. The module can be compiled and its documentation accessed. ```elixir defmodule Math do @moduledoc """ Provides math-related functions. ## Examples iex> Math.sum(1, 2) 3 """ @doc """Calculates the sum of two numbers.""" def sum(a, b), do: a + b ``` -------------------------------- ### Doctest Example with Multiple Lines Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/docs-tests-and-with.md Illustrates how multiple `iex>` prompts on consecutive lines within a documentation string are treated as separate doctests. Each prompt initiates a new test case. ```elixir iex> KV.Command.parse("UNKNOWN shopping eggs\r\n") {:error, :unknown_command} iex> KV.Command.parse("GET shopping\r\n") {:error, :unknown_command} ``` -------------------------------- ### Elixir GenServer Process Monitoring Example Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/genservers.md Shows how to monitor a process using Process.monitor and receive a DOWN message when the monitored process terminates normally after a delay. ```elixir iex> pid = spawn(fn -> Process.sleep(5000) end) #PID<0.119.0> iex> Process.monitor(pid) #Reference<0.1076459149.2159017989.118674> iex> flush() :ok # Wait five seconds iex> flush() {:DOWN, #Reference<0.1076459149.2159017989.118674>, :process, #PID<0.119.0>, :normal} :ok ``` -------------------------------- ### Non-Imported Functions Starting with Underscore in Elixir Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/references/naming-conventions.md Functions starting with an underscore are not imported by default. This is useful for defining helper functions or internal module functions that should not be directly accessible. ```elixir iex> defmodule Example do ...> def _wont_be_imported do ...> :oops ...> end ...> ...> ...> end iex> import Example iex> _wont_be_imported() ** (CompileError) iex:1: undefined function _wont_be_imported/0 ``` -------------------------------- ### Incorrect Process Start in Elixir Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/supervisor-and-application.md Avoid starting processes directly within the `start/2` callback without a supervisor. This approach bypasses Elixir's fault-tolerance mechanisms. ```elixir def start(_type, _args) do Registry.start_link(name: KV, keys: :unique) Supervisor.start_link([], strategy: :one_for_one) end ``` -------------------------------- ### Library Configuration via Application Environment (config.exs) Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/anti-patterns/design-anti-patterns.md Example of how a library might configure itself using the application environment in config.exs. Avoid this pattern for library configuration. ```elixir import Config config :app_config, parts: 3 import_config "#{config_env()}.exs" ``` -------------------------------- ### Start KV.Bucket with a test-specific name Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/agents.md Starts a KV.Bucket agent using a test-specific name derived from the test context. This avoids name collisions in concurrent test runs. ```elixir test "stores values by key on a named process", config do {:ok, _} = KV.Bucket.start_link(name: config.test) assert KV.Bucket.get(config.test, "milk") == nil KV.Bucket.put(config.test, "milk", 3) assert KV.Bucket.get(config.test, "milk") == 3 end ``` -------------------------------- ### Release Management Commands Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/releases.md Interact with your assembled release using various commands provided by the release's entry point script. These commands cover starting, stopping, remote access, and evaluation. ```bash _build/prod/rel/kv/bin/kv start ``` ```bash _build/prod/rel/kv/bin/kv start_iex ``` ```bash _build/prod/rel/kv/bin/kv restart ``` ```bash _build/prod/rel/kv/bin/kv stop ``` ```bash _build/prod/rel/kv/bin/kv rpc COMMAND ``` ```bash _build/prod/rel/kv/bin/kv remote ``` ```bash _build/prod/rel/kv/bin/kv eval COMMAND ``` ```bash _build/prod/rel/kv/bin/kv daemon ``` ```bash _build/prod/rel/kv/bin/kv daemon_iex ``` ```bash _build/prod/rel/kv/bin/kv install ``` ```bash _build/prod/rel/kv/bin/kv ``` -------------------------------- ### List All Available Mix Tasks Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/mix-and-otp/introduction-to-mix.md Invoke the `mix help` task to display a comprehensive list of all available Mix tasks. This is useful for discovering Mix's capabilities. ```bash $ mix help ``` -------------------------------- ### Module and Function Documentation with Attributes Source: https://github.com/elixir-lang/elixir/blob/main/lib/elixir/pages/getting-started/writing-documentation.md Use `@moduledoc` for module documentation and `@doc` for function documentation. Includes examples of `since` metadata and doctests. ```elixir defmodule MyApp.Hello do @moduledoc """ This is the Hello module. """ @moduledoc since: "1.0.0" @doc """ Says hello to the given `name`. Returns `:ok`. ## Examples iex> MyApp.Hello.world(:john) :ok """ @doc since: "1.3.0" def world(name) do IO.puts("hello #{name}") end end ```