Added redirect after saving memory.

Added redirect after saving memory.

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/inchingforward/monument.git/'


Use longform names for calendar calls

Use longform names for calendar calls

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/evercam/evercam-media.git/'


Wrap camera update in try/catch

Wrap camera update in try/catch


Chapter 14 answers

Chapter 14 answers

In the pmap code, I assigned the value of self to the variable me at the top of the method and then used me as the target of the message returned by the spawned processes. Why use a separate variable here?

Because the self in the fn passed to spawn_link, when evaluated, will
refer to the spawned process pid, not to the parent pid

error: pathspec 'WorkingWithMultipleProcesses/14.6.exs' did not match any file(s) known to git


Disable lazy database connections

Disable lazy database connections


Change the snapshot timestamp endpoint to require notes param

This enables us to avoid acessing the database when doing the lookup.


Keep checking the camera if it's online and returns an error

This is useful when the camera isn't set to record, it will continue
checking in the background until it either gets a successful snapshot
or determines that the camera is actually offline. This is done even
if the user closes the live view.


plain old fizzbuzz... in elixir... love the economy.

defmodule FizzBuzz do

  def fizzbuzz(n) when is_integer(n), do: fizzbuzz(n, {rem(n,3), rem(n,5)})
  def fizzbuzz(_, {0,0}), do: :fizzbuzz
  def fizzbuzz(_, {0,_}), do: :fizz
  def fizzbuzz(_, {_,0}), do: :buzz
  def fizzbuzz(n, {_,_}), do: n

  def run(i \\ 100), do: (1..i) |> Enum.map(&fizzbuzz/1)

end

IO.inspect FizzBuzz.run

error: pathspec 'fizzbuzz.exs' did not match any file(s) known to git


add context plug to employee_requests list endpoint (#796)

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/edenlabllc/ehealth.api.git/'


revert: get id instead party_id

revert: get id instead party_id


Added Dash2 link in Users report

Added Dash2 link in Users report

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/evercam/evercam-admin.git/'


Add test for proposed new check AliasOrder

defmodule Credo.Check.Readability.AliasOrderTest do
  use Credo.TestHelper

  @described_check Credo.Check.Readability.AliasOrder

  @moduletag :to_be_implemented

  #
  # cases NOT raising issues
  #

  test "it should NOT report violation" do
    """
    defmodule Test do
      alias App.Module1
      alias App.Module2
      alias Credo.CLI.Command
      alias Credo.CLI.Filename
      alias Credo.CLI.Sorter
    end
    """
    |> to_source_file
    |> refute_issues(@described_check)
  end

  test "it should NOT report violation for independent blocks of alpha-ordered aliases" do
    """
    defmodule Test do
      alias Credo.CLI.Command
      alias Credo.CLI.Filename
      alias Credo.CLI.Sorter

      alias App.Module1
      alias App.Module2
    end
    """
    |> to_source_file
    |> refute_issues(@described_check)
  end

  test "it should work with __MODULE__" do
    """
    defmodule Test do
      alias __MODULE__.SubModule

      alias Credo.CLI.Command
      alias Credo.CLI.Filename
      alias Credo.CLI.Sorter
    end
    """
    |> to_source_file
    |> refute_issues(@described_check)
  end

  #
  # cases raising issues
  #

  test "it should report a violation" do
    """
    defmodule CredoSampleModule do
      alias Credo.CLI.Sorter
      alias Credo.CLI.Command
      alias Credo.CLI.Filename
    end
    """
    |> to_source_file
    |> assert_issue(@described_check)
  end

  test "it should report a violation /2" do
    """
    defmodule CredoSampleModule do
      alias Credo.CLI.Command
      alias Credo.CLI.Filename
      alias Credo.CLI.Sorter

      alias App.Module2
      alias App.Module1
    end
    """
    |> to_source_file
    |> assert_issue(@described_check)
  end
end

error: pathspec 'test/credo/check/readability/alias_order_test.exs' did not match any file(s) known to git


Increment version [ci skip]

Increment version [ci skip]


Fix for MarcoPolo failure to list deps in applications

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/Remesh/ex_orient.git/'


pun_in

nested = %{
  buttercup: %{
    actor: %{
      first: "Robin",
      last: "Wright"
    },
    role: "princess"
  },
  westley: %{
    actor: %{
      first: "Carey",
      last: "Ewes"
    },
    role: "farm boy"
  }
}

IO.inspect get_in(nested, [:buttercup])

IO.inspect get_in(nested, [:buttercup, :actor])

IO.inspect get_in(nested, [:buttercup, :actor, :first])

error: pathspec 'elixir/119.exs' did not match any file(s) known to git


Added error message on invalid token

Added error message on invalid token


Added new recording cameras

Added new recording cameras

defmodule Camera do
  use Ecto.Model

  schema "cameras" do
    belongs_to :owner, User, foreign_key: :owner_id
    belongs_to :vendor_model, VendorModel, foreign_key: :model_id
    has_many :camera_shares, CameraShare
    has_many :snapshots, Snapshot

    field :exid, :string
    field :is_online, :boolean
    field :config, EvercamMedia.Types.JSON
    field :last_polled_at, Ecto.DateTime, default: Ecto.DateTime.utc
    field :last_online_at, Ecto.DateTime, default: Ecto.DateTime.utc
    field :updated_at, Ecto.DateTime, default: Ecto.DateTime.utc
    field :created_at, Ecto.DateTime, default: Ecto.DateTime.utc
  end

  def by_exid(camera_id) do
    from cam in Camera,
    where: cam.exid == ^camera_id,
    select: cam
  end

  def by_exid_with_owner(camera_id) do
    from cam in Camera,
    where: cam.exid == ^camera_id,
    select: cam,
    preload: :owner
  end

  def limit(count) do
    from cam in Camera,
    limit: ^count
  end

  def external_url(camera, type \\ "http") do
    host = camera.config["external_host"] |> to_string
    port = camera.config["external_#{type}_port"] |> to_string
    camera_url(host, port, type)
  end

  defp camera_url("", port, type) do
    nil
  end

  defp camera_url(host, "", type) do
    "#{type}://#{host}"
  end

  defp camera_url(host, port, type) do
    "#{type}://#{host}:#{port}"
  end

  def auth(camera) do
    "#{camera.config["auth"]["basic"]["username"]}:#{camera.config["auth"]["basic"]["password"]}"
  end

  def res_url(camera, type \\ "jpg") do
    url = "#{camera.config["snapshots"][type]}"
    if String.starts_with?(url, "/") || String.length(url) == 0 do
      "#{url}"
    else
      "/#{url}"
    end
  end

  def recording?(camera) do
    recording_cameras = [
      "beefcam1",
      "beefcam2",
      "beefcammobile",
      "bennett",
      "carrollszoocam",
      "centralbankbuild",
      "dancecam",
      "dcctestdumpinghk",
      "devilsbitcidercam",
      "evercam-remembrance-camera",
      "gemcon-cathalbrugha",
      "gpocam",
      "hw-hack-auditorium",
      "landing-zone-backdoor",
      "landing-zone-front",
      "mac1",
      "mac2",
      "pch-hackcam1",
      "pch-hackcam2",
      "smartcity1",
      "stephens-green",
      "treacyconsulting1",
      "treacyconsulting2",
      "treacyconsulting3",
      "wayra-agora",
      "wayra_office",
      "wayrahikvision",
      "zipyard-navan-foh",
      "zipyard-ranelagh-foh"
    ]
    Enum.any?(recording_cameras, &(camera.exid == &1))
  end
end

defmodule Camera do
  use Ecto.Model

  schema "cameras" do
    belongs_to :owner, User, foreign_key: :owner_id
    belongs_to :vendor_model, VendorModel, foreign_key: :model_id
    has_many :camera_shares, CameraShare
    has_many :snapshots, Snapshot

    field :exid, :string
    field :is_online, :boolean
    field :config, EvercamMedia.Types.JSON
    field :last_polled_at, Ecto.DateTime, default: Ecto.DateTime.utc
    field :last_online_at, Ecto.DateTime, default: Ecto.DateTime.utc
    field :updated_at, Ecto.DateTime, default: Ecto.DateTime.utc
    field :created_at, Ecto.DateTime, default: Ecto.DateTime.utc
  end

  def by_exid(camera_id) do
    from cam in Camera,
    where: cam.exid == ^camera_id,
    select: cam
  end

  def by_exid_with_owner(camera_id) do
    from cam in Camera,
    where: cam.exid == ^camera_id,
    select: cam,
    preload: :owner
  end

  def limit(count) do
    from cam in Camera,
    limit: ^count
  end

  def external_url(camera, type \\ "http") do
    host = camera.config["external_host"] |> to_string
    port = camera.config["external_#{type}_port"] |> to_string
    camera_url(host, port, type)
  end

  defp camera_url("", port, type) do
    nil
  end

  defp camera_url(host, "", type) do
    "#{type}://#{host}"
  end

  defp camera_url(host, port, type) do
    "#{type}://#{host}:#{port}"
  end

  def auth(camera) do
    "#{camera.config["auth"]["basic"]["username"]}:#{camera.config["auth"]["basic"]["password"]}"
  end

  def res_url(camera, type \\ "jpg") do
    url = "#{camera.config["snapshots"][type]}"
    if String.starts_with?(url, "/") || String.length(url) == 0 do
      "#{url}"
    else
      "/#{url}"
    end
  end

  def recording?(camera) do
    recording_cameras = [
      "beefcam1",
      "beefcam2",
      "beefcammobile",
      "bennett",
      "carrollszoocam",
      "centralbankbuild",
      "dancecam",
      "dcctestdumpinghk",
      "devilsbitcidercam",
      "evercam-remembrance-camera",
      "gemcon-cathalbrugha",
      "gpocam",
      "hw-hack-auditorium",
      "landing-zone-backdoor",
      "landing-zone-front",
      "pch-hackcam1",
      "pch-hackcam2",
      "smartcity1",
      "stephens-green",
      "treacyconsulting1",
      "treacyconsulting2",
      "treacyconsulting3",
      "wayra-agora",
      "wayra_office",
      "wayrahikvision",
      "zipyard-navan-foh",
      "zipyard-ranelagh-foh"
    ]
    Enum.any?(recording_cameras, &(camera.exid == &1))
  end
end


simplify regex group passing

simplify regex group passing

defmodule WhiteBread.Context.StepExecutor do

  def execute_step({string_steps, regex_steps}, %{text: step_text} = step, state) do
    try do
      if (Dict.has_key?(string_steps, step_text)) do
        function = Dict.fetch!(string_steps, step_text)
        apply(function, [state, []])
      else
        regex_steps |> apply_regex_function(step_text, state)
      end
    rescue
      assertion_error in ExUnit.AssertionError       -> {:assertion_failure, step, assertion_error}
      missing_step in WhiteBread.Context.MissingStep -> {:missing_step, step, missing_step}
      clause_match_error in FunctionClauseError      -> {:no_clause_match, step, clause_match_error}
    end
  end

  defp apply_regex_function(regex_steps, step_text, state) do
    {regex, function} = regex_steps |> find_regex_and_function(step_text)
    extra = WhiteBread.RegexExtension.atom_keyed_named_captures(regex, step_text)
    apply(function, [state, extra])
  end

  defp find_regex_and_function(regex_steps, string) do
    matches = regex_steps
    |> Stream.filter(fn {regex, _} -> Regex.run(regex, string) end)
    |> Enum.take(1)

    case matches do
      [{regex, function}] -> {regex, function}
      []                  -> raise WhiteBread.Context.MissingStep
    end
  end

end

defmodule WhiteBread.Context.StepExecutor do

  def execute_step({string_steps, regex_steps}, %{text: step_text} = step, state) do
    try do
      if (Dict.has_key?(string_steps, step_text)) do
        function = Dict.fetch!(string_steps, step_text)
        apply(function, [state, []])
      else
        regex_steps |> apply_regex_function(step_text, state)
      end
    rescue
      assertion_error in ExUnit.AssertionError       -> {:assertion_failure, step, assertion_error}
      missing_step in WhiteBread.Context.MissingStep -> {:missing_step, step, missing_step}
      clause_match_error in FunctionClauseError      -> {:no_clause_match, step, clause_match_error}
    end
  end

  defp apply_regex_function(regex_steps, step_text, state) do
    {regex, function} = regex_steps |> find_regex_and_function(step_text)
    extra = unless Regex.names(regex) == [] do
      WhiteBread.RegexExtension.atom_keyed_named_captures(regex, step_text)
    else
      []
    end
    apply(function, [state, extra])
  end

  defp find_regex_and_function(regex_steps, string) do
    matches = regex_steps
    |> Stream.filter(fn {regex, _} -> Regex.run(regex, string) end)
    |> Enum.take(1)

    case matches do
      [{regex, function}] -> {regex, function}
      []                  -> raise WhiteBread.Context.MissingStep
    end
  end

end


reader wip.

reader wip.

defmodule Scheme.Reader do
  # 1. ignore lines of pure whitespace
  # 2. print non-lists immediately
  # 3. if the number of ( equal the number of ), then print
  # 4. if the number of ( are greater than ), then recur until they do
  # 5. if the number of ( is less than ), then raise an error.
  def read do
    IO.gets("# ") |> String.strip |> IO.puts

    read
  end

  # Enum.filter(to_char_list("((("), fn (e) -> e == 40 end) |> length
  # Enum.filter(to_char_list("))"), fn (e) -> e == 41 end) |> length
end

error: pathspec 'lib/scheme/reader.ex' did not match any file(s) known to git


Added new factories

Added new factories

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/gtcode/phoenix-trello.git/'


Remove snapshot cleanup module

Remove snapshot cleanup module


Don't save a snapshot record in the database for thumbnails


remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/sharkspeed/dororis.git/'


Decrease Pool size of db connections to 10.


add db

add db

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/wwselleck/Rekrewtor.git/'


Remove test module prefix

Remove test module prefix


no https

no https

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/colbydehart/TrainWhistle.git/'


Create a place for translations from models into view models

defmodule Eecrit.ViewModel do
  def animal(model), do: Map.take(model, [:name, :id])

  def procedure(list) when is_list(list), do: Enum.map(list, &procedure/1)
  def procedure(%Eecrit.OldProcedure{} = model), do: Map.take(model, [:name, :id])
  def procedure(%Ecto.Association.NotLoaded{}), do: []

  def reservation(list) when is_list(list), do: Enum.map(list, &reservation/1)
  def reservation(%Eecrit.OldReservation{} = model) do
    base =
      model
      |> Map.take([:course, :instructor, :time_bits])
      |> Map.put(:date_range, {Ecto.Date.to_iso8601(model.first_date),
                              Ecto.Date.to_iso8601(model.last_date)})
      |> Map.put(:procedures, procedure(model.procedures))
  end
end

error: pathspec 'web/txs/view_model.ex' did not match any file(s) known to git


connection test

connection test

defmodule Romeo.ConnectionTest do
  use ExUnit.Case
  use UserHelper
  use Romeo.XML
  import Romeo.XML

  setup do
    romeo = register_user("romeo")
    juliet = register_user("juliet")
    Application.put_env(:ex_unit, :assert_receive_timeout, 500)
    {:ok, romeo: romeo, juliet: juliet}
  end

  test "connection no TLS", %{romeo: romeo} do
    {:ok, pid} = Romeo.Connection.start_link(romeo)

    assert_receive {:stanza_received, {:xmlstreamstart, "stream:stream", _}}
    assert_receive {:stanza_received, {:xmlel, "stream:features", _, _}}
    assert_receive {:stanza_received, {:xmlel, "success", _, _}}
    assert_receive {:stanza_received, {:xmlstreamstart, "stream:stream", _}}
    assert_receive {:stanza_received, {:xmlel, "stream:features", _, _}}
    assert_receive {:resource_bound, _}, 500
    assert_receive :connection_ready
  end
end

error: pathspec 'test/romeo/connection_test.exs' did not match any file(s) known to git


list and map

list and map

defmodule MyList do
  def map([], _func), do: []
  def map([head|tail], func), do: [func.(head) | map(tail, func)]
end

IO.inspect MyList.map [1,2,3,4], fn(n) -> n * n end

error: pathspec 'elixir/103.exs' did not match any file(s) known to git


Moved everything to the API section

Moved everything to the API section

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/WilliamRobertCodes/fbclone.git/'


fix medication_request list filters

fix medication_request list filters


Add GoalController.index_html test

Add GoalController.index_html test

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/babie/goal-server.git/'


[patch] Add status for GetDeclarationsList (1808)


Update prod config for Heroku.

Update prod config for Heroku.

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/futhr/fux.git/'


Add support for variable length arguments

defmodule Mal.Env do
  def initialize(outer \\ nil, binds \\ [], exprs \\ [])
  def initialize(outer, binds, exprs) do
    {:ok, pid} = Agent.start_link(fn ->
      %{outer: outer, env: %{}}
    end)

    set_bindings(pid, binds, exprs)
  end

  defp set_bindings(pid, [], []), do: pid
  defp set_bindings(pid, ["&", key], exprs) do
    set(pid, key, exprs)
    pid
  end

  defp set_bindings(pid, [key | binds], [value | exprs]) do
    set(pid, key, value)
    set_bindings(pid, binds, exprs)
  end

  def set(pid, key, value) do
    Agent.update(pid, fn map ->
      %{map | :env => Map.put(map.env, key, value)}
    end)
  end

  def merge(pid, env_values) do
    Agent.update(pid, fn map ->
      %{map | :env => Map.merge(map.env, env_values)}
    end)
  end

  def find(pid, key) do
    Agent.get(pid, fn map ->
      case Map.has_key?(map.env, key) do
        true -> pid
        false -> map.outer && find(map.outer, key)
      end
    end)
  end

  def retrieve_key(pid, key) do
    Agent.get(pid, fn map ->
      case Map.fetch(map.env, key) do
        {:ok, value} -> {:ok, value}
        :error -> :not_found
      end
    end)
  end

  def get(pid, key) do
    case find(pid, key) do
      nil -> :not_found
      env -> retrieve_key(env, key)
    end
  end
end

defmodule Mal.Env do
  def initialize(outer \\ nil, binds \\ [], exprs \\ [])
  def initialize(outer, binds, exprs) do
    {:ok, pid} = Agent.start_link(fn ->
      %{outer: outer, env: %{}}
    end)

    Enum.zip(binds, exprs)
      |> Enum.map(fn {key, value} -> set(pid, key, value) end)

    pid
  end

  def set(pid, key, value) do
    Agent.update(pid, fn map ->
      %{map | :env => Map.put(map.env, key, value)}
    end)
  end

  def merge(pid, env_values) do
    Agent.update(pid, fn map ->
      %{map | :env => Map.merge(map.env, env_values)}
    end)
  end

  def find(pid, key) do
    Agent.get(pid, fn map ->
      case Map.has_key?(map.env, key) do
        true -> pid
        false -> map.outer && find(map.outer, key)
      end
    end)
  end

  def retrieve_key(pid, key) do
    Agent.get(pid, fn map ->
      case Map.fetch(map.env, key) do
        {:ok, value} -> {:ok, value}
        :error -> :not_found
      end
    end)
  end

  def get(pid, key) do
    case find(pid, key) do
      nil -> :not_found
      env -> retrieve_key(env, key)
    end
  end
end


Fix program_medication fix for mrr

Fix program_medication fix for mrr


Task to associate company with user

Task to associate company with user

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/evercam/evercam-media.git/'


Add 'remove_duplicate_history' script

Add 'remove_duplicate_history' script

# Due to restarts there is a chance for multiple language history points to
# exist for the same date. They are redundant and slow down getting the history
# page. This script remove the duplicates.

defmodule HistoryDuplicatesCleaner do
  alias Krihelinator.{Repo, LanguageHistory}
  require Logger

  @moduledoc """
  A module to organize the duplication cleaning functions with meaningful names.
  """

  @doc """
  A datum is considered duplicate if there is already another datum for the same
  date (day) and language as this one. Therefore, remove it!
  """
  def remove_duplicates() do
    get_duplicates()
    |> Enum.each(&Repo.delete/1)
  end

  @doc """
  Get a list of all of the duplicates.
  """
  def get_duplicates() do
    LanguageHistory
    |> Repo.all
    |> log_length("history points")
    |> Enum.reduce({MapSet.new, []}, &filter_duplicates/2)
    |> elem(1)  # 2nd element is the duplicates
    |> log_length("duplicates")
  end

  @doc """
  Should be used in reduce to check if for a datum we already have another
  one from the same date and language.
  """
  def filter_duplicates(datum, {date_language_set, duplicates}) do
    date = DateTime.to_date(datum.timestamp)
    language = datum.name
    date_language = {date, language}
    if MapSet.member?(date_language_set, date_language) do
      {date_language_set, [datum | duplicates]}
    else
      {MapSet.put(date_language_set, date_language), duplicates}
    end
  end

  def log_length(items, what) do
    num = length(items)
    Logger.info "Found #{num} #{what}"
    items
  end
end

HistoryDuplicatesCleaner.remove_duplicates()

error: pathspec 'priv/scripts/remove_duplicate_history.exs' did not match any file(s) known to git


Add tests for `Serum.BuildDataStorage`

Add tests for `Serum.BuildDataStorage`

fatal: unable to access 'https://github.com/Dalgona/Serum.git/': The requested URL returned error: 403


Added xend action

Added xend action

fatal: unable to access 'https://github.com/bit-engine/dustbin.git/': The requested URL returned error: 403


Handle requests for public cameras from unauthenticated requests


Add TweetConsumer module

Add TweetConsumer module

defmodule EmojiMap.TweetConsumer do
  @moduledoc """
  The consumer side. Subscribes to the producer once it is started so when
  it crashes and the supervisor restarts it, it automatically re-subscribes
  """

  use GenStage

  @doc """
  Starts the consumer.
  """
  def start_link() do
    GenStage.start_link(__MODULE__, :ok)
  end

  def init(:ok) do
    # Starts a permanent subscription to the broadcaster
    # which will automatically start requesting items.
    {:consumer, :ok, subscribe_to: [EmojiMap.TweetBroadcaster]}
  end

  def handle_events(events, _from, state) do
    for event <- events do
      IO.inspect {self(), event, state}
    end
    {:noreply, [], state}
  end
end

error: pathspec 'backend/lib/emoji_map/tweet_consumer.ex' did not match any file(s) known to git


Added Log on login failure

Added Log on login failure


Fix for test config error

Fix for test config error

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/colindensem/phoenix-travis-nanobox.git/'


chore: list

chore: list

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/rockdragon/julia-programming.git/'


Disable automatic thumbnail update

Disable automatic thumbnail update

fatal: unable to access 'https://github.com/evercam/evercam-media.git/': The requested URL returned error: 403


[patch] fix legal_entity search by settlement_id (#1937)

fatal: unable to access 'https://github.com/edenlabllc/ehealth.api.git/': The requested URL returned error: 403


changing camera image

changing camera image

fatal: unable to access 'https://github.com/thluiz/ddd21.git/': The requested URL returned error: 403


Remove file committed by accident

Remove file committed by accident

error: pathspec 'installer/tmp/new' did not match any file(s) known to git
error: pathspec 'inside' did not match any file(s) known to git
error: pathspec 'umbrella/mix.exs' did not match any file(s) known to git


Fixed syntax errors in Channel.subscribe/2 docs

defmodule Phoenix.Channel do
  @moduledoc """
  Defines a Phoenix Channel.

  Channels provide a means for bidirectional communication from clients that
  integrate with the `Phoenix.PubSub` layer for soft-realtime functionality.

  ## Topics & Callbacks

  Everytime you join a channel, you need to choose which particular topic you
  want to listen to. The topic is just an identifier, but by convention it is
  often made of two parts: `"topic:subtopic"`. Using the `"topic:subtopic"`
  approach pairs nicely with the `Phoenix.Socket.channel/2` allowing you to
  match on all topics starting with a given prefix:

      channel "room:*", MyApp.RoomChannel

  Any topic coming into the router with the `"room:"` prefix would dispatch
  to `MyApp.RoomChannel` in the above example. Topics can also be pattern
  matched in your channels' `join/3` callback to pluck out the scoped pattern:

      # handles the special `"lobby"` subtopic
      def join("room:lobby", _auth_message, socket) do
        {:ok, socket}
      end

      # handles any other subtopic as the room ID, for example `"room:12"`, `"room:34"`
      def join("room:" <> room_id, auth_message, socket) do
        {:ok, socket}
      end

  ## Authorization

  Clients must join a channel to send and receive PubSub events on that channel.
  Your channels must implement a `join/3` callback that authorizes the socket
  for the given topic. For example, you could check if the user is allowed to
  join that particular room.

  To authorize a socket in `join/3`, return `{:ok, socket}`.
  To refuse authorization in `join/3`, return `{:error, reply}`.

  ## Incoming Events

  After a client has successfully joined a channel, incoming events from the
  client are routed through the channel's `handle_in/3` callbacks. Within these
  callbacks, you can perform any action. Typically you'll either forward a
  message to all listeners with `broadcast!/3`, or push a message directly down
  the socket with `push/3`. Incoming callbacks must return the `socket` to
  maintain ephemeral state.

  Here's an example of receiving an incoming `"new_msg"` event from one client,
  and broadcasting the message to all topic subscribers for this socket.

      def handle_in("new_msg", %{"uid" => uid, "body" => body}, socket) do
        broadcast! socket, "new_msg", %{uid: uid, body: body}
        {:noreply, socket}
      end

  You can also push a message directly down the socket:

      # client asks for their current rank, push sent directly as a new event.
      def handle_in("current_rank", socket) do
        push socket, "current_rank", %{val: Game.get_rank(socket.assigns[:user])}
        {:noreply, socket}
      end

  ## Replies

  In addition to pushing messages out when you receive a `handle_in` event,
  you can also reply directly to a client event for request/response style
  messaging. This is useful when a client must know the result of an operation
  or to simply ack messages.

  For example, imagine creating a resource and replying with the created record:

      def handle_in("create:post", attrs, socket) do
        changeset = Post.changeset(%Post{}, attrs)

        if changeset.valid? do
          Repo.insert!(changeset)
          {:reply, {:ok, changeset}, socket}
        else
          {:reply,{:error, MyApp.ChangesetView.render("errors.json",
            %{changeset: changeset}), socket}
        end
      end

  Alternatively, you may just want to ack the status of the operation:

      def handle_in("create:post", attrs, socket) do
        changeset = Post.changeset(%Post{}, attrs)

        if changeset.valid? do
          Repo.insert!(changeset)
          {:reply, :ok, socket}
        else
          {:reply, :error, socket}
        end
      end

  ## Intercepting Outgoing Events

  When an event is broadcasted with `broadcast/3`, each channel subscriber can
  choose to intercept the event and have their `handle_out/3` callback triggered.
  This allows the event's payload to be customized on a socket by socket basis
  to append extra information, or conditionally filter the message from being
  delivered. If the event is not intercepted with `Phoenix.Channel.intercept/1`,
  then the message is pushed directly to the client:

      intercept ["new_msg", "user_joined"]

      # for every socket subscribing to this topic, append an `is_editable`
      # value for client metadata.
      def handle_out("new_msg", msg, socket) do
        push socket, "new_msg", Map.merge(msg,
          %{is_editable: User.can_edit_message?(socket.assigns[:user], msg)}
        )
        {:noreply, socket}
      end

      # do not send broadcasted `"user_joined"` events if this socket's user
      # is ignoring the user who joined.
      def handle_out("user_joined", msg, socket) do
        unless User.ignoring?(socket.assigns[:user], msg.user_id) do
          push socket, "user_joined", msg
        end
        {:noreply, socket}
      end

  ## Broadcasting to an external topic

  In some cases, you will want to broadcast messages without the context of
  a `socket`. This could be for broadcasting from within your channel to an
  external topic, or broadcasting from elsewhere in your application like a
  controller or another process. Such can be done via your endpoint:

      # within channel
      def handle_in("new_msg", %{"uid" => uid, "body" => body}, socket) do
        ...
        broadcast_from! socket, "new_msg", %{uid: uid, body: body}
        MyApp.Endpoint.broadcast_from! self(), "room:superadmin",
          "new_msg", %{uid: uid, body: body}
        {:noreply, socket}
      end

      # within controller
      def create(conn, params) do
        ...
        MyApp.Endpoint.broadcast! "room:" <> rid, "new_msg", %{uid: uid, body: body}
        MyApp.Endpoint.broadcast! "room:superadmin", "new_msg", %{uid: uid, body: body}
        redirect conn, to: "/"
      end

  ## Terminate

  On termination, the channel callback `terminate/2` will be invoked with
  the error reason and the socket.

  If we are terminating because the client left, the reason will be
  `{:shutdown, :left}`. Similarly, if we are terminating because the
  client connection was closed, the reason will be `{:shutdown, :closed}`.

  If any of the callbacks return a `:stop` tuple, it will also
  trigger terminate with the reason given in the tuple.

  `terminate/2`, however, won't be invoked in case of errors nor in
  case of exits. This is the same behaviour as you find in Elixir
  abstractions like `GenServer` and others. Typically speaking, if you
  want to clean something up, it is better to monitor your channel
  process and do the clean up from another process.  Similar to GenServer,
  it would also be possible `:trap_exit` to guarantee that `terminate/2`
  is invoked. This practice is not encouraged though.
  """

  alias Phoenix.Socket
  alias Phoenix.Channel.Server

  @type reply :: status :: atom | {status :: atom, response :: map}
  @type socket_ref :: {transport_pid :: Pid, serializer :: Module.t,
                       topic :: binary, ref :: binary}

  @callback code_change(old_vsn, Socket.t, extra :: term) ::
              {:ok, Socket.t} |
              {:error, reason :: term} when old_vsn: term | {:down, term}

  @callback join(topic :: binary, auth_msg :: map, Socket.t) ::
              {:ok, Socket.t} |
              {:ok, map, Socket.t} |
              {:error, map}

  @callback handle_in(event :: String.t, msg :: map, Socket.t) ::
              {:noreply, Socket.t} |
              {:reply, reply, Socket.t} |
              {:stop, reason :: term, Socket.t} |
              {:stop, reason :: term, reply, Socket.t}

  @callback handle_info(term, Socket.t) ::
              {:noreply, Socket.t} |
              {:stop, reason :: term, Socket.t}

  @callback terminate(msg :: map, Socket.t) ::
              {:shutdown, :left | :closed} |
              term

  defmacro __using__(_) do
    quote do
      @behaviour unquote(__MODULE__)
      @on_definition unquote(__MODULE__)
      @before_compile unquote(__MODULE__)
      @phoenix_intercepts []

      import unquote(__MODULE__)
      import Phoenix.Socket, only: [assign: 3]

      def code_change(_old, socket, _extra), do: {:ok, socket}

      def handle_in(_event, _message, socket) do
        {:noreply, socket}
      end

      def handle_info(_message, socket), do: {:noreply, socket}

      def terminate(_reason, _socket), do: :ok

      defoverridable code_change: 3, handle_info: 2, handle_in: 3, terminate: 2
    end
  end

  defmacro __before_compile__(_) do
    quote do
      def __intercepts__, do: @phoenix_intercepts
    end
  end

  @doc """
  Defines which Channel events to intercept for `handle_out/3` callbacks.

  By default, broadcasted events are pushed directly to the client, but
  intercepting events gives your channel a chance to customize the event
  for the client to append extra information or filter the message from being
  delivered.

  *Note*: intercepting events can introduce significantly more overhead if a
  large number of subscribers must customize a message since the broadcast will
  be encoded N times instead of a single shared encoding across all subscribers.

  ## Examples

      intercept ["new_msg"]

      def handle_out("new_msg", payload, socket) do
        push socket, "new_msg", Map.merge(payload,
          is_editable: User.can_edit_message?(socket.assigns[:user], payload)
        )
        {:noreply, socket}
      end

  `handle_out/3` callbacks must return one of:

      {:noreply, Socket.t} |
      {:stop, reason :: term, Socket.t}

  """
  defmacro intercept(events) do
    quote do
      @phoenix_intercepts unquote(events)
    end
  end

  @doc false
  def __on_definition__(env, :def, :handle_out, [event, _payload, _socket], _, _)
    when is_binary(event) do

    unless event in Module.get_attribute(env.module, :phoenix_intercepts) do
      IO.write "#{Path.relative_to(env.file, File.cwd!)}:#{env.line}: [warning] " <>
               "An intercept for event \"#{event}\" has not yet been defined in #{env.module}.handle_out/3. " <>
               "Add \"#{event}\" to your list of intercepted events with intercept/1"
    end
  end
  def __on_definition__(_env, _kind, _name, _args, _guards, _body) do
  end

  @doc """
  Broadcast an event to all subscribers of the socket topic.

  The event's message must be a serializable map.

  ## Examples

      iex> broadcast socket, "new_message", %{id: 1, content: "hello"}
      :ok

  """
  def broadcast(socket, event, message) do
    %{pubsub_server: pubsub_server, topic: topic} = assert_joined!(socket)
    Server.broadcast pubsub_server, topic, event, message
  end

  @doc """
  Same as `broadcast/3` but raises if broadcast fails.
  """
  def broadcast!(socket, event, message) do
    %{pubsub_server: pubsub_server, topic: topic} = assert_joined!(socket)
    Server.broadcast! pubsub_server, topic, event, message
  end

  @doc """
  Broadcast event from pid to all subscribers of the socket topic.

  The channel that owns the socket will not receive the published
  message. The event's message must be a serializable map.

  ## Examples

      iex> broadcast_from socket, "new_message", %{id: 1, content: "hello"}
      :ok

  """
  def broadcast_from(socket, event, message) do
    %{pubsub_server: pubsub_server, topic: topic, channel_pid: channel_pid} = assert_joined!(socket)
    Server.broadcast_from pubsub_server, channel_pid, topic, event, message
  end

  @doc """
  Same as `broadcast_from/3` but raises if broadcast fails.
  """
  def broadcast_from!(socket, event, message) do
    %{pubsub_server: pubsub_server, topic: topic, channel_pid: channel_pid} = assert_joined!(socket)
    Server.broadcast_from! pubsub_server, channel_pid, topic, event, message
  end

  @doc """
  Sends event to the socket.

  The event's message must be a serializable map.

  ## Examples

      iex> push socket, "new_message", %{id: 1, content: "hello"}
      :ok

  """
  def push(socket, event, message) do
    %{transport_pid: transport_pid, topic: topic} = assert_joined!(socket)
    Server.push(transport_pid, topic, event, message, socket.serializer)
  end

  @doc ~S"""
  Subscribes the socket to an external topic.

  Useful for circumstances you need to programmatically subscribe a
  socket to external topics in addition to the the internal `socket.topic`.
  For example, imagine you have a bidding system where a remote client
  dynamically sets preferences on products they want to receiving bidding
  notifications on. Instead of requiring a unique channel process and topic per
  preference, a more efficient and simple approach would be to subscribe a
  single socket to relevant notifications.

  ## Examples

      def NotificationChannel do
        use Phoenix.Channel

        def join("notifications:" <> user_id, %{"ids" => ids}, socket) do
          topics = for product_id <- ids, do: "products:#{product_id}"

          {:ok, socket
                |> assign(:topics, [])
                |> put_new_topics(topics)}
        end

        def handle_in("watch", %{"product_id" => id}, socket) do
          {:reply, :ok, put_new_topics(socket, ["products:#{id}"])}
        end

        def handle_in("unwatch", %{"product_id" => id}, socket) do
          {:reply, :ok, unsubscribe(socket, "products:#{id}")}
        end

        defp put_new_topics(socket, topics) do
          Enum.reduce(topics, socket, fn topic, acc ->
            if topic in acc.assigns.topics do
              acc
            else
              :ok = subscribe(acc, topic)
              assign(acc, :topics, [topic | topics])
            end
          end)
        end
      end

  Note: Like `Phoenix.PubSub.subscribe`, the caller must be responsible
  for preventing duplicate subscriptions. After calling
  `Phoenix.Channel.subscribe/2`, the same flow applies to normal channel
  messages. By default, the messages are relayed directly to the client,
  but the events can be intercepted with `intercept/1` causing `handle_out/3`
  callbacks to invoked.
  """
  def subscribe(%Socket{} = socket, topic) do
    Phoenix.PubSub.subscribe(socket.pubsub_server, topic,
      link: true,
      fastlane: {socket.transport_pid,
                 socket.serializer,
                 socket.channel.__intercepts__()})
  end

  @doc """
  Unsubscribes the socket from an external topic.

  ## Examples

      iex> unsubscribe(socket, "another:topic")
      :ok
  """
  def unsubscribe(%Socket{topic: topic}, topic) do
    raise ArgumentError, "cannot unsubscribe socket from its own topic"
  end
  def unsubscribe(%Socket{} = socket, topic) do
    Phoenix.PubSub.unsubscribe(socket.pubsub_server, topic)
  end

  @doc """
  Replies asynchronously to a socket push.

  Useful when you need to reply to a push that can't otherwise be handled using
  the `{:reply, {status, payload}, socket}` return from your `handle_in`
  callbacks. `reply/3` will be used in the rare cases you need to perform work in
  another process and reply when finished by generating a reference to the push
  with `socket_ref/1`.

  *Note*: In such cases, a `socket_ref` should be generated and
  passed to the external process, so the `socket` itself is not leaked outside
  the channel. The `socket` holds information such as assigns and transport
  configuration, so it's important to not copy this information outside of the
  channel that owns it.

  ## Examples

      def handle_in("work", payload, socket) do
        Worker.perform(payload, socket_ref(socket))
        {:noreply, socket}
      end

      def handle_info({:work_complete, result, ref}, socket) do
        reply ref, {:ok, result}
        {:noreply, socket}
      end

  """
  @spec reply(socket_ref, reply) :: :ok
  def reply({transport_pid, serializer, topic, ref}, {status, payload}) do
    Server.reply(transport_pid, ref, topic, {status, payload}, serializer)
  end

  @doc """
  Generates a `socket_ref` for an async reply.

  See `reply/2` for example usage.
  """
  @spec socket_ref(Socket.t) :: socket_ref
  def socket_ref(%Socket{joined: true, ref: ref} = socket) when not is_nil(ref) do
    {socket.transport_pid, socket.serializer, socket.topic, ref}
  end
  def socket_ref(_socket) do
    raise ArgumentError, """
    Socket refs can only be generated for a socket that has joined with a push ref
    """
  end

  defp assert_joined!(%Socket{joined: true} = socket) do
    socket
  end

  defp assert_joined!(%Socket{joined: false}) do
    raise """
    `push`, `reply`, and `broadcast` can only be called after the socket has finished joining.
    To push a message on join, send to self and handle in handle_info/2, ie:

        def join(topic, auth_msg, socket) do
          ...
          send(self, :after_join)
          {:ok, socket}
        end

        def handle_info(:after_join, socket) do
          push socket, "feed", %{list: feed_items(socket)}
          {:noreply, socket}
        end
    """
  end
end

defmodule Phoenix.Channel do
  @moduledoc """
  Defines a Phoenix Channel.

  Channels provide a means for bidirectional communication from clients that
  integrate with the `Phoenix.PubSub` layer for soft-realtime functionality.

  ## Topics & Callbacks

  Everytime you join a channel, you need to choose which particular topic you
  want to listen to. The topic is just an identifier, but by convention it is
  often made of two parts: `"topic:subtopic"`. Using the `"topic:subtopic"`
  approach pairs nicely with the `Phoenix.Socket.channel/2` allowing you to
  match on all topics starting with a given prefix:

      channel "room:*", MyApp.RoomChannel

  Any topic coming into the router with the `"room:"` prefix would dispatch
  to `MyApp.RoomChannel` in the above example. Topics can also be pattern
  matched in your channels' `join/3` callback to pluck out the scoped pattern:

      # handles the special `"lobby"` subtopic
      def join("room:lobby", _auth_message, socket) do
        {:ok, socket}
      end

      # handles any other subtopic as the room ID, for example `"room:12"`, `"room:34"`
      def join("room:" <> room_id, auth_message, socket) do
        {:ok, socket}
      end

  ## Authorization

  Clients must join a channel to send and receive PubSub events on that channel.
  Your channels must implement a `join/3` callback that authorizes the socket
  for the given topic. For example, you could check if the user is allowed to
  join that particular room.

  To authorize a socket in `join/3`, return `{:ok, socket}`.
  To refuse authorization in `join/3`, return `{:error, reply}`.

  ## Incoming Events

  After a client has successfully joined a channel, incoming events from the
  client are routed through the channel's `handle_in/3` callbacks. Within these
  callbacks, you can perform any action. Typically you'll either forward a
  message to all listeners with `broadcast!/3`, or push a message directly down
  the socket with `push/3`. Incoming callbacks must return the `socket` to
  maintain ephemeral state.

  Here's an example of receiving an incoming `"new_msg"` event from one client,
  and broadcasting the message to all topic subscribers for this socket.

      def handle_in("new_msg", %{"uid" => uid, "body" => body}, socket) do
        broadcast! socket, "new_msg", %{uid: uid, body: body}
        {:noreply, socket}
      end

  You can also push a message directly down the socket:

      # client asks for their current rank, push sent directly as a new event.
      def handle_in("current_rank", socket) do
        push socket, "current_rank", %{val: Game.get_rank(socket.assigns[:user])}
        {:noreply, socket}
      end

  ## Replies

  In addition to pushing messages out when you receive a `handle_in` event,
  you can also reply directly to a client event for request/response style
  messaging. This is useful when a client must know the result of an operation
  or to simply ack messages.

  For example, imagine creating a resource and replying with the created record:

      def handle_in("create:post", attrs, socket) do
        changeset = Post.changeset(%Post{}, attrs)

        if changeset.valid? do
          Repo.insert!(changeset)
          {:reply, {:ok, changeset}, socket}
        else
          {:reply,{:error, MyApp.ChangesetView.render("errors.json",
            %{changeset: changeset}), socket}
        end
      end

  Alternatively, you may just want to ack the status of the operation:

      def handle_in("create:post", attrs, socket) do
        changeset = Post.changeset(%Post{}, attrs)

        if changeset.valid? do
          Repo.insert!(changeset)
          {:reply, :ok, socket}
        else
          {:reply, :error, socket}
        end
      end

  ## Intercepting Outgoing Events

  When an event is broadcasted with `broadcast/3`, each channel subscriber can
  choose to intercept the event and have their `handle_out/3` callback triggered.
  This allows the event's payload to be customized on a socket by socket basis
  to append extra information, or conditionally filter the message from being
  delivered. If the event is not intercepted with `Phoenix.Channel.intercept/1`,
  then the message is pushed directly to the client:

      intercept ["new_msg", "user_joined"]

      # for every socket subscribing to this topic, append an `is_editable`
      # value for client metadata.
      def handle_out("new_msg", msg, socket) do
        push socket, "new_msg", Map.merge(msg,
          %{is_editable: User.can_edit_message?(socket.assigns[:user], msg)}
        )
        {:noreply, socket}
      end

      # do not send broadcasted `"user_joined"` events if this socket's user
      # is ignoring the user who joined.
      def handle_out("user_joined", msg, socket) do
        unless User.ignoring?(socket.assigns[:user], msg.user_id) do
          push socket, "user_joined", msg
        end
        {:noreply, socket}
      end

  ## Broadcasting to an external topic

  In some cases, you will want to broadcast messages without the context of
  a `socket`. This could be for broadcasting from within your channel to an
  external topic, or broadcasting from elsewhere in your application like a
  controller or another process. Such can be done via your endpoint:

      # within channel
      def handle_in("new_msg", %{"uid" => uid, "body" => body}, socket) do
        ...
        broadcast_from! socket, "new_msg", %{uid: uid, body: body}
        MyApp.Endpoint.broadcast_from! self(), "room:superadmin",
          "new_msg", %{uid: uid, body: body}
        {:noreply, socket}
      end

      # within controller
      def create(conn, params) do
        ...
        MyApp.Endpoint.broadcast! "room:" <> rid, "new_msg", %{uid: uid, body: body}
        MyApp.Endpoint.broadcast! "room:superadmin", "new_msg", %{uid: uid, body: body}
        redirect conn, to: "/"
      end

  ## Terminate

  On termination, the channel callback `terminate/2` will be invoked with
  the error reason and the socket.

  If we are terminating because the client left, the reason will be
  `{:shutdown, :left}`. Similarly, if we are terminating because the
  client connection was closed, the reason will be `{:shutdown, :closed}`.

  If any of the callbacks return a `:stop` tuple, it will also
  trigger terminate with the reason given in the tuple.

  `terminate/2`, however, won't be invoked in case of errors nor in
  case of exits. This is the same behaviour as you find in Elixir
  abstractions like `GenServer` and others. Typically speaking, if you
  want to clean something up, it is better to monitor your channel
  process and do the clean up from another process.  Similar to GenServer,
  it would also be possible `:trap_exit` to guarantee that `terminate/2`
  is invoked. This practice is not encouraged though.
  """

  alias Phoenix.Socket
  alias Phoenix.Channel.Server

  @type reply :: status :: atom | {status :: atom, response :: map}
  @type socket_ref :: {transport_pid :: Pid, serializer :: Module.t,
                       topic :: binary, ref :: binary}

  @callback code_change(old_vsn, Socket.t, extra :: term) ::
              {:ok, Socket.t} |
              {:error, reason :: term} when old_vsn: term | {:down, term}

  @callback join(topic :: binary, auth_msg :: map, Socket.t) ::
              {:ok, Socket.t} |
              {:ok, map, Socket.t} |
              {:error, map}

  @callback handle_in(event :: String.t, msg :: map, Socket.t) ::
              {:noreply, Socket.t} |
              {:reply, reply, Socket.t} |
              {:stop, reason :: term, Socket.t} |
              {:stop, reason :: term, reply, Socket.t}

  @callback handle_info(term, Socket.t) ::
              {:noreply, Socket.t} |
              {:stop, reason :: term, Socket.t}

  @callback terminate(msg :: map, Socket.t) ::
              {:shutdown, :left | :closed} |
              term

  defmacro __using__(_) do
    quote do
      @behaviour unquote(__MODULE__)
      @on_definition unquote(__MODULE__)
      @before_compile unquote(__MODULE__)
      @phoenix_intercepts []

      import unquote(__MODULE__)
      import Phoenix.Socket, only: [assign: 3]

      def code_change(_old, socket, _extra), do: {:ok, socket}

      def handle_in(_event, _message, socket) do
        {:noreply, socket}
      end

      def handle_info(_message, socket), do: {:noreply, socket}

      def terminate(_reason, _socket), do: :ok

      defoverridable code_change: 3, handle_info: 2, handle_in: 3, terminate: 2
    end
  end

  defmacro __before_compile__(_) do
    quote do
      def __intercepts__, do: @phoenix_intercepts
    end
  end

  @doc """
  Defines which Channel events to intercept for `handle_out/3` callbacks.

  By default, broadcasted events are pushed directly to the client, but
  intercepting events gives your channel a chance to customize the event
  for the client to append extra information or filter the message from being
  delivered.

  *Note*: intercepting events can introduce significantly more overhead if a
  large number of subscribers must customize a message since the broadcast will
  be encoded N times instead of a single shared encoding across all subscribers.

  ## Examples

      intercept ["new_msg"]

      def handle_out("new_msg", payload, socket) do
        push socket, "new_msg", Map.merge(payload,
          is_editable: User.can_edit_message?(socket.assigns[:user], payload)
        )
        {:noreply, socket}
      end

  `handle_out/3` callbacks must return one of:

      {:noreply, Socket.t} |
      {:stop, reason :: term, Socket.t}

  """
  defmacro intercept(events) do
    quote do
      @phoenix_intercepts unquote(events)
    end
  end

  @doc false
  def __on_definition__(env, :def, :handle_out, [event, _payload, _socket], _, _)
    when is_binary(event) do

    unless event in Module.get_attribute(env.module, :phoenix_intercepts) do
      IO.write "#{Path.relative_to(env.file, File.cwd!)}:#{env.line}: [warning] " <>
               "An intercept for event \"#{event}\" has not yet been defined in #{env.module}.handle_out/3. " <>
               "Add \"#{event}\" to your list of intercepted events with intercept/1"
    end
  end
  def __on_definition__(_env, _kind, _name, _args, _guards, _body) do
  end

  @doc """
  Broadcast an event to all subscribers of the socket topic.

  The event's message must be a serializable map.

  ## Examples

      iex> broadcast socket, "new_message", %{id: 1, content: "hello"}
      :ok

  """
  def broadcast(socket, event, message) do
    %{pubsub_server: pubsub_server, topic: topic} = assert_joined!(socket)
    Server.broadcast pubsub_server, topic, event, message
  end

  @doc """
  Same as `broadcast/3` but raises if broadcast fails.
  """
  def broadcast!(socket, event, message) do
    %{pubsub_server: pubsub_server, topic: topic} = assert_joined!(socket)
    Server.broadcast! pubsub_server, topic, event, message
  end

  @doc """
  Broadcast event from pid to all subscribers of the socket topic.

  The channel that owns the socket will not receive the published
  message. The event's message must be a serializable map.

  ## Examples

      iex> broadcast_from socket, "new_message", %{id: 1, content: "hello"}
      :ok

  """
  def broadcast_from(socket, event, message) do
    %{pubsub_server: pubsub_server, topic: topic, channel_pid: channel_pid} = assert_joined!(socket)
    Server.broadcast_from pubsub_server, channel_pid, topic, event, message
  end

  @doc """
  Same as `broadcast_from/3` but raises if broadcast fails.
  """
  def broadcast_from!(socket, event, message) do
    %{pubsub_server: pubsub_server, topic: topic, channel_pid: channel_pid} = assert_joined!(socket)
    Server.broadcast_from! pubsub_server, channel_pid, topic, event, message
  end

  @doc """
  Sends event to the socket.

  The event's message must be a serializable map.

  ## Examples

      iex> push socket, "new_message", %{id: 1, content: "hello"}
      :ok

  """
  def push(socket, event, message) do
    %{transport_pid: transport_pid, topic: topic} = assert_joined!(socket)
    Server.push(transport_pid, topic, event, message, socket.serializer)
  end

  @doc ~S"""
  Subscribes the socket to an external topic.

  Useful for circumstances you need to programmatically subscribe a
  socket to external topics in addition to the the internal `socket.topic`.
  For example, imagine you have a bidding system where a remote client
  dynamically sets preferences on products they want to receiving bidding
  notifications on. Instead of requiring a unique channel process and topic per
  preference, a more efficient and simple approach would be to subscribe a
  single socket to relevant notifications.

  ## Examples

      def NotificationChannel do
        use Phoenix.Channel

        def join("notifications:" <> user_id, %{"ids" => ids}, socket) do
          topics = for product_id <- ids, do: "products:#{product_id}"

          {:ok, socket,
                |> assign(:topics, [])
                |> put_new_topics(topics)}
        end

        def handle_in("watch", %{"product_id" => id}, socket) do
          {:reply, :ok, put_new_topics(socket, "products:#{id}")}
        end

        def handle_in("unwatch", %{"product_id" => id}, socket) do
          {:reply, :ok, unsubscribe(socket, "products:#{id}")}
        end

        defp put_new_topics(socket, topics) do
          Enum.reduce(topics, socket, fn topic, acc ->
            if topic in acc.assigns.topics do
              acc
            else
              :ok = subscribe(acc, topic)
              assign(acc, :topics, [topic | topics])
            end
          end)
        end
      end

  Note: Like `Phoenix.PubSub.subscribe`, the caller must be responsible
  for preventing duplicate subscriptions. After calling
  `Phoenix.Channel.subscribe/2`, the same flow applies to normal channel
  messages. By default, the messages are relayed directly to the client,
  but the events can be intercepted with `intercept/1` causing `handle_out/3`
  callbacks to invoked.
  """
  def subscribe(%Socket{} = socket, topic) do
    Phoenix.PubSub.subscribe(socket.pubsub_server, topic,
      link: true,
      fastlane: {socket.transport_pid,
                 socket.serializer,
                 socket.channel.__intercepts__()})
  end

  @doc """
  Unsubscribes the socket from an external topic.

  ## Examples

      iex> unsubscribe(socket, "another:topic")
      :ok
  """
  def unsubscribe(%Socket{topic: topic}, topic) do
    raise ArgumentError, "cannot unsubscribe socket from its own topic"
  end
  def unsubscribe(%Socket{} = socket, topic) do
    Phoenix.PubSub.unsubscribe(socket.pubsub_server, topic)
  end

  @doc """
  Replies asynchronously to a socket push.

  Useful when you need to reply to a push that can't otherwise be handled using
  the `{:reply, {status, payload}, socket}` return from your `handle_in`
  callbacks. `reply/3` will be used in the rare cases you need to perform work in
  another process and reply when finished by generating a reference to the push
  with `socket_ref/1`.

  *Note*: In such cases, a `socket_ref` should be generated and
  passed to the external process, so the `socket` itself is not leaked outside
  the channel. The `socket` holds information such as assigns and transport
  configuration, so it's important to not copy this information outside of the
  channel that owns it.

  ## Examples

      def handle_in("work", payload, socket) do
        Worker.perform(payload, socket_ref(socket))
        {:noreply, socket}
      end

      def handle_info({:work_complete, result, ref}, socket) do
        reply ref, {:ok, result}
        {:noreply, socket}
      end

  """
  @spec reply(socket_ref, reply) :: :ok
  def reply({transport_pid, serializer, topic, ref}, {status, payload}) do
    Server.reply(transport_pid, ref, topic, {status, payload}, serializer)
  end

  @doc """
  Generates a `socket_ref` for an async reply.

  See `reply/2` for example usage.
  """
  @spec socket_ref(Socket.t) :: socket_ref
  def socket_ref(%Socket{joined: true, ref: ref} = socket) when not is_nil(ref) do
    {socket.transport_pid, socket.serializer, socket.topic, ref}
  end
  def socket_ref(_socket) do
    raise ArgumentError, """
    Socket refs can only be generated for a socket that has joined with a push ref
    """
  end

  defp assert_joined!(%Socket{joined: true} = socket) do
    socket
  end

  defp assert_joined!(%Socket{joined: false}) do
    raise """
    `push`, `reply`, and `broadcast` can only be called after the socket has finished joining.
    To push a message on join, send to self and handle in handle_info/2, ie:

        def join(topic, auth_msg, socket) do
          ...
          send(self, :after_join)
          {:ok, socket}
        end

        def handle_info(:after_join, socket) do
          push socket, "feed", %{list: feed_items(socket)}
          {:noreply, socket}
        end
    """
  end
end


remember state function

remember state function

fatal: unable to access 'https://github.com/merxer/kata.git/': The requested URL returned error: 403


Adding a game type

Adding a game type

defmodule Next.Types do
  defmodule Game do
    defstruct [:id, :art_path, :critic_score, :developer, :esrb,
               :genre, :link_path, :platforms, :publisher,
               :release_date, :summary, :title]
  end
end

error: pathspec 'lib/shipbit/types.ex' did not match any file(s) known to git


Use this module in the main application to setup pact elixir

defmodule PactElixir.Helpers do
  @moduledoc false
  defmacro __using__([]) do
    quote do
      import PactElixir.Dsl
      import unquote(__MODULE__)
    end
  end

  # Raise an error if called with an unknown framework
  #
  # defp setup_framework_integration(pact_elixir = %{pid: pid}) do
  #   ExUnit.Callbacks.on_exit({PactElixir, pid}, fn ->
  #     after_test_suite(pact_elixir.pid, ExUnit.AssertionError)
  #   end)
  # end

  defmacro pact_session(opts \\ []) do
    quote do
      setup do
        on_exit(fn -> after_test_suite(unquote(opts)) end)

        :ok
      end
    end
  end
end

error: pathspec 'lib/pact_elixir/helpers.ex' did not match any file(s) known to git


Initial code chapter 5.

Initial code chapter 5.

sum = fn (a, b) -> a + b end
sum.(4, 5)

greet = fn -> IO.puts "Hello" end
greet.()

f1 = fn a, b -> a * b end
IO.puts f1.(4, 5)

error: pathspec 'programming_elixir/chapter5/functions.exs' did not match any file(s) known to git


chore: tuple

chore: tuple

fatal: unable to access 'https://github.com/rockdragon/julia-programming.git/': The requested URL returned error: 403


updated tests to query options for a friday in the future

fatal: unable to access 'https://github.com/davidgrupp/Option-Calc.git/': The requested URL returned error: 403


Add deploy task placeholder

Add deploy task placeholder

fatal: unable to access 'https://github.com/labzero/bootleg.git/': The requested URL returned error: 403


hides all unavailable crunchers from state display

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/elixytics/report.git/'


add golos block schema

add golos block schema

defmodule Glasnost.Golos.Block do
    use Ecto.Schema
    import Ecto.Changeset
    import Ecto.Query
    alias Ecto.Adapters.SQL
    alias Ecto.Multi
    alias Glasnost.Repo

    @primary_key false

    schema "golos_blocks" do
      field :extensions, {:array, :map}
      field :previous, :string
      field :timestamp, :naive_datetime
      field :transaction_merkle_root, :string
      field :transactions, {:array, :map}
      field :witness, :string
      field :witness_signatures, {:array, :string}
      field :height, :integer, primary_key: true

      timestamps
    end

    def changeset(data, params \\ %{}) do
      allowed_params = [:previous, :timestamp, :transaction_merkle_root, :witness, :witness_signatures, :transactions, :height]
      data
      |> cast(params, allowed_params)
      |> unique_constraint(:height)
    end

end

error: pathspec 'lib/glasnost/schemas/golos_block.ex' did not match any file(s) known to git


Rename unused variable

Rename unused variable

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/evercam/evercam-media.git/'


Add TriggerEvent integration tests

Add TriggerEvent integration tests

error: RPC failed; HTTP 403 curl 22 The requested URL returned error: 403
fatal: the remote end hung up unexpectedly


Add registratoin controller

Add registratoin controller


Fix match error on contract terminate (#3937)

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/edenlabllc/ehealth.api.git/'


Add test support

Add test support

defmodule Readme do
  @moduledoc File.read!("README.md")
end

error: pathspec 'test/support/readme.ex' did not match any file(s) known to git


Add Credo.Outdated to check for newer versions

fatal: unable to access 'https://github.com/rrrene/credo.git/': The requested URL returned error: 403


Use guard clause.

Use guard clause.

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/tchoutri/magnetissimo.git/'


Add helpers and factory to conn case.

Add helpers and factory to conn case.

fatal: unable to access 'https://github.com/futhr/fux.git/': The requested URL returned error: 403


tree traversal dfs style with a but of metaprogramming

defmodule Tree do
    defstruct [:left, :right, :root]
end

defmodule MatchNullTraverse do
    require Tree

    defmacro __using__(_) do
        Enum.map ~w(preorder inorder postorder), fn func ->
            quote do
                def unquote(:"#{func}")(%Tree{root: nil}), do: []
                def unquote(:"#{func}")(%Tree{root: root, left: nil, right: nil}), do: [root]

                case unquote(:"#{func}") do
                    :preorder ->
                        def unquote(:"#{func}")(%Tree{root: root, left: nil, right: %Tree{}=right}) do
                            [root] ++ unquote(:"#{func}")(right)
                        end
                        def unquote(:"#{func}")(%Tree{root: root, right: nil, left: %Tree{}=left}) do
                            [root] ++ unquote(:"#{func}")(left)
                        end
                    :inorder ->
                        def unquote(:"#{func}")(%Tree{root: root, left: nil, right: %Tree{}=right}) do
                            [root] ++ unquote(:"#{func}")(right)
                        end
                        def unquote(:"#{func}")(%Tree{root: root, right: nil, left: %Tree{}=left}) do
                            unquote(:"#{func}")(left) ++ [root]
                        end
                    :postorder ->
                        def unquote(:"#{func}")(%Tree{root: root, left: nil, right: %Tree{}=right}) do
                            unquote(:"#{func}")(right) ++ [root]
                        end
                        def unquote(:"#{func}")(%Tree{root: root, right: nil, left: %Tree{}=left}) do
                            unquote(:"#{func}")(left) ++ [root]
                        end
                end
            end
            # |> Macro.expand_once(__ENV__) |> Macro.to_string |> IO.puts
        end
    end
end

defmodule TraverseTree do
    use MatchNullTraverse

    def preorder(%Tree{root: root, left: left, right: right}) do
        [root] ++ preorder(left) ++ preorder(right)
    end

    def inorder(%Tree{root: root, left: left, right: right}) do
        inorder(left) ++ [root] ++ inorder(right)
    end

    def postorder(%Tree{root: root, left: left, right: right}) do
        postorder(left) ++ postorder(right) ++ [root]
    end

end

defmodule Test do
    require TraverseTree

    def run do
        t = %Tree{root: 4, left: %Tree{root: 2, left: %Tree{root: 1}, right: %Tree{root: 3}}, right: %Tree{root: 5, right: %Tree{root: 6}}}

        IO.inspect TraverseTree.preorder(t)
        IO.inspect TraverseTree.inorder(t)
        IO.inspect TraverseTree.postorder(t)
    end
end

Test.run

error: pathspec 'tree/dfs_traversal.ex' did not match any file(s) known to git


add spec

add spec

fatal: unable to access 'https://github.com/jeremy-miller/life-elixir.git/': The requested URL returned error: 403


Add Elixir solution for problem 2

Add Elixir solution for problem 2

defmodule Benchmark do
  def measure(function) do
    function
    |> :timer.tc
    |> elem(0)
    |> Kernel./(1_000_000)
    |> Float.to_string([decimals: 10, compact: true])
  end
end

defmodule ProblemTwo do

  def sum_fibonacci(_, second, third, sum) when third < 4000000 do
    new_first = second + third
    new_second = new_first + third
    new_third = new_first + new_second

    sum_fibonacci(new_first, new_second, new_third, sum + third)
  end

  def sum_fibonacci(_, _, _, sum), do: sum

  def sum_even_fibonacci_numbers do
    IO.puts "=> Result: #{sum_fibonacci(1, 1, 2, 0)}"
    IO.puts "=> Time: #{Benchmark.measure(fn -> sum_fibonacci(1, 1, 2, 0) end)}"
  end
end

ProblemTwo.sum_even_fibonacci_numbers

error: pathspec 'solutions/problem_2/solution.ex' did not match any file(s) known to git


Consider a timeout connecting to the camera as being offline


Log which specific error code made camera go offline


Update thumbnail_url only if it's older than 5 minutes


Add Allocator.

Add Allocator.

defmodule Wobserver.Allocator do
  @moduledoc ~S"""
  Allocator

  TODO:
    - Needs docs.
    - Needs cleanup.
    - Needs tests.
  """

  @spec list :: list(map)
  def list do
    :alloc_util_allocators
    |> :erlang.system_info
    |> info()
  end

  defp info(type) do
    {:allocator_sizes, type}
    |> :erlang.system_info
    |> Enum.map(&sum_data/1)
    |> Enum.filter(&non_zero?/1)
  end

  defp non_zero?(%{carrier: c, block: b}), do: c != 0 && b != 0

  defp sum_data({type, data}) do
    data
    |> Enum.map(fn {_, _, d} -> Keyword.get(d,:mbcs) end)
    |> Enum.map(&block_and_carrier_size/1)
    |> Enum.reduce({0,0}, fn {x, y}, {a, b} -> {a + x, y + b} end)
    |> (fn {x, y} -> %{type: type, block: x, carrier: y} end).()
  end

  defp block_and_carrier_size([{_, x, _, _}, {_, y, _, _}]), do: {x, y}
end

error: pathspec 'lib/wobserver/util/allocator.ex' did not match any file(s) known to git


Reject .json files in .jpg list of files. (#1109)


list operator

list operator

error: pathspec 'elixirv1.3/7.exs' did not match any file(s) known to git


Add query tests from Plug

Add query tests from Plug

# The following module test was copied from Plug:
# https://raw.githubusercontent.com/elixir-lang/plug/91b8f57dcc495735925553bcf6c53a0d0e413d86/test/plug/conn/query_test.exs
# With permission: https://github.com/elixir-lang/plug/issues/539
defmodule Maxwell.QueryTest do
  use ExUnit.Case, async: true

  import Maxwell.Query, only: [decode: 1, encode: 1, encode: 2]
  doctest Maxwell.Query

  test "decode queries" do
    params = decode("foo=bar&baz=bat")
    assert params["foo"] == "bar"
    assert params["baz"] == "bat"

    params = decode("users[name]=hello&users[age]=17")
    assert params["users"]["name"] == "hello"
    assert params["users"]["age"]  == "17"

    params = decode("my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F")
    assert params["my weird field"] == "q1!2\"'w$5&7/z8)?"

    assert decode("=")[""] == ""
    assert decode("key=")["key"] == ""
    assert decode("=value")[""] == "value"

    assert decode("foo[]")["foo"]  == []
    assert decode("foo[]=")["foo"] == [""]
    assert decode("foo[]=bar&foo[]=baz")["foo"] == ["bar", "baz"]
    assert decode("foo[]=bar&foo[]=baz")["foo"] == ["bar", "baz"]

    params = decode("foo[]=bar&foo[]=baz&bat[]=1&bat[]=2")
    assert params["foo"] == ["bar", "baz"]
    assert params["bat"] == ["1", "2"]

    assert decode("x[y][z]=1")["x"]["y"]["z"] == "1"
    assert decode("x[y][z][]=1")["x"]["y"]["z"] == ["1"]
    assert decode("x[y][z]=1&x[y][z]=2")["x"]["y"]["z"] == "2"
    assert decode("x[y][z][]=1&x[y][z][]=2")["x"]["y"]["z"] == ["1", "2"]

    assert (Enum.at(decode("x[y][][z]=1")["x"]["y"], 0))["z"] == "1"
    assert (Enum.at(decode("x[y][][z][]=1")["x"]["y"], 0))["z"] |> Enum.at(0) == "1"
  end

  test "last always wins on bad queries" do
    assert decode("x[]=1&x[y]=1")["x"]["y"] == "1"
    assert decode("x[y][][w]=2&x[y]=1")["x"]["y"] == "1"
    assert decode("x=1&x[y]=1")["x"]["y"] == "1"
  end

  test "decode_pair simple queries" do
    params = decode_pair [{"foo", "bar"}, {"baz", "bat"}]
    assert params["foo"] == "bar"
    assert params["baz"] == "bat"
  end

  test "decode_pair one-level nested query" do
    params = decode_pair [{"users[name]", "hello"}]
    assert params["users"]["name"] == "hello"

    params = decode_pair [{"users[name]", "hello"}, {"users[age]", "17"}]
    assert params["users"]["name"] == "hello"
    assert params["users"]["age"]  == "17"
  end

  test "decode_pair query no override" do
    params = decode_pair [{"foo", "bar"}, {"foo", "baz"}]
    assert params["foo"] == "baz"

    params = decode_pair [{"users[name]", "bar"}, {"users[name]", "baz"}]
    assert params["users"]["name"] == "baz"
  end

  test "decode_pair many-levels nested query" do
    params = decode_pair [{"users[name]", "hello"}]
    assert params["users"]["name"] == "hello"

    params = decode_pair [{"users[name]", "hello"}, {"users[age]", "17"}, {"users[address][street]", "Mourato"}]
    assert params["users"]["name"]              == "hello"
    assert params["users"]["age"]               == "17"
    assert params["users"]["address"]["street"] == "Mourato"
  end

  test "decode_pair list query" do
    params = decode_pair [{"foo[]", "bar"}, {"foo[]", "baz"}]
    assert params["foo"] == ["bar", "baz"]
  end

  defp decode_pair(pairs) do
    Enum.reduce Enum.reverse(pairs), %{}, &Maxwell.Query.decode_pair(&1, &2)
  end

  test "encode" do
    assert encode(%{foo: "bar", baz: "bat"}) == "baz=bat&foo=bar"

    assert encode(%{foo: nil}) == "foo="
    assert encode(%{foo: "bå®"}) == "foo=b%C3%A5%C2%AE"
    assert encode(%{foo: 1337})  == "foo=1337"
    assert encode(%{foo: ["bar", "baz"]}) == "foo[]=bar&foo[]=baz"

    assert encode(%{users: %{name: "hello", age: 17}}) == "users[age]=17&users[name]=hello"
    assert encode(%{users: [name: "hello", age: 17]}) == "users[name]=hello&users[age]=17"
    assert encode(%{users: [name: "hello", age: 17, name: "goodbye"]}) == "users[name]=hello&users[age]=17"

    assert encode(%{"my weird field": "q1!2\"'w$5&7/z8)?"}) == "my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F"
    assert encode(%{foo: %{"my weird field": "q1!2\"'w$5&7/z8)?"}}) == "foo[my+weird+field]=q1%212%22%27w%245%267%2Fz8%29%3F"

    assert encode(%{}) == ""
    assert encode([]) == ""

    assert encode(%{foo: [""]}) == "foo[]="

    assert encode(%{foo: ["bar", "baz"], bat: [1, 2]}) == "bat[]=1&bat[]=2&foo[]=bar&foo[]=baz"

    assert encode(%{x: %{y: %{z: 1}}}) == "x[y][z]=1"
    assert encode(%{x: %{y: %{z: [1]}}}) == "x[y][z][]=1"
    assert encode(%{x: %{y: %{z: [1, 2]}}}) == "x[y][z][]=1&x[y][z][]=2"
    assert encode(%{x: %{y: [%{z: 1}]}}) == "x[y][][z]=1"
    assert encode(%{x: %{y: [%{z: [1]}]}}) == "x[y][][z][]=1"
  end

  test "encode with custom encoder" do
    encoder = &(&1 |> to_string |> String.duplicate(2))

    assert encode(%{foo: "bar", baz: "bat"}, encoder) ==
           "baz=batbat&foo=barbar"

    assert encode(%{foo: ["bar", "baz"]}, encoder) ==
           "foo[]=barbar&foo[]=bazbaz"

    assert encode(%{foo: URI.parse("/bar")}, encoder) ==
           "foo=%2Fbar%2Fbar"
  end

  test "encode ignores empty maps or lists" do
    assert encode(%{filter: %{}, foo: "bar", baz: "bat"}) == "baz=bat&foo=bar"
    assert encode(%{filter: [], foo: "bar", baz: "bat"}) == "baz=bat&foo=bar"
  end

  test "encode raises when there's a map with 0 or >1 elems in a list" do
    message = ~r/cannot encode maps inside lists/

    assert_raise ArgumentError, message, fn ->
      encode(%{foo: [%{a: 1, b: 2}]})
    end

    assert_raise ArgumentError, message, fn ->
      encode(%{foo: [%{valid: :map}, %{}]})
    end
  end

  test "raise exception on bad www-form" do
    assert_raise ArgumentError, fn ->
      decode("_utf8=%R2%9P%93")
    end
  end
end

error: pathspec 'test/maxwell/query.exs' did not match any file(s) known to git


Remove IEx.pry

Remove IEx.pry

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/izakp/APR.git/'


Log snapshot success

Log snapshot success


Preloaded country for updating a user (#334)


fix validation for dismissed users on employee request create (#631)


Add offer admin view

Add offer admin view

defmodule ElixirJobsWeb.Admin.OfferView do
  use ElixirJobsWeb, :view
end

error: pathspec 'lib/elixir_jobs_web/views/admin/offer_view.ex' did not match any file(s) known to git


Fix the Ecto warning about references

Fix the Ecto warning about references


Downloader improvements.

Downloader improvements.


dont need to page pictures

dont need to page pictures

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/sschneider1207/Geosnap.git/'


Increment version [ci skip]

Increment version [ci skip]


typo on prod config

typo on prod config

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/udia-software/udia.git/'


Log database queries

Log database queries

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/evercam/evercam-media.git/'


Cleaned token before use

Cleaned token before use


make creado happy

make creado happy


add coveralls

add coveralls

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/mononym/exmud.git/'


Bump version to 0.4.2

Bump version to 0.4.2

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/preciz/insta_scrapex.git/'


Increment version [ci skip]

Increment version [ci skip]

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/edenlabllc/ehealth.api.git/'


add mix.exs file for using in elixir projects

relax dependency requirements (solves -Werror bug)

defmodule Switchboard.Mixfile do
  use Mix.Project

  def project do
    [app: :switchboard,
     version: "0.3.2",
     compilers: [:erlang, :app],
     erlc_options: [{:parse_transform, :lager_transform}, {:i, "include"}],
     deps: deps()]
  end

  def application do
    [applications: [:kernel,
                    :stdlib,
                    :inets,
                    :crypto,
                    :poolboy,
                    :lager,
                    :gproc,
                    :jsx]]
  end

  defp deps do
    [
     {:lager,    github: "basho/lager"},
     {:poolboy,  github: "devinus/poolboy"},
     {:cowboy,   github: "ninenines/cowboy",  tag: "1.0.3"},
     {:gproc,    github: "uwiger/gproc"},
     {:jsx,      github: "talentdeficit/jsx"},
     {:ranch,    github: "ninenines/ranch",   tag: "1.1.0", override: true}
    ]
  end
end

error: pathspec 'mix.exs' did not match any file(s) known to git


simple generic server

simple generic server

# Generic server process.
defmodule ServerProcess do
  def start(callback_module) do
    spawn(fn ->
      intitial_state = callback_module.init()
      loop(callback_module, intitial_state)
    end)
  end

  def call(server_pid, request) do
    send(server_pid, {request, self()})

    receive do
      {:response, response} -> response
    end
  end

  defp loop(callback_module, current_state) do
    receive do
      {request, caller} ->
        {response, new_state} =
          callback_module.handle_call(
            request,
            current_state
          )

        send(caller, {:response, response})

        loop(callback_module, new_state)
    end
  end
end

# Callback module for generic server process.
defmodule KeyValueStore do
  def init do
    %{}
  end

  def handle_call({:put, key, value}, state) do
    {:ok, Map.put(state, key, value)}
  end

  def handle_call({:get, key}, state) do
    {Map.get(state, key), state}
  end
end

error: pathspec 'elixir/my_generic_server/server_process.ex' did not match any file(s) known to git


BoxLed tests

BoxLed tests

defmodule FarmbotCore.Asset.BoxLedTest do
  use ExUnit.Case, async: false
  alias FarmbotCore.Asset.BoxLed

  test "to_string" do
    assert "BoxLed 23" == to_string(%BoxLed{id: 23})
  end
end

error: pathspec 'farmbot_core/test/asset/box_led_test.exs' did not match any file(s) known to git


add second_name to person view (#1356)

add second_name to person view (#1356)


Fix to execute GoalController.index test

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/babie/goal-server.git/'


Remove unused variable

Remove unused variable


Rename unused variables

Rename unused variables


Remove data field from snapshots

Remove data field from snapshots


Speed up snapshot latest query

Speed up snapshot latest query


Link process

Link process

defmodule Link2 do
  import :timer, only: [ sleep: 1 ]

  def sad_function do
    sleep 500
    exit(:boom)
  end
  def run do
    spawn_link(Link2, :sad_function, [])
    receive do
      msg ->
        IO.puts "MESSAGE RECEIVED: #{inspect msg}"
    after 1000 ->
        IO.puts "Nothing happened as far as I am concerned"
    end
  end
end

Link2.run

error: pathspec 'programming_elixir/chapter14/link2.exs' did not match any file(s) known to git


Backfill test

Backfill test

defmodule BorsNG.BatchControllerTest do
  use BorsNG.ConnCase

  alias BorsNG.Database.Batch
  alias BorsNG.Database.Installation
  alias BorsNG.Database.LinkPatchBatch
  alias BorsNG.Database.Patch
  alias BorsNG.Database.Project
  alias BorsNG.Database.Repo
  alias BorsNG.Database.Status
  alias BorsNG.Database.User

  setup do
    installation = Repo.insert!(%Installation{
      installation_xref: 31,
      })
    project = Repo.insert!(%Project{
      installation_id: installation.id,
      repo_xref: 13,
      name: "example/project",
      })
    user = Repo.insert!(%User{
      user_xref: 23,
      login: "ghost",
      })
    patch = Repo.insert!(%Patch{
      project_id: project.id,
      pr_xref: 43
    })
    batch = Repo.insert!(%Batch{
      project_id: project.id,
      priority: 33
    })
    {:ok, installation: installation, project: project, user: user, batch: batch, patch: patch}
  end

  test "need to log in to see this", %{conn: conn, batch: batch} do
    conn = get conn, "/batches/#{batch.id}"
    assert html_response(conn, 302) =~ "auth"
  end

  def login(conn) do
    conn = get conn, auth_path(conn, :index, "github")
    assert html_response(conn, 302) =~ "MOCK_GITHUB_AUTHORIZE_URL"
    conn = get conn, auth_path(
      conn,
      :callback,
      "github",
      %{"code" => "MOCK_GITHUB_AUTHORIZE_CODE"})
    html_response(conn, 302)
    conn
  end

  test "shows the batch details", %{conn: conn, patch: patch, batch: batch} do
    Repo.insert!(%LinkPatchBatch{
      patch_id: patch.id,
      batch_id: batch.id,
    })
    Repo.insert!(%Status{
      batch_id: batch.id,
      identifier: "some-identifier"
    })
    Repo.insert!(%Status{
      batch_id: batch.id,
      identifier: "with-url-identifier",
      url: "http://example.com"
    })

    conn = login conn
    conn = get conn, "/batches/#{batch.id}"

    assert html_response(conn, 200) =~ "Batch Details"
    assert html_response(conn, 200) =~ "Priority: 33"
    assert html_response(conn, 200) =~ "State: Invalid"
    assert html_response(conn, 200) =~ "#43"
    assert html_response(conn, 200) =~ "some-identifier"
    assert html_response(conn, 200) =~ ~S(with-url-identifier)
  end

end

error: pathspec 'test/controllers/batch_controller_test.exs' did not match any file(s) known to git


back to elixir, now in production (here I record some of my practice)

defmodule TodoList do
  defstruct auto_id: 1, entries: %{}

  def new(), do: %TodoList {}

  def add_entry(todo_list, entry) do
    entry = Map.put(entry, :id, todo_list.auto_id)

    new_entries = Map.put(
      todo_list.entries,
      todo_list.auto_id,
      entry
    )

    %TodoList{ todo_list | entries: new_entries, auto_id: todo_list.auto_id + 1 }
  end

  def update_entry(todo_list, entry_id, update_fun) do
    case Map.fetch(todo_list.entries, entry_id) do
      :error ->
        todo_list
      {:ok, old_entry} ->
        new_entry = update_fun.(old_entry)
        new_entries = Map.put(todo_list.entries, new_entry.id, new_entry)

        %TodoList{ todo_list | entries: new_entries }
    end
  end

  def entries(todo_list, date) do
    todo_list.entries
    |> Stream.filter(fn {_, entry} -> entry.date == date end)
    |> Enum.map(fn {_, entry} -> entry end)
  end
end

error: pathspec 'elixir/todolist/todo_crud.ex' did not match any file(s) known to git


Added config Must find a cleaner way to handle this tokens

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/bit-engine/dustbin.git/'


Wrap RTSP url in quotes in order to escape special characters


Add not test

Add not test

defmodule Xema.NotTest do
  use ExUnit.Case, async: true

  import Xema, only: [validate: 2]

  describe "keyword not:" do
    setup do
      %{schema: Xema.new(:any, not: :integer)}
    end

    test "type", %{schema: schema} do
      assert schema.content.type == :any
    end

    test "validate/2 with a valid value", %{schema: schema} do
      assert validate(schema, "foo") == :ok
    end

    test "validate/2 with an invalid value", %{schema: schema} do
      assert validate(schema, 1) == {:error, %{not: :ok, value: 1}}
    end
  end

  describe "keyword not (shortcut):" do
    setup do
      %{schema: Xema.new(:not, :integer)}
    end

    test "equal long version", %{schema: schema} do
      assert schema == Xema.new(:any, not: :integer)
    end
  end

  describe "nested keyword not:" do
    setup do
      %{
        schema:
          Xema.new(
            :map,
            properties: %{
              foo: {:any, not: {:string, min_length: 3}}
            }
          )
      }
    end

    test "validate/2 with a valid value", %{schema: schema} do
      assert validate(schema, %{foo: ""}) == :ok
    end

    test "validate/2 with an invalid value", %{schema: schema} do
      assert validate(schema, %{foo: "foo"}) ==
               {:error, %{properties: %{foo: %{not: :ok, value: "foo"}}}}
    end
  end

  describe "nested keyword not (shortcut):" do
    setup do
      %{
        schema:
          Xema.new(
            :map,
            properties: %{
              foo: {:not, {:string, min_length: 3}}
            }
          )
      }
    end

    test "equal long version", %{schema: schema} do
      assert schema ==
               Xema.new(
                 :map,
                 properties: %{
                   foo: {:any, not: {:string, min_length: 3}}
                 }
               )
    end
  end
end

error: pathspec 'test/xema/not_test.exs' did not match any file(s) known to git


Increment version [ci skip]

Increment version [ci skip]


Moved earmark and ex_doc from docs env to dev

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/cs-victor-nascimento/joken.git/'


add Mailgun dependency

add Mailgun dependency


trying to catch the right row for the update

defmodule EvercamMedia.MotionDetection.ComparatorHandler do
  use GenEvent
  require Logger
  alias EvercamMedia.Repo
  import Ecto.Query

  @moduledoc """
  TODO
  """

  def handle_event({:got_snapshot, data}, state) do
    {camera_exid, timestamp, image} = data
    image_byte_size = byte_size image
    Logger.info "Inside EvercamMedia.MotionDetection.ComparatorHandler -> handle_event"
    Logger.info "camera_exid=#{camera_exid}"

    camera_exid_last = "#{camera_exid}_last"
    camera_exid_previous = "#{camera_exid}_previous"

    # last_timestamp = result[:timestamp]
    # last_notes = result[:notes]

    last = ConCache.get(:cache, camera_exid_last)
    previous = ConCache.get(:cache, camera_exid_previous)

    last_image = last[:image]
    previous_image = previous[:image]

    Logger.info "last = #{last[:timestamp]}, previous = #{previous[:timestamp]}"

    if last_image && previous_image do
      EvercamMedia.MotionDetection.Lib.init
      motion_level = EvercamMedia.MotionDetection.Lib.compare(last_image,previous_image)
      Logger.info "motion_level = #{motion_level}"

      update_snapshot_status("#{camera_exid}", last[:timestamp], motion_level)
    end

    {:ok, state}
  end

  def update_snapshot_status(camera_exid, seconds, motion_level) do
    camera = Repo.one! Camera.by_exid(camera_exid)
    tt = Timex.Date.from(seconds, :secs)
    # Timex.DateTime{calendar: :gregorian, day: 13, hour: 22, minute: 41, month: 10, ms: 0, second: 25, timezone: %Timex.TimezoneInfo{abbreviation: "UTC", from: :min, full_name: "UTC", offset_std: 0, offset_utc: 0, until: :max}, year: 2015}}
    year = tt.year
    month = tt.month
    day = tt.day

    hour = tt.hour
    min = tt.minute
    sec = tt.second
    usec = tt.ms

    date = {year, month, day}
    time = {hour, min, sec, usec}
    datetime = {date, time}

    date_str = date |> :erlang.tuple_to_list |> Enum.join
    time_str = time |> :erlang.tuple_to_list |> Enum.join

    Logger.info "date is #{date_str} and time is #{time_str}"

    data = Ecto.DateTime.cast(datetime)
    {_,timestamp} = data

    snapshot = Repo.one Snapshot.for_camera(camera.id,timestamp)
    # snapshot = Repo.one! Snapshot.for_camera(camera.id,timestamp)
    # Logger.info "update_snapshot_status snapshot.id=#{snapshot[:id]}"

    case snapshot do
      nil -> Logger.info "No snapshot for #{date_str} and #{time_str}"
      _ ->
        snapshot = %{snapshot | motionlevel: motion_level}
        Logger.info "Updating the snapshot #{snapshot.id}"
        Repo.update snapshot
    end
  end

  def handle_event(_, state) do
    {:ok, state}
  end

end

defmodule EvercamMedia.MotionDetection.ComparatorHandler do
  use GenEvent
  require Logger
  alias EvercamMedia.Repo
  import Ecto.Query

  @moduledoc """
  TODO
  """

  def handle_event({:got_snapshot, data}, state) do
    {camera_exid, timestamp, image} = data
    image_byte_size = byte_size image
    Logger.info "Inside EvercamMedia.MotionDetection.ComparatorHandler -> handle_event"
    Logger.info "camera_exid=#{camera_exid}"

    camera_exid_last = "#{camera_exid}_last"
    camera_exid_previous = "#{camera_exid}_previous"

    # last_timestamp = result[:timestamp]
    # last_notes = result[:notes]

    last = ConCache.get(:cache, camera_exid_last)
    previous = ConCache.get(:cache, camera_exid_previous)

    last_image = last[:image]
    previous_image = previous[:image]

    Logger.info "last = #{last[:timestamp]}, previous = #{previous[:timestamp]}"

    if last_image && previous_image do
      EvercamMedia.MotionDetection.Lib.init
      motion_level = EvercamMedia.MotionDetection.Lib.compare(last_image,previous_image)
      Logger.info "motion_level = #{motion_level}"

      update_snapshot_status("#{camera_exid}", last[:timestamp], motion_level)
    end

    {:ok, state}
  end

  def update_snapshot_status(camera_exid, seconds, motion_level) do
    camera = Repo.one! Camera.by_exid(camera_exid)
    tt = Timex.Date.from(seconds, :secs)
    # Timex.DateTime{calendar: :gregorian, day: 13, hour: 22, minute: 41, month: 10, ms: 0, second: 25, timezone: %Timex.TimezoneInfo{abbreviation: "UTC", from: :min, full_name: "UTC", offset_std: 0, offset_utc: 0, until: :max}, year: 2015}}
    year = tt.year
    month = tt.month
    day = tt.day

    hour = tt.hour
    min = tt.minute
    sec = tt.second
    usec = tt.ms

    date = {year, month, day}
    time = {hour, min, sec, usec}
    datetime = {date, time}

    date_str = date |> :erlang.tuple_to_list |> Enum.join
    time_str = time |> :erlang.tuple_to_list |> Enum.join

    Logger.info "date is #{date_str} and time is #{time_str}"

    data = Ecto.DateTime.cast(datetime)
    {_,timestamp} = data

    snapshot = Repo.one Snapshot.for_camera(camera.id,timestamp)
    # snapshot = Repo.one! Snapshot.for_camera(camera.id,timestamp)
    # Logger.info "update_snapshot_status snapshot.id=#{snapshot[:id]}"

    case snapshot do
      nil -> Logger.info "Not snapshot for #{date_str} and #{time_str}"
      _ ->
        snapshot = %{snapshot | motionlevel: motion_level}
        Logger.info "Updating the snapshot #{snapshot.id}"
        Repo.update snapshot
    end
  end

  def handle_event(_, state) do
    {:ok, state}
  end

end


Use dotenv only in development

Use dotenv only in development


Remove newlines from thumbnails sent by email


:+1: Add ex0505

:+1: Add ex0505

IO.puts "Problem"
IO.inspect Enum.map [1,2,3,4], fn x -> x + 2 end
IO.puts "Answer"
IO.inspect Enum.map [1,2,3,4], &(&1 + 2)

IO.puts "Problem"
Enum.each [1,2,3,4], fn x -> IO.inspect x end
IO.puts "Answer"
Enum.map [1,2,3,4], &(IO.inspect &1)

error: pathspec 'ch05/ex05.exs' did not match any file(s) known to git


[minor] Temporary decrease version

[minor] Temporary decrease version

Make sure it matches latest existing tag


very simple Elixir

very simple Elixir

defmodule Sieve do
  def isprime(n, primes) when is_list(primes) and is_integer(n) do
    case primes do
      [] -> true
      [p|ps] -> if rem(n,p) == 0, do: false, else: isprime(n,ps)
    end
  end

  def primes(maxn, n, ps) when is_integer(n) and is_integer(maxn) and n <= maxn and n > 0 do
    cond do
      n == maxn -> ps
      isprime n, ps -> primes maxn, n+1, [n|ps]
      true -> primes maxn, n+1, ps
    end
  end

  def primes(maxn) when maxn > 0 do
    primes(maxn,3,[2])
  end
end

#Enum.each(Sieve.primes(100000), &IO.puts/1)
IO.puts hd Sieve.primes(100000)

error: pathspec 'elixir/simple.exs' did not match any file(s) known to git


increases coverage for matrix controller

defmodule CoursePlanner.MatrixControllerTest do
  use CoursePlannerWeb.ConnCase

  import CoursePlanner.Factory

  setup do
    {:ok, conn: login_as(:coordinator)}
  end

  defp login_as(user_type) do
    user = insert(user_type)

    Phoenix.ConnTest.build_conn()
    |> assign(:current_user, user)
  end

  test "request index page", %{conn: conn} do
    conn = get conn, term_course_matrix_path(conn, :index, 1)
    assert html_response(conn, 200) =~ "Course Conflict"
  end
end

error: pathspec 'test/controllers/matrix_controller_test.exs' did not match any file(s) known to git