hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
list
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
list
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
list
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
08aa5f86c5e04f9696a323ae1e3c5a03cb8b9bc7
3,284
ex
Elixir
lib/mix/lib/mix/tasks/compile.elixir.ex
gabrielelana/elixir
7e78113f925d438568b7efa8eaded5ae43dce4b1
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/tasks/compile.elixir.ex
gabrielelana/elixir
7e78113f925d438568b7efa8eaded5ae43dce4b1
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/tasks/compile.elixir.ex
gabrielelana/elixir
7e78113f925d438568b7efa8eaded5ae43dce4b1
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Compile.Elixir do use Mix.Task @recursive true @manifest ".compile.elixir" @moduledoc """ Compiles Elixir source files. Elixir is smart enough to recompile only files that changed and their dependencies. This means if `lib/a.ex` is invoking a function defined over `lib/b.ex`, whenever `lib/b.ex` changes, `lib/a.ex` is also recompiled. Note it is important to recompile a file dependencies because often there are compilation time dependencies between them. ## Command line options * `--force` - forces compilation regardless of modification times * `--docs` (`--no-docs`) - attach (or not) documentation to compiled modules * `--debug-info` (`--no-debug-info`) - attach (or not) debug info to compiled modules * `--ignore-module-conflict` - do not emit warnings if a module was previously defined * `--warnings-as-errors` - treat warnings as errors and return a non-zero exit code * `--elixirc-paths` - restrict the original elixirc paths to a subset of the ones specified. Can be given multiple times. ## Configuration * `:elixirc_paths` - directories to find source files. Defaults to `["lib"]`. * `:elixirc_options` - compilation options that apply to Elixir's compiler, they are: `:ignore_module_conflict`, `:docs` and `:debug_info`. By default, uses the same defaults as `elixirc` and they can always be overridden from the command line according to the options above. """ @switches [force: :boolean, docs: :boolean, warnings_as_errors: :boolean, ignore_module_conflict: :boolean, debug_info: :boolean, elixirc_paths: :keep] @doc """ Runs this task. """ @spec run(OptionParser.argv) :: :ok | :noop def run(args) do {opts, _, _} = OptionParser.parse(args, switches: @switches) project = Mix.Project.config dest = Mix.Project.compile_path(project) srcs = project[:elixirc_paths] skip = case Keyword.get_values(opts, :elixirc_paths) do [] -> [] ep -> srcs -- ep end manifest = manifest() configs = Mix.Project.config_files ++ Mix.Tasks.Compile.Erlang.manifests force = opts[:force] || local_deps_changed?(manifest) || Mix.Utils.stale?(configs, [manifest]) Mix.Compilers.Elixir.compile(manifest, srcs, skip, [:ex], dest, force, fn -> set_compiler_opts(project, opts, []) end) end @doc """ Returns Elixir manifests. """ def manifests, do: [manifest] defp manifest, do: Path.join(Mix.Project.manifest_path, @manifest) @doc """ Cleans up compilation artifacts. """ def clean do Mix.Compilers.Elixir.clean(manifest()) end defp set_compiler_opts(project, opts, extra) do opts = Dict.take(opts, Code.available_compiler_options) opts = Keyword.merge(project[:elixirc_options] || [], opts) Code.compiler_options Keyword.merge(opts, extra) end defp local_deps_changed?(manifest) do manifest = Path.absname(manifest) Enum.any?(Mix.Dep.children([]), fn(dep) -> not dep.scm.fetchable? and Mix.Dep.in_dependency(dep, fn(_) -> files = Mix.Project.config_files ++ Mix.Tasks.Compile.manifests Mix.Utils.stale?(files, [manifest]) end) end) end end
32.196078
90
0.672351
08aa74e10fac6aa7e3fe6bbf3bce017c8a96c5e3
3,469
ex
Elixir
lib/level/web_push.ex
mindriot101/level
0a2cbae151869c2d9b79b3bfb388f5d00739ae12
[ "Apache-2.0" ]
928
2018-04-03T16:18:11.000Z
2019-09-09T17:59:55.000Z
lib/level/web_push.ex
mindriot101/level
0a2cbae151869c2d9b79b3bfb388f5d00739ae12
[ "Apache-2.0" ]
74
2018-04-03T00:46:50.000Z
2019-03-10T18:57:27.000Z
lib/level/web_push.ex
mindriot101/level
0a2cbae151869c2d9b79b3bfb388f5d00739ae12
[ "Apache-2.0" ]
89
2018-04-03T17:33:20.000Z
2019-08-19T03:40:20.000Z
defmodule Level.WebPush do @moduledoc """ The subsystem for recording push subscriptions and send them. """ use Supervisor import Ecto.Query alias Ecto.Changeset alias Level.Repo alias Level.WebPush.Payload alias Level.WebPush.Schema alias Level.WebPush.Subscription alias Level.WebPush.SubscriptionSupervisor alias Level.WebPush.UserSupervisor alias Level.WebPush.UserWorker @doc """ Starts the process supervisor. """ def start_link(arg) do Supervisor.start_link(__MODULE__, arg, name: __MODULE__) end @impl true def init(_arg) do children = [ UserSupervisor, SubscriptionSupervisor ] Supervisor.init(children, strategy: :one_for_one) end @doc """ Registers a push subscription. """ @spec subscribe(String.t(), String.t()) :: {:ok, %{digest: String.t(), subscription: Subscription.t()}} | {:error, :invalid_keys | :parse_error | :database_error} def subscribe(user_id, data) do case parse_subscription(data) do {:ok, subscription} -> subscription |> persist(user_id, data) |> after_persist() err -> err end end defp persist(subscription, user_id, data) do result = %Schema{} |> Changeset.change(%{user_id: user_id, data: data}) |> Changeset.change(%{digest: compute_digest(data)}) |> Repo.insert(on_conflict: :nothing) {result, subscription} end defp after_persist({{:ok, record}, subscription}) do {:ok, %{digest: record.digest, subscription: subscription}} end defp after_persist({_, _}) do {:error, :database_error} end defp compute_digest(data) do :sha256 |> :crypto.hash(data) |> Base.encode16() end @doc """ Fetches all subscriptions for a list of user ids. """ @spec get_subscriptions([String.t()]) :: %{ optional(String.t()) => [Subscription.t()] } def get_subscriptions(user_ids) do user_ids |> build_query() |> Repo.all() |> parse_records() end defp build_query(user_ids) do from r in Schema, where: r.user_id in ^user_ids end defp parse_records(records) do records |> Enum.map(fn %Schema{user_id: user_id, data: data} -> case parse_subscription(data) do {:ok, subscription} -> [user_id, subscription] _ -> nil end end) |> Enum.reject(&is_nil/1) |> Enum.group_by(&List.first/1, &List.last/1) end @doc """ Parses raw stringified JSON subscription data. """ @spec parse_subscription(String.t()) :: {:ok, Subscription.t()} | {:error, :invalid_keys} | {:error, :parse_error} def parse_subscription(data) do Subscription.parse(data) end @doc """ Sends a notification to a particular subscription. """ @spec send_web_push(String.t(), Payload.t()) :: :ok | :ignore | {:error, any()} def send_web_push(user_id, %Payload{} = payload) do user_id |> UserSupervisor.start_worker() |> handle_start_worker(user_id, payload) end defp handle_start_worker({:ok, _pid}, user_id, payload) do UserWorker.send_web_push(user_id, payload) end defp handle_start_worker({:ok, _pid, _info}, user_id, payload) do UserWorker.send_web_push(user_id, payload) end defp handle_start_worker({:error, {:already_started, _pid}}, user_id, payload) do UserWorker.send_web_push(user_id, payload) end defp handle_start_worker(err, _, _), do: err end
24.429577
83
0.650908
08aa8a9c4935442d2cc0850fe0ac9391c8318647
75
ex
Elixir
web/views/page_view.ex
Gronex/wishlist_manager
be240ebc85a737f31bd64bc913a2c3716827fd26
[ "MIT" ]
null
null
null
web/views/page_view.ex
Gronex/wishlist_manager
be240ebc85a737f31bd64bc913a2c3716827fd26
[ "MIT" ]
7
2015-12-30T19:43:10.000Z
2016-01-04T14:38:38.000Z
web/views/page_view.ex
Gronex/wishlist_manager
be240ebc85a737f31bd64bc913a2c3716827fd26
[ "MIT" ]
null
null
null
defmodule WishlistManager.PageView do use WishlistManager.Web, :view end
18.75
37
0.826667
08aacbbe44ced959e01bd8fbd4f9e92a2affcace
656
ex
Elixir
test/support/gen/plug/post_test_hmac_with_body.ex
dvlp123456/oasis
a1b2ec720277ced6956094ceb139124f5459b78e
[ "MIT" ]
11
2021-02-24T09:21:11.000Z
2021-12-26T03:51:25.000Z
test/support/gen/plug/post_test_hmac_with_body.ex
dvlp123456/oasis
a1b2ec720277ced6956094ceb139124f5459b78e
[ "MIT" ]
5
2021-03-18T14:15:37.000Z
2022-03-02T09:53:42.000Z
test/support/gen/plug/post_test_hmac_with_body.ex
dvlp123456/oasis
a1b2ec720277ced6956094ceb139124f5459b78e
[ "MIT" ]
6
2021-02-24T09:21:01.000Z
2021-11-16T08:45:03.000Z
defmodule Oasis.Gen.Plug.PostTestHMACWithBody do # NOTICE: This module is generated when run `mix oas.gen.plug` task command with the OpenAPI Specification file # in the first time, and then it WILL NOT be modified in the future generation command(s) once this file exists, # please write your business code in this module. use Oasis.Controller def init(opts), do: opts def call(conn, _opts) do conn |> json(%{"hmac" => "with_body"}) end def handle_errors(conn, %{kind: _kind, reason: reason, stack: _stack}) do message = Map.get(reason, :message) || "Something went wrong" send_resp(conn, conn.status, message) end end
36.444444
114
0.714939
08aaedff69ab263909eb6d22a106be82de25ec75
1,503
ex
Elixir
clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3beta1_export_test_cases_metadata.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3beta1_export_test_cases_metadata.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3beta1_export_test_cases_metadata.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3beta1ExportTestCasesMetadata do @moduledoc """ Metadata returned for the TestCases.ExportTestCases long running operation. This message currently has no fields. ## Attributes """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{} end defimpl Poison.Decoder, for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3beta1ExportTestCasesMetadata do def decode(value, options) do GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3beta1ExportTestCasesMetadata.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3beta1ExportTestCasesMetadata do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.978723
115
0.779108
08ab02ccedf5cbf6897716458cc30bfe8a850daa
4,347
ex
Elixir
apps/shell/lib/server.ex
lowlandresearch/kudzu
f65da5061c436afb114a2e95bc6d115b6ec7be53
[ "MIT" ]
null
null
null
apps/shell/lib/server.ex
lowlandresearch/kudzu
f65da5061c436afb114a2e95bc6d115b6ec7be53
[ "MIT" ]
4
2020-05-16T16:05:33.000Z
2020-05-16T19:52:12.000Z
apps/shell/lib/server.ex
lowlandresearch/kudzu
f65da5061c436afb114a2e95bc6d115b6ec7be53
[ "MIT" ]
null
null
null
defmodule Shell.Server do use GenServer require Logger def start_link(opts) do GenServer.start_link(__MODULE__, :ok, opts) end # ------------------------------------------------------------ # Client API # ------------------------------------------------------------ def fetch(name) do GenServer.call(__MODULE__, {:fetch, name}) end def status(name) do GenServer.call(__MODULE__, {:status, name}) end def status() do GenServer.call(__MODULE__, :status) end def outcome(name, sleep \\ 1000) do case Shell.Server.status(name) do {:running, _} -> :timer.sleep(sleep) outcome(name, sleep) status -> status end end def outcomes(names, sleep \\ 1000) do statuses = names |> Enum.map(&Shell.Server.status/1) has_running = statuses |> Enum.any?(fn {state, _} -> state == :running end) if has_running do :timer.sleep(sleep) outcomes(names, sleep) else statuses end end def list() do GenServer.call(__MODULE__, :list) end def start(module, name, args) do GenServer.cast(__MODULE__, {:start, module, name, args}) end def halt(name) do GenServer.call(__MODULE__, {:halt, name}) end def flush() do GenServer.call(__MODULE__, :flush) end # ------------------------------------------------------------ # Server API # ------------------------------------------------------------ @impl true def init(:ok) do processes = %{} monitors = %{} {:ok, {processes, monitors}} end @impl true def handle_call(:flush, _from, {processes, _} = state) do finished = processes |> Enum.filter(fn {_, pid} -> case Shell.Command.status(pid) do {:success, _} -> true {:failure, _} -> true _ -> false end end) |> Enum.map(fn {_, pid} -> Shell.Command.halt(pid) end) {:reply, {:ok, finished}, state} end @impl true def handle_call(:list, _from, {processes, _} = state) do {:reply, {:ok, processes |> Map.keys()}, state} end @impl true def handle_call({:fetch, name}, _from, {processes, _} = state) do {:reply, Map.fetch(processes, name), state} end @impl true def handle_call({:status, name}, _from, {processes, _} = state) do case Map.fetch(processes, name) do {:ok, pid} -> {:reply, Shell.Command.status(pid), state} _ -> {:reply, :error, state} end end @impl true def handle_call(:status, _from, {processes, _} = state) do status = processes |> Enum.map(fn {name, pid} -> case Shell.Command.status(pid) do {:running, nil} -> {name, "Starting..."} {:running, %{task: task, percent: percent, remaining: remaining}} -> {name, "#{task}: #{remaining}s (#{percent}%)"} {:success, _} -> {name, "Done."} {:failure, _} -> {name, "FAILED."} end end) |> Enum.into(%{}) {:reply, status, state} end @impl true def handle_call({:halt, name}, _from, {processes, _} = state) do pid = Map.get(processes, name) case Shell.Command.halt(pid) do :ok -> {:reply, :ok, state} error -> {:reply, error, state} end end @impl true def handle_cast({:start, module, name, args}, {processes, monitors}) do if Map.has_key?(processes, name) do {:noreply, {processes, monitors}} else # IO.inspect(args) {:ok, pid} = DynamicSupervisor.start_child( Shell.CommandSupervisor, {module, args} ) ref = Process.monitor(pid) monitors = Map.put(monitors, ref, name) processes = Map.put(processes, name, pid) {:noreply, {processes, monitors}} end end @impl true def handle_info( {:DOWN, ref, :process, _pid, _reason}, {processes, monitors} ) do {name, monitors} = Map.pop(monitors, ref) # Logger.info("Process down: #{name}") {_pid, processes} = Map.pop(processes, name) # if Process.alive?(pid) do # case Shell.Command.status(pid) do # {:running, _} -> GenServer.stop(pid) # _ -> 1 # end {:noreply, {processes, monitors}} end @impl true def handle_info(_msg, state) do {:noreply, state} end end
22.878947
78
0.536462
08ab092f980e43f338f0f12be8b63d5b93ec0ea7
1,862
ex
Elixir
web/web.ex
w0rd-driven/scratch_phoenix
465e01af6e7d649bfb308edf91247e9d6c6a5876
[ "MIT" ]
null
null
null
web/web.ex
w0rd-driven/scratch_phoenix
465e01af6e7d649bfb308edf91247e9d6c6a5876
[ "MIT" ]
null
null
null
web/web.ex
w0rd-driven/scratch_phoenix
465e01af6e7d649bfb308edf91247e9d6c6a5876
[ "MIT" ]
null
null
null
defmodule ScratchPhoenix.Web do @moduledoc """ A module that keeps using definitions for controllers, views and so on. This can be used in your application as: use ScratchPhoenix.Web, :controller use ScratchPhoenix.Web, :view The definitions below will be executed for every view, controller, etc, so keep them short and clean, focused on imports, uses and aliases. Do NOT define functions inside the quoted expressions below. """ def model do quote do use Ecto.Schema import Ecto import Ecto.Changeset import Ecto.Query, only: [from: 1, from: 2] @primary_key {:id, :binary_id, autogenerate: true} @foreign_key_type :binary_id end end def controller do quote do use Phoenix.Controller alias ScratchPhoenix.Repo import Ecto import Ecto.Query, only: [from: 1, from: 2] import ScratchPhoenix.Router.Helpers import ScratchPhoenix.Gettext end end def view do quote do use Phoenix.View, root: "web/templates" # Import convenience functions from controllers import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1] # Use all HTML functionality (forms, tags, etc) use Phoenix.HTML import ScratchPhoenix.Router.Helpers import ScratchPhoenix.ErrorHelpers import ScratchPhoenix.Gettext end end def router do quote do use Phoenix.Router end end def channel do quote do use Phoenix.Channel alias ScratchPhoenix.Repo import Ecto import Ecto.Query, only: [from: 1, from: 2] import ScratchPhoenix.Gettext end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
21.905882
88
0.675081
08ab15f888cb9f967a2574429591b616c31e1f5c
2,537
ex
Elixir
apps/blockchain/lib/mix/tasks/sync/from_file.ex
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
152
2018-10-27T04:52:03.000Z
2022-03-26T10:34:00.000Z
apps/blockchain/lib/mix/tasks/sync/from_file.ex
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
270
2018-04-14T07:34:57.000Z
2018-10-25T18:10:45.000Z
apps/blockchain/lib/mix/tasks/sync/from_file.ex
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
25
2018-10-27T12:15:13.000Z
2022-01-25T20:31:14.000Z
defmodule Mix.Tasks.Sync.FromFile do @shortdoc "Allows users to sync the blockchain from a file exported by parity" @moduledoc """ SyncFromFile allows users to sync the blockchain from a file exported by parity. You can make an export with the following command: `parity export blocks ./export-blocks-mainnet.bin` And then run `sync_with_file` to verify the chain: `mix run apps/blockchain/scripts/sync_from_file.ex export-blocks-mainnet.bin` """ use Mix.Task require Logger alias Blockchain.Block alias Blockchain.Blocktree alias Blockchain.Chain alias Blockchain.Genesis alias MerklePatriciaTree.DB alias MerklePatriciaTree.DB.RocksDB alias MerklePatriciaTree.Trie def run(args) do {db, chain} = setup() current_block_number = case DB.get(db, "current_block_number") do {:ok, current_block_number} -> current_block_number _ -> 0 end tree = case DB.get(db, "current_block_tree") do {:ok, current_block_tree} -> :erlang.binary_to_term(current_block_tree) _ -> Blocktree.new_tree() end {first_block_data, blocks_data} = args |> File.read!() |> ExRLP.decode() |> Enum.split(3) first_block = Block.deserialize(first_block_data) trie = Trie.new(db) blocks = [Genesis.create_block(chain, trie), first_block] ++ (blocks_data |> Enum.map(&Block.deserialize/1)) add_block_to_tree(db, chain, tree, blocks, current_block_number) end @spec setup() :: {DB.t(), Chain.t()} defp setup() do db = RocksDB.init(db_name()) chain = Chain.load_chain(:foundation) {db, chain} end defp add_block_to_tree(db, chain, tree, blocks, n) do next_block = Enum.at(blocks, n) if is_nil(next_block) do :ok = Logger.info("Validation complete") DB.put!(db, "current_block_number", 0) else case Blocktree.verify_and_add_block(tree, chain, next_block, db) do {:ok, next_tree} -> :ok = Logger.info("Verified Block #{n}") DB.put!(db, "current_block_number", next_block.header.number) add_block_to_tree(db, chain, next_tree, blocks, n + 1) {:invalid, error} -> :ok = Logger.info("Failed to Verify Block #{n}") _ = Logger.error(inspect(error)) DB.put!(db, "current_block_tree", :erlang.term_to_binary(tree)) end end end defp db_name() do env = Mix.env() |> to_string() 'db/mana-' ++ env end end
26.427083
82
0.642491
08ab207d78f56fd28965e06f5d868b155acecc34
5,145
ex
Elixir
lib/flix/catalogs/movie.ex
conradwt/flix-elixir
e4d6bf6fd79be12fbed6fb6250f78e929247c1a4
[ "MIT" ]
3
2021-03-21T23:52:16.000Z
2021-06-02T03:47:00.000Z
lib/flix/catalogs/movie.ex
conradwt/flix-elixir
e4d6bf6fd79be12fbed6fb6250f78e929247c1a4
[ "MIT" ]
44
2021-04-09T04:04:13.000Z
2022-03-29T06:29:37.000Z
lib/flix/catalogs/movie.ex
conradwt/flix-elixir
e4d6bf6fd79be12fbed6fb6250f78e929247c1a4
[ "MIT" ]
null
null
null
defmodule Flix.Catalogs.Movie do use Ecto.Schema use Waffle.Ecto.Schema import Ecto.Changeset import Ecto.Query, only: [from: 2] import Parameterize alias Flix.Catalogs.{Favorite, Genre, Review, Characterization} alias Flix.Repo schema "movies" do field(:description, :string) field(:director, :string) field(:duration, :string) field(:rating, :string) field(:released_on, :date) field(:slug, :string) field(:title, :string) field(:total_gross, :decimal) field(:main_image, Flix.MainImageUploader.Type) has_many(:reviews, Review) has_many(:favorites, Favorite) # TODO: In Rails: has_many :fans, through: :favorites, source: :user has_many(:fans, through: [:favorites, :user]) # has_many(:characterizations, Characterization) # has_many(:genres, through: [:characterizations, :genre]) # https://hexdocs.pm/phoenix_mtm/PhoenixMTM.Changeset.html many_to_many(:genres, Genre, join_through: Characterization, on_replace: :delete, on_delete: :delete_all ) timestamps() end @doc false def filters, do: ~w(released upcoming recent hits flops) @doc false def ratings, do: ~w(G PG PG-13 R NC-17) @doc false def changeset(movie, attrs) do movie |> cast(attrs, [ :description, :director, :duration, :rating, :released_on, :slug, :title, :total_gross ]) |> cast_attachments(attrs, [:main_image]) |> PhoenixMTM.Changeset.cast_collection(:genres, fn ids -> # Convert Strings back to Integers ids = Enum.map(ids, &String.to_integer/1) Repo.all(from(g in Genre, where: g.id in ^ids)) end) |> validate_description |> validate_director |> validate_duration |> validate_genres |> validate_main_image |> validate_rating |> validate_released_on |> validate_title |> validate_total_gross end defp validate_description(changeset) do changeset |> validate_required(:description) |> validate_length(:description, min: 25) end defp validate_director(changeset) do changeset |> validate_required(:director) end defp validate_duration(changeset) do changeset |> validate_required(:duration) end defp validate_genres(changeset) do changeset |> PhoenixMTM.Changeset.cast_collection(:genres, fn ids -> # Convert Strings back to Integers ids = Enum.map(ids, &String.to_integer/1) Repo.all(from(g in Genre, where: g.id in ^ids)) end) end defp validate_main_image(changeset) do changeset |> validate_required(:main_image) end defp validate_rating(changeset) do changeset |> validate_required(:rating) |> validate_inclusion(:rating, ratings()) end defp validate_released_on(changeset) do changeset |> validate_required(:released_on) end defp validate_title(changeset) do changeset |> slugify_title |> validate_required(:title) |> unique_constraint(:title) end defp validate_total_gross(changeset) do changeset |> validate_required(:total_gross) |> validate_number(:total_gross, greater_than_or_equal_to: 0) end defp slugify_title(changeset) do case fetch_change(changeset, :title) do {:ok, new_title} -> put_change(changeset, :slug, parameterize(new_title)) :error -> changeset end end @doc false def flops(query) do from(movie in query, where: movie.total_gross < 225_000_000 ) end @doc false def grossed_greater_than(query, amount) do from(movie in query, where: movie.total_gross > ^amount ) end @doc false def grossed_less_than(query, amount) do from(movie in query, where: movie.total_gross < ^amount ) end @doc false def hits(query) do from(movie in query, where: movie.total_gross >= 300_000_000, order_by: [desc: movie.total_gross] ) end @doc false def recent(query, max_number \\ 5) do from(movie in query, where: movie.released_on < ^Date.utc_today(), order_by: [desc: movie.released_on], limit: ^max_number ) end @doc false def released(query) do from(movie in query, where: movie.released_on < ^Date.utc_today(), order_by: [desc: movie.released_on] ) end @doc false def upcoming(query) do from(movie in query, where: movie.released_on > ^Date.utc_today(), order_by: [asc: movie.released_on] ) end @doc false def flop?(movie) do movie.total_gross < 225_000_000 end @doc false def created(query) do from(movie in query, order_by: [:desc, movie.created_at], limit: 3 ) end def average_stars_as_percent(movie) do average = movie |> average_stars() average / 5.0 * 100 end def average_stars(movie) do movie = movie |> Repo.preload(:reviews) if Enum.empty?(movie.reviews) do 0.0 else Repo.one( from(r in Review, where: ^movie.id == r.movie_id, select: avg(r.stars) ) ) |> Decimal.to_float() end end end
22.565789
72
0.653256
08ab4d662f2d237991718c148e886cae31ccab7b
2,737
ex
Elixir
clients/ad_sense/lib/google_api/ad_sense/v14/api/payments.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/ad_sense/lib/google_api/ad_sense/v14/api/payments.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/ad_sense/lib/google_api/ad_sense/v14/api/payments.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AdSense.V14.Api.Payments do @moduledoc """ API calls for all endpoints tagged `Payments`. """ alias GoogleApi.AdSense.V14.Connection import GoogleApi.AdSense.V14.RequestBuilder @doc """ List the payments for this AdSense account. ## Parameters - connection (GoogleApi.AdSense.V14.Connection): Connection to server - opts (KeywordList): [optional] Optional parameters - :alt (String): Data format for the response. - :fields (String): Selector specifying which fields to include in a partial response. - :key (String): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String): OAuth 2.0 token for the current user. - :pretty_print (Boolean): Returns response with indentations and line breaks. - :quota_user (String): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - :user_ip (String): IP address of the site where the request originates. Use this if you want to enforce per-user limits. ## Returns {:ok, %GoogleApi.AdSense.V14.Model.Payments{}} on success {:error, info} on failure """ @spec adsense_payments_list(Tesla.Env.client, keyword()) :: {:ok, GoogleApi.AdSense.V14.Model.Payments.t} | {:error, Tesla.Env.t} def adsense_payments_list(connection, opts \\ []) do optional_params = %{ :"alt" => :query, :"fields" => :query, :"key" => :query, :"oauth_token" => :query, :"prettyPrint" => :query, :"quotaUser" => :query, :"userIp" => :query } %{} |> method(:get) |> url("/payments") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.AdSense.V14.Model.Payments{}) end end
39.666667
217
0.704421
08ab51878ba0139333c2610f643e0f0867c9d645
331
ex
Elixir
lib/vimdoc/file.ex
liquidz/ex_vimdoc
3b3df4b53d45045f1ef60d4db965ea4e4d2d8a40
[ "MIT" ]
null
null
null
lib/vimdoc/file.ex
liquidz/ex_vimdoc
3b3df4b53d45045f1ef60d4db965ea4e4d2d8a40
[ "MIT" ]
null
null
null
lib/vimdoc/file.ex
liquidz/ex_vimdoc
3b3df4b53d45045f1ef60d4db965ea4e4d2d8a40
[ "MIT" ]
null
null
null
defmodule Vimdoc.File do def find(path) do case File.ls(path) do {:error, _} -> [] {:ok, list} -> list |> Enum.flat_map(fn f -> path = Path.join(path, f) if File.dir?(path) do find path else [path] end end) end end end
18.388889
35
0.435045
08ab58b6e6f925bbf385c205f3c68edd5e635164
4,528
exs
Elixir
test/changelog/kits/url_kit_test.exs
boneskull/changelog.com
2fa2e356bb0e8fcf038c46a4a947fef98822e37d
[ "MIT" ]
null
null
null
test/changelog/kits/url_kit_test.exs
boneskull/changelog.com
2fa2e356bb0e8fcf038c46a4a947fef98822e37d
[ "MIT" ]
null
null
null
test/changelog/kits/url_kit_test.exs
boneskull/changelog.com
2fa2e356bb0e8fcf038c46a4a947fef98822e37d
[ "MIT" ]
null
null
null
defmodule Changelog.UrlKitTest do use Changelog.DataCase alias Changelog.UrlKit describe "is_youtube" do test "is true for youtube URLS" do assert UrlKit.is_youtube("https://youtu.be/7msERxu7ivg") assert UrlKit.is_youtube("https://www.youtube.com/watch?v=7msERxu7ivg") end test "is false for non-youtube URLS" do refute UrlKit.is_youtube("https://vimeo.com/239702317") refute UrlKit.is_youtube("https://www.twitch.tv/skacle") end end describe "get_object_id" do test "defaults to nil" do assert is_nil(UrlKit.get_object_id(:link, nil)) end test "returns podcast and episode slug when hosted audio" do assert UrlKit.get_object_id(:audio, "https://changelog.com/gotime/123") == "gotime:123" assert UrlKit.get_object_id(:audio, "https://changelog.com/rfc/15") == "rfc:15" end test "returns nil when non-hosted audio" do assert is_nil(UrlKit.get_object_id(:audio, "https://test.com/gotime/123")) end test "returns post and slug when hosted" do assert UrlKit.get_object_id(:announcement, "https://changelog.com/posts/oscon-2017-free-pass") == "posts:oscon-2017-free-pass" end test "returns nil when type has no known objects" do assert is_nil(UrlKit.get_object_id(:project, "https://test.com")) end end describe "get_source" do test "defaults to nil" do assert UrlKit.get_source(nil) == nil assert UrlKit.get_source("https://test.com") == nil end test "returns nil if there's a source with a bad regex" do insert(:news_source, regex: "*wired.com*") assert UrlKit.get_source("https://wired.com") == nil end test "returns the source when a match is found in the db" do wired = insert(:news_source, regex: "wired.com|twitter.com/wired") url = "https://www.wired.com/2017/10/things-we-loved-in-october/" assert UrlKit.get_source(url) == wired url = "https://twitter.com/wired/status/8675309" assert UrlKit.get_source(url) == wired end end describe "get_type" do test "defaults to link" do assert UrlKit.get_type(nil) == :link url = "https://example.com/whatevs?oh=yeah" assert UrlKit.get_type(url) == :link end test "returns project with a GitHub url" do url = "https://github.com/pixelandtonic/CommerceEasyPost" assert UrlKit.get_type(url) == :project end test "returns *not* a project with a GitHub blog url" do url = "https://github.com/blog" assert UrlKit.get_type(url) == :link end test "returns project with a GitLab url" do url = "https://gitlab.com/masterofolympus/le-maitre-des-titans" assert UrlKit.get_type(url) == :project end test "returns *not* a project with a GitLab about url" do url = "https://about.gitlab.com/features" assert UrlKit.get_type(url) == :link end test "returns video with a YouTube, Vimeo, or Twitch" do for url <- ~w(https://www.youtube.com/watch?v=dQw4w9WgXcQ https://vimeo.com/226379658 https://go.twitch.tv/videos/92287997) do assert UrlKit.get_type(url) == :video end end end describe "get_youtube_id" do test "defaults to nil" do assert is_nil(UrlKit.get_youtube_id("https://vimeo.com/239702317")) end test "works with query param style" do id = UrlKit.get_youtube_id("https://www.youtube.com/watch?v=7msERxu7ivg") assert id == "7msERxu7ivg" end test "works with url-style" do id = UrlKit.get_youtube_id("https://youtu.be/7msERxu7ivg") assert id == "7msERxu7ivg" end end describe "normalize_url" do test "defaults to nil" do assert UrlKit.normalize_url(nil) == nil end test "leaves 'normal' URLs alone" do url = "https://changelog.com/ohai-there" assert UrlKit.normalize_url(url) == url end test "removes UTM params" do url = "https://www.theverge.com/2017/11/7/16613234/next-level-ar-vr-memories-holograms-8i-actress-shoah-foundation?utm_campaign=theverge" normalized = "https://www.theverge.com/2017/11/7/16613234/next-level-ar-vr-memories-holograms-8i-actress-shoah-foundation" assert UrlKit.normalize_url(url) == normalized end end describe "sans_scheme" do test "it removes the scheme, but leaves everything else" do url = "https://news.ycombinator.com/item?id=18120667" sans = UrlKit.sans_scheme(url) assert sans == "news.ycombinator.com/item?id=18120667" end end end
33.294118
143
0.672924
08ab620c93cb7f920d4eb8f1fac21e32b9705123
881
ex
Elixir
lib/extwitter/api/v1/places_and_geo.ex
PJUllrich/extwitter
edee88d5b9411bd0e3226c295362e328ae73255d
[ "MIT" ]
null
null
null
lib/extwitter/api/v1/places_and_geo.ex
PJUllrich/extwitter
edee88d5b9411bd0e3226c295362e328ae73255d
[ "MIT" ]
null
null
null
lib/extwitter/api/v1/places_and_geo.ex
PJUllrich/extwitter
edee88d5b9411bd0e3226c295362e328ae73255d
[ "MIT" ]
null
null
null
defmodule ExTwitter.API.V1.PlacesAndGeo do @moduledoc """ Provides places and geo API interfaces. """ import ExTwitter.API.Base def geo_search(options) when is_list(options) do params = ExTwitter.API.AuthParser.parse_request_params(options) request(:get, "1.1/geo/search.json", params) |> ExTwitter.JSON.get(:result) |> ExTwitter.JSON.get(:places) |> Enum.map(&ExTwitter.API.V1.ModelParser.parse_place/1) end def geo_search(query, options \\ []) do geo_search([query: query] ++ options) end def reverse_geocode(lat, long, options \\ []) do params = ExTwitter.API.AuthParser.parse_request_params([lat: lat, long: long] ++ options) request(:get, "1.1/geo/reverse_geocode.json", params) |> ExTwitter.JSON.get(:result) |> ExTwitter.JSON.get(:places) |> Enum.map(&ExTwitter.API.V1.ModelParser.parse_place/1) end end
29.366667
93
0.694665
08ab6407e399b16b65f216313a5b98287610e1a3
421
exs
Elixir
elixir/acronym/acronym.exs
ErikSchierboom/exercism
3da5d41ad3811c5963a0da62f862602ba01a9f55
[ "Apache-2.0" ]
23
2017-02-22T16:57:12.000Z
2022-02-11T20:32:36.000Z
elixir/acronym/acronym.exs
ErikSchierboom/exercism
3da5d41ad3811c5963a0da62f862602ba01a9f55
[ "Apache-2.0" ]
36
2020-07-21T09:34:05.000Z
2020-07-21T10:29:20.000Z
elixir/acronym/acronym.exs
ErikSchierboom/exercism
3da5d41ad3811c5963a0da62f862602ba01a9f55
[ "Apache-2.0" ]
14
2017-02-22T16:58:23.000Z
2021-10-06T00:21:57.000Z
defmodule Acronym do @doc """ Generate an acronym from a string. "This is a string" => "TIAS" """ @spec abbreviate(String.t()) :: String.t() def abbreviate(string) do string |> words |> Enum.map(&acronym_letter/1) |> Enum.join("") end defp words(string), do: Regex.scan(~r/[A-Z]+[a-z]*|[a-z]+/, string) |> Enum.concat() defp acronym_letter(string), do: String.first(string) |> String.upcase() end
28.066667
86
0.631829
08ab693ca34bc0020dbcac32c2b4fe459e178d71
8,082
exs
Elixir
bench/witchcraft/foldable/map_bench.exs
doma-engineering/witchcraft
c84fa6b2146e7de745105e21f672ed413df93ad3
[ "MIT" ]
454
2019-06-05T22:56:45.000Z
2022-03-27T23:03:02.000Z
bench/witchcraft/foldable/map_bench.exs
doma-engineering/witchcraft
c84fa6b2146e7de745105e21f672ed413df93ad3
[ "MIT" ]
26
2019-07-08T09:29:08.000Z
2022-02-04T02:40:48.000Z
bench/witchcraft/foldable/map_bench.exs
doma-engineering/witchcraft
c84fa6b2146e7de745105e21f672ed413df93ad3
[ "MIT" ]
36
2019-06-25T17:45:27.000Z
2022-03-21T01:53:42.000Z
defmodule Witchcraft.Foldable.MapBench do require Integer use Benchfella use Witchcraft.Foldable ######### # Setup # ######### # ---------- # # Data Types # # ---------- # @list Enum.to_list(0..10) @map @list |> Enum.zip(@list) |> Enum.into(%{}) ############ # Foldable # ############ bench "Enum.all?/1" do %{a: true, b: false, c: true, d: true, e: false} |> Map.values() |> Enum.all?() end bench "all?/1", do: all?(%{a: true, b: false, c: true, d: true, e: false}) bench "all?/2", do: all?(@map, fn x -> x > 5 end) bench "Enum.any?/1" do %{a: true, b: false, c: true, d: true, e: false} |> Map.values() |> Enum.any?() end bench "any?/1", do: any?(%{a: true, b: false, c: true, d: true, e: false}) bench "any?/2", do: any?(@map, fn x -> x > 5 end) bench "flatten/1", do: flatten(%{a: @list, b: @list, c: @list, d: @list}) bench "Enum.flat_map/2", do: @map |> Map.values() |> Enum.flat_map(fn x -> [x, x + 1] end) bench "flat_map/2", do: flat_map(@map, fn x -> [x, x + 1] end) bench "Enum.count/1", do: Enum.count(@map) bench "count/1", do: count(@map) bench "length/1", do: length(@map) bench "empty?/1", do: empty?(@map) bench "null?/1", do: null?(@map) bench "Enum.member?/2", do: @map |> Map.values() |> Enum.member?(99) bench "member?/2", do: member?(@map, 99) bench "Enum.max/1", do: @map |> Map.values() |> Enum.max() bench "max/1", do: max(@map) bench "Enum.max_by/2", do: @map |> Map.values() |> Enum.max_by(fn(x) -> Integer.mod(x, 3) end) # Cheating a bit bench "max/2", do: max(@map, by: fn(x, y) -> Integer.mod(x, 3) > y end) bench "Enum.min/1", do: @map |> Map.values() |> Enum.min() bench "min/1", do: min(@map) bench "Enum.min_by/2", do: @map |> Map.values() |> Enum.min_by(fn(x) -> Integer.mod(x, 3) end) # Cheating a bit bench "min/2", do: min(@map, by: fn(x, y) -> Integer.mod(x, 3) > y end) bench "Enum.sum/1", do: @map |> Map.values() |> Enum.sum() bench "sum/1", do: sum(@map) bench "&Enum.reduce(&1, &*/2)", do: @map |> Map.values() |> Enum.reduce(&*/2) bench "product/1", do: product(@map) bench "Enum.random/1" do @map |> Map.values() |> Enum.random() true # get Benchfella to match on multiple runs end bench "random/1" do random(@map) true # get Benchfella to match on multiple runs end bench "fold/1", do: fold(@map) bench "fold_map/2", do: fold_map(@map, fn x -> [x, x + 1] end) bench "Enum.map_reduce/3 + []" do @map |> Map.values() |> Enum.map_reduce([], fn(x, acc) -> {[x + 1 | acc], nil} end) |> elem(0) end bench "left_fold/2", do: left_fold(@map, fn(acc, x) -> [x + 1 | acc] end) bench "left_fold/3", do: left_fold(@map, @map, fn(acc, x) -> [x + 1 | acc] end) bench "List.foldl/3 + []", do: @map |> Map.values() |> List.foldl([], fn(x, acc) -> [x + 1 | acc]end) bench "List.foldl/3", do: List.foldl(Map.values(@map), Map.values(@map), fn(x, acc) -> [x + 1 | acc] end) bench "right_fold/3 + []", do: right_fold(@map, [], fn(x, acc) -> [x + 1 | acc] end) bench "right_fold/3", do: right_fold(@map, @map, fn(x, acc) -> [x + 1 | acc] end) bench "Enum.reduce/2", do: @map |> Map.values() |> Enum.reduce(fn(x, acc) -> [x + 1 | acc] end) bench "Enum.reduce/3", do: Enum.reduce(Map.values(@map), Map.values(@map), fn(x, acc) -> [x + 1 | acc] end) bench "List.foldr/3 + []", do: @map |> Map.values() |> List.foldr([], fn(x, acc) -> [x + 1 | acc]end) bench "List.foldr/3", do: List.foldr(Map.values(@map), Map.values(@map), fn(x, acc) -> [x + 1 | acc] end) bench "size/1", do: size(@map) bench "then_sequence/1", do: then_sequence(%{a: @list, b: @list, c: @list, d: @list}) bench "Map.values/1", do: Map.values(@map) bench "to_list/1", do: to_list(@map) # ---------- # # Large Data # # ---------- # @med_list Enum.to_list(0..250) @big_list Enum.to_list(0..10_000) @big_map @big_list |> Enum.zip(@big_list) |> Enum.into(%{}) @bools Enum.map(@big_map, fn _ -> Enum.random([true, false]) end) @nested fn -> [1, 2, 3] end |> Stream.repeatedly() |> Enum.take(10) bench "$$$ Enum.all?/1" do %{a: true, b: false, c: true, d: true, e: false} |> Map.values() |> Enum.all?() end bench "$$$ all?/1", do: all?(%{a: true, b: false, c: true, d: true, e: false}) bench "$$$ all?/2", do: all?(@big_map, fn x -> x > 5 end) bench "$$$ Enum.any?/1" do %{a: true, b: false, c: true, d: true, e: false} |> Map.values() |> Enum.any?() end bench "$$$ any?/1", do: any?(%{a: true, b: false, c: true, d: true, e: false}) bench "$$$ any?/2", do: any?(@big_map, fn x -> x > 5 end) bench "$$$ flatten/1", do: flatten(%{a: @big_list, b: @big_list, c: @big_list, d: @big_list}) bench "$$$ Enum.flat_map/2", do: @big_map |> Map.values() |> Enum.flat_map(fn x -> [x, x + 1] end) bench "$$$ flat_map/2", do: flat_map(@big_map, fn x -> [x, x + 1] end) bench "$$$ Enum.count/1", do: Enum.count(@big_map) bench "$$$ count/1", do: count(@big_map) bench "$$$ length/1", do: length(@big_map) bench "$$$ empty?/1", do: empty?(@big_map) bench "$$$ null?/1", do: null?(@big_map) bench "$$$ Enum.member?/2", do: @big_map |> Map.values() |> Enum.member?(99) bench "$$$ member?/2", do: member?(@big_map, 99) bench "$$$ Enum.max/1", do: @big_map |> Map.values() |> Enum.max() bench "$$$ max/1", do: max(@big_map) bench "$$$ Enum.max_by/2", do: @big_map |> Map.values() |> Enum.max_by(fn(x) -> Integer.mod(x, 3) end) # Cheating a bit bench "$$$ max/2", do: max(@big_map, by: fn(x, y) -> Integer.mod(x, 3) > y end) bench "$$$ Enum.min/1", do: @big_map |> Map.values() |> Enum.min() bench "$$$ min/1", do: min(@big_map) bench "$$$ Enum.min_by/2", do: @big_map |> Map.values() |> Enum.min_by(fn(x) -> Integer.mod(x, 3) end) # Cheating a bit bench "$$$ min/2", do: min(@big_map, by: fn(x, y) -> Integer.mod(x, 3) > y end) bench "$$$ Enum.sum/1", do: @big_map |> Map.values() |> Enum.sum() bench "$$$ sum/1", do: sum(@big_map) bench "$$$ &Enum.reduce(&1, &*/2)", do: @big_map |> Map.values() |> Enum.reduce(&*/2) bench "$$$ product/1", do: product(@big_map) bench "$$$ Enum.random/1" do @big_map |> Map.values() |> Enum.random() true # get Benchfella to match on multiple runs end bench "$$$ random/1" do random(@big_map) true # get Benchfella to match on multiple runs end bench "$$$ fold/1", do: fold(@big_map) bench "$$$ fold_map/2", do: fold_map(@big_map, fn x -> [x, x + 1] end) bench "$$$ Enum.map_reduce/3 + []" do @big_map |> Map.values() |> Enum.map_reduce([], fn(x, acc) -> {[x + 1 | acc], nil} end) |> elem(0) end bench "$$$ left_fold/2", do: left_fold(@big_map, fn(acc, x) -> [x + 1 | acc] end) bench "$$$ left_fold/3", do: left_fold(@big_map, @big_map, fn(acc, x) -> [x + 1 | acc] end) bench "$$$ List.foldl/3 + []" do @big_map |> Map.values() |> List.foldl([], fn(x, acc) -> [x + 1 | acc]end) end bench "$$$ List.foldl/3" do List.foldl(Map.values(@big_map), Map.values(@big_map), fn(x, acc) -> [x + 1 | acc] end) end bench "$$$ right_fold/3 + []", do: right_fold(@big_map, [], fn(x, acc) -> [x + 1 | acc] end) bench "$$$ right_fold/3", do: right_fold(@big_map, @big_map, fn(x, acc) -> [x + 1 | acc] end) bench "$$$ Enum.reduce/2", do: @big_map |> Map.values() |> Enum.reduce(fn(x, acc) -> [x + 1 | acc] end) bench "$$$ Enum.reduce/3" do Enum.reduce(Map.values(@big_map), Map.values(@big_map), fn(x, acc) -> [x + 1 | acc] end) end bench "$$$ List.foldr/3 + []", do: @big_map |> Map.values() |> List.foldr([], fn(x, acc) -> [x + 1 | acc]end) bench "$$$ List.foldr/3" do List.foldr(Map.values(@big_map), Map.values(@big_map), fn(x, acc) -> [x + 1 | acc] end) end bench "$$$ size/1", do: size(@big_map) bench "$$$ then_sequence/1", do: then_sequence(%{a: @med_list, b: @med_list, c: @med_list}) bench "$$$ Map.values/1", do: Map.values(@big_map) bench "$$$ to_list/1", do: to_list(@big_map) end
33.53527
121
0.54776
08ab6d4d9754d3452db164bf46003a38667cf7e5
260
ex
Elixir
apps/api/web/views/status_view.ex
elicopter/core
7731dc7558dea39bd1c473ab9e512c9db9e1b2c9
[ "MIT" ]
39
2016-11-01T07:21:51.000Z
2021-02-05T20:19:02.000Z
apps/api/web/views/status_view.ex
elicopter/core
7731dc7558dea39bd1c473ab9e512c9db9e1b2c9
[ "MIT" ]
null
null
null
apps/api/web/views/status_view.ex
elicopter/core
7731dc7558dea39bd1c473ab9e512c9db9e1b2c9
[ "MIT" ]
null
null
null
defmodule Api.StatusView do use Api.Web, :view def render("show.json", %{status: status}) do %{ data: render_one(status, __MODULE__, "status.json", as: :status) } end def render("status.json", %{status: status}) do status end end
18.571429
70
0.630769
08ab72e6dd376debd9f88d3bdcefb6db2053d8f0
1,738
exs
Elixir
mix.exs
humphreyja/http_event_server
27da75ea9508f6c35511cc242061e55a783e1b9d
[ "MIT" ]
null
null
null
mix.exs
humphreyja/http_event_server
27da75ea9508f6c35511cc242061e55a783e1b9d
[ "MIT" ]
null
null
null
mix.exs
humphreyja/http_event_server
27da75ea9508f6c35511cc242061e55a783e1b9d
[ "MIT" ]
null
null
null
defmodule HTTPEventServer.Mixfile do use Mix.Project def project do [app: :http_event_server, name: "HTTP Event Server", description: description(), package: package(), source_url: "https://github.com/humphreyja/http_event_server", version: "0.2.4", elixir: "~> 1.4", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps()] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do # Specify extra applications you'll use from Erlang/Elixir [ extra_applications: [:logger, :cowboy, :plug, :httpoison] ] end # Dependencies can be Hex packages: # # {:my_dep, "~> 0.3.0"} # # Or git/path repositories: # # {:my_dep, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} # # To depend on another app inside the umbrella: # # {:my_app, in_umbrella: true} # # Type "mix help deps" for more examples and options defp deps do [ {:cowboy, ">= 1.0.0"}, {:plug, "~> 1.3"}, {:httpoison, "0.11.1"}, {:poison, "~> 3.1"}, {:ex_doc, ">= 0.0.0", only: :dev} ] end defp description do """ Simple HTTP/HTTPS message handler for running tasks from other apps. This allows for both async and sync message sending between the apps for use on Heroku. """ end defp package do # These are the default files included in the package [ name: :http_event_server, files: ["lib", "mix.exs", "README*", "LICENSE*"], maintainers: ["Jake Humphrey"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/codelation/elixir-messenger"} ] end end
25.558824
91
0.60702
08aba0d83c2ebb8cdec95061e3da4bd4620c7388
1,078
ex
Elixir
lib/rocketpay/user.ex
Truta446/rocketpay
7e39f284999a30399a8495b899326e9174dc6544
[ "MIT" ]
80
2021-02-26T13:26:00.000Z
2022-01-31T15:13:18.000Z
lib/rocketpay/user.ex
Truta446/rocketpay
7e39f284999a30399a8495b899326e9174dc6544
[ "MIT" ]
null
null
null
lib/rocketpay/user.ex
Truta446/rocketpay
7e39f284999a30399a8495b899326e9174dc6544
[ "MIT" ]
42
2021-02-26T13:26:19.000Z
2021-12-11T16:32:47.000Z
defmodule Rocketpay.User do use Ecto.Schema import Ecto.Changeset alias Ecto.Changeset alias Rocketpay.Account @primary_key {:id, :binary_id, autogenerate: true} @required_params [:name, :age, :email, :password, :nickname] schema "users" do field :name, :string field :age, :integer field :email, :string field :password, :string, virtual: true field :password_hash, :string field :nickname, :string has_one :account, Account timestamps() end def changeset(params) do %__MODULE__{} |> cast(params, @required_params) |> validate_required(@required_params) |> validate_length(:password, min: 6) |> validate_number(:age, greater_than_or_equal_to: 18) |> validate_format(:email, ~r/@/) |> unique_constraint([:email]) |> unique_constraint([:nickname]) |> put_password_hash() end defp put_password_hash(%Changeset{valid?: true, changes: %{password: password}} = changeset) do change(changeset, Bcrypt.add_hash(password)) end defp put_password_hash(changeset), do: changeset end
25.666667
97
0.691095
08abbff0fcf0b9743a6e01da33925db424766af4
14,332
ex
Elixir
lib/ja_serializer/dsl.ex
tompesman/ja_serializer
2b4aafece514add516784a6a81f7d6c724df8ac2
[ "Apache-2.0" ]
null
null
null
lib/ja_serializer/dsl.ex
tompesman/ja_serializer
2b4aafece514add516784a6a81f7d6c724df8ac2
[ "Apache-2.0" ]
null
null
null
lib/ja_serializer/dsl.ex
tompesman/ja_serializer
2b4aafece514add516784a6a81f7d6c724df8ac2
[ "Apache-2.0" ]
null
null
null
defmodule JaSerializer.DSL do @moduledoc """ A DSL for defining JSON-API.org spec compliant payloads. Built on top of the `JaSerializer.Serializer` behaviour. The following macros are available: * `location/1` - Define the url of a single serialized object. * `attributes/1` - Define the attributes to be returned. * `has_many/2` - Define a has_many relationship. * `has_one/2` - Define a has_one or belongs_to relationship. This module should always be used in conjunction with `JaSerializer.Serializer`, see `JaSerializer` for the best way to do so. ## DSL Usage Example defmodule PostSerializer do use JaSerializer, dsl: true location "/posts/:id" attributes [:title, :body, :excerpt, :tags] has_many :comments, links: [related: "/posts/:id/comments"] has_one :author, serializer: PersonSerializer, include: true def excerpt(post, _conn) do [first | _ ] = String.split(post.body, ".") first end end post = %Post{ id: 1, title: "jsonapi.org + Elixir = Awesome APIs", body: "so. much. awesome.", author: %Person{name: "Alan"} } post |> PostSerializer.format |> Poison.encode! When `use`ing JaSerializer.DSL the default implementations of the `links/2`, `attributes/2`, and `relationships/2` callbacks will be defined on your module. Overriding these callbacks can be a great way to customize your serializer beyond what the DSL provides. See `JaSerializer.Serializer` for examples. """ alias JaSerializer.Relationship.HasMany alias JaSerializer.Relationship.HasOne @doc false defmacro __using__(_) do quote do @attributes [] @relations [] @location nil import JaSerializer.DSL, only: [ attributes: 1, location: 1, has_many: 2, has_one: 2, has_many: 1, has_one: 1 ] unquote(define_default_attributes()) unquote(define_default_relationships()) unquote(define_default_links()) @before_compile JaSerializer.DSL end end @doc false defmacro __before_compile__(env) do quote do def __relations, do: @relations def __location, do: @location def __attributes, do: @attributes unquote(define_inlined_attributes_map(env)) end end defp define_inlined_attributes_map(env) do attributes = Module.get_attribute(env.module, :attributes) conn = quote do: conn struct = quote do: struct # Construct ASL for map with keys from attributes calling the attribute fn body = {:%{}, [], Enum.map(attributes, fn k -> {k, {k, [], [struct, conn]}} end) } quote do @compile {:inline, inlined_attributes_map: 2} def inlined_attributes_map(unquote(struct), unquote(conn)), do: unquote(body) defoverridable [attributes: 2] end end defp define_default_attributes do quote do @compile {:inline, attributes: 2} def attributes(struct, conn) do inlined_attributes_map(struct, conn) end defoverridable [attributes: 2] end end defp define_default_relationships do quote do def relationships(struct, _conn) do JaSerializer.DSL.default_relationships(__MODULE__) end defoverridable [relationships: 2] end end @doc false def default_relationships(serializer) do serializer.__relations |> Enum.map(&dsl_to_struct/1) |> Enum.into(%{}) end defp dsl_to_struct({:has_one, name, opts}), do: {name, HasOne.from_dsl(name, opts)} defp dsl_to_struct({:has_many, name, opts}), do: {name, HasMany.from_dsl(name, opts)} defp define_default_links do quote do def links(data, conn) do JaSerializer.DSL.default_links(__MODULE__) end defoverridable [links: 2] end end @doc false def default_links(serializer) do %{self: serializer.__location} end @doc """ Defines the canonical path for retrieving this resource. ## String Examples String may be either a relative or absolute path. Path segments beginning with a colon are called as functions on the serializer with the struct and conn passed in. defmodule PostSerializer do use JaSerializer location "/posts/:id" end defmodule CommentSerializer do use JaSerializer location "http://api.example.com/posts/:post_id/comments/:id" def post_id(comment, _conn), do: comment.post_id end ## Atom Example When an atom is passed in, it is called as a function on the serializer with the struct and conn passed in. The function should return a full path/url. defmodule PostSerializer do use JaSerializer import MyPhoenixApp.Router.Helpers location :post_url def post_url(post, conn) do post_path(conn, :show, post.id) end end """ defmacro location(uri) do quote bind_quoted: [uri: uri] do @location uri end end @doc """ Defines a list of attributes as atoms to be included in the payload. An overridable function for each attribute is generated with the same name as the attribute. The function's default behavior is to retrieve a field with the same name from the struct. For example, if you have `attributes [:body]` a function `body/2` is defined on the serializer with a default behavior of `Map.get(struct, :body)`. defmodule PostSerializer do use JaSerializer, dsl: true attributes [:title, :body, :html] def html(post, _conn) do Earmark.to_html(post.body) end end ## Conditional attribute inclusion JaSerializer supports the `fields` option as per the JSONAPI spec. This option allows clients to request only the fields they want. For example if you only wanted the html and the title for the post: field_param = %{"post" => "title,html", "comment" => "html"} # Direct Serialization PostSerializer.format(post, conn, fields: field_param) # via PhoenixView integrations from controller render(conn, :show, data: post, opts: [fields: field_param]) ## Further customization Further customization of the attributes returned can be handled by overriding the `attributes/2` callback. This can be done in conjunction with the DSL using super, or without the DSL just returning a map. """ defmacro attributes(atts) when is_list(atts) do quote bind_quoted: [atts: atts] do # Save attributes @attributes @attributes ++ atts # Define default attribute function, make overridable for att <- atts do @compile {:inline, [{att, 1}, {att, 2}]} def unquote(att)(m), do: Map.get(m, unquote(att)) def unquote(att)(m, c), do: unquote(att)(m) defoverridable [{att, 2}, {att, 1}] end end end @doc """ Add a has_many relationship to be serialized. JSONAPI.org supports three types or relationships: * As links - Great for clients lazy loading relationships with lots of data. * As "Resource Indentifiers" - A type/id pair, useful to relate to data the client already has. * As Included Resources - The full resource is serialized in the same request (also includes Resource Identifiers). Links can be combined with either resource identifiers or fully included resources. See http://jsonapi.org/format/#document-resource-object-relationships for more details on the spec. ## Link based relationships Specify a URI or path which responds with the related resource. For example: defmodule MyApp.PostView do use JaSerializer has_many :comments, link: :comments_link has_one :author, link: "/api/posts/:id/author" def comments_link(post, conn) do MyApp.Router.Helpers.post_comment_url(conn, :index, post.id) end end Links can be defined with an atom or string. String may be either a relative or absolute path. Path segments beginning with a colon are called as functions on the serializer with the struct and conn passed in. In the above example id/2 would be called which is defined as a default callback. When an atom is passed in, it is called as a function on the serializer with the struct and conn passed in. The function should return a full path/url. Both `related` and `self` links are supported, the default `link` creates a related link: defmodule PostSerializer do use JaSerializer has_many :comments, links: [ related: "/posts/:id/comments" self: "/posts/:id/relationships/comments" ] end ## Resource Identifiers (without including) Return id and type for each related object ("Resource Identifier"). For example: defmodule MyApp.PostView do use JaSerializer has_many :comments, serializer: MyApp.CommentView, include: false has_many :tags, type: "tags" has_one :author, type: "user", field: :created_by_id # ... end When you use the `has_many` and `has_one` macros an overridable "data source" function is defined on your module. The data source function has the same name as the relationship name and accepts the struct and conn. The data source function should return the related struct(s) or id(s). In the example above the following functions are defined for you: def comments(post, _conn), do: Map.get(post, :comments) def tags(post, _conn), do: Map.get(post, :tags) def author(post, _conn), do: Map.get(post, :created_by_id) These data source functions are expected to return either related objects or ids, by default they just access the field with the same name as the relationship. The `field` option can be used to grab the id or struct from a different field in the serialized object. The author is an example of customizing this, and is frequently used when returning resource identifiers for has_one relationships when you have the foreign key in the serialized struct. In the comments example when a `serializer` plus `include: false` options are used the `id/2` and `type/2` functions are called on the defined serializer. In the tags example where just the `type` option is used the `id` field is automatically used on each map/struct returned by the data source. It is important to note that when accessing the relationship fields it is expected that the relationship is preloaded. For this reason you may want to consider using links for has_many relationships where possible. ## Including related data Returns a "Resource Identifier" (see above) as well as the fully serialized object in the top level `included` key. Example: defmodule MyApp.PostView do use JaSerializer has_many :comments, serializer: MyApp.CommentView, include: true, identifiers: :when_included has_many :tags, serializer: MyApp.TagView, include: true, identifiers: :always has_many :author, serializer: MyApp.AuthorView, include: true, field: :created_by # ... end Just like when working with only Resource Identifiers this will define a 'data source' function for each relationship with an arity of two. They will be overridable and are expected to return maps/structs. ## Conditional Inclusion JaSerializer supports the `include` option as per the JSONAPI spec. This option allows clients to include only the relationships they want. JaSerializer handles the serialization of this for you, however you will have to handle intellegent preloading of relationships yourself. When a relationship is not loaded via includes the `identifiers` option will be used to determine if Resource Identifiers should be serialized or not. The `identifiers` options accepts the atoms `:when_included` and `:always`. When specifying the include param, only the relationship requested will be included. For example, to only include the author and comments: include_param = "author,comments" # Direct Serialization PostSerializer.format(post, conn, include: include_param) # via PhoenixView integrations from controller render(conn, :show, data: post, opts: [include: include_param]) ## Further Customization For further customization override the `relationships/2` callback directly. """ defmacro has_many(name, opts \\ []) do normalized_opts = normalize_relation_opts(opts, __CALLER__) quote do @relations [{:has_many, unquote(name), unquote(normalized_opts)} | @relations] unquote(JaSerializer.Relationship.default_function(name, normalized_opts)) end end @doc """ See documentation for <a href='#has_many/2'>has_many/2</a>. API is the exact same. """ defmacro has_one(name, opts \\ []) do normalized_opts = normalize_relation_opts(opts, __CALLER__) quote do @relations [{:has_one, unquote(name), unquote(normalized_opts)} | @relations] unquote(JaSerializer.Relationship.default_function(name, normalized_opts)) end end defp normalize_relation_opts(opts, caller) do include = opts[:include] if opts[:field] && !opts[:type] do IO.write :stderr, IO.ANSI.format([:red, :bright, "warning: The `field` option must be used with a `type` option\n" <> Exception.format_stacktrace(Macro.Env.stacktrace(caller)) ]) end opts = if opts[:link] do updated = opts |> Keyword.get(:links, []) |> Keyword.put_new(:related, opts[:link]) Keyword.put(opts, :links, updated) else opts end case is_boolean(include) or is_nil(include) do true -> opts false -> IO.write :stderr, IO.ANSI.format([:red, :bright, "warning: Specifying a non-boolean as the `include` option is " <> "deprecated. If you are specifying the serializer for this " <> "relation, use the `serializer` option instead. To always " <> "side-load the relationship, use `include: true` in addition to " <> "the `serializer` option\n" <> Exception.format_stacktrace(Macro.Env.stacktrace(caller)) ]) [serializer: include, include: true] ++ opts end end end
31.991071
119
0.686436
08abe83e24ca45a5a886fd11e49e79386b777e83
519
exs
Elixir
test/models/query_test.exs
mntns/artus
958380f42612ec0bc9d059037cf7b59dfbe1cfa9
[ "MIT" ]
null
null
null
test/models/query_test.exs
mntns/artus
958380f42612ec0bc9d059037cf7b59dfbe1cfa9
[ "MIT" ]
null
null
null
test/models/query_test.exs
mntns/artus
958380f42612ec0bc9d059037cf7b59dfbe1cfa9
[ "MIT" ]
null
null
null
defmodule Artus.QueryTest do use Artus.ModelCase alias Artus.Query @valid_attrs %{created_at: %{day: 17, hour: 14, min: 0, month: 4, sec: 0, year: 2010}, request: "some content", uuid: "some content", views: 42} @invalid_attrs %{} test "changeset with valid attributes" do changeset = Query.changeset(%Query{}, @valid_attrs) assert changeset.valid? end test "changeset with invalid attributes" do changeset = Query.changeset(%Query{}, @invalid_attrs) refute changeset.valid? end end
27.315789
146
0.699422
08ac04acfd47537ca7c01a5fa3a37a7cecc52751
9,526
ex
Elixir
lib/elixir/lib/integer.ex
lytedev/elixir
dc25bb8e1484e2328eef819402d268dec7bb908a
[ "Apache-2.0" ]
1
2018-08-08T12:15:48.000Z
2018-08-08T12:15:48.000Z
lib/elixir/lib/integer.ex
lytedev/elixir
dc25bb8e1484e2328eef819402d268dec7bb908a
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/integer.ex
lytedev/elixir
dc25bb8e1484e2328eef819402d268dec7bb908a
[ "Apache-2.0" ]
null
null
null
defmodule Integer do @moduledoc """ Functions for working with integers. Some functions that work on integers are found in `Kernel`: * `abs/2` * `div/2` * `max/2` * `min/2` * `rem/2` """ import Bitwise @doc """ Determines if `integer` is odd. Returns `true` if the given `integer` is an odd number, otherwise it returns `false`. Allowed in guard clauses. ## Examples iex> Integer.is_odd(5) true iex> Integer.is_odd(6) false iex> Integer.is_odd(-5) true iex> Integer.is_odd(0) false """ defguard is_odd(integer) when is_integer(integer) and (integer &&& 1) == 1 @doc """ Determines if an `integer` is even. Returns `true` if the given `integer` is an even number, otherwise it returns `false`. Allowed in guard clauses. ## Examples iex> Integer.is_even(10) true iex> Integer.is_even(5) false iex> Integer.is_even(-10) true iex> Integer.is_even(0) true """ defguard is_even(integer) when is_integer(integer) and (integer &&& 1) == 0 @doc """ Computes the modulo remainder of an integer division. `Integer.mod/2` uses floored division, which means that the result will always have the sign of the `divisor`. Raises an `ArithmeticError` exception if one of the arguments is not an integer, or when the `divisor` is `0`. ## Examples iex> Integer.mod(5, 2) 1 iex> Integer.mod(6, -4) -2 """ @doc since: "1.4.0" @spec mod(integer, neg_integer | pos_integer) :: integer def mod(dividend, divisor) do remainder = rem(dividend, divisor) if remainder * divisor < 0 do remainder + divisor else remainder end end @doc """ Performs a floored integer division. Raises an `ArithmeticError` exception if one of the arguments is not an integer, or when the `divisor` is `0`. `Integer.floor_div/2` performs *floored* integer division. This means that the result is always rounded towards negative infinity. If you want to perform truncated integer division (rounding towards zero), use `Kernel.div/2` instead. ## Examples iex> Integer.floor_div(5, 2) 2 iex> Integer.floor_div(6, -4) -2 iex> Integer.floor_div(-99, 2) -50 """ @doc since: "1.4.0" @spec floor_div(integer, neg_integer | pos_integer) :: integer def floor_div(dividend, divisor) do if dividend * divisor < 0 and rem(dividend, divisor) != 0 do div(dividend, divisor) - 1 else div(dividend, divisor) end end @doc """ Returns the ordered digits for the given `integer`. An optional `base` value may be provided representing the radix for the returned digits. This one must be an integer >= 2. ## Examples iex> Integer.digits(123) [1, 2, 3] iex> Integer.digits(170, 2) [1, 0, 1, 0, 1, 0, 1, 0] iex> Integer.digits(-170, 2) [-1, 0, -1, 0, -1, 0, -1, 0] """ @spec digits(integer, pos_integer) :: [integer, ...] def digits(integer, base \\ 10) when is_integer(integer) and is_integer(base) and base >= 2 do do_digits(integer, base, []) end defp do_digits(integer, base, acc) when abs(integer) < base, do: [integer | acc] defp do_digits(integer, base, acc), do: do_digits(div(integer, base), base, [rem(integer, base) | acc]) @doc """ Returns the integer represented by the ordered `digits`. An optional `base` value may be provided representing the radix for the `digits`. Base has to be an integer greater or equal than `2`. ## Examples iex> Integer.undigits([1, 2, 3]) 123 iex> Integer.undigits([1, 4], 16) 20 iex> Integer.undigits([]) 0 """ @spec undigits([integer], pos_integer) :: integer def undigits(digits, base \\ 10) when is_list(digits) and is_integer(base) and base >= 2 do do_undigits(digits, base, 0) end defp do_undigits([], _base, acc), do: acc defp do_undigits([digit | _], base, _) when is_integer(digit) and digit >= base, do: raise(ArgumentError, "invalid digit #{digit} in base #{base}") defp do_undigits([digit | tail], base, acc) when is_integer(digit), do: do_undigits(tail, base, acc * base + digit) @doc """ Parses a text representation of an integer. An optional `base` to the corresponding integer can be provided. If `base` is not given, 10 will be used. If successful, returns a tuple in the form of `{integer, remainder_of_binary}`. Otherwise `:error`. Raises an error if `base` is less than 2 or more than 36. If you want to convert a string-formatted integer directly to an integer, `String.to_integer/1` or `String.to_integer/2` can be used instead. ## Examples iex> Integer.parse("34") {34, ""} iex> Integer.parse("34.5") {34, ".5"} iex> Integer.parse("three") :error iex> Integer.parse("34", 10) {34, ""} iex> Integer.parse("f4", 16) {244, ""} iex> Integer.parse("Awww++", 36) {509216, "++"} iex> Integer.parse("fab", 10) :error iex> Integer.parse("a2", 38) ** (ArgumentError) invalid base 38 """ @spec parse(binary, 2..36) :: {integer, binary} | :error def parse(binary, base \\ 10) def parse(_binary, base) when base not in 2..36 do raise ArgumentError, "invalid base #{inspect(base)}" end def parse(binary, base) do case count_digits(binary, base) do 0 -> :error count -> {digits, rem} = :erlang.split_binary(binary, count) {:erlang.binary_to_integer(digits, base), rem} end end defp count_digits(<<sign, rest::binary>>, base) when sign in '+-' do case count_digits_nosign(rest, base, 1) do 1 -> 0 count -> count end end defp count_digits(<<rest::binary>>, base) do count_digits_nosign(rest, base, 0) end digits = [{?0..?9, -?0}, {?A..?Z, 10 - ?A}, {?a..?z, 10 - ?a}] for {chars, diff} <- digits, char <- chars do digit = char + diff defp count_digits_nosign(<<unquote(char), rest::binary>>, base, count) when base > unquote(digit) do count_digits_nosign(rest, base, count + 1) end end defp count_digits_nosign(<<_::binary>>, _, count), do: count @doc """ Returns a binary which corresponds to the text representation of `integer`. Inlined by the compiler. ## Examples iex> Integer.to_string(123) "123" iex> Integer.to_string(+456) "456" iex> Integer.to_string(-789) "-789" iex> Integer.to_string(0123) "123" """ @spec to_string(integer) :: String.t() def to_string(integer) do :erlang.integer_to_binary(integer) end @doc """ Returns a binary which corresponds to the text representation of `integer` in the given `base`. `base` can be an integer between 2 and 36. Inlined by the compiler. ## Examples iex> Integer.to_string(100, 16) "64" iex> Integer.to_string(-100, 16) "-64" iex> Integer.to_string(882_681_651, 36) "ELIXIR" """ @spec to_string(integer, 2..36) :: String.t() def to_string(integer, base) do :erlang.integer_to_binary(integer, base) end @doc """ Returns a charlist which corresponds to the text representation of the given `integer`. Inlined by the compiler. ## Examples iex> Integer.to_charlist(123) '123' iex> Integer.to_charlist(+456) '456' iex> Integer.to_charlist(-789) '-789' iex> Integer.to_charlist(0123) '123' """ @spec to_charlist(integer) :: charlist def to_charlist(integer) do :erlang.integer_to_list(integer) end @doc """ Returns a charlist which corresponds to the text representation of `integer` in the given `base`. `base` can be an integer between 2 and 36. Inlined by the compiler. ## Examples iex> Integer.to_charlist(100, 16) '64' iex> Integer.to_charlist(-100, 16) '-64' iex> Integer.to_charlist(882_681_651, 36) 'ELIXIR' """ @spec to_charlist(integer, 2..36) :: charlist def to_charlist(integer, base) do :erlang.integer_to_list(integer, base) end @doc """ Returns the greatest common divisor of the two given integers. The greatest common divisor (GCD) of `integer1` and `integer2` is the largest positive integer that divides both `integer1` and `integer2` without leaving a remainder. By convention, `gcd(0, 0)` returns `0`. ## Examples iex> Integer.gcd(2, 3) 1 iex> Integer.gcd(8, 12) 4 iex> Integer.gcd(8, -12) 4 iex> Integer.gcd(10, 0) 10 iex> Integer.gcd(7, 7) 7 iex> Integer.gcd(0, 0) 0 """ @doc since: "1.5.0" @spec gcd(0, 0) :: 0 @spec gcd(integer, integer) :: pos_integer def gcd(integer1, integer2) when is_integer(integer1) and is_integer(integer2) do gcd_positive(abs(integer1), abs(integer2)) end defp gcd_positive(0, integer2), do: integer2 defp gcd_positive(integer1, 0), do: integer1 defp gcd_positive(integer1, integer2), do: gcd_positive(integer2, rem(integer1, integer2)) # TODO: Remove by 2.0 @doc false @deprecated "Use Integer.to_charlist/1 instead" def to_char_list(integer), do: Integer.to_charlist(integer) # TODO: Remove by 2.0 @doc false @deprecated "Use Integer.to_charlist/2 instead" def to_char_list(integer, base), do: Integer.to_charlist(integer, base) end
22.57346
99
0.628805
08ac21f57f8f64febc9f59d40605b3b5f8e0d66b
233
ex
Elixir
example-source/ex06.ex
guidiego/elixir-study-repository
9f7e8b50f310b27b75fd65e7f8deb4bf2d35f624
[ "MIT" ]
null
null
null
example-source/ex06.ex
guidiego/elixir-study-repository
9f7e8b50f310b27b75fd65e7f8deb4bf2d35f624
[ "MIT" ]
null
null
null
example-source/ex06.ex
guidiego/elixir-study-repository
9f7e8b50f310b27b75fd65e7f8deb4bf2d35f624
[ "MIT" ]
null
null
null
defmodule Recursive do def repeatMessage(msg, times) when times == 1 do IO.puts msg end def repeatMessage(msg, times) do IO.puts msg repeatMessage(msg, times - 1) end end Recursive.repeatMessage("R U Mine?", 3)
17.923077
50
0.686695
08ac27b2b8805ad453b248c22d110d1020c209b0
57
ex
Elixir
godin_umbrella/apps/godin_web/lib/godin_web/views/page_view.ex
ruben44bac/god-n
af78dc683b58bb3a5e4dbfec2dd53887651a8aa7
[ "MIT" ]
null
null
null
godin_umbrella/apps/godin_web/lib/godin_web/views/page_view.ex
ruben44bac/god-n
af78dc683b58bb3a5e4dbfec2dd53887651a8aa7
[ "MIT" ]
null
null
null
godin_umbrella/apps/godin_web/lib/godin_web/views/page_view.ex
ruben44bac/god-n
af78dc683b58bb3a5e4dbfec2dd53887651a8aa7
[ "MIT" ]
null
null
null
defmodule GodinWeb.PageView do use GodinWeb, :view end
14.25
30
0.789474
08ac63b8e33b42e1dddba80fa967ee7daea3be4a
225
exs
Elixir
test/test_helper.exs
chungwong/timex
bcd2504119f5c11ada7455d19726b5a49254dabf
[ "MIT" ]
1,623
2015-01-03T16:53:19.000Z
2022-03-27T01:25:50.000Z
test/test_helper.exs
chungwong/timex
bcd2504119f5c11ada7455d19726b5a49254dabf
[ "MIT" ]
654
2015-01-04T23:59:47.000Z
2022-03-08T01:02:01.000Z
test/test_helper.exs
chungwong/timex
bcd2504119f5c11ada7455d19726b5a49254dabf
[ "MIT" ]
428
2015-01-04T19:37:37.000Z
2022-03-31T10:48:44.000Z
# Ensure tzdata is up to date {:ok, _} = Application.ensure_all_started(:tzdata) Application.ensure_all_started(:stream_data) _ = Tzdata.ReleaseUpdater.poll_for_update() ExUnit.configure(exclude: [skip: true]) ExUnit.start()
32.142857
50
0.786667
08ac6d2d7ea973b01fe792e0524ce4c61a5ada72
702
exs
Elixir
config/test.exs
ldd/hn_comments_game
5f720621c549a3737c155f9d59fa8277491f3b16
[ "MIT" ]
5
2020-05-15T17:06:22.000Z
2020-06-20T12:05:46.000Z
config/test.exs
ldd/hn_comments_game
5f720621c549a3737c155f9d59fa8277491f3b16
[ "MIT" ]
null
null
null
config/test.exs
ldd/hn_comments_game
5f720621c549a3737c155f9d59fa8277491f3b16
[ "MIT" ]
null
null
null
use Mix.Config # Configure your database # # The MIX_TEST_PARTITION environment variable can be used # to provide built-in test partitioning in CI environment. # Run `mix help test` for more information. config :hn_comments_game, HnCommentsGame.Repo, username: "postgres", password: "postgres", database: "hn_comments_game_test#{System.get_env("MIX_TEST_PARTITION")}", hostname: "localhost", pool: Ecto.Adapters.SQL.Sandbox # We don't run a server during test. If one is required, # you can enable the server option below. config :hn_comments_game, HnCommentsGameWeb.Endpoint, http: [port: 4002], server: false # Print only warnings and errors during test config :logger, level: :warn
30.521739
75
0.763533
08ac9dfc3468961ca37357d5068da02f5cacaa70
55
ex
Elixir
web/views/page_view.ex
bagilevi/uptom
50894abb8f7bd052e12c37155b5c33450abcc9bd
[ "MIT" ]
6
2017-05-12T04:20:09.000Z
2020-11-07T02:00:56.000Z
web/views/page_view.ex
bagilevi/uptom
50894abb8f7bd052e12c37155b5c33450abcc9bd
[ "MIT" ]
null
null
null
web/views/page_view.ex
bagilevi/uptom
50894abb8f7bd052e12c37155b5c33450abcc9bd
[ "MIT" ]
2
2020-05-18T08:06:22.000Z
2020-12-19T14:24:40.000Z
defmodule Uptom.PageView do use Uptom.Web, :view end
13.75
27
0.763636
08acb1bbad2e83d45acfcb4786e700ee0f272bf9
2,356
ex
Elixir
clients/service_networking/lib/google_api/service_networking/v1/model/status.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/service_networking/lib/google_api/service_networking/v1/model/status.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/service_networking/lib/google_api/service_networking/v1/model/status.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.ServiceNetworking.V1.Model.Status do @moduledoc """ The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). ## Attributes * `code` (*type:* `integer()`, *default:* `nil`) - The status code, which should be an enum value of google.rpc.Code. * `details` (*type:* `list(map())`, *default:* `nil`) - A list of messages that carry the error details. There is a common set of message types for APIs to use. * `message` (*type:* `String.t`, *default:* `nil`) - A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :code => integer() | nil, :details => list(map()) | nil, :message => String.t() | nil } field(:code) field(:details, type: :list) field(:message) end defimpl Poison.Decoder, for: GoogleApi.ServiceNetworking.V1.Model.Status do def decode(value, options) do GoogleApi.ServiceNetworking.V1.Model.Status.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceNetworking.V1.Model.Status do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
44.45283
427
0.722835
08acc0336e0ec35c11116d63f4a595dee2f48f95
3,146
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/popup_window_properties.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/popup_window_properties.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/popup_window_properties.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.DFAReporting.V33.Model.PopupWindowProperties do @moduledoc """ Popup Window Properties. ## Attributes * `dimension` (*type:* `GoogleApi.DFAReporting.V33.Model.Size.t`, *default:* `nil`) - Popup dimension for a creative. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA and all VPAID * `offset` (*type:* `GoogleApi.DFAReporting.V33.Model.OffsetPosition.t`, *default:* `nil`) - Upper-left corner coordinates of the popup window. Applicable if positionType is COORDINATES. * `positionType` (*type:* `String.t`, *default:* `nil`) - Popup window position either centered or at specific coordinate. * `showAddressBar` (*type:* `boolean()`, *default:* `nil`) - Whether to display the browser address bar. * `showMenuBar` (*type:* `boolean()`, *default:* `nil`) - Whether to display the browser menu bar. * `showScrollBar` (*type:* `boolean()`, *default:* `nil`) - Whether to display the browser scroll bar. * `showStatusBar` (*type:* `boolean()`, *default:* `nil`) - Whether to display the browser status bar. * `showToolBar` (*type:* `boolean()`, *default:* `nil`) - Whether to display the browser tool bar. * `title` (*type:* `String.t`, *default:* `nil`) - Title of popup window. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :dimension => GoogleApi.DFAReporting.V33.Model.Size.t(), :offset => GoogleApi.DFAReporting.V33.Model.OffsetPosition.t(), :positionType => String.t(), :showAddressBar => boolean(), :showMenuBar => boolean(), :showScrollBar => boolean(), :showStatusBar => boolean(), :showToolBar => boolean(), :title => String.t() } field(:dimension, as: GoogleApi.DFAReporting.V33.Model.Size) field(:offset, as: GoogleApi.DFAReporting.V33.Model.OffsetPosition) field(:positionType) field(:showAddressBar) field(:showMenuBar) field(:showScrollBar) field(:showStatusBar) field(:showToolBar) field(:title) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.PopupWindowProperties do def decode(value, options) do GoogleApi.DFAReporting.V33.Model.PopupWindowProperties.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.PopupWindowProperties do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
44.309859
221
0.703751
08acdb3cbe49d08d8943853963fb87d9e75b64f6
1,296
ex
Elixir
clients/elixir/generated/lib/swaggy_jenkins/model/pipeline_run_impl.ex
PankTrue/swaggy-jenkins
aca35a7cca6e1fcc08bd399e05148942ac2f514b
[ "MIT" ]
23
2017-08-01T12:25:26.000Z
2022-01-25T03:44:11.000Z
clients/elixir/generated/lib/swaggy_jenkins/model/pipeline_run_impl.ex
PankTrue/swaggy-jenkins
aca35a7cca6e1fcc08bd399e05148942ac2f514b
[ "MIT" ]
35
2017-06-14T03:28:15.000Z
2022-02-14T10:25:54.000Z
clients/elixir/generated/lib/swaggy_jenkins/model/pipeline_run_impl.ex
PankTrue/swaggy-jenkins
aca35a7cca6e1fcc08bd399e05148942ac2f514b
[ "MIT" ]
11
2017-08-31T19:00:20.000Z
2021-12-19T12:04:12.000Z
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule SwaggyJenkins.Model.PipelineRunImpl do @moduledoc """ """ @derive [Poison.Encoder] defstruct [ :"_class", :"_links", :"durationInMillis", :"enQueueTime", :"endTime", :"estimatedDurationInMillis", :"id", :"organization", :"pipeline", :"result", :"runSummary", :"startTime", :"state", :"type", :"commitId" ] @type t :: %__MODULE__{ :"_class" => String.t, :"_links" => PipelineRunImpllinks, :"durationInMillis" => integer(), :"enQueueTime" => String.t, :"endTime" => String.t, :"estimatedDurationInMillis" => integer(), :"id" => String.t, :"organization" => String.t, :"pipeline" => String.t, :"result" => String.t, :"runSummary" => String.t, :"startTime" => String.t, :"state" => String.t, :"type" => String.t, :"commitId" => String.t } end defimpl Poison.Decoder, for: SwaggyJenkins.Model.PipelineRunImpl do import SwaggyJenkins.Deserializer def decode(value, options) do value |> deserialize(:"_links", :struct, SwaggyJenkins.Model.PipelineRunImpllinks, options) end end
23.142857
91
0.616512
08acdbcf9cd096f5c1a2d3f9c329b56408c4578e
2,767
ex
Elixir
clients/proximity_beacon/lib/google_api/proximity_beacon/v1beta1/model/attachment_info.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/proximity_beacon/lib/google_api/proximity_beacon/v1beta1/model/attachment_info.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/proximity_beacon/lib/google_api/proximity_beacon/v1beta1/model/attachment_info.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.ProximityBeacon.V1beta1.Model.AttachmentInfo do @moduledoc """ A subset of attachment information served via the `beaconinfo.getforobserved` method, used when your users encounter your beacons. ## Attributes * `data` (*type:* `String.t`, *default:* `nil`) - An opaque data container for client-provided data. * `maxDistanceMeters` (*type:* `float()`, *default:* `nil`) - The distance away from the beacon at which this attachment should be delivered to a mobile app. Setting this to a value greater than zero indicates that the app should behave as if the beacon is "seen" when the mobile device is less than this distance away from the beacon. Different attachments on the same beacon can have different max distances. Note that even though this value is expressed with fractional meter precision, real-world behavior is likley to be much less precise than one meter, due to the nature of current Bluetooth radio technology. Optional. When not set or zero, the attachment should be delivered at the beacon's outer limit of detection. * `namespacedType` (*type:* `String.t`, *default:* `nil`) - Specifies what kind of attachment this is. Tells a client how to interpret the `data` field. Format is <var>namespace/type</var>, for example <code>scrupulous-wombat-12345/welcome-message</code> """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :data => String.t(), :maxDistanceMeters => float(), :namespacedType => String.t() } field(:data) field(:maxDistanceMeters) field(:namespacedType) end defimpl Poison.Decoder, for: GoogleApi.ProximityBeacon.V1beta1.Model.AttachmentInfo do def decode(value, options) do GoogleApi.ProximityBeacon.V1beta1.Model.AttachmentInfo.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ProximityBeacon.V1beta1.Model.AttachmentInfo do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.971831
134
0.72931
08acec929bd6267a3ab25ef5401d19ff3ec695ca
1,780
ex
Elixir
lib/powit_web.ex
tenzil-rpx/powit
0feebbfc11c7bd2a45ef0664632deb9b0537fb5c
[ "MIT" ]
null
null
null
lib/powit_web.ex
tenzil-rpx/powit
0feebbfc11c7bd2a45ef0664632deb9b0537fb5c
[ "MIT" ]
null
null
null
lib/powit_web.ex
tenzil-rpx/powit
0feebbfc11c7bd2a45ef0664632deb9b0537fb5c
[ "MIT" ]
null
null
null
defmodule PowitWeb do @moduledoc """ The entrypoint for defining your web interface, such as controllers, views, channels and so on. This can be used in your application as: use PowitWeb, :controller use PowitWeb, :view The definitions below will be executed for every view, controller, etc, so keep them short and clean, focused on imports, uses and aliases. Do NOT define functions inside the quoted expressions below. Instead, define any helper function in modules and import those modules here. """ def controller do quote do use Phoenix.Controller, namespace: PowitWeb import Plug.Conn import PowitWeb.Gettext alias PowitWeb.Router.Helpers, as: Routes end end def view do quote do use Phoenix.View, root: "lib/powit_web/templates", namespace: PowitWeb # Import convenience functions from controllers import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1] # Use all HTML functionality (forms, tags, etc) use Phoenix.HTML import PowitWeb.ErrorHelpers import PowitWeb.Gettext alias PowitWeb.Router.Helpers, as: Routes end end def router do quote do use Phoenix.Router import Plug.Conn import Phoenix.Controller end end def channel do quote do use Phoenix.Channel import PowitWeb.Gettext end end def mailer_view do quote do use Phoenix.View, root: "lib/powit_web/templates", namespace: PowitWeb use Phoenix.HTML end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
22.531646
83
0.673034
08ad1660456bb72156b778e02489340f9e2258ba
915
ex
Elixir
Microsoft.Azure.Management.Database.PostgreSql/lib/microsoft/azure/management/database/postgre_sql/model/performance_tier_properties.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
4
2018-09-29T03:43:15.000Z
2021-04-01T18:30:46.000Z
Microsoft.Azure.Management.Database.PostgreSql/lib/microsoft/azure/management/database/postgre_sql/model/performance_tier_properties.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
Microsoft.Azure.Management.Database.PostgreSql/lib/microsoft/azure/management/database/postgre_sql/model/performance_tier_properties.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
# NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule Microsoft.Azure.Management.Database.PostgreSql.Model.PerformanceTierProperties do @moduledoc """ Performance tier properties """ @derive [Poison.Encoder] defstruct [ :"id", :"serviceLevelObjectives" ] @type t :: %__MODULE__{ :"id" => String.t, :"serviceLevelObjectives" => [PerformanceTierServiceLevelObjectives] } end defimpl Poison.Decoder, for: Microsoft.Azure.Management.Database.PostgreSql.Model.PerformanceTierProperties do import Microsoft.Azure.Management.Database.PostgreSql.Deserializer def decode(value, options) do value |> deserialize(:"serviceLevelObjectives", :list, Microsoft.Azure.Management.Database.PostgreSql.Model.PerformanceTierServiceLevelObjectives, options) end end
30.5
153
0.765027
08ad5ce84832c733780c464e2688c147082a1177
1,270
ex
Elixir
lib/discuss_web/channels/user_socket.ex
albertocsouto/udemy-phoenix-bootcamp
f2506fee672fe22c8b6ff80805bd7324a3a629a9
[ "Apache-2.0" ]
null
null
null
lib/discuss_web/channels/user_socket.ex
albertocsouto/udemy-phoenix-bootcamp
f2506fee672fe22c8b6ff80805bd7324a3a629a9
[ "Apache-2.0" ]
null
null
null
lib/discuss_web/channels/user_socket.ex
albertocsouto/udemy-phoenix-bootcamp
f2506fee672fe22c8b6ff80805bd7324a3a629a9
[ "Apache-2.0" ]
null
null
null
defmodule DiscussWeb.UserSocket do use Phoenix.Socket ## Channels channel("comments:*", DiscussWeb.CommentsChannel) # Socket params are passed from the client and can # be used to verify and authenticate a user. After # verification, you can put default assigns into # the socket that will be set for all channels, ie # # {:ok, assign(socket, :user_id, verified_user_id)} # # To deny connection, return `:error`. # # See `Phoenix.Token` documentation for examples in # performing token verification on connect. @impl true def connect(%{"token" => token}, socket, _connect_info) do case Phoenix.Token.verify(socket, "key", token) do {:ok, user_id} -> {:ok, assign(socket, :user_id, user_id)} {:error, _error} -> :error end end # Socket id's are topics that allow you to identify all sockets for a given user: # # def id(socket), do: "user_socket:#{socket.assigns.user_id}" # # Would allow you to broadcast a "disconnect" event and terminate # all active sockets and channels for a given user: # # DiscussWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. @impl true def id(_socket), do: nil end
30.238095
83
0.673228
08ad5e33a3ae8656fb9128f7853c7d4e0c8941b5
1,503
ex
Elixir
apps/diagnostics/lib/diagnostics/application.ex
niclaslind/signalbroker-server
afb80514dcbabe561ac2da42adc08843a15c37c5
[ "Apache-2.0" ]
17
2020-06-20T11:29:43.000Z
2022-03-21T05:53:06.000Z
apps/diagnostics/lib/diagnostics/application.ex
niclaslind/signalbroker-server
afb80514dcbabe561ac2da42adc08843a15c37c5
[ "Apache-2.0" ]
2
2020-07-09T10:22:50.000Z
2020-09-01T14:46:40.000Z
apps/diagnostics/lib/diagnostics/application.ex
niclaslind/signalbroker-server
afb80514dcbabe561ac2da42adc08843a15c37c5
[ "Apache-2.0" ]
3
2020-07-17T20:04:36.000Z
2022-01-24T14:19:46.000Z
# Copyright 2019 Volvo Cars # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # ”License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # “AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. defmodule Diagnostics.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do config = Util.Config.get_config() # List all child processes to be supervised children = [ {Diagnostics, {config.gateway.gateway_pid}} # Starts a worker by calling: Diagnostics.Worker.start_link(arg) # {Diagnostics.Worker, arg}, ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Diagnostics.Supervisor] Supervisor.start_link(children, opts) end end
34.159091
70
0.744511
08ad6a0ee500ca2e6671b045b1f797b54e49e260
3,420
ex
Elixir
lib/growlex/registration.ex
atomic-fads/growlex
438e837540afaff5391f62c4490b67038ece1b6a
[ "Apache-2.0" ]
null
null
null
lib/growlex/registration.ex
atomic-fads/growlex
438e837540afaff5391f62c4490b67038ece1b6a
[ "Apache-2.0" ]
null
null
null
lib/growlex/registration.ex
atomic-fads/growlex
438e837540afaff5391f62c4490b67038ece1b6a
[ "Apache-2.0" ]
null
null
null
defmodule Growlex.Registration do import Growlex.Headers import Growlex.Options alias Growlex.Icon alias Growlex.Network def register([]) do {:undefined, :notifications} end def register(options) do check_options(options, options) |> do_register end def do_register({:ok, options}) do options |> normalized_options |> message |> Network.send_and_receive end def do_register(result), do: result def check_options(options, [{name, value} | rest]) do case check_option(name, value) do :ok -> check_options(options, rest) result -> result end end def check_options(options, []) do {:ok, options} end def check_option(:notifications, notifications) do case length(notifications) do 0 -> {:invalid, :notifications, notifications} _ -> :ok end end def check_option(_, _), do: :ok def message(options) do notifications = options[:notifications] app_name = options[:app_name] common_headers(app_name: app_name) <> notifications_count_header(notifications) <> "\r\n" <> notification_headers(notifications) <> binary_headers(notifications) <> "\r\n" end def common_headers(app_name: app_name) do start_header <> application_name_header(app_name) <> origin_headers end def common_headers(app_name: app_name, app_icon_path: nil) do start_header <> application_name_header(app_name) <> origin_headers end def common_headers(app_name: app_name, app_icon_path: app_icon_path) do start_header <> application_name_header(app_name) <> application_icon_header(app_icon_path) <> origin_headers end def start_header do "#{start_header("REGISTER")}\r\n" end def notifications_count_header(notifications) do "Notifications-Count: #{length(notifications)}\r\n" end def notification_name_header(name) do "Notification-Name: #{name}\r\n" end def notification_enabled_header(enabled) do "Notification-Enabled: #{if enabled, do: "True", else: "False"}\r\n" end def notification_icon_header(nil), do: "" def notification_icon_header(icon_path) do "Notification-Icon: x-growl-resource://#{Icon.icon(icon_path)[:id]}\r\n" end def notification_headers(notifications) do Enum.reduce notifications, "", fn(notification, result) -> result <> notification_name_header(notification[:name]) <> notification_enabled_header(notification[:enabled]) <> notification_icon_header(notification[:icon_path]) <> "\r\n" end end def binary_headers(notifications) do Enum.reduce notifications, "", fn(notification, result) -> result <> binary_header(notification[:icon_path]) end end def binary_header(nil), do: "" def binary_header(icon_path) do icon = Icon.icon(icon_path) "Identifier: #{icon[:id]}\r\n" <> "Length: #{icon[:size]}\r\n" <> "\r\n" <> icon[:data] <> "\r\n" <> "\r\n" end def normalized_options do normalized_options([]) end def normalized_options(options) do register_options = [ notifications: options[:notifications] || [ [name: "notify", enabled: true], [name: "failed", enabled: true], [name: "pending", enabled: true], [name: "success", enabled: true], ] ] register_options ++ normalized_shared_options(options) end end
24.604317
76
0.67076
08ad768c33429ef493e37b89f1238e38fd8d1408
10,464
exs
Elixir
lib/logger/test/logger_test.exs
wstrinz/elixir
1048b34d6c816f8e5dbd4fdbaaf9baa41b4f0d95
[ "Apache-2.0" ]
null
null
null
lib/logger/test/logger_test.exs
wstrinz/elixir
1048b34d6c816f8e5dbd4fdbaaf9baa41b4f0d95
[ "Apache-2.0" ]
null
null
null
lib/logger/test/logger_test.exs
wstrinz/elixir
1048b34d6c816f8e5dbd4fdbaaf9baa41b4f0d95
[ "Apache-2.0" ]
null
null
null
defmodule LoggerTest do use Logger.Case require Logger setup_all do Logger.configure_backend(:console, metadata: [:application, :module]) on_exit(fn -> Logger.configure_backend(:console, metadata: []) end) end defp msg_with_meta(text) do msg("module=LoggerTest #{text}") end test "add_translator/1 and remove_translator/1" do defmodule CustomTranslator do def t(:debug, :info, :format, {'hello: ~p', [:ok]}) do :skip end def t(:debug, :info, :format, {'world: ~p', [:ok]}) do {:ok, "rewritten"} end def t(_, _, _, _) do :none end end assert Logger.add_translator({CustomTranslator, :t}) assert capture_log(fn -> :error_logger.info_msg('hello: ~p', [:ok]) end) == "" assert capture_log(fn -> :error_logger.info_msg('world: ~p', [:ok]) end) =~ "\[info\] rewritten" after assert Logger.remove_translator({CustomTranslator, :t}) end test "add_backend/1 and remove_backend/1" do assert :ok = Logger.remove_backend(:console) assert Application.get_env(:logger, :backends) == [] assert Logger.remove_backend(:console) == {:error, :not_found} assert capture_log(fn -> assert Logger.debug("hello", []) == :ok end) == "" assert {:ok, _pid} = Logger.add_backend(:console) assert Application.get_env(:logger, :backends) == [:console] assert Logger.add_backend(:console) == {:error, :already_present} assert Application.get_env(:logger, :backends) == [:console] end test "add_backend/1 with {module, id}" do defmodule MyBackend do @behaviour :gen_event def init({MyBackend, :hello}) do {:ok, :hello} end def handle_event(_event, state) do {:ok, state} end def handle_call(:error, _) do raise "oops" end def handle_info(_msg, state) do {:ok, state} end def code_change(_old_vsn, state, _extra) do {:ok, state} end def terminate(_reason, _state) do :ok end end assert {:ok, _} = Logger.add_backend({MyBackend, :hello}) assert {:error, :already_present} = Logger.add_backend({MyBackend, :hello}) assert :ok = Logger.remove_backend({MyBackend, :hello}) end test "level/0" do assert Logger.level() == :debug end test "process metadata" do assert Logger.metadata(data: true) == :ok assert Logger.metadata() == [data: true] assert Logger.metadata(data: true) == :ok assert Logger.metadata() == [data: true] assert Logger.metadata(meta: 1) == :ok metadata = Logger.metadata() assert Enum.sort(metadata) == [data: true, meta: 1] assert Logger.metadata(data: nil) == :ok assert Logger.metadata() == [meta: 1] assert Logger.reset_metadata(meta: 2) == :ok assert Logger.metadata() == [meta: 2] assert Logger.reset_metadata(data: true, app: nil) == :ok assert Logger.metadata() == [data: true] assert Logger.reset_metadata() == :ok assert Logger.metadata() == [] end test "metadata merge" do assert Logger.metadata(module: Sample) == :ok assert capture_log(fn -> assert Logger.bare_log(:info, "ok", application: nil, module: LoggerTest) == :ok end) =~ msg("application= module=LoggerTest [info] ok") end test "metadata compile-time merge" do assert Logger.metadata(module: Sample) == :ok assert capture_log(fn -> assert Logger.log(:info, "ok", application: nil, module: CustomTest) == :ok end) =~ msg("application= module=CustomTest [info] ok") end test "metadata merge when the argument function returns metadata" do assert Logger.metadata(module: Sample) == :ok fun = fn -> {"ok", [module: "Function"]} end assert capture_log(fn -> assert Logger.bare_log(:info, fun, application: nil, module: LoggerTest) == :ok end) =~ msg("application= module=Function [info] ok") end test "enable/1 and disable/1" do assert Logger.metadata([]) == :ok assert capture_log(fn -> assert Logger.debug("hello", []) == :ok end) =~ msg_with_meta("[debug] hello") assert Logger.disable(self()) == :ok assert capture_log(fn -> assert Logger.debug("hello", []) == :ok end) == "" assert Logger.metadata([]) == :ok assert capture_log(fn -> assert Logger.debug("hello", []) == :ok end) == "" assert Logger.enable(self()) == :ok assert capture_log(fn -> assert Logger.debug("hello", []) == :ok end) =~ msg_with_meta("[debug] hello") end test "compare_levels/2" do assert Logger.compare_levels(:debug, :debug) == :eq assert Logger.compare_levels(:debug, :info) == :lt assert Logger.compare_levels(:debug, :warn) == :lt assert Logger.compare_levels(:debug, :error) == :lt assert Logger.compare_levels(:info, :debug) == :gt assert Logger.compare_levels(:info, :info) == :eq assert Logger.compare_levels(:info, :warn) == :lt assert Logger.compare_levels(:info, :error) == :lt assert Logger.compare_levels(:warn, :debug) == :gt assert Logger.compare_levels(:warn, :info) == :gt assert Logger.compare_levels(:warn, :warn) == :eq assert Logger.compare_levels(:warn, :error) == :lt assert Logger.compare_levels(:error, :debug) == :gt assert Logger.compare_levels(:error, :info) == :gt assert Logger.compare_levels(:error, :warn) == :gt assert Logger.compare_levels(:error, :error) == :eq end test "debug/2" do assert capture_log(fn -> assert Logger.debug("hello", []) == :ok end) =~ msg_with_meta("[debug] hello") assert capture_log(:info, fn -> assert Logger.debug("hello", []) == :ok end) == "" end test "info/2" do assert capture_log(fn -> assert Logger.info("hello", []) == :ok end) =~ msg_with_meta("[info] hello") assert capture_log(:warn, fn -> assert Logger.info("hello", []) == :ok end) == "" end test "warn/2" do assert capture_log(fn -> assert Logger.warn("hello", []) == :ok end) =~ msg_with_meta("[warn] hello") assert capture_log(:error, fn -> assert Logger.warn("hello", []) == :ok end) == "" end test "error/2" do assert capture_log(fn -> assert Logger.error("hello", []) == :ok end) =~ msg_with_meta("[error] hello") end test "remove unused calls at compile time" do Logger.configure(compile_time_purge_level: :info) defmodule Sample do def debug do Logger.debug("hello") end def info do Logger.info("hello") end end assert capture_log(fn -> assert Sample.debug() == :ok end) == "" assert capture_log(fn -> assert Sample.info() == :ok end) =~ msg("module=LoggerTest.Sample [info] hello") after Logger.configure(compile_time_purge_level: :debug) end test "unused variable warnings suppressed when we remove macros from the AST" do Logger.configure(compile_time_purge_level: :info) # This should not warn, even if the Logger call is purged from the AST. assert ExUnit.CaptureIO.capture_io(:stderr, fn -> defmodule Unused do require Logger def hello(a, b, c) do Logger.debug(["a: ", inspect(a), ", b: ", inspect(b)], c: c) end end end) == "" assert LoggerTest.Unused.hello(1, 2, 3) == :ok after Logger.configure(compile_time_purge_level: :debug) end test "set application metadata at compile time" do Logger.configure(compile_time_application: nil) defmodule SampleNoApp do def info do Logger.info("hello") end end assert capture_log(fn -> assert SampleNoApp.info() == :ok end) =~ msg("module=LoggerTest.SampleNoApp [info] hello") Logger.configure(compile_time_application: :sample_app) defmodule SampleApp do def info do Logger.info("hello") end end assert capture_log(fn -> assert SampleApp.info() == :ok end) =~ msg("application=sample_app module=LoggerTest.SampleApp [info] hello") after Logger.configure(compile_time_application: nil) end test "log/2 truncates messages" do Logger.configure(truncate: 4) assert capture_log(fn -> Logger.log(:debug, "hello") end) =~ "hell (truncated)" after Logger.configure(truncate: 8096) end test "log/2 with to_string/1 conversion" do Logger.configure(truncate: 4) assert capture_log(fn -> Logger.log(:debug, :hello) end) =~ "hell (truncated)" after Logger.configure(truncate: 8096) end test "log/2 does not fails when the logger is off" do logger = Process.whereis(Logger) Process.unregister(Logger) try do assert Logger.log(:debug, "hello") == {:error, :noproc} after Process.register(logger, Logger) end end test "log/2 prunes bad unicode chars" do assert capture_log(fn -> assert Logger.log(:debug, "he" <> <<185>> <> "lo") == :ok end) =~ "he�lo" end test "logging something that is not a binary or chardata fails right away" do assert_raise Protocol.UndefinedError, "protocol String.Chars not implemented for %{}", fn -> Logger.log(:debug, %{}) end message = "cannot truncate chardata because it contains something that is not valid chardata: %{}" # Something that looks like chardata but then inside isn't still raises an error, but a # different one. assert_raise ArgumentError, message, fn -> Logger.log(:debug, [%{}]) end end test "stops the application silently" do Application.put_env(:logger, :backends, []) Logger.App.stop() Application.start(:logger) assert capture_log(fn -> assert Logger.debug("hello", []) == :ok end) == "" assert {:ok, _} = Logger.add_backend(:console) assert Logger.add_backend(:console) == {:error, :already_present} after Application.put_env(:logger, :backends, [:console]) Logger.App.stop() Application.start(:logger) end end
28.512262
96
0.602446
08adc22a0a3ecc545581a7ddde660e10282bc2e0
575
exs
Elixir
test/web/controllers/webapp_controller_test.exs
isshindev/accent
ae4c13139b0a0dfd64ff536b94c940a4e2862150
[ "BSD-3-Clause" ]
806
2018-04-07T20:40:33.000Z
2022-03-30T01:39:57.000Z
test/web/controllers/webapp_controller_test.exs
isshindev/accent
ae4c13139b0a0dfd64ff536b94c940a4e2862150
[ "BSD-3-Clause" ]
194
2018-04-07T13:49:37.000Z
2022-03-30T19:58:45.000Z
test/web/controllers/webapp_controller_test.exs
doc-ai/accent
e337e16f3658cc0728364f952c0d9c13710ebb06
[ "BSD-3-Clause" ]
89
2018-04-09T13:55:49.000Z
2022-03-24T07:09:31.000Z
defmodule AccentTest.WebappController do use Accent.ConnCase test "index", %{conn: conn} do response = conn |> get(web_app_path(conn, [])) assert response.status == 200 assert response.state == :sent assert get_resp_header(response, "content-type") == ["text/html; charset=utf-8"] end test "catch all", %{conn: conn} do response = conn |> get("/app/foo") assert response.status == 200 assert response.state == :sent assert get_resp_header(response, "content-type") == ["text/html; charset=utf-8"] end end
23.958333
84
0.636522
08adc2f547200a07ea06b0ebbbce4dc31a30fcb8
1,349
ex
Elixir
lib/square_up/resources/v2/cash_drawer_shifts.ex
beaver21/SquareUp
c9791d96ed9335926933403a966eba5076fbc15b
[ "MIT" ]
4
2020-10-21T18:34:50.000Z
2022-03-16T06:25:44.000Z
lib/square_up/resources/v2/cash_drawer_shifts.ex
beaver21/SquareUp
c9791d96ed9335926933403a966eba5076fbc15b
[ "MIT" ]
5
2020-10-21T23:16:32.000Z
2021-05-13T13:42:44.000Z
lib/square_up/resources/v2/cash_drawer_shifts.ex
beaver21/SquareUp
c9791d96ed9335926933403a966eba5076fbc15b
[ "MIT" ]
3
2020-10-21T21:20:36.000Z
2021-03-15T18:00:30.000Z
defmodule SquareUp.V2.CashDrawerShifts do import Norm import SquareUp.Client, only: [call: 2] @spec list(SquareUp.Client.t(), %{}, %{}, %{ required(:location_id) => binary(), optional(:sort_order) => binary(), optional(:begin_time) => binary(), optional(:end_time) => binary(), optional(:limit) => integer(), optional(:cursor) => binary() }) :: SquareUp.Client.response(SquareUp.TypeSpecs.list_cash_drawer_shifts_response()) def list(client, path_params \\ %{}, params \\ %{}, query_params \\ %{}) do path_params_spec = schema(%{}) params_spec = schema(%{}) query_params_spec = schema(%{ location_id: spec(is_binary()), sort_order: spec(is_binary()), begin_time: spec(is_binary()), end_time: spec(is_binary()), limit: spec(is_integer()), cursor: spec(is_binary()) }) response_spec = {:delegate, &SquareUp.ResponseSchema.list_cash_drawer_shifts_response/0} call(client, %{ method: :get, path_params: path_params, params: params, query_params: query_params, path_params_spec: path_params_spec, params_spec: params_spec, query_params_spec: query_params_spec, response_spec: response_spec, path: "/v2/cash-drawers/shifts" }) end end
32.119048
93
0.619718
08add1d9e118db6384196fac1281e80cfb72f198
78
exs
Elixir
config/prod.exs
icanmakeitbetter/decipher_api
3e2152f8fd87f4a92489d08e0bd4f53d18e3c0d2
[ "MIT" ]
null
null
null
config/prod.exs
icanmakeitbetter/decipher_api
3e2152f8fd87f4a92489d08e0bd4f53d18e3c0d2
[ "MIT" ]
null
null
null
config/prod.exs
icanmakeitbetter/decipher_api
3e2152f8fd87f4a92489d08e0bd4f53d18e3c0d2
[ "MIT" ]
null
null
null
use Mix.Config config :decipher_api, service: DecipherAPI.Service.HTTPClient
19.5
61
0.833333
08ade533c1ada3d3af732ab1f00336081a594eb8
22,018
ex
Elixir
lib/phoenix/presence.ex
fekle/phoenix
3e0979b5d91bab771fa03aeca232094f4d5ab4b0
[ "MIT" ]
null
null
null
lib/phoenix/presence.ex
fekle/phoenix
3e0979b5d91bab771fa03aeca232094f4d5ab4b0
[ "MIT" ]
null
null
null
lib/phoenix/presence.ex
fekle/phoenix
3e0979b5d91bab771fa03aeca232094f4d5ab4b0
[ "MIT" ]
null
null
null
defmodule Phoenix.Presence do @moduledoc """ Provides Presence tracking to processes and channels. This behaviour provides presence features such as fetching presences for a given topic, as well as handling diffs of join and leave events as they occur in real-time. Using this module defines a supervisor and a module that implements the `Phoenix.Tracker` behaviour that uses `Phoenix.PubSub` to broadcast presence updates. In case you want to use only a subset of the functionality provided by `Phoenix.Presence`, such as tracking processes but without broadcasting updates, we recommend that you look at the `Phoenix.Tracker` functionality from the `phoenix_pubsub` project. ## Example Usage Start by defining a presence module within your application which uses `Phoenix.Presence` and provide the `:otp_app` which holds your configuration, as well as the `:pubsub_server`. defmodule MyAppWeb.Presence do use Phoenix.Presence, otp_app: :my_app, pubsub_server: MyApp.PubSub end The `:pubsub_server` must point to an existing pubsub server running in your application, which is included by default as `MyApp.PubSub` for new applications. Next, add the new supervisor to your supervision tree in `lib/my_app/application.ex`. It must be after the PubSub child and before the endpoint: children = [ ... {Phoenix.PubSub, name: MyApp.PubSub}, MyAppWeb.Presence, MyAppWeb.Endpoint ] Once added, presences can be tracked in your channel after joining: defmodule MyAppWeb.MyChannel do use MyAppWeb, :channel alias MyAppWeb.Presence def join("some:topic", _params, socket) do send(self(), :after_join) {:ok, assign(socket, :user_id, ...)} end def handle_info(:after_join, socket) do {:ok, _} = Presence.track(socket, socket.assigns.user_id, %{ online_at: inspect(System.system_time(:second)) }) push(socket, "presence_state", Presence.list(socket)) {:noreply, socket} end end In the example above, `Presence.track` is used to register this channel's process as a presence for the socket's user ID, with a map of metadata. Next, the current presence information for the socket's topic is pushed to the client as a `"presence_state"` event. Finally, a diff of presence join and leave events will be sent to the client as they happen in real-time with the "presence_diff" event. The diff structure will be a map of `:joins` and `:leaves` of the form: %{ joins: %{"123" => %{metas: [%{status: "away", phx_ref: ...}]}}, leaves: %{"456" => %{metas: [%{status: "online", phx_ref: ...}]}} }, See `c:list/1` for more information on the presence data structure. ## Fetching Presence Information Presence metadata should be minimized and used to store small, ephemeral state, such as a user's "online" or "away" status. More detailed information, such as user details that need to be fetched from the database, can be achieved by overriding the `c:fetch/2` function. The `c:fetch/2` callback is triggered when using `c:list/1` and on every update, and it serves as a mechanism to fetch presence information a single time, before broadcasting the information to all channel subscribers. This prevents N query problems and gives you a single place to group isolated data fetching to extend presence metadata. The function must return a map of data matching the outlined Presence data structure, including the `:metas` key, but can extend the map of information to include any additional information. For example: def fetch(_topic, presences) do users = presences |> Map.keys() |> Accounts.get_users_map() for {key, %{metas: metas}} <- presences, into: %{} do {key, %{metas: metas, user: users[String.to_integer(key)]}} end end Where `Account.get_users_map/1` could be implemented like: def get_users_map(ids) do query = from u in User, where: u.id in ^ids, select: {u.id, u} query |> Repo.all() |> Enum.into(%{}) end The `fetch/2` function above fetches all users from the database who have registered presences for the given topic. The presences information is then extended with a `:user` key of the user's information, while maintaining the required `:metas` field from the original presence data. ## Using Elixir as a Presence Client Presence is great for external clients, such as JavaScript applications, but it can also be used from an Elixir client process to keep track of presence changes as they happen on the server. This can be accomplished by implementing the optional `init/1` and handle_metas/4` callback on your presence module. For example, the following callback receives presence metadata changes, and broadcasts to other Elixir processes about users joining and leaving: defmodule MyApp.Presence do use Phoenix.Presence, otp_app: :my_app, pubsub_server: MyApp.PubSub def init(_opts) do {:ok, %{}} # user-land state end def handle_metas(topic, %{joins: joins, leaves: leaves}, presences, state) do # fetch existing presence information for the joined users and broadcast the # event to all subscribers for {user_id, presence} <- joins do user_data = %{user: presence.user, metas: Map.fetch!(presences, user_id)} msg = {LiveBeats.PresenceClient, {:join, user_data}} Phoenix.PubSub.local_broadcast(MyApp.PubSub, topic, msg) end # fetch existing presence information for the left users and broadcast the # event to all subscribers for {user_id, presence} <- leaves do metas = case Map.fetch(presences, user_id) do {:ok, presence_metas} -> presence_metas :error -> [] end user_data = %{user: presence.user, metas: metas} msg = {LiveBeats.PresenceClient, {:leave, user_data}} Phoenix.PubSub.local_broadcast(MyApp.PubSub, topic, msg) end {:ok, state} end end The `handle_metas/4` callback receives the topic, presence diff, current presences for the topic with their metadata, and any user-land state accumulated from init and subsequent `handle_metas/4` calls. In our example implementation, we walk the `:joins` and `:leaves` in the diff, and populate a complete presence from our known presence information. Then we broadcast to the local node subscribers about user joins and leaves. ## Testing with Presence Every time the `fetch` callback is invoked, it is done from a separate process. Given those processes run asynchronously, it is often necessary to guarantee they have been shutdown at the end of every test. This can be done by using ExUnit's `on_exit` hook plus `fetchers_pids` function: on_exit(fn -> for pid <- MyAppWeb.Presence.fetchers_pids() do ref = Process.monitor(pid) assert_receive {:DOWN, ^ref, _, _, _}, 1000 end end) """ @type presences :: %{String.t() => %{metas: [map()]}} @type presence :: %{key: String.t(), meta: map()} @type topic :: String.t() @doc """ Track a channel's process as a presence. Tracked presences are grouped by `key`, cast as a string. For example, to group each user's channels together, use user IDs as keys. Each presence can be associated with a map of metadata to store small, ephemeral state, such as a user's online status. To store detailed information, see `c:fetch/2`. ## Example alias MyApp.Presence def handle_info(:after_join, socket) do {:ok, _} = Presence.track(socket, socket.assigns.user_id, %{ online_at: inspect(System.system_time(:second)) }) {:noreply, socket} end """ @callback track(socket :: Phoenix.Socket.t(), key :: String.t(), meta :: map()) :: {:ok, ref :: binary()} | {:error, reason :: term()} @doc """ Track an arbitrary process as a presence. Same with `track/3`, except track any process by `topic` and `key`. """ @callback track(pid, topic, key :: String.t(), meta :: map()) :: {:ok, ref :: binary()} | {:error, reason :: term()} @doc """ Stop tracking a channel's process. """ @callback untrack(socket :: Phoenix.Socket.t(), key :: String.t()) :: :ok @doc """ Stop tracking a process. """ @callback untrack(pid, topic, key :: String.t()) :: :ok @doc """ Update a channel presence's metadata. Replace a presence's metadata by passing a new map or a function that takes the current map and returns a new one. """ @callback update( socket :: Phoenix.Socket.t(), key :: String.t(), meta :: map() | (map() -> map()) ) :: {:ok, ref :: binary()} | {:error, reason :: term()} @doc """ Update a process presence's metadata. Same as `update/3`, but with an arbitrary process. """ @callback update(pid, topic, key :: String.t(), meta :: map() | (map() -> map())) :: {:ok, ref :: binary()} | {:error, reason :: term()} @doc """ Returns presences for a socket/topic. ## Presence data structure The presence information is returned as a map with presences grouped by key, cast as a string, and accumulated metadata, with the following form: %{key => %{metas: [%{phx_ref: ..., ...}, ...]}} For example, imagine a user with id `123` online from two different devices, as well as a user with id `456` online from just one device. The following presence information might be returned: %{"123" => %{metas: [%{status: "away", phx_ref: ...}, %{status: "online", phx_ref: ...}]}, "456" => %{metas: [%{status: "online", phx_ref: ...}]}} The keys of the map will usually point to a resource ID. The value will contain a map with a `:metas` key containing a list of metadata for each resource. Additionally, every metadata entry will contain a `:phx_ref` key which can be used to uniquely identify metadata for a given key. In the event that the metadata was previously updated, a `:phx_ref_prev` key will be present containing the previous `:phx_ref` value. """ @callback list(Phoenix.Socket.t() | topic) :: presences @doc """ Returns the map of presence metadata for a socket/topic-key pair. ## Examples Uses the same data format as `c:list/1`, but only returns metadata for the presences under a topic and key pair. For example, a user with key `"user1"`, connected to the same chat room `"room:1"` from two devices, could return: iex> MyPresence.get_by_key("room:1", "user1") [%{name: "User 1", metas: [%{device: "Desktop"}, %{device: "Mobile"}]}] Like `c:list/1`, the presence metadata is passed to the `fetch` callback of your presence module to fetch any additional information. """ @callback get_by_key(Phoenix.Socket.t() | topic, key :: String.t()) :: presences @doc """ Extend presence information with additional data. When `c:list/1` is used to list all presences of the given `topic`, this callback is triggered once to modify the result before it is broadcasted to all channel subscribers. This avoids N query problems and provides a single place to extend presence metadata. You must return a map of data matching the original result, including the `:metas` key, but can extend the map to include any additional information. The default implementation simply passes `presences` through unchanged. ## Example def fetch(_topic, presences) do query = from u in User, where: u.id in ^Map.keys(presences), select: {u.id, u} users = query |> Repo.all() |> Enum.into(%{}) for {key, %{metas: metas}} <- presences, into: %{} do {key, %{metas: metas, user: users[key]}} end end """ @callback fetch(topic, presences) :: presences @callback init(state :: term) :: {:ok, new_state :: term} @callback handle_metas(topic :: String.t(), diff :: map(), presences :: map(), state :: term) :: {:ok, term} @optional_callbacks init: 1, handle_metas: 4 defmacro __using__(opts) do quote location: :keep, bind_quoted: [opts: opts] do @behaviour Phoenix.Presence @opts opts @task_supervisor Module.concat(__MODULE__, "TaskSupervisor") _ = opts[:otp_app] || raise "use Phoenix.Presence expects :otp_app to be given" # User defined def fetch(_topic, presences), do: presences defoverridable fetch: 2 # Private def child_spec(opts) do opts = Keyword.merge(@opts, opts) %{ id: __MODULE__, start: {Phoenix.Presence, :start_link, [__MODULE__, @task_supervisor, opts]}, type: :supervisor } end # API def track(%Phoenix.Socket{} = socket, key, meta) do track(socket.channel_pid, socket.topic, key, meta) end def track(pid, topic, key, meta) do Phoenix.Tracker.track(__MODULE__, pid, topic, key, meta) end def untrack(%Phoenix.Socket{} = socket, key) do untrack(socket.channel_pid, socket.topic, key) end def untrack(pid, topic, key) do Phoenix.Tracker.untrack(__MODULE__, pid, topic, key) end def update(%Phoenix.Socket{} = socket, key, meta) do update(socket.channel_pid, socket.topic, key, meta) end def update(pid, topic, key, meta) do Phoenix.Tracker.update(__MODULE__, pid, topic, key, meta) end def list(%Phoenix.Socket{topic: topic}), do: list(topic) def list(topic), do: Phoenix.Presence.list(__MODULE__, topic) def get_by_key(%Phoenix.Socket{topic: topic}, key), do: get_by_key(topic, key) def get_by_key(topic, key), do: Phoenix.Presence.get_by_key(__MODULE__, topic, key) def fetchers_pids(), do: Task.Supervisor.children(@task_supervisor) end end defmodule Tracker do @moduledoc false use Phoenix.Tracker def start_link({module, task_supervisor, opts}) do pubsub_server = opts[:pubsub_server] || raise "use Phoenix.Presence expects :pubsub_server to be given" Phoenix.Tracker.start_link( __MODULE__, {module, task_supervisor, pubsub_server}, opts ) end def init(state), do: Phoenix.Presence.init(state) def handle_diff(diff, state), do: Phoenix.Presence.handle_diff(diff, state) def handle_info(msg, state), do: Phoenix.Presence.handle_info(msg, state) end @doc false def start_link(module, task_supervisor, opts) do otp_app = opts[:otp_app] opts = opts |> Keyword.merge(Application.get_env(otp_app, module, [])) |> Keyword.put(:name, module) children = [ {Task.Supervisor, name: task_supervisor}, {Tracker, {module, task_supervisor, opts}} ] sup_opts = [ strategy: :rest_for_one, name: Module.concat(module, "Supervisor") ] Supervisor.start_link(children, sup_opts) end @doc false def init({module, task_supervisor, pubsub_server}) do state = %{ module: module, task_supervisor: task_supervisor, pubsub_server: pubsub_server, topics: %{}, tasks: :queue.new(), current_task: nil, client_state: nil } client_state = if function_exported?(module, :handle_metas, 4) do case module.init(%{}) do {:ok, client_state} -> client_state other -> raise ArgumentError, """ expected #{inspect(module)}.init/1 to return {:ok, state}, got: #{inspect(other)} """ end end {:ok, %{state | client_state: client_state}} end @doc false def handle_diff(diff, state) do {:ok, async_merge(state, diff)} end @doc false def handle_info({task_ref, {:phoenix, ref, computed_diffs}}, state) do %{current_task: current_task} = state {^ref, %Task{ref: ^task_ref} = task} = current_task {:exit, _} = Task.shutdown(task) Enum.each(computed_diffs, fn {topic, presence_diff} -> Phoenix.Channel.Server.local_broadcast( state.pubsub_server, topic, "presence_diff", presence_diff ) end) new_state = if function_exported?(state.module, :handle_metas, 4) do do_handle_metas(state, computed_diffs) else state end {:noreply, next_task(new_state)} end @doc false def list(module, topic) do grouped = module |> Phoenix.Tracker.list(topic) |> group() module.fetch(topic, grouped) end @doc false def get_by_key(module, topic, key) do string_key = to_string(key) case Phoenix.Tracker.get_by_key(module, topic, key) do [] -> [] [_ | _] = pid_metas -> metas = Enum.map(pid_metas, fn {_pid, meta} -> meta end) %{^string_key => fetched_metas} = module.fetch(topic, %{string_key => %{metas: metas}}) fetched_metas end end @doc false def group(presences) do presences |> Enum.reverse() |> Enum.reduce(%{}, fn {key, meta}, acc -> Map.update(acc, to_string(key), %{metas: [meta]}, fn %{metas: metas} -> %{metas: [meta | metas]} end) end) end defp send_continue(%Task{} = task, ref), do: send(task.pid, {ref, :continue}) defp next_task(state) do case :queue.out(state.tasks) do {{:value, {ref, %Task{} = next}}, remaining_tasks} -> send_continue(next, ref) %{state | current_task: {ref, next}, tasks: remaining_tasks} {:empty, _} -> %{state | current_task: nil, tasks: :queue.new()} end end defp do_handle_metas(state, computed_diffs) do Enum.reduce(computed_diffs, state, fn {topic, presence_diff}, acc -> updated_topics = merge_diff(acc.topics, topic, presence_diff) topic_presences = case Map.fetch(updated_topics, topic) do {:ok, presences} -> presences :error -> %{} end case acc.module.handle_metas(topic, presence_diff, topic_presences, acc.client_state) do {:ok, updated_client_state} -> %{acc | topics: updated_topics, client_state: updated_client_state} other -> raise ArgumentError, """ expected #{inspect(acc.module)}.handle_metas/4 to return {:ok, new_state}. got: #{inspect(other)} """ end end) end defp async_merge(state, diff) do %{module: module} = state ref = make_ref() new_task = Task.Supervisor.async(state.task_supervisor, fn -> computed_diffs = Enum.map(diff, fn {topic, {joins, leaves}} -> joins = module.fetch(topic, Phoenix.Presence.group(joins)) leaves = module.fetch(topic, Phoenix.Presence.group(leaves)) {topic, %{joins: joins, leaves: leaves}} end) receive do {^ref, :continue} -> {:phoenix, ref, computed_diffs} end end) if state.current_task do %{state | tasks: :queue.in({ref, new_task}, state.tasks)} else send_continue(new_task, ref) %{state | current_task: {ref, new_task}} end end defp merge_diff(topics, topic, %{leaves: leaves, joins: joins} = _diff) do # add new topic if needed updated_topics = if Map.has_key?(topics, topic) do topics else add_new_topic(topics, topic) end # merge diff into topics {updated_topics, _topic} = Enum.reduce(joins, {updated_topics, topic}, &handle_join/2) {updated_topics, _topic} = Enum.reduce(leaves, {updated_topics, topic}, &handle_leave/2) # if no more presences for given topic, remove topic if topic_presences_count(updated_topics, topic) == 0 do remove_topic(updated_topics, topic) else updated_topics end end defp handle_join({joined_key, presence}, {topics, topic}) do joined_metas = Map.get(presence, :metas, []) {add_new_presence_or_metas(topics, topic, joined_key, joined_metas), topic} end defp handle_leave({left_key, presence}, {topics, topic}) do {remove_presence_or_metas(topics, topic, left_key, presence), topic} end defp add_new_presence_or_metas( topics, topic, key, new_metas ) do topic_presences = topics[topic] updated_topic = case Map.fetch(topic_presences, key) do # existing presence, add new metas {:ok, existing_metas} -> remaining_metas = new_metas -- existing_metas updated_metas = existing_metas ++ remaining_metas Map.put(topic_presences, key, updated_metas) # there are no presences for that key :error -> Map.put_new(topic_presences, key, new_metas) end Map.put(topics, topic, updated_topic) end defp remove_presence_or_metas( topics, topic, key, deleted_metas ) do topic_presences = topics[topic] presence_metas = Map.get(topic_presences, key, []) remaining_metas = presence_metas -- Map.get(deleted_metas, :metas, []) updated_topic = case remaining_metas do [] -> Map.delete(topic_presences, key) _ -> Map.put(topic_presences, key, remaining_metas) end Map.put(topics, topic, updated_topic) end defp add_new_topic(topics, topic) do Map.put_new(topics, topic, %{}) end defp remove_topic(topics, topic) do Map.delete(topics, topic) end defp topic_presences_count(topics, topic) do map_size(topics[topic]) end end
31.956459
98
0.639386
08adf08ff9adf95434f099d35dd909e586c9c81d
8,758
exs
Elixir
lib/ex_unit/test/ex_unit/doc_test_test.exs
jquadrin/elixir
98746e08eaa2bf58c202e8500b6cf83ed2368cc0
[ "Apache-2.0" ]
null
null
null
lib/ex_unit/test/ex_unit/doc_test_test.exs
jquadrin/elixir
98746e08eaa2bf58c202e8500b6cf83ed2368cc0
[ "Apache-2.0" ]
null
null
null
lib/ex_unit/test/ex_unit/doc_test_test.exs
jquadrin/elixir
98746e08eaa2bf58c202e8500b6cf83ed2368cc0
[ "Apache-2.0" ]
null
null
null
Code.require_file "../test_helper.exs", __DIR__ import ExUnit.TestHelpers defmodule ExUnit.DocTestTest.GoodModule do @doc """ iex> test_fun 1 iex> test_fun + 1 2 """ def test_fun, do: 1 @doc ~S""" iex> ~S(f#{o}o) "f\#{o}o" """ def test_sigil, do: :ok @doc """ iex> a = 1 iex> b = a + 2 3 iex> a + b 4 """ def single_context, do: :ok @doc """ iex> 1 + (fn() -> "" end).() ** (ArithmeticError) bad argument in arithmetic expression iex> 2 + (fn() -> :a end).() ** (ArithmeticError) bad argument in arithmetic expression """ def two_exceptions, do: :ok @doc """ iex> 1 + (fn() -> :a end).() ** (ArithmeticError) bad argument in arithmetic expression """ def exception_test, do: :ok @doc """ iex> Enum.into([a: 0, b: 1, c: 2], HashDict.new) #HashDict<[c: 2, b: 1, a: 0]> """ def inspect1_test, do: :ok @doc """ iex> x = Enum.into([a: 0, b: 1, c: 2], HashDict.new) ...> x #HashDict<[c: 2, b: 1, a: 0]> """ def inspect2_test, do: :ok end |> write_beam defmodule ExUnit.DocTestTest.MultipleExceptions do @doc """ iex> 1 + "" ** (ArithmeticError) bad argument in arithmetic expression iex> 2 + "" ** (ArithmeticError) bad argument in arithmetic expression """ def two_exceptions, do: :ok end |> write_beam defmodule ExUnit.DocTestTest.SomewhatGoodModuleWithOnly do @doc """ iex> test_fun 1 iex> test_fun + 1 2 """ def test_fun, do: 1 @doc """ iex> test_fun 1 iex> test_fun + 1 1 """ def test_fun1, do: 1 end |> write_beam defmodule ExUnit.DocTestTest.SomewhatGoodModuleWithExcept do @doc """ iex> test_fun 1 iex> test_fun + 1 2 """ def test_fun, do: 1 @doc """ iex> test_fun 1 iex> test_fun + 1 1 """ def test_fun1, do: 1 end |> write_beam defmodule ExUnit.DocTestTest.NoImport do @doc """ iex> ExUnit.DocTestTest.NoImport.min(1, 2) 2 """ def min(a, b), do: max(a, b) end |> write_beam defmodule ExUnit.DocTestTest.Invalid do @moduledoc """ iex> 1 + * 1 1 iex> 1 + hd(List.flatten([1])) 3 iex> :oops #HashDict<[]> iex> Hello.world :world iex> raise "oops" ** (WhatIsThis) oops iex> raise "oops" ** (RuntimeError) hello """ end |> write_beam defmodule ExUnit.DocTestTest.IndentationHeredocs do @doc ~S''' Receives a test and formats its failure. ## Examples iex> " 1\n 2\n" """ 1 2 """ ''' def heredocs, do: :ok end |> write_beam defmodule ExUnit.DocTestTest.IndentationMismatchedPrompt do @doc ~S''' iex> foo = 1 iex> bar = 2 iex> foo + bar 3 ''' def mismatched, do: :ok end |> write_beam defmodule ExUnit.DocTestTest.IndentationTooMuch do @doc ~S''' iex> 1 + 2 3 ''' def too_much, do: :ok end |> write_beam defmodule ExUnit.DocTestTest.IndentationNotEnough do @doc ~S''' iex> 1 + 2 3 ''' def not_enough, do: :ok end |> write_beam defmodule ExUnit.DocTestTest.Incomplete do @doc ~S''' iex> 1 + 2 ''' def not_enough, do: :ok end |> write_beam defmodule ExUnit.DocTestTest do use ExUnit.Case # This is intentional. The doctests in DocTest's docs # fail for demonstration purposes. # doctest ExUnit.DocTest doctest ExUnit.DocTestTest.GoodModule, import: true doctest ExUnit.DocTestTest.SomewhatGoodModuleWithOnly, only: [test_fun: 0], import: true doctest ExUnit.DocTestTest.SomewhatGoodModuleWithExcept, except: [test_fun1: 0], import: true doctest ExUnit.DocTestTest.NoImport doctest ExUnit.DocTestTest.IndentationHeredocs import ExUnit.CaptureIO test "doctest failures" do defmodule ActuallyCompiled do use ExUnit.Case doctest ExUnit.DocTestTest.Invalid end ExUnit.configure(seed: 0, colors: [enabled: false]) output = capture_io(fn -> ExUnit.run end) # Test order is not guaranteed, we can't match this as a string for each failing doctest assert output =~ ~r/\d+\) test moduledoc at ExUnit\.DocTestTest\.Invalid \(\d+\) \(ExUnit\.DocTestTest\.ActuallyCompiled\)/ assert output =~ """ 1) test moduledoc at ExUnit.DocTestTest.Invalid (1) (ExUnit.DocTestTest.ActuallyCompiled) test/ex_unit/doc_test_test.exs:204 Doctest did not compile, got: (SyntaxError) test/ex_unit/doc_test_test.exs:112: syntax error before: '*' code: 1 + * 1 stacktrace: test/ex_unit/doc_test_test.exs:112: ExUnit.DocTestTest.Invalid (module) """ assert output =~ """ 2) test moduledoc at ExUnit.DocTestTest.Invalid (2) (ExUnit.DocTestTest.ActuallyCompiled) test/ex_unit/doc_test_test.exs:204 Doctest failed code: 1 + hd(List.flatten([1])) === 3 lhs: 2 stacktrace: test/ex_unit/doc_test_test.exs:112: ExUnit.DocTestTest.Invalid (module) """ assert output =~ """ 3) test moduledoc at ExUnit.DocTestTest.Invalid (3) (ExUnit.DocTestTest.ActuallyCompiled) test/ex_unit/doc_test_test.exs:204 Doctest failed code: inspect(:oops) === "#HashDict<[]>" lhs: ":oops" stacktrace: test/ex_unit/doc_test_test.exs:112: ExUnit.DocTestTest.Invalid (module) """ assert output =~ """ 4) test moduledoc at ExUnit.DocTestTest.Invalid (4) (ExUnit.DocTestTest.ActuallyCompiled) test/ex_unit/doc_test_test.exs:204 Doctest failed: got UndefinedFunctionError with message undefined function: Hello.world/0 (module Hello is not available) code: Hello.world stacktrace: test/ex_unit/doc_test_test.exs:112: ExUnit.DocTestTest.Invalid (module) """ assert output =~ """ 5) test moduledoc at ExUnit.DocTestTest.Invalid (5) (ExUnit.DocTestTest.ActuallyCompiled) test/ex_unit/doc_test_test.exs:204 Doctest failed: expected exception WhatIsThis with message "oops" but got RuntimeError with message "oops" code: raise "oops" stacktrace: test/ex_unit/doc_test_test.exs:112: ExUnit.DocTestTest.Invalid (module) """ assert output =~ """ 6) test moduledoc at ExUnit.DocTestTest.Invalid (6) (ExUnit.DocTestTest.ActuallyCompiled) test/ex_unit/doc_test_test.exs:204 Doctest failed: expected exception RuntimeError with message "hello" but got RuntimeError with message "oops" code: raise "oops" stacktrace: test/ex_unit/doc_test_test.exs:112: ExUnit.DocTestTest.Invalid (module) """ end test "tags tests as doctests" do defmodule DoctestTag do use ExUnit.Case doctest ExUnit.DocTestTest.NoImport setup test do assert test.doctest :ok end end assert capture_io(fn -> ExUnit.run end) =~ "1 test, 0 failures" end test "multiple exceptions in one test case is not supported" do assert_raise ExUnit.DocTest.Error, ~r"multiple exceptions in one doctest case are not supported", fn -> defmodule NeverCompiled do import ExUnit.DocTest doctest ExUnit.DocTestTest.MultipleExceptions end end end test "fails on invalid module" do assert_raise CompileError, ~r"module ExUnit.DocTestTest.Unknown is not loaded and could not be found", fn -> defmodule NeverCompiled do import ExUnit.DocTest doctest ExUnit.DocTestTest.Unknown end end end test "fails when there are no docs" do assert_raise ExUnit.DocTest.Error, ~r"could not retrieve the documentation for module ExUnit.DocTestTest", fn -> defmodule NeverCompiled do import ExUnit.DocTest doctest ExUnit.DocTestTest end end end test "fails in indentation mismatch" do assert_raise ExUnit.DocTest.Error, ~r/indentation level mismatch: " iex> bar = 2", should have been 2 spaces/, fn -> defmodule NeverCompiled do import ExUnit.DocTest doctest ExUnit.DocTestTest.IndentationMismatchedPrompt end end assert_raise ExUnit.DocTest.Error, ~r/indentation level mismatch: " 3", should have been 2 spaces/, fn -> defmodule NeverCompiled do import ExUnit.DocTest doctest ExUnit.DocTestTest.IndentationTooMuch end end assert_raise ExUnit.DocTest.Error, ~r/indentation level mismatch: \" 3\", should have been 4 spaces/, fn -> defmodule NeverCompiled do import ExUnit.DocTest doctest ExUnit.DocTestTest.IndentationNotEnough end end assert_raise ExUnit.DocTest.Error, ~r/expected non-blank line to follow iex> prompt/, fn -> defmodule NeverCompiled do import ExUnit.DocTest doctest ExUnit.DocTestTest.Incomplete end end end end
25.683284
130
0.64992
08adf5c8c4b8fc4e9caec96528d4e6689f7691b9
2,146
ex
Elixir
kousa/lib/broth/message/manifest.ex
MeztliRA/dogehouse
8bbc4d09efcbff757249c27373e61b9d6d3cd920
[ "MIT" ]
null
null
null
kousa/lib/broth/message/manifest.ex
MeztliRA/dogehouse
8bbc4d09efcbff757249c27373e61b9d6d3cd920
[ "MIT" ]
null
null
null
kousa/lib/broth/message/manifest.ex
MeztliRA/dogehouse
8bbc4d09efcbff757249c27373e61b9d6d3cd920
[ "MIT" ]
null
null
null
defmodule Broth.Message.Manifest do alias Broth.Message.Auth alias Broth.Message.Chat alias Broth.Message.Room alias Broth.Message.User alias Broth.Message.Misc @actions %{ "test:operator" => BrothTest.MessageTest.TestOperator, "user:create_bot" => User.CreateBot, "user:ban" => User.Ban, "user:block" => User.Block, "user:unblock" => User.Unblock, "user:follow" => User.Follow, "user:get_following" => User.GetFollowing, "user:get_followers" => User.GetFollowers, "user:update" => User.Update, "user:get_info" => User.GetInfo, "user:get_bots" => User.GetBots, "user:revoke_api_key" => User.RevokeApiKey, "user:get_relationship" => User.GetRelationship, "user:unfollow" => User.Unfollow, "room:invite" => Room.Invite, "room:update" => Room.Update, "room:get_invite_list" => Room.GetInviteList, "room:leave" => Room.Leave, "room:ban" => Room.Ban, "room:set_role" => Room.SetRole, "room:set_auth" => Room.SetAuth, "room:join" => Room.Join, "room:get_banned_users" => Room.GetBannedUsers, "room:update_scheduled" => Room.UpdateScheduled, "room:delete_scheduled" => Room.DeleteScheduled, "room:create" => Room.Create, "room:create_scheduled" => Room.CreateScheduled, "room:unban" => Room.Unban, "room:get_info" => Room.GetInfo, "room:get_top" => Room.GetTop, "room:set_active_speaker" => Room.SetActiveSpeaker, "room:mute" => Room.Mute, "room:deafen" => Room.Deafen, "room:get_scheduled" => Room.GetScheduled, "chat:ban" => Chat.Ban, "chat:unban" => Chat.Unban, "chat:send_msg" => Chat.Send, "chat:delete" => Chat.Delete, "auth:request" => Auth.Request, "misc:search" => Misc.Search } # verify that all of the actions are accounted for in the # operators list alias Broth.Message.Types.Operator require Operator @actions |> Map.values() |> Enum.each(fn module -> Operator.valid_value?(module) || raise CompileError, description: "the module #{inspect(module)} is not a member of #{inspect(Operator)}" end) def actions, do: @actions end
32.515152
92
0.658434
08ae091ff570621dfa8364cde3bc6bde3edf4908
155
ex
Elixir
lib/timeularex/resources/time_entry.ex
r-frederick/timeularex
9ede39350b4d0095300d291fb2ab1049461e3381
[ "MIT" ]
1
2018-06-01T19:14:57.000Z
2018-06-01T19:14:57.000Z
lib/timeularex/resources/time_entry.ex
r-frederick/timeularex
9ede39350b4d0095300d291fb2ab1049461e3381
[ "MIT" ]
null
null
null
lib/timeularex/resources/time_entry.ex
r-frederick/timeularex
9ede39350b4d0095300d291fb2ab1049461e3381
[ "MIT" ]
null
null
null
defmodule Timeularex.Resources.TimeEntry do defstruct activityId: nil, startedAt: nil, stoppedAt: nil, note: nil end
22.142857
43
0.612903
08ae7bfb26d996cc814d4ea02e585d9a98b93ba2
2,133
exs
Elixir
test/erlef_web/controllers/working_group/report_controller_test.exs
dhadka/website
e67c23d7052b4ef00a1af52b0b9ebc952d34776e
[ "Apache-2.0" ]
null
null
null
test/erlef_web/controllers/working_group/report_controller_test.exs
dhadka/website
e67c23d7052b4ef00a1af52b0b9ebc952d34776e
[ "Apache-2.0" ]
null
null
null
test/erlef_web/controllers/working_group/report_controller_test.exs
dhadka/website
e67c23d7052b4ef00a1af52b0b9ebc952d34776e
[ "Apache-2.0" ]
null
null
null
defmodule ErlefWeb.WorkingGroup.ReportControllerTest do use ErlefWeb.ConnCase alias Erlef.Groups @create_attrs %{content: "some content", is_private: true, meta: %{}, type: "quarterly"} @invalid_attrs %{content: nil, is_private: nil, meta: nil, type: nil} def fixture(:working_group_report) do {:ok, working_group_report} = Groups.create_wg_report(@create_attrs) working_group_report end setup do {:ok, member} = Erlef.Accounts.get_member("wg_chair") opts = [audit: %{member_id: member.id}] {:ok, v} = Erlef.Groups.create_volunteer(%{name: member.name, member_id: member.id}, opts) wgv = insert(:working_group_volunteer, volunteer: v) insert(:working_group_chair, volunteer: wgv.volunteer, working_group: wgv.working_group) [chair: member, working_group: wgv.working_group] end describe "new working_group_report" do setup :chair_session test "renders form", %{conn: conn, working_group: wg} do conn = get(conn, Routes.working_group_report_path(conn, :new, wg.slug)) assert html_response(conn, 200) =~ "New #{wg.name} Working Group Report" end end describe "create working_group_report" do setup :chair_session test "redirects to show when data is valid", %{conn: conn, working_group: wg, chair: chair} do upload = %Plug.Upload{path: "test/fixtures/markdown.md", filename: "markdown.md"} conn = post(conn, Routes.working_group_report_path(conn, :create, wg.slug), working_group_report: Map.put(@create_attrs, :file, upload) ) [report] = Groups.list_wg_reports_by_member_id(chair.id) assert %{slug: _slug} = redirected_params(conn) assert redirected_to(conn) == Routes.working_group_report_path(conn, :show, wg.slug, report.id) end test "renders errors when data is invalid", %{conn: conn, working_group: wg} do conn = post(conn, Routes.working_group_report_path(conn, :create, wg.slug), working_group_report: @invalid_attrs ) assert html_response(conn, 200) =~ "New #{wg.name} Working Group Report" end end end
35.55
98
0.691514
08ae8ef7508ca29cd641ad7ff474f1a06c1de87a
1,559
ex
Elixir
lib/hauer/fs.ex
nanaki82/hauer
7d717a913933c7f71391d0eadb724c41bdd3ed77
[ "MIT" ]
null
null
null
lib/hauer/fs.ex
nanaki82/hauer
7d717a913933c7f71391d0eadb724c41bdd3ed77
[ "MIT" ]
null
null
null
lib/hauer/fs.ex
nanaki82/hauer
7d717a913933c7f71391d0eadb724c41bdd3ed77
[ "MIT" ]
null
null
null
defmodule Hauer.FS do @moduledoc false @resources_dir Application.get_env(:hauer, :resources_dir) @conf_file Application.get_env(:hauer, :conf_file) defp create_resources_dir() do resources_dir = get_resources_dir() if !File.exists?(resources_dir) do File.mkdir!(resources_dir) end :ok end defp get_resources_dir() do {:ok, pwd} = File.cwd() "#{pwd}/lib/#{@resources_dir}" end def get_resource_dir(resource_name) do "#{get_resources_dir()}/#{resource_name}.ex" end def add_resource(resource_name) do create_resources_dir() resource_file_path = get_resource_dir(resource_name) already_exists = File.exists?(resource_file_path) case already_exists do true -> {:error, "Resource file already exists: #{resource_file_path}"} _ -> File.touch!(resource_file_path) {:ok, resource_file_path} end end def remove_resource(resource_name) do resource_file_path = get_resource_dir(resource_name) File.rm!(resource_file_path) :ok end def get_conf_path() do {:ok, pwd} = File.cwd() "#{pwd}/#{@conf_file}" end def write_conf(encoded_conf) do conf_file_path = get_conf_path() conf_file_exists? = File.exists?(conf_file_path) if conf_file_exists? == false do File.touch!(conf_file_path) end File.write!(conf_file_path, encoded_conf, [:write, :utf8]) end def read_conf() do File.open!(get_conf_path(), [:read, :utf8], fn file -> IO.read(file, :all) end) end end
21.356164
71
0.669019
08aeb1d46f4040f16d7804e40266531e59cc7b31
295
exs
Elixir
backend/priv/repo/migrations/20211105185233_add_connection_info_to_devices.exs
bejolithic/honeyland
8c4a0d3b56543648d3acb96cc6906df86526743b
[ "Apache-2.0" ]
null
null
null
backend/priv/repo/migrations/20211105185233_add_connection_info_to_devices.exs
bejolithic/honeyland
8c4a0d3b56543648d3acb96cc6906df86526743b
[ "Apache-2.0" ]
null
null
null
backend/priv/repo/migrations/20211105185233_add_connection_info_to_devices.exs
bejolithic/honeyland
8c4a0d3b56543648d3acb96cc6906df86526743b
[ "Apache-2.0" ]
null
null
null
defmodule Honeyland.Repo.Migrations.AddConnectionInfoToDevices do use Ecto.Migration def change do alter table(:devices) do add :online, :boolean, default: false, null: false add :last_connection, :utc_datetime add :last_disconnection, :utc_datetime end end end
24.583333
65
0.728814
08aecc89e0f0a5bee8ab323213e910b9f3fa63dd
1,112
ex
Elixir
lib/mix/tasks/analyze.ex
carguero/carguero_task_bunny
e6f4346904433a5ffe3b3b256a97f348839ab514
[ "MIT" ]
2
2020-12-03T18:09:00.000Z
2021-01-17T22:44:50.000Z
lib/mix/tasks/analyze.ex
carguero/carguero_task_bunny
e6f4346904433a5ffe3b3b256a97f348839ab514
[ "MIT" ]
null
null
null
lib/mix/tasks/analyze.ex
carguero/carguero_task_bunny
e6f4346904433a5ffe3b3b256a97f348839ab514
[ "MIT" ]
null
null
null
defmodule Mix.Tasks.Analyze do # Analyze the code and exit if errors have been found. # # It is a private mix task for CargueroTaskBunny. # @moduledoc false use Mix.Task @shortdoc "Analyze the code and exit if errors have been found." @spec execute(String.t(), [String.t()], boolean) :: any defp execute(command, options, show_output \\ false) do commands = ["-q", "/dev/null", command] label = "\e[1m#{command} #{Enum.join(options, " ")}\e[0m" " " |> Kernel.<>(label) |> String.pad_trailing(60, " ") |> IO.write() case System.cmd("script", commands ++ options) do {output, 0} -> IO.puts("\e[32msuccess\e[0m") if show_output, do: IO.puts(output) {output, _} -> IO.puts("\e[31mfailed\e[0m") IO.puts(output) IO.puts("#{label} \e[31mfailed\e[0m") System.halt(1) end end @spec run([binary]) :: any def run(_) do IO.puts("Running:") execute("mix", ["credo", "--strict"]) execute("mix", ["dialyzer", "--halt-exit-status"]) execute("mix", ["coveralls.html"], true) end end
24.711111
66
0.580935
08af0b61999b1df93ecde398dc9884cec5091fe9
2,390
exs
Elixir
elixir/diamond/diamond_test.exs
macborowy/exercism
c5d45e074e81b946a82a340b2730e0d2732b7e0a
[ "MIT" ]
null
null
null
elixir/diamond/diamond_test.exs
macborowy/exercism
c5d45e074e81b946a82a340b2730e0d2732b7e0a
[ "MIT" ]
null
null
null
elixir/diamond/diamond_test.exs
macborowy/exercism
c5d45e074e81b946a82a340b2730e0d2732b7e0a
[ "MIT" ]
null
null
null
if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("diamond.exs") end ExUnit.start ExUnit.configure exclude: :pending, trace: true defmodule IndentTests do use ExUnit.Case test "for ?A should not add spaces" do assert Diamond.indent(?A, ?A) == [] end test "for ?B should return one space" do assert Diamond.indent(?B, ?A) == [" "] end end defmodule LineTests do use ExUnit.Case test "for A and B should return A with one space" do assert Diamond.line(?A, ?B) == " A" end test "for A and B should return B B" do assert Diamond.line(?B, ?B) == "B B" end end # defmodule CreateLinesTests do # use ExUnit.Case # # test "for " do # assert Diamond.create_lines([{?A, {0, 0}}], ?A) == [[?A]] # end # end # # defmodule GetPostionsTests do # use ExUnit.Case # # test "for range 'AB'" do # assert Diamond.get_positions({?A, 0}, 2) == {?A, {1, 1}} # assert Diamond.get_positions({?B, 1}, 2) == {?B, {0, 2}} # end # end # # defmodule SetLettersPositionsTests do # use ExUnit.Case # # test "for [A] and letter A should return {'A', 0}" do # assert Diamond.set_letters_positions('A') == [{?A, {0, 0}}] # end # # test "for [A, B] should return list of character positions" do # assert Diamond.set_letters_positions('AB') == [{?A, {1, 1}}, {?B, {0, 2}}] # end # end # # defmodule GetLettersTests do # use ExUnit.Case # # test "when ?A is passed should return list with single element A" do # assert Diamond.get_letters(?A) == 'A' # end # # test "when ?E is passed should return list of characters from E to A" do # assert Diamond.get_letters(?E) == 'ABCDE' # end # # test "when character is not in range A-Z should return Error" do # assert_raise FunctionClauseError, fn -> Diamond.get_letters(?1) end # assert_raise FunctionClauseError, fn -> Diamond.get_letters(?a) end # end # end defmodule DiamondTest do use ExUnit.Case # @tag :pending test "letter A" do shape = Diamond.build_shape(?A) assert shape == "A\n" end # @tag :pending test "letter C" do shape = Diamond.build_shape(?C) assert shape == """ \s A \sB B C C \sB B \s A """ end # @tag :pending test "letter E" do shape = Diamond.build_shape(?E) assert shape == """ \s A \s B B \s C C \sD D E E \sD D \s C C \s B B \s A """ end end
20.782609
80
0.615481
08af2829bdd3b894131f54ac1df0c9d1233fbb3d
4,400
ex
Elixir
lib/bamboo/adapters/ses_adapter.ex
goodells/bamboo_ses
3a3961d63862e8eef4c013dbf0612591b971d5a3
[ "MIT" ]
null
null
null
lib/bamboo/adapters/ses_adapter.ex
goodells/bamboo_ses
3a3961d63862e8eef4c013dbf0612591b971d5a3
[ "MIT" ]
null
null
null
lib/bamboo/adapters/ses_adapter.ex
goodells/bamboo_ses
3a3961d63862e8eef4c013dbf0612591b971d5a3
[ "MIT" ]
null
null
null
defmodule Bamboo.SesAdapter do @moduledoc """ Sends email using AWS SES API. Use this adapter to send emails through AWS SES API. """ @behaviour Bamboo.Adapter alias Bamboo.SesAdapter.RFC2822Renderer alias ExAws.SES import Bamboo.ApiError @doc false def supports_attachments?, do: true @doc false def handle_config(config) do config end def deliver(email, config) do ex_aws_config = Map.get(config, :ex_aws, []) template = email.private[:template] configuration_set_name = email.private[:configuration_set_name] ses_opts = [ configuration_set_name: configuration_set_name ] case ( if is_binary template do template_data = email.private[:template_data] SES.send_templated_email( %{ to: prepare_addresses(email.to), cc: prepare_addresses(email.cc), bcc: prepare_addresses(email.bcc) }, prepare_address(email.from), template, template_data, ses_opts ) |> ExAws.request(ex_aws_config) else Mail.build_multipart() |> Mail.put_from(prepare_address(email.from)) |> Mail.put_to(prepare_addresses(email.to)) |> Mail.put_cc(prepare_addresses(email.cc)) |> Mail.put_bcc(prepare_addresses(email.bcc)) |> Mail.put_subject(b_encode(email.subject)) |> put_headers(email.headers) |> put_text(email.text_body) |> put_html(email.html_body) |> put_attachments(email.attachments) |> Mail.render(RFC2822Renderer) |> SES.send_raw_email(ses_opts) |> ExAws.request(ex_aws_config) end ) do {:ok, response} -> {:ok, response} {:error, reason} -> {:error, build_api_error(inspect(reason))} end end defp put_headers(message, headers) when is_map(headers), do: put_headers(message, Map.to_list(headers)) defp put_headers(message, []), do: message defp put_headers(message, [{"Reply-To" = key, {_name, _address} = value} | tail]) do message |> Mail.Message.put_header(key, prepare_address(value)) |> put_headers(tail) end defp put_headers(message, [{key, value} | tail]) do message |> Mail.Message.put_header(key, value) |> put_headers(tail) end defp put_attachments(message, []), do: message defp put_attachments(message, attachments) do Enum.reduce( attachments, message, fn attachment, message -> headers = if attachment.content_id do [content_id: attachment.content_id] else [] end opts = [headers: headers] Mail.put_attachment(message, {attachment.filename, attachment.data}, opts) end ) end defp put_text(message, nil), do: message defp put_text(message, body), do: Mail.put_text(message, body) defp put_html(message, nil), do: message defp put_html(message, body), do: Mail.put_html(message, body) @doc """ Set the SES configuration set name. """ def set_configuration_set(mail, configuration_set_name), do: Bamboo.Email.put_private(mail, :configuration_set_name, configuration_set_name) @doc """ Set the SES template """ def set_template(mail, template), do: Bamboo.Email.put_private(mail, :template, template) @doc """ Set the SES template data """ def set_template_data(mail, template_data) when is_map(template_data) do Bamboo.Email.put_private(mail, :template_data, template_data) end defp prepare_addresses(recipients), do: Enum.map(recipients, &prepare_address(&1)) defp prepare_address({nil, address}), do: encode_address(address) defp prepare_address({"", address}), do: encode_address(address) defp prepare_address({name, address}), do: {b_encode(name), encode_address(address)} defp b_encode(string) when is_binary(string) do if ascii_only(string) do string else encoded_string = Base.encode64(string) "=?utf-8?B?#{encoded_string}?=" end end defp b_encode(string), do: string defp encode_address(address) do [local_part, domain_part] = String.split(address, "@") Enum.join([Mail.Encoders.SevenBit.encode(local_part), :idna.utf8_to_ascii(domain_part)], "@") end defp ascii_only(string) do String.to_charlist(string) |> Enum.all?(fn char -> 0 < char and char <= 127 end) end end
27.5
97
0.660227
08af2e33c60d4e3399b9aef231e52c428b13ff11
2,604
exs
Elixir
mix.exs
wmnnd/ex_doc
c287e821b56b7c58052ef26be891519e68b3dd11
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
mix.exs
wmnnd/ex_doc
c287e821b56b7c58052ef26be891519e68b3dd11
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
mix.exs
wmnnd/ex_doc
c287e821b56b7c58052ef26be891519e68b3dd11
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
defmodule ExDoc.Mixfile do use Mix.Project @source_url "https://github.com/elixir-lang/ex_doc" @version "0.27.2" def project do [ app: :ex_doc, version: @version, elixir: "~> 1.10", deps: deps(), aliases: aliases(), package: package(), escript: escript(), elixirc_paths: elixirc_paths(Mix.env()), source_url: @source_url, test_coverage: [tool: ExCoveralls], preferred_cli_env: [coveralls: :test], name: "ExDoc", description: "ExDoc is a documentation generation tool for Elixir", docs: docs() ] end def application do [ extra_applications: [:eex, :crypto], mod: {ExDoc.Application, []} ] end defp deps do [ {:earmark_parser, "~> 1.4.19"}, {:makeup_elixir, "~> 0.14"}, {:makeup_erlang, "~> 0.1"}, {:jason, "~> 1.2", only: :test} ] end defp aliases do [ build: ["cmd npm run --prefix assets build", "compile --force", "docs"], clean: [&clean_test_fixtures/1, "clean"], fix: ["format", "cmd npm run --prefix assets lint:fix"], lint: ["format --check-formatted", "cmd npm run --prefix assets lint"], setup: ["deps.get", "cmd npm install --prefix assets"] ] end defp package do [ licenses: ["Apache-2.0"], maintainers: ["José Valim", "Eksperimental", "Milton Mazzarri", "Wojtek Mach"], files: ["formatters", "lib", "mix.exs", "LICENSE", "CHANGELOG.md", "README.md"], links: %{ "GitHub" => @source_url, "Changelog" => "https://hexdocs.pm/ex_doc/changelog.html", "Writing documentation" => "https://hexdocs.pm/elixir/writing-documentation.html" } ] end defp escript do [ main_module: ExDoc.CLI ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] defp docs do [ main: "readme", extras: [ "README.md", "CHANGELOG.md", "LICENSE" ], source_ref: "v#{@version}", source_url: @source_url, groups_for_modules: [ Markdown: [ ExDoc.Markdown, ExDoc.Markdown.Earmark ], "Formatter API": [ ExDoc.Config, ExDoc.Formatter.EPUB, ExDoc.Formatter.HTML, ExDoc.Formatter.HTML.Autolink, ExDoc.FunctionNode, ExDoc.ModuleNode, ExDoc.TypeNode ] ], skip_undefined_reference_warnings_on: ["CHANGELOG.md"] ] end defp clean_test_fixtures(_args) do File.rm_rf("test/tmp") end end
24.336449
89
0.56298
08af34eac12565eb75f782037110e47ef6a26b6f
1,290
exs
Elixir
config/config.exs
philihp/welcome2_umbrella
f5f494b98fe4b64a3e1bbfc1b8b432aad7f8c3b2
[ "MIT" ]
null
null
null
config/config.exs
philihp/welcome2_umbrella
f5f494b98fe4b64a3e1bbfc1b8b432aad7f8c3b2
[ "MIT" ]
13
2020-03-22T08:00:57.000Z
2022-03-07T16:35:36.000Z
config/config.exs
philihp/welcome2_umbrella
f5f494b98fe4b64a3e1bbfc1b8b432aad7f8c3b2
[ "MIT" ]
null
null
null
# This file is responsible for configuring your umbrella # and **all applications** and their dependencies with the # help of Mix.Config. # # Note that all applications in your umbrella share the # same configuration and dependencies, which is why they # all use the same configuration file. If you want different # configurations or dependencies per app, it is best to # move said applications out of the umbrella. use Mix.Config # Configure Mix tasks and generators config :welcome2_ecto, ecto_repos: [Welcome2Ecto.Repo] config :welcome2_web, generators: [context_app: :welcome2] # Configures the endpoint config :welcome2_web, Welcome2Web.Endpoint, url: [host: "localhost"], secret_key_base: "hPeIweqI/t0LIsXH6JKMp8w0tbxJ7/ucBc/wSIJGd1BMhNcAg/3QM5FOLE1JYlxC", render_errors: [view: Welcome2Web.ErrorView, accepts: ~w(html json)], pubsub: [name: Welcome2Web.PubSub, adapter: Phoenix.PubSub.PG2] # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # Use Jason for JSON parsing in Phoenix config :phoenix, :json_library, Jason # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{Mix.env()}.exs"
33.076923
86
0.769767
08af35930691f55cc995792824a0427ae589ff05
3,237
exs
Elixir
test/level_web/controllers/postbot_controller_test.exs
mindriot101/level
0a2cbae151869c2d9b79b3bfb388f5d00739ae12
[ "Apache-2.0" ]
928
2018-04-03T16:18:11.000Z
2019-09-09T17:59:55.000Z
test/level_web/controllers/postbot_controller_test.exs
mindriot101/level
0a2cbae151869c2d9b79b3bfb388f5d00739ae12
[ "Apache-2.0" ]
74
2018-04-03T00:46:50.000Z
2019-03-10T18:57:27.000Z
test/level_web/controllers/postbot_controller_test.exs
mindriot101/level
0a2cbae151869c2d9b79b3bfb388f5d00739ae12
[ "Apache-2.0" ]
89
2018-04-03T17:33:20.000Z
2019-08-19T03:40:20.000Z
defmodule LevelWeb.PostbotControllerTest do use LevelWeb.ConnCase, async: true alias Level.Posts describe "POST /postbot/:space_slug/:key" do test "if space does not exist", %{conn: conn} do conn = conn |> post("/postbot/dontexist/xyz", %{"body" => "Hello world"}) assert %{"success" => false, "reason" => "url_not_recognized"} = json_response(conn, 422) end test "if space exists but key is bad", %{conn: conn} do {:ok, _} = create_user_and_space(%{}, %{slug: "myspace"}) conn = conn |> post("/postbot/myspace/xyz", %{"body" => "Hello world"}) assert %{"success" => false, "reason" => "url_not_recognized"} = json_response(conn, 422) end test "if valid returns a success response", %{conn: conn} do {:ok, %{space: space, space_user: space_user, user: user}} = create_user_and_space(%{}, %{slug: "myspace"}) {:ok, %{group: _}} = create_group(space_user, %{name: "peeps"}) conn = conn |> post("/postbot/myspace/#{space.postbot_key}", %{ "body" => "Hello #peeps", "display_name" => "The Bot" }) %{"success" => true, "post_id" => post_id} = json_response(conn, 200) {:ok, post} = Posts.get_post(user, post_id) assert post.body == "Hello #peeps" assert post.display_name == "The Bot" assert post.initials == nil assert post.avatar_color == nil end test "accepts display name and avatar overrides", %{conn: conn} do {:ok, %{space: space, space_user: space_user, user: user}} = create_user_and_space(%{}, %{slug: "myspace"}) {:ok, %{group: _}} = create_group(space_user, %{name: "peeps"}) conn = conn |> post("/postbot/myspace/#{space.postbot_key}", %{ "body" => "Hello #peeps", "display_name" => "Twitter", "initials" => "tw", "avatar_color" => "4265c7" }) %{"success" => true, "post_id" => post_id} = json_response(conn, 200) {:ok, post} = Posts.get_post(user, post_id) assert post.body == "Hello #peeps" assert post.display_name == "Twitter" assert post.initials == "TW" assert post.avatar_color == "4265c7" end test "returns validation errors", %{conn: conn} do {:ok, %{space: space, space_user: space_user}} = create_user_and_space(%{}, %{slug: "myspace"}) {:ok, %{group: _}} = create_group(space_user, %{name: "peeps"}) conn = conn |> post("/postbot/myspace/#{space.postbot_key}", %{ "body" => "Hello #peeps", "display_name" => "Twitter", "initials" => "foo", "avatar_color" => "q4265c7" }) assert %{ "errors" => [ %{ "attribute" => "avatar_color", "message" => "has invalid format" }, %{ "attribute" => "initials", "message" => "should be at most 2 character(s)" } ], "reason" => "validation_errors", "success" => false } = json_response(conn, 422) end end end
31.427184
95
0.526104
08af3bd9ef6e24e44dffa46fcd1922ac10a348a5
569
ex
Elixir
lib/utils/bacen_id.ex
starkinfra/sdk-elixir
d434de336ad7d2331b860519f04e9d107bb9c9cd
[ "MIT" ]
1
2022-03-15T18:58:21.000Z
2022-03-15T18:58:21.000Z
lib/utils/bacen_id.ex
starkinfra/sdk-elixir
d434de336ad7d2331b860519f04e9d107bb9c9cd
[ "MIT" ]
null
null
null
lib/utils/bacen_id.ex
starkinfra/sdk-elixir
d434de336ad7d2331b860519f04e9d107bb9c9cd
[ "MIT" ]
null
null
null
defmodule StarkInfra.Utils.BacenId do def create(bank_code) do [bank_code, datetime_to_string(DateTime.utc_now), random_alphanumeric(11)] |> Enum.join("") end defp datetime_to_string(datetime) do [datetime.year, datetime.month, datetime.day, datetime.hour, datetime.minute] |> Enum.map(&to_string/1) |> Enum.map(&String.pad_leading(&1, 2, "0")) |> Enum.join("") end defp random_alphanumeric(length) do for _ <- 1..length, into: "", do: << Enum.random('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWYZ') >> end end
31.611111
120
0.704745
08af48b816127fb91ab9ea044c9708fe372b636e
842
ex
Elixir
lib/radiator_web/graphql/admin/resolvers/storage.ex
djschilling/radiator
382e22904d7e400a8ffba54e9ddfd2845bc2b623
[ "MIT" ]
null
null
null
lib/radiator_web/graphql/admin/resolvers/storage.ex
djschilling/radiator
382e22904d7e400a8ffba54e9ddfd2845bc2b623
[ "MIT" ]
null
null
null
lib/radiator_web/graphql/admin/resolvers/storage.ex
djschilling/radiator
382e22904d7e400a8ffba54e9ddfd2845bc2b623
[ "MIT" ]
null
null
null
defmodule RadiatorWeb.GraphQL.Admin.Resolvers.Storage do use Radiator.Constants alias Radiator.Storage alias Radiator.Media alias Radiator.Directory.Editor def create_upload(_parent, %{filename: filename}, _resolution) do {:ok, upload_url} = Storage.get_upload_url(filename) {:ok, %{upload_url: upload_url}} end def upload_audio_file(_parent, %{audio_id: id, file: file}, %{ context: %{authenticated_user: user} }) do case Editor.get_audio(user, id) do {:ok, audio} -> case Media.AudioFileUpload.upload(file, audio) do {:ok, audio_file} -> {:ok, audio_file} {:error, reason} -> {:error, "Upload failed: #{reason}"} end @not_found_match -> @not_found_response @not_authorized_match -> @not_authorized_response end end end
27.16129
67
0.654394
08af4c6bbbc38cda45be88d5aac3b96f8db424b4
2,812
ex
Elixir
priv/templates/phx.gen.presence/presence.ex
zorn/phoenix
ac88958550fbd861e2f1e1af6e3c6b787b1a202e
[ "MIT" ]
2
2016-11-01T15:01:48.000Z
2016-11-01T15:07:20.000Z
priv/templates/phx.gen.presence/presence.ex
zorn/phoenix
ac88958550fbd861e2f1e1af6e3c6b787b1a202e
[ "MIT" ]
1
2020-07-17T10:07:44.000Z
2020-07-17T10:07:44.000Z
priv/templates/phx.gen.presence/presence.ex
zorn/phoenix
ac88958550fbd861e2f1e1af6e3c6b787b1a202e
[ "MIT" ]
null
null
null
defmodule <%= module %> do @moduledoc """ Provides presence tracking to channels and processes. See the [`Phoenix.Presence`](http://hexdocs.pm/phoenix/Phoenix.Presence.html) docs for more details. ## Usage Presences can be tracked in your channel after joining: defmodule <%= base %>.MyChannel do use <%= base %>Web, :channel alias <%= base %>Web.Presence def join("some:topic", _params, socket) do send(self(), :after_join) {:ok, assign(socket, :user_id, ...)} end def handle_info(:after_join, socket) do push(socket, "presence_state", Presence.list(socket)) {:ok, _} = Presence.track(socket, socket.assigns.user_id, %{ online_at: inspect(System.system_time(:second)) }) {:noreply, socket} end end In the example above, `Presence.track` is used to register this channel's process as a presence for the socket's user ID, with a map of metadata. Next, the current presence list for the socket's topic is pushed to the client as a `"presence_state"` event. Finally, a diff of presence join and leave events will be sent to the client as they happen in real-time with the "presence_diff" event. See `Phoenix.Presence.list/2` for details on the presence data structure. ## Fetching Presence Information The `fetch/2` callback is triggered when using `list/1` and serves as a mechanism to fetch presence information a single time, before broadcasting the information to all channel subscribers. This prevents N query problems and gives you a single place to group isolated data fetching to extend presence metadata. The function receives a topic and map of presences and must return a map of data matching the Presence data structure: %{"123" => %{metas: [%{status: "away", phx_ref: ...}], "456" => %{metas: [%{status: "online", phx_ref: ...}]} The `:metas` key must be kept, but you can extend the map of information to include any additional information. For example: def fetch(_topic, entries) do users = entries |> Map.keys() |> Accounts.get_users_map(entries) # => %{"123" => %{name: "User 123"}, "456" => %{name: nil}} for {key, %{metas: metas}} <- entries, into: %{} do {key, %{metas: metas, user: users[key]}} end end The function above fetches all users from the database who have registered presences for the given topic. The fetched information is then extended with a `:user` key of the user's information, while maintaining the required `:metas` field from the original presence data. """ use Phoenix.Presence, otp_app: <%= inspect otp_app %>, pubsub_server: <%= inspect binding()[:pubsub_server] %> end
38
79
0.661095
08af547df0cccfc6e2abc9ccefd1554070828cd0
1,650
ex
Elixir
clients/service_user/lib/google_api/service_user/v1/model/experimental.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/service_user/lib/google_api/service_user/v1/model/experimental.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/service_user/lib/google_api/service_user/v1/model/experimental.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.ServiceUser.V1.Model.Experimental do @moduledoc """ Experimental service configuration. These configuration options can only be used by whitelisted users. ## Attributes - authorization (AuthorizationConfig): Authorization configuration. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :authorization => GoogleApi.ServiceUser.V1.Model.AuthorizationConfig.t() } field(:authorization, as: GoogleApi.ServiceUser.V1.Model.AuthorizationConfig) end defimpl Poison.Decoder, for: GoogleApi.ServiceUser.V1.Model.Experimental do def decode(value, options) do GoogleApi.ServiceUser.V1.Model.Experimental.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceUser.V1.Model.Experimental do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.375
104
0.76303
08af696f1282f9d779c73999de6dda3484618f08
2,034
ex
Elixir
lib/pathex/builder/composition/or.ex
devstopfix/pathex
0a7087d31eefb9c0c2988fd5bf6dd0385e68dd80
[ "BSD-2-Clause" ]
51
2020-04-23T11:55:36.000Z
2022-03-28T10:01:39.000Z
lib/pathex/builder/composition/or.ex
devstopfix/pathex
0a7087d31eefb9c0c2988fd5bf6dd0385e68dd80
[ "BSD-2-Clause" ]
4
2021-03-12T14:44:27.000Z
2021-12-29T11:00:02.000Z
lib/pathex/builder/composition/or.ex
devstopfix/pathex
0a7087d31eefb9c0c2988fd5bf6dd0385e68dd80
[ "BSD-2-Clause" ]
3
2020-10-16T18:05:16.000Z
2021-06-03T21:54:26.000Z
defmodule Pathex.Builder.Composition.Or do @moduledoc """ This builder builds composition for `|||` operator """ @behaviour Pathex.Builder.Composition alias Pathex.Builder.Code def build(items) do [ view: build_view(items), update: build_update(items), force_update: build_force_update(items) ] end defp build_view([head | tail]) do structure = {:input_struct, [], Elixir} func = {:func, [], Elixir} first_case = to_view(head, structure, func) [first_case | Enum.map(tail, & to_view(&1, structure, func))] |> to_with() |> Code.new([structure, func]) end defp build_update([head | tail]) do structure = {:input_struct, [], Elixir} func = {:func, [], Elixir} first_case = to_update(head, structure, func) [first_case | Enum.map(tail, & to_update(&1, structure, func))] |> to_with() |> Code.new([structure, func]) end defp build_force_update([head | tail]) do structure = {:input_struct, [], Elixir} func = {:func, [], Elixir} default = {:default, [], Elixir} first_case = to_force_update(head, structure, func, default) [first_case | Enum.map(tail, & to_force_update(&1, structure, func, default))] |> to_with() |> Code.new([structure, func, default]) end # You can find the same code in `Pathex.Builder.Composition.And` # But I don't mind some duplication defp to_with(cases) do quote do with unquote_splicing(cases) do :error end end end defp to_view(item, structure, func) do quote do :error <- unquote(item).(:view, {unquote(structure), unquote(func)}) end end defp to_update(item, structure, func) do quote do :error <- unquote(item).(:update, {unquote(structure), unquote(func)}) end end defp to_force_update(item, structure, func, default) do quote do :error <- unquote(item).(:force_update, {unquote(structure), unquote(func), unquote(default)}) end end end
26.076923
100
0.627335
08af90309e98e4ffd002bb3abbadf6a16a774dc6
1,123
exs
Elixir
config/config.exs
bhelx/bhelky
9d5c225de01fe10836e46a291543535c4db0b34e
[ "MIT" ]
2
2018-11-19T19:04:03.000Z
2020-04-26T17:34:00.000Z
config/config.exs
bhelx/bhelky
9d5c225de01fe10836e46a291543535c4db0b34e
[ "MIT" ]
null
null
null
config/config.exs
bhelx/bhelky
9d5c225de01fe10836e46a291543535c4db0b34e
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :bhelky, key: :value # # and access this configuration in your application as: # # Application.get_env(:bhelky, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env()}.exs"
36.225806
73
0.749777
08af9b78f4f5424d2d11feeb2f8fc33ef8837df8
2,916
ex
Elixir
deps/credo/lib/credo/config.ex
robot-overlord/starter_kit
254153221d0a3a06324c65ad8e89d610de2429c3
[ "MIT" ]
1
2020-01-31T10:23:37.000Z
2020-01-31T10:23:37.000Z
deps/credo/lib/credo/config.ex
robot-overlord/starter_kit
254153221d0a3a06324c65ad8e89d610de2429c3
[ "MIT" ]
null
null
null
deps/credo/lib/credo/config.ex
robot-overlord/starter_kit
254153221d0a3a06324c65ad8e89d610de2429c3
[ "MIT" ]
null
null
null
defmodule Credo.Config do @doc """ Every run of Credo is configured via a `Config` object, which is created and manipulated via the `Credo.Config` module. """ defstruct args: [], files: nil, source_files: [], color: true, checks: nil, requires: [], strict: false, check_for_updates: true, # checks if there is a new version of Credo # options, set by the command line min_priority: 0, help: false, version: false, verbose: false, all: false, format: nil, only_checks: nil, ignore_checks: nil, crash_on_error: true, read_from_stdin: false, # state, which is maintained over the course of Credo's execution skipped_checks: nil, assigns: %{}, lint_attribute_map: %{} # maps filenames to @lint attributes @doc """ Returns the checks that should be run for a given `config` object. Takes all checks from the `checks:` field of the config, matches those against any patterns to include or exclude certain checks given via the command line. """ def checks(%__MODULE__{checks: checks, only_checks: only_checks, ignore_checks: ignore_checks}) do match_regexes = only_checks |> List.wrap |> to_match_regexes ignore_regexes = ignore_checks |> List.wrap |> to_match_regexes checks |> Enum.filter(&match_regex(&1, match_regexes, true)) |> Enum.reject(&match_regex(&1, ignore_regexes, false)) end defp match_regex(_tuple, [], default_for_empty), do: default_for_empty defp match_regex(tuple, regexes, _default_for_empty) do check_name = tuple |> Tuple.to_list |> List.first |> to_string Enum.any?(regexes, &Regex.run(&1, check_name)) end defp to_match_regexes(list) do Enum.map(list, fn(match_check) -> {:ok, match_pattern} = Regex.compile(match_check, "i") match_pattern end) end @doc """ Sets the config values which `strict` implies (if applicable). """ def set_strict(%__MODULE__{strict: true} = config) do %__MODULE__{config | all: true, min_priority: -99} end def set_strict(%__MODULE__{strict: false} = config) do %__MODULE__{config | min_priority: 0} end def set_strict(config), do: config def get_assign(config, name) do Map.get(config.assigns, name) end def put_assign(config, name, value) do %__MODULE__{config | assigns: Map.put(config.assigns, name, value)} end def put_source_files(config, source_files) do %__MODULE__{config | source_files: source_files} end end
30.375
100
0.589849
08af9e19cac4f6d725159fd7f938ede83cffaeff
3,277
ex
Elixir
lib/momento.ex
agix/momento
cd42abe9322f27e65278b65fb35d223baa317423
[ "MIT" ]
37
2016-07-01T22:35:41.000Z
2020-10-02T23:41:45.000Z
lib/momento.ex
agix/momento
cd42abe9322f27e65278b65fb35d223baa317423
[ "MIT" ]
5
2016-07-02T14:15:57.000Z
2016-07-24T09:46:22.000Z
lib/momento.ex
agix/momento
cd42abe9322f27e65278b65fb35d223baa317423
[ "MIT" ]
5
2016-07-02T03:46:52.000Z
2019-04-23T14:15:54.000Z
defmodule Momento do require Momento.Guards @moduledoc """ Momento is an Elixir port of [Moment.js](https://github.com/moment/moment) for the purpose of parsing, validating, manipulating, and formatting dates. """ @doc """ Provides a DateTime struct representing the current date and time. ## Examples iex> Momento.date {:ok, %DateTime{calendar: Calendar.ISO, day: 1, hour: 21, microsecond: {827272, 6}, minute: 27, month: 7, second: 19, std_offset: 0, time_zone: "Etc/UTC", utc_offset: 0, year: 2016, zone_abbr: "UTC"}} """ @spec date :: {:ok, DateTime.t} def date, do: Momento.Date.date @doc """ Provides a DateTime struct from any recognizeable form of input, such as an ISO string or UNIX timestamp. ## Examples Momento.date {:ok, %DateTime{calendar: Calendar.ISO, day: 1, hour: 21, microsecond: {827272, 6}, minute: 27, month: 7, second: 19, std_offset: 0, time_zone: "Etc/UTC", utc_offset: 0, year: 2016, zone_abbr: "UTC"}} """ @spec date(any) :: {:ok, DateTime.t} def date(arg), do: Momento.Date.date(arg) @doc """ Shortcut to get a `DateTime` struct representing now. ## Examples iex> Momento.date! %DateTime{calendar: Calendar.ISO, day: 1, hour: 21, microsecond: {0, 0}, minute: 32, month: 7, second: 15, std_offset: 0, time_zone: "Etc/UTC", utc_offset: 0, year: 2016, zone_abbr: "UTC"} """ @spec date! :: DateTime.t def date!, do: Momento.Date.date! @doc """ Provides a DateTime struct from any recognizeable form of input, such as an ISO string or UNIX timestamp. ## Examples iex> Momento.date!(1467408735) %DateTime{calendar: Calendar.ISO, day: 1, hour: 21, microsecond: {0, 0}, minute: 32, month: 7, second: 15, std_offset: 0, time_zone: "Etc/UTC", utc_offset: 0, year: 2016, zone_abbr: "UTC"} """ @spec date!(any) :: DateTime.t def date!(arg), do: Momento.Date.date!(arg) @doc """ Add a specified amount of time to a given DateTime struct. ## Examples iex> Momento.date! |> Momento.add(2, :years) %DateTime{calendar: Calendar.ISO, day: 1, hour: 21, microsecond: {796482, 6}, minute: 38, month: 7, second: 18, std_offset: 0, time_zone: "Etc/UTC", utc_offset: 0, year: 2018, zone_abbr: "UTC"} """ @spec add(DateTime.t, integer, atom) :: DateTime.t def add(datetime, num, time), do: Momento.Add.add(datetime, num, time) @doc """ Subtract a specified amount of time to a given DateTime struct. ## Examples iex> Momento.date! |> Momento.subtract(2, :years) %DateTime{calendar: Calendar.ISO, day: 1, hour: 21, microsecond: {19292, 6}, minute: 39, month: 7, second: 11, std_offset: 0, time_zone: "Etc/UTC", utc_offset: 0, year: 2014, zone_abbr: "UTC"} """ @spec subtract(DateTime.t, integer, atom) :: DateTime.t def subtract(datetime, num, time), do: Momento.Subtract.subtract(datetime, num, time) @doc """ Format a given DateTime struct to a desired date string. ## Examples iex> Momento.date! |> Momento.format("YYYY-MM-DD") "2016-07-01" """ @spec format(DateTime.t, String.t) :: DateTime.t def format(datetime, tokens), do: Momento.Format.format(datetime, tokens) end
33.783505
116
0.641745
08afa04bdaea3be5ba8fe825817e932901b1ea53
96
exs
Elixir
chapter7/ListAndRecursion-0.exs
matheustp/programming-elixir-1.3-exercises
f32ad2f6c53da11a24e602fc63299f65a3c48dfc
[ "MIT" ]
null
null
null
chapter7/ListAndRecursion-0.exs
matheustp/programming-elixir-1.3-exercises
f32ad2f6c53da11a24e602fc63299f65a3c48dfc
[ "MIT" ]
null
null
null
chapter7/ListAndRecursion-0.exs
matheustp/programming-elixir-1.3-exercises
f32ad2f6c53da11a24e602fc63299f65a3c48dfc
[ "MIT" ]
null
null
null
defmodule MyList do def sum([]), do: 0 def sum([ head | tail ]), do: head + sum(tail) end
24
49
0.583333
08afd0ab11ab4fbe010ee927df597541e7ca465e
1,960
exs
Elixir
test/views/worker_definition_view_test.exs
nipierre/ex_step_flow
4345ee57bd4e5eb79138df68d10579ba1b9ec6a1
[ "MIT" ]
null
null
null
test/views/worker_definition_view_test.exs
nipierre/ex_step_flow
4345ee57bd4e5eb79138df68d10579ba1b9ec6a1
[ "MIT" ]
null
null
null
test/views/worker_definition_view_test.exs
nipierre/ex_step_flow
4345ee57bd4e5eb79138df68d10579ba1b9ec6a1
[ "MIT" ]
null
null
null
defmodule StepFlow.WorkerDefinitionViewTest do use ExUnit.Case use Plug.Test alias Ecto.Adapters.SQL.Sandbox # Bring render/3 and render_to_string/3 for testing custom views import Phoenix.View setup do # Explicitly get a connection before each test Sandbox.checkout(StepFlow.Repo) end @worker_definition %{ queue_name: "my_queue", label: "My Worker", version: "1.2.3", short_description: "short description", description: "long description" } test "render a Worker Definition" do {:ok, worker_definition} = StepFlow.WorkerDefinitions.create_worker_definition(@worker_definition) assert render(StepFlow.WorkerDefinitionView, "show.json", %{ worker_definition: worker_definition }) == %{ data: %{ id: worker_definition.id, created_at: worker_definition.inserted_at, description: "long description", label: "My Worker", parameters: %{}, queue_name: "my_queue", short_description: "short description", version: "1.2.3" } } end test "render many Worker Definitions" do {:ok, worker_definition} = StepFlow.WorkerDefinitions.create_worker_definition(@worker_definition) assert render(StepFlow.WorkerDefinitionView, "index.json", %{ worker_definitions: %{data: [worker_definition], total: 1} }) == %{ data: [ %{ id: worker_definition.id, created_at: worker_definition.inserted_at, description: "long description", label: "My Worker", parameters: %{}, queue_name: "my_queue", short_description: "short description", version: "1.2.3" } ], total: 1 } end end
29.69697
77
0.57398
08aff557e20374e12ba4d65bc08ee08d5e4844b8
5,843
ex
Elixir
lib/plug/conn/utils.ex
fishcakez/plug
9fafa1527536b0b1895cad9fb464bc62e6e80123
[ "Apache-2.0" ]
null
null
null
lib/plug/conn/utils.ex
fishcakez/plug
9fafa1527536b0b1895cad9fb464bc62e6e80123
[ "Apache-2.0" ]
null
null
null
lib/plug/conn/utils.ex
fishcakez/plug
9fafa1527536b0b1895cad9fb464bc62e6e80123
[ "Apache-2.0" ]
null
null
null
defmodule Plug.Conn.Utils do @moduledoc """ Utilities for working with connection data """ @type params :: [{binary, binary}] @upper ?A..?Z @lower ?a..?z @alpha ?0..?9 @other [?., ?-, ?+] @space [?\s, ?\t] @specials [?(, ?), ?<, ?>, ?@, ?,, ?;, ?:, ?\\, ?", ?/, ?[, ?], ??, ?., ?=] @doc ~S""" Parses the request content type header. Type and subtype are case insensitive while the sensitiveness of params depends on its key and therefore are not handled by this parser. ## Examples iex> content_type "text/plain" {:ok, "text", "plain", %{}} iex> content_type "APPLICATION/vnd.ms-data+XML" {:ok, "application", "vnd.ms-data+xml", %{}} iex> content_type "x-sample/json; charset=utf-8" {:ok, "x-sample", "json", %{"charset" => "utf-8"}} iex> content_type "x-sample/json ; charset=utf-8 ; foo=bar" {:ok, "x-sample", "json", %{"charset" => "utf-8", "foo" => "bar"}} iex> content_type "\r\n text/plain;\r\n charset=utf-8\r\n" {:ok, "text", "plain", %{"charset" => "utf-8"}} iex> content_type "x y" :error iex> content_type "/" :error iex> content_type "x/y z" :error """ @spec content_type(binary) :: {:ok, type :: binary, subtype :: binary, params} | :error def content_type(binary) do ct_first(strip_spaces(binary), "") end defp ct_first(<< ?/, t :: binary >>, acc) when acc != "", do: ct_second(t, "", acc) defp ct_first(<< h, t :: binary >>, acc) when h in @upper, do: ct_first(t, << acc :: binary, h + 32 >>) defp ct_first(<< h, t :: binary >>, acc) when h in @lower or h in @alpha or h == ?-, do: ct_first(t, << acc :: binary, h >>) defp ct_first(_, _acc), do: :error defp ct_second(<< h, t :: binary >>, acc, first) when h in @upper, do: ct_second(t, << acc :: binary, h + 32 >>, first) defp ct_second(<< h, t :: binary >>, acc, first) when h in @lower or h in @alpha or h in @other, do: ct_second(t, << acc :: binary, h >>, first) defp ct_second(t, acc, first), do: ct_params(t, first, acc) defp ct_params(t, first, second) do case strip_spaces(t) do "" -> {:ok, first, second, %{}} ";" <> t -> {:ok, first, second, params(t)} _ -> :error end end @doc """ Parses headers parameters. Keys are case insensitive and downcased, invalid key-value pairs are discarded. ## Examples iex> params("foo=bar") %{"foo" => "bar"} iex> params(" foo=bar ") %{"foo" => "bar"} iex> params("FOO=bar") %{"foo" => "bar"} iex> params("foo=BAR ; wat") %{"foo" => "BAR"} iex> params("=") %{} """ @spec params(binary) :: params def params(t) do params(:binary.split(t, ";", [:global]), %{}) end defp params([], acc), do: acc defp params([h|t], acc) do case params_key(strip_spaces(h), "") do {k, v} -> params(t, Map.put(acc, k, v)) false -> params(t, acc) end end defp params_key(<< ?=, t :: binary >>, acc) when acc != "", do: params_value(t, acc) defp params_key(<< h, _ :: binary >>, _acc) when h in @specials or h in @space or h < 32 or h === 127, do: false defp params_key(<< h, t :: binary >>, acc) when h in @upper, do: params_key(t, << acc :: binary, h + 32 >>) defp params_key(<< h, t :: binary >>, acc), do: params_key(t, << acc :: binary, h >>) defp params_key(<<>>, _acc), do: false defp params_value(token, key) do case token(token) do false -> false value -> {key, value} end end @doc ~S""" Parses a value as defined in [RFC-1341](1). For convenience, trims whitespace at the end of the token. Returns false is the token is invalid. [1]: http://www.w3.org/Protocols/rfc1341/4_Content-Type.html ## Examples iex> token("foo") "foo" iex> token("foo-bar") "foo-bar" iex> token("<foo>") false iex> token(~s["<foo>"]) "<foo>" iex> token(~S["<f\oo>\"<b\ar>"]) "<foo>\"<bar>" iex> token("foo ") "foo" iex> token("foo bar") false """ @spec token(binary) :: binary | false def token(""), do: false def token(<< ?", quoted :: binary >>), do: quoted_token(quoted, "") def token(token), do: unquoted_token(token, "") defp quoted_token(<<>>, _acc), do: false defp quoted_token(<< ?", t :: binary >>, acc), do: strip_spaces(t) == "" and acc defp quoted_token(<< ?\\, h, t :: binary >>, acc), do: quoted_token(t, << acc :: binary, h >>) defp quoted_token(<< h, t :: binary >>, acc), do: quoted_token(t, << acc :: binary, h >>) defp unquoted_token("\r\n" <> t, acc), do: strip_spaces(t) == "" and acc defp unquoted_token(<< h, t :: binary >>, acc) when h in @space, do: strip_spaces(t) == "" and acc defp unquoted_token(<< h, _ :: binary >>, _acc) when h in @specials or h < 32 or h === 127, do: false defp unquoted_token(<< h, t :: binary >>, acc), do: unquoted_token(t, << acc :: binary, h >>) defp unquoted_token(<< >>, acc), do: acc @doc """ Parses a comma-separated header list. ## Examples iex> list("foo, bar") ["foo", "bar"] iex> list("foobar") ["foobar"] iex> list("") [] iex> list("empties, , are,, filtered") ["empties", "are", "filtered"] """ @spec list(binary) :: [binary] def list(binary) do elems = :binary.split(binary, ",", [:global]) Enum.reduce(elems, [], fn elem, acc -> elem = strip_spaces(elem) if elem != "", do: [elem|acc], else: acc end) |> Enum.reverse end defp strip_spaces("\r\n" <> t), do: strip_spaces(t) defp strip_spaces(<<h, t :: binary>>) when h in [?\s, ?\t], do: strip_spaces(t) defp strip_spaces(t), do: t end
25.853982
104
0.538422
08b00596ec721e3f88cdeef6bd468f30da9defb6
1,119
exs
Elixir
config/config.exs
camcaine/north
d1193d3cdab219a2b91136cf2c4938f30d0a9c86
[ "MIT" ]
null
null
null
config/config.exs
camcaine/north
d1193d3cdab219a2b91136cf2c4938f30d0a9c86
[ "MIT" ]
null
null
null
config/config.exs
camcaine/north
d1193d3cdab219a2b91136cf2c4938f30d0a9c86
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :north, key: :value # # and access this configuration in your application as: # # Application.get_env(:north, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
36.096774
73
0.75067
08b00a89aafc6530cf6e04d5a58050e5b1b68c5a
1,734
exs
Elixir
exercises/connect/example.exs
jerith/elixir
9a3f2a2fbee26a7b6a6b3ad74a9e6d1ff2495ed4
[ "Apache-2.0" ]
343
2017-06-22T16:28:28.000Z
2022-03-25T21:33:32.000Z
exercises/connect/example.exs
jerith/elixir
9a3f2a2fbee26a7b6a6b3ad74a9e6d1ff2495ed4
[ "Apache-2.0" ]
583
2017-06-19T10:48:40.000Z
2022-03-28T21:43:12.000Z
exercises/connect/example.exs
jerith/elixir
9a3f2a2fbee26a7b6a6b3ad74a9e6d1ff2495ed4
[ "Apache-2.0" ]
228
2017-07-05T07:09:32.000Z
2022-03-27T08:59:08.000Z
defmodule Connect do @doc """ Calculates the winner (if any) of a board using "O" as the white player and "X" as the black player """ @spec result_for([String.t()]) :: :none | :black | :white def result_for(board) do cond do black_wins?(board) -> :black white_wins?(board) -> :white true -> :none end end defp black_wins?(board) do board |> Enum.with_index() |> Enum.any?(fn {row, index} -> String.first(row) == "X" && black_wins?(board, [{index, 0}]) end) end defp black_wins?(board, [{_, y} | _]) when y + 1 == byte_size(hd(board)), do: true defp black_wins?(board, history = [last_loc | _]) do last_loc |> locs_next_to(history) |> Enum.filter(&(get_loc(board, &1) == "X")) |> Enum.any?(&black_wins?(board, [&1 | history])) end defp white_wins?(board) do board |> hd |> String.graphemes() |> Enum.with_index() |> Enum.any?(fn {spot, index} -> spot == "O" && white_wins?(board, [{0, index}]) end) end defp white_wins?(board, [{x, _} | _]) when x + 1 == length(board), do: true defp white_wins?(board, history = [last_loc | _]) do last_loc |> locs_next_to(history) |> Enum.filter(&(get_loc(board, &1) == "O")) |> Enum.any?(&white_wins?(board, [&1 | history])) end defp locs_next_to({x, y}, history) do [ {x, y - 1}, {x, y + 1}, {x + 1, y}, {x - 1, y}, {x + 1, y - 1}, {x - 1, y + 1} ] |> Enum.filter(&valid_next_loc(&1, history)) end defp valid_next_loc({x, y}, history) do x >= 0 && y >= 0 && !({x, y} in history) end defp get_loc(board, {x, y}) do row = Enum.at(board, x) row && String.at(row, y) end end
23.753425
84
0.540946
08b010f2db4b6b809671cbc378ed35cdaa1ee7d0
8,042
ex
Elixir
lib/conversations_client.ex
jmnsf/ex_microsoftbot
c1c2185f1414b1cbb03999b2195745e35936c2d9
[ "MIT" ]
35
2016-05-11T02:34:27.000Z
2021-04-29T07:34:11.000Z
lib/conversations_client.ex
jmnsf/ex_microsoftbot
c1c2185f1414b1cbb03999b2195745e35936c2d9
[ "MIT" ]
27
2016-07-10T18:32:25.000Z
2021-09-29T07:00:22.000Z
lib/conversations_client.ex
jmnsf/ex_microsoftbot
c1c2185f1414b1cbb03999b2195745e35936c2d9
[ "MIT" ]
23
2016-05-10T18:53:13.000Z
2021-06-25T22:04:21.000Z
defmodule ExMicrosoftBot.Client.Conversations do @moduledoc """ This module provides the functions for conversations """ import ExMicrosoftBot.Client, only: [deserialize_response: 2, delete: 1, get: 1, post: 2, put: 2] alias ExMicrosoftBot.Models alias ExMicrosoftBot.Client @doc """ Create a new Conversation. @see [API Reference](https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-connector-api-reference?view=azure-bot-service-4.0#conversation-object) """ @spec create_conversation( service_url :: String.t(), params :: Models.ConversationParameters.t() ) :: {:ok, Models.ConversationResourceResponse.t()} | Client.error_type() def create_conversation(service_url, %Models.ConversationParameters{} = params) do service_url |> conversations_url() |> post(params) |> deserialize_response(&Models.ConversationResourceResponse.parse/1) end @doc """ This method allows you to send an activity to a conversation regardless of previous posts to a conversation. @see [API Reference](https://docs.botframework.com/en-us/restapi/connector/#!/Conversations/Conversations_SendToConversation) """ @spec send_to_conversation(conversation_id :: String.t(), activity :: Models.Activity.t()) :: {:ok, Models.ResourceResponse.t()} | Client.error_type() def send_to_conversation(conversation_id, %Models.Activity{serviceUrl: service_url} = activity), do: send_to_conversation(service_url, conversation_id, activity) @doc """ This method allows you to send an activity to a conversation regardless of previous posts to a conversation. @see [API Reference](https://docs.botframework.com/en-us/restapi/connector/#!/Conversations/Conversations_SendToConversation) """ @spec send_to_conversation( service_url :: String.t(), conversation_id :: String.t(), activity :: Models.Activity.t() ) :: {:ok, Models.ResourceResponse.t()} | Client.error_type() def send_to_conversation(service_url, conversation_id, %Models.Activity{} = activity) do service_url |> conversations_url("/#{conversation_id}/activities") |> post(activity) |> deserialize_response(&Models.ResourceResponse.parse/1) end @doc """ This method allows you to reply to an activity. @see [API Reference](https://docs.botframework.com/en-us/restapi/connector/#!/Conversations/Conversations_ReplyToActivity) """ @spec reply_to_activity( conversation_id :: String.t(), activity_id :: String.t(), activity :: Models.Activity.t() ) :: {:ok, Models.ResourceResponse.t()} | Client.error_type() def reply_to_activity( conversation_id, activity_id, %Models.Activity{serviceUrl: service_url} = activity ), do: reply_to_activity(service_url, conversation_id, activity_id, activity) @doc """ This method allows you to reply to an activity. @see [API Reference](https://docs.botframework.com/en-us/restapi/connector/#!/Conversations/Conversations_ReplyToActivity) """ @spec reply_to_activity( service_url :: String.t(), conversation_id :: String.t(), activity_id :: String.t(), activity :: Models.Activity.t() ) :: {:ok, Models.ResourceResponse.t()} | Client.error_type() def reply_to_activity(service_url, conversation_id, activity_id, %Models.Activity{} = activity) do service_url |> conversations_url("/#{conversation_id}/activities/#{activity_id}") |> post(activity) |> deserialize_response(&Models.ResourceResponse.parse/1) end @doc """ This function takes a ConversationId and returns an array of ChannelAccount[] objects which are the members of the conversation. @see [API Reference](https://docs.botframework.com/en-us/restapi/connector/#!/Conversations/Conversations_GetConversationMembers). When ActivityId is passed in then it returns the members of the particular activity in the conversation. @see [API Reference](https://docs.botframework.com/en-us/restapi/connector/#!/Conversations/Conversations_GetActivityMembers) """ @spec get_members( service_url :: String.t(), conversation_id :: String.t(), activity_id :: String.t() | nil ) :: {:ok, [Models.ChannelAccount.t()]} | Client.error_type() def get_members(service_url, conversation_id, activity_id \\ nil) do path = if activity_id, do: "/#{conversation_id}/activities/#{activity_id}/members", else: "/#{conversation_id}/members" service_url |> conversations_url(path) |> get() |> deserialize_response(&Models.ChannelAccount.parse/1) end @doc """ This function takes a conversation ID and a member ID and returns a ChannelAccount struct for that member of the conversation. @see [API Reference](https://github.com/microsoft/botbuilder-js/blob/5b164105a2f289baaa7b89829e09ddbeda88bfc5/libraries/botframework-connector/src/connectorApi/operations/conversations.ts#L733-L749). """ @spec get_member( service_url :: String.t(), conversation_id :: String.t(), member_id :: String.t() ) :: {:ok, Models.ChannelAccount.t()} | Client.error_type() def get_member(service_url, conversation_id, member_id) do service_url |> conversations_url("/#{conversation_id}/members/#{member_id}") |> get() |> deserialize_response(&Models.ChannelAccount.parse/1) end @doc """ This method allows you to upload an attachment directly into a channels blob storage. @see [API Reference](https://docs.botframework.com/en-us/restapi/connector/#!/Conversations/Conversations_UploadAttachment) """ @spec upload_attachment( service_url :: String.t(), conversation_id :: String.t(), attachment :: Models.AttachmentData.t() ) :: {:ok, Models.ResourceResponse.t()} | Client.error_type() def upload_attachment(service_url, conversation_id, %Models.AttachmentData{} = attachment) do service_url |> conversations_url("/#{conversation_id}/attachments") |> post(attachment) |> deserialize_response(&Models.ResourceResponse.parse/1) end @doc """ Updates an existing activity. The activity struct is expected to have an ID. @see [API Reference](https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-connector-api-reference?view=azure-bot-service-4.0#update-activity) """ @spec update_activity( service_url :: String.t(), conversation_id :: String.t(), activity :: Models.Activity.t() ) :: {:ok, Models.ResourceResponse.t()} | Client.error_type() def update_activity(service_url, conversation_id, %Models.Activity{id: activity_id} = activity) do service_url |> conversations_url("/#{conversation_id}/activities/#{activity_id}") |> put(activity) |> deserialize_response(&Models.ResourceResponse.parse/1) end @doc """ Deletes an existing activity. The returned content will always be empty. @see [API Reference](https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/update-and-delete-bot-messages?tabs=rest#deleting-messages) """ @spec delete_activity( service_url :: String.t(), conversation_id :: String.t(), activity_or_id :: Models.Activity.t() | String.t() ) :: {:ok, binary()} | Client.error_type() def delete_activity(service_url, conversation_id, %Models.Activity{id: activity_id}), do: delete_activity(service_url, conversation_id, activity_id) def delete_activity(service_url, conversation_id, activity_id) do service_url |> conversations_url("/#{conversation_id}/activities/#{activity_id}") |> delete() |> deserialize_response(nil) end defp conversations_url(service_url) do service_url = String.trim_trailing(service_url, "/") "#{service_url}/v3/conversations" end defp conversations_url(service_url, path), do: conversations_url(service_url) <> path end
41.030612
201
0.702313
08b0259f7f8c1f7145791411ecfa04fecfb1c9ed
1,449
exs
Elixir
test/bitcoin/script/number_test.exs
coinscript/bitcoinsv-elixir
2dda03c81edc5662743ed2922abb5b1910d9c09a
[ "Apache-2.0" ]
2
2019-08-12T04:53:57.000Z
2019-09-03T03:47:33.000Z
test/bitcoin/script/number_test.exs
coinscript/bitcoinsv-elixir
2dda03c81edc5662743ed2922abb5b1910d9c09a
[ "Apache-2.0" ]
null
null
null
test/bitcoin/script/number_test.exs
coinscript/bitcoinsv-elixir
2dda03c81edc5662743ed2922abb5b1910d9c09a
[ "Apache-2.0" ]
null
null
null
defmodule Bitcoin.Script.NumberTest do use ExUnit.Case alias Bitcoin.Script.Number @cases [ {<<>>, 0}, # check if we do minimal encoding # https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#numbers {<<0xFF>>, -127}, {<<0x82>>, -2}, {<<0x11>>, 17}, {<<0x7F>>, 127}, {<<0xFF, 0xFF>>, -32767}, {<<0x80, 0x80>>, -128}, {<<0x80, 0x00>>, 128}, {<<0xFF, 0x7F>>, 32767}, {<<0xFF, 0xFF, 0xFF>>, -8_388_607}, {<<0x00, 0x80, 0x80>>, -32768}, {<<0x00, 0x80, 0x00>>, 32768}, {<<0xFF, 0xFF, 0x7F>>, 8_388_607}, {<<0xFF, 0xFF, 0xFF, 0xFF>>, -2_147_483_647}, # no 8 {<<0x00, 0x00, 0x80, 0x80>>, -8_388_608}, {<<0x00, 0x00, 0x80, 0x00>>, 8_388_608}, {<<0xFF, 0xFF, 0xFF, 0x7F>>, 2_147_483_647} ] @cases |> Enum.each(fn {bin, num} -> @bin bin @num num test "decoding #{bin |> inspect}" do assert Number.num(@bin) == @num end test "encoding #{num |> inspect}" do assert Number.bin(@num) == @bin end end) # regtest, this failed with prev implementation test "encoding 4294967294" do assert Number.bin(4_294_967_294) == <<254, 255, 255, 255, 0>> end test "invalid ints" do # can be serialized, can't be interpreted as ints [4_294_967_294, -2_147_483_648] |> Enum.each(fn int -> assert_raise FunctionClauseError, fn -> int |> Number.bin() |> Number.num() end end) end end
24.982759
76
0.565908
08b03adfa5c2a59a03d8b7023c98b5ce78b02a90
245
ex
Elixir
lib/sibt.ex
amacgregor/sibt
9819a9de4735612ee59de00f71ca1a6dfa275860
[ "MIT" ]
null
null
null
lib/sibt.ex
amacgregor/sibt
9819a9de4735612ee59de00f71ca1a6dfa275860
[ "MIT" ]
2
2020-07-18T02:22:22.000Z
2021-03-09T15:46:44.000Z
lib/sibt.ex
amacgregor/shouldibuildthat
572b0ba95f93f6ea0dc7b250baaa1bc90efd521b
[ "MIT" ]
null
null
null
defmodule Sibt do @moduledoc """ Sibt keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ end
24.5
66
0.746939
08b0470fbf2174ab872f1963f8eda3e4a46d92f0
13
ex
Elixir
testData/org/elixir_lang/parser_definition/no_parentheses_no_arguments_call_parsing_test_case/CharTokenDotIdentifier.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
1,668
2015-01-03T05:54:27.000Z
2022-03-25T08:01:20.000Z
testData/org/elixir_lang/parser_definition/no_parentheses_no_arguments_call_parsing_test_case/CharTokenDotIdentifier.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
2,018
2015-01-01T22:43:39.000Z
2022-03-31T20:13:08.000Z
testData/org/elixir_lang/parser_definition/no_parentheses_no_arguments_call_parsing_test_case/CharTokenDotIdentifier.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
?a.identifier
13
13
0.846154
08b05d70d105af5f7edd198cae1f2d5a2a8ed38f
11,040
exs
Elixir
lib/elixir/test/elixir/kernel/docs_test.exs
felipelincoln/elixir
6724c1d1819f2926dac561980b4beab281bbd3c2
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/kernel/docs_test.exs
felipelincoln/elixir
6724c1d1819f2926dac561980b4beab281bbd3c2
[ "Apache-2.0" ]
1
2021-07-01T17:58:37.000Z
2021-07-01T19:05:37.000Z
lib/elixir/test/elixir/kernel/docs_test.exs
felipelincoln/elixir
6724c1d1819f2926dac561980b4beab281bbd3c2
[ "Apache-2.0" ]
null
null
null
Code.require_file("../test_helper.exs", __DIR__) defmodule Kernel.DocsTest do use ExUnit.Case import PathHelpers defmacro wrong_doc_baz do quote do @doc "Wrong doc" @doc since: "1.2" def baz(_arg) def baz(arg), do: arg + 1 end end test "attributes format" do defmodule DocAttributes do @moduledoc "Module doc" assert @moduledoc == "Module doc" assert Module.get_attribute(__MODULE__, :moduledoc) == {__ENV__.line - 2, "Module doc"} @typedoc "Type doc" assert @typedoc == "Type doc" assert Module.get_attribute(__MODULE__, :typedoc) == {__ENV__.line - 2, "Type doc"} @type foobar :: any @doc "Function doc" assert @doc == "Function doc" assert Module.get_attribute(__MODULE__, :doc) == {__ENV__.line - 2, "Function doc"} def foobar() do :ok end end end test "compiled without docs" do Code.compiler_options(docs: false) write_beam( defmodule WithoutDocs do @moduledoc "Module doc" @doc "Some doc" def foobar(arg), do: arg end ) assert Code.fetch_docs(WithoutDocs) == {:error, :chunk_not_found} after Code.compiler_options(docs: true) end test "compiled in memory does not have accessible docs" do defmodule InMemoryDocs do @moduledoc "Module doc" @doc "Some doc" def foobar(arg), do: arg end assert Code.fetch_docs(InMemoryDocs) == {:error, :module_not_found} end test "non-existent beam file" do assert {:error, :module_not_found} = Code.fetch_docs("bad.beam") end test "raises on invalid @doc since: ..." do assert_raise ArgumentError, ~r"should be a string representing the version", fn -> defmodule InvalidSince do @doc since: 1.2 def foo, do: :bar end end end test "raises on invalid @doc" do assert_raise ArgumentError, ~r/When set dynamically, it should be {line, doc}/, fn -> defmodule DocAttributesFormat do Module.put_attribute(__MODULE__, :moduledoc, "Other") end end message = ~r/should be either false, nil, a string, or a keyword list/ assert_raise ArgumentError, message, fn -> defmodule AtSyntaxDocAttributesFormat do @moduledoc :not_a_binary end end assert_raise ArgumentError, message, fn -> defmodule AtSyntaxDocAttributesFormat do @moduledoc true end end end describe "compiled with docs" do test "infers signatures" do write_beam( defmodule SignatureDocs do def arg_names([], [], %{}, [], %{}), do: false @year 2015 def with_defaults(@year, arg \\ 0, year \\ @year, fun \\ &>=/2) do {fun, arg + year} end def with_map_and_default(%{key: value} \\ %{key: :default}), do: value def with_struct(%URI{}), do: :ok def with_underscore({_, _} = _two_tuple), do: :ok def with_underscore(_), do: :error def only_underscore(_), do: :ok def two_good_names(first, :ok), do: first def two_good_names(second, :error), do: second end ) assert {:docs_v1, _, :elixir, _, _, _, docs} = Code.fetch_docs(SignatureDocs) signatures = for {{:function, n, a}, _, signature, _, %{}} <- docs, do: {{n, a}, signature} assert [ arg_names, only_underscore, two_good_names, with_defaults, with_map_and_default, with_struct, with_underscore ] = Enum.sort(signatures) # arg_names/5 assert {{:arg_names, 5}, ["arg_names(list1, list2, map1, list3, map2)"]} = arg_names # only_underscore/1 assert {{:only_underscore, 1}, ["only_underscore(_)"]} = only_underscore # two_good_names/2 assert {{:two_good_names, 2}, ["two_good_names(first, atom)"]} = two_good_names # with_defaults/4 assert {{:with_defaults, 4}, ["with_defaults(int, arg \\\\ 0, year \\\\ 2015, fun \\\\ &>=/2)"]} = with_defaults # with_map_and_default/1 assert {{:with_map_and_default, 1}, ["with_map_and_default(map \\\\ %{key: :default})"]} = with_map_and_default # with_struct/1 assert {{:with_struct, 1}, ["with_struct(uri)"]} = with_struct # with_underscore/1 assert {{:with_underscore, 1}, ["with_underscore(two_tuple)"]} = with_underscore end test "includes docs for functions, modules, types and callbacks" do write_beam( defmodule SampleDocs do @moduledoc "Module doc" @moduledoc authors: "Elixir Contributors", purpose: :test @doc "My struct" defstruct [:sample] @typedoc "Type doc" @typedoc since: "1.2.3", color: :red @type foo(any) :: any @typedoc "Opaque type doc" @opaque bar(any) :: any @doc "Callback doc" @doc since: "1.2.3", color: :red, deprecated: "use baz/2 instead" @doc color: :blue, stable: true @callback foo(any) :: any @doc false @doc since: "1.2.3" @callback bar() :: term @callback baz(any, term) :: any @doc "Callback with multiple clauses" @callback callback_multi(integer) :: integer @callback callback_multi(atom) :: atom @doc "Macrocallback doc" @macrocallback qux(any) :: any @doc "Macrocallback with multiple clauses" @macrocallback macrocallback_multi(integer) :: integer @macrocallback macrocallback_multi(atom) :: atom @doc "Function doc" @doc since: "1.2.3", color: :red @doc color: :blue, stable: true @deprecated "use baz/2 instead" def foo(arg \\ 0), do: arg + 1 @doc "Multiple function head doc" @deprecated "something else" def bar(_arg) def bar(arg), do: arg + 1 require Kernel.DocsTest Kernel.DocsTest.wrong_doc_baz() @doc "Multiple function head and docs" @doc since: "1.2.3" def baz(_arg) @doc false def qux(true), do: false @doc "A guard" defguard is_zero(v) when v == 0 # We do this to avoid the deprecation warning. module = Module module.add_doc(__MODULE__, __ENV__.line, :def, {:nullary, 0}, [], "add_doc") def nullary, do: 0 end ) assert {:docs_v1, _, :elixir, "text/markdown", %{"en" => module_doc}, module_doc_meta, docs} = Code.fetch_docs(SampleDocs) assert module_doc == "Module doc" assert %{authors: "Elixir Contributors", purpose: :test} = module_doc_meta [ callback_bar, callback_baz, callback_multi, callback_foo, function_struct_0, function_struct_1, function_bar, function_baz, function_foo, function_nullary, function_qux, guard_is_zero, macrocallback_multi, macrocallback_qux, type_bar, type_foo ] = Enum.sort(docs) assert {{:callback, :bar, 0}, _, [], :hidden, %{}} = callback_bar assert {{:callback, :baz, 2}, _, [], %{}, %{}} = callback_baz assert {{:callback, :foo, 1}, _, [], %{"en" => "Callback doc"}, %{since: "1.2.3", deprecated: "use baz/2 instead", color: :blue, stable: true}} = callback_foo assert {{:callback, :callback_multi, 1}, _, [], %{"en" => "Callback with multiple clauses"}, %{}} = callback_multi assert {{:function, :__struct__, 0}, _, ["%Kernel.DocsTest.SampleDocs{}"], %{"en" => "My struct"}, %{}} = function_struct_0 assert {{:function, :__struct__, 1}, _, ["__struct__(kv)"], :none, %{}} = function_struct_1 assert {{:function, :bar, 1}, _, ["bar(arg)"], %{"en" => "Multiple function head doc"}, %{deprecated: "something else"}} = function_bar assert {{:function, :baz, 1}, _, ["baz(arg)"], %{"en" => "Multiple function head and docs"}, %{since: "1.2.3"}} = function_baz assert {{:function, :foo, 1}, _, ["foo(arg \\\\ 0)"], %{"en" => "Function doc"}, %{ since: "1.2.3", deprecated: "use baz/2 instead", color: :blue, stable: true, defaults: 1 }} = function_foo assert {{:function, :nullary, 0}, _, ["nullary()"], %{"en" => "add_doc"}, %{}} = function_nullary assert {{:function, :qux, 1}, _, ["qux(bool)"], :hidden, %{}} = function_qux assert {{:macro, :is_zero, 1}, _, ["is_zero(v)"], %{"en" => "A guard"}, %{guard: true}} = guard_is_zero assert {{:macrocallback, :macrocallback_multi, 1}, _, [], %{"en" => "Macrocallback with multiple clauses"}, %{}} = macrocallback_multi assert {{:macrocallback, :qux, 1}, _, [], %{"en" => "Macrocallback doc"}, %{}} = macrocallback_qux assert {{:type, :bar, 1}, _, [], %{"en" => "Opaque type doc"}, %{opaque: true}} = type_bar assert {{:type, :foo, 1}, _, [], %{"en" => "Type doc"}, %{since: "1.2.3", color: :red}} = type_foo end end test "fetch docs chunk from doc/chunks" do Code.compiler_options(docs: false) doc_chunks_path = Path.join([tmp_path(), "doc", "chunks"]) File.rm_rf!(doc_chunks_path) File.mkdir_p!(doc_chunks_path) write_beam( defmodule ExternalDocs do end ) assert Code.fetch_docs(ExternalDocs) == {:error, :chunk_not_found} path = Path.join([doc_chunks_path, "#{ExternalDocs}.chunk"]) chunk = {:docs_v1, 1, :elixir, "text/markdown", %{"en" => "Some docs"}, %{}} File.write!(path, :erlang.term_to_binary(chunk)) assert Code.fetch_docs(ExternalDocs) == chunk after Code.compiler_options(docs: true) end test "@impl true doesn't set @doc false if previous implementation has docs" do write_beam( defmodule Docs do defmodule SampleBehaviour do @callback foo(any()) :: any() @callback bar() :: any() @callback baz() :: any() end @behaviour SampleBehaviour @doc "Foo docs" def foo(nil), do: nil @impl true def foo(_), do: false @impl true def bar(), do: true @doc "Baz docs" @impl true def baz(), do: true def fuz(), do: true end ) {:docs_v1, _, _, _, _, _, docs} = Code.fetch_docs(Docs) function_docs = for {{:function, name, arity}, _, _, doc, _} <- docs, do: {{name, arity}, doc} assert [ {{:bar, 0}, :hidden}, {{:baz, 0}, %{"en" => "Baz docs"}}, {{:foo, 1}, %{"en" => "Foo docs"}}, {{:fuz, 0}, %{}} ] = Enum.sort(function_docs) end end
29.918699
100
0.558243
08b07c81bd527aa4508a4185372e6b5a42cf2490
4,571
exs
Elixir
apps/re_web/test/graphql/dashboard/query_test.exs
caspg/backend
34df9dc14ab8ed75de4578fefa2e087580c7e867
[ "MIT" ]
1
2021-01-19T05:01:15.000Z
2021-01-19T05:01:15.000Z
apps/re_web/test/graphql/dashboard/query_test.exs
caspg/backend
34df9dc14ab8ed75de4578fefa2e087580c7e867
[ "MIT" ]
null
null
null
apps/re_web/test/graphql/dashboard/query_test.exs
caspg/backend
34df9dc14ab8ed75de4578fefa2e087580c7e867
[ "MIT" ]
null
null
null
defmodule ReWeb.GraphQL.Dashboard.QueryTest do use ReWeb.ConnCase import Re.Factory alias ReWeb.AbsintheHelpers setup %{conn: conn} do conn = put_req_header(conn, "accept", "application/json") admin_user = insert(:user, email: "admin@email.com", role: "admin") user_user = insert(:user, email: "user@email.com", role: "user") {:ok, unauthenticated_conn: conn, admin_conn: login_as(conn, admin_user), user_conn: login_as(conn, user_user)} end describe "dashboard" do test "admin should query dashboard", %{admin_conn: conn} do insert(:listing, status: "inactive") insert( :listing, listings_visualisations: [build(:listing_visualisation)], tour_visualisations: [build(:tour_visualisation)], listings_favorites: [build(:listings_favorites)], maintenance_fee: 123.321, property_tax: 321.123, matterport_code: "asdsa", area: 50 ) insert( :listing, maintenance_fee: nil, property_tax: nil, matterport_code: nil, area: nil ) query = """ query Dashboard { dashboard { activeListingCount favoriteCount visualizationCount tourVisualizationCount maintenanceFeeCount propertyTaxCount tourCount areaCount } } """ conn = post(conn, "/graphql_api", AbsintheHelpers.query_wrapper(query)) assert %{ "activeListingCount" => 2, "favoriteCount" => 1, "visualizationCount" => 1, "tourVisualizationCount" => 1, "maintenanceFeeCount" => 1, "propertyTaxCount" => 1, "tourCount" => 1, "areaCount" => 1 } == json_response(conn, 200)["data"]["dashboard"] end test "user should not query dashboard", %{user_conn: conn} do query = """ query Dashboard { dashboard { activeListingCount favoriteCount visualizationCount tourVisualizationCount maintenanceFeeCount propertyTaxCount tourCount areaCount } } """ conn = post(conn, "/graphql_api", AbsintheHelpers.query_wrapper(query)) assert [%{"message" => "Forbidden", "code" => 403}] = json_response(conn, 200)["errors"] end test "anonymous should not query dashboard", %{unauthenticated_conn: conn} do query = """ query Dashboard { dashboard { activeListingCount favoriteCount visualizationCount tourVisualizationCount maintenanceFeeCount propertyTaxCount tourCount areaCount } } """ conn = post(conn, "/graphql_api", AbsintheHelpers.query_wrapper(query)) assert [%{"message" => "Unauthorized", "code" => 401}] = json_response(conn, 200)["errors"] end end describe "listings" do test "query all listings", %{admin_conn: conn} do variables = %{ "pagination" => %{ "page" => 1, "pageSize" => 2 }, "filters" => %{ "maxPrice" => 2_000_000 }, "orderBy" => [ %{ "field" => "ID", "type" => "ASC" } ] } insert_list(4, :listing, price: 2_500_000) [l1, l2 | _] = insert_list(6, :listing, price: 1_500_000) query = """ query MyQuery( $pagination: ListingPaginationAdminInput, $filters: ListingFilterInput, $orderBy: OrderBy ) { Dashboard { listings(pagination: $pagination, filters: $filters, orderBy: $orderBy) { entries { id } pageNumber pageSize totalPages totalEntries } } } """ conn = post(conn, "/graphql_api", AbsintheHelpers.query_wrapper(query, variables)) query_response = json_response(conn, 200)["data"]["Dashboard"]["listings"] assert [%{"id" => to_string(l1.id)}, %{"id" => to_string(l2.id)}] == query_response["entries"] assert 1 == query_response["pageNumber"] assert 2 == query_response["pageSize"] assert 3 == query_response["totalPages"] assert 6 == query_response["totalEntries"] end end end
27.047337
97
0.537519
08b08afeb2056317015dc92f48d7b18187f15be3
7,616
ex
Elixir
lib/ex_component_schema/validator/error/string_formatter.ex
lenra-io/ex_component_schema
a051ba94057cdd3218c4625e24f56a834a586aa6
[ "MIT" ]
2
2022-03-18T08:52:29.000Z
2022-03-18T08:52:33.000Z
lib/ex_component_schema/validator/error/string_formatter.ex
lenra-io/ex_component_schema
a051ba94057cdd3218c4625e24f56a834a586aa6
[ "MIT" ]
8
2021-09-15T11:52:45.000Z
2022-01-10T13:13:53.000Z
lib/ex_component_schema/validator/error/string_formatter.ex
lenra-io/ex_component_schema
a051ba94057cdd3218c4625e24f56a834a586aa6
[ "MIT" ]
null
null
null
defmodule ExComponentSchema.Validator.Error.StringFormatter do alias ExComponentSchema.Validator.Error @spec format(ExComponentSchema.Validator.errors()) :: [{String.t(), String.t()}] def format(errors) do Enum.map(errors, fn %Error{error: error, path: path} -> {to_string(error), path} end) end defimpl String.Chars, for: Error.AdditionalItems do def to_string(%Error.AdditionalItems{}) do "Schema does not allow additional items." end end defimpl String.Chars, for: Error.AdditionalProperties do def to_string(%Error.AdditionalProperties{}) do "Schema does not allow additional properties." end end defimpl String.Chars, for: Error.AllOf do def to_string(%Error.AllOf{invalid: invalid}) do "Expected all of the schemata to match, but the schemata at the following indexes did not: #{Enum.map_join(invalid, ", ", & &1.index)}." end end defimpl String.Chars, for: Error.AnyOf do def to_string(%Error.AnyOf{}) do "Expected any of the schemata to match but none did." end end defimpl String.Chars, for: Error.Const do def to_string(%Error.Const{expected: expected}) do "Expected data to be #{inspect(expected)}." end end defimpl String.Chars, for: Error.Contains do def to_string(%Error.Contains{}) do "Expected any of the items to match the schema but none did." end end defimpl String.Chars, for: Error.ContentEncoding do def to_string(%Error.ContentEncoding{expected: expected}) do "Expected the content to be #{expected}-encoded." end end defimpl String.Chars, for: Error.ContentMediaType do def to_string(%Error.ContentMediaType{expected: expected}) do "Expected the content to be of media type #{expected}." end end defimpl String.Chars, for: Error.Dependencies do def to_string(%Error.Dependencies{property: property, missing: [missing]}) do "Property #{property} depends on property #{missing} to be present but it was not." end def to_string(%Error.Dependencies{property: property, missing: missing}) do "Property #{property} depends on properties #{Enum.join(missing, ", ")} to be present but they were not." end end defimpl String.Chars, for: Error.Enum do def to_string(%Error.Enum{enum: [item], actual: actual}) when is_bitstring(actual) and is_bitstring(item) do "#{actual} is invalid. Should have been #{item}" end def to_string(%Error.Enum{}) do "Value is not allowed in enum." end end defimpl String.Chars, for: Error.False do def to_string(%Error.False{}) do "False schema never matches." end end defimpl String.Chars, for: Error.Format do def to_string(%Error.Format{expected: expected}) do "Expected to be a valid #{format_name(expected)}." end defp format_name("date-time"), do: "ISO 8601 date-time" defp format_name("ipv4"), do: "IPv4 address" defp format_name("ipv6"), do: "IPv6 address" defp format_name(expected), do: expected end defimpl String.Chars, for: Error.IfThenElse do def to_string(%Error.IfThenElse{branch: branch}) do "Expected the schema in the #{branch} branch to match but it did not." end end defimpl String.Chars, for: Error.ItemsNotAllowed do def to_string(%Error.ItemsNotAllowed{}) do "Items are not allowed." end end defimpl String.Chars, for: Error.MaxItems do def to_string(%Error.MaxItems{expected: expected, actual: actual}) do "Expected a maximum of #{expected} items but got #{actual}." end end defimpl String.Chars, for: Error.MaxLength do def to_string(%Error.MaxLength{expected: expected, actual: actual}) do "Expected value to have a maximum length of #{expected} but was #{actual}." end end defimpl String.Chars, for: Error.MaxProperties do def to_string(%Error.MaxProperties{expected: expected, actual: actual}) do "Expected a maximum of #{expected} properties but got #{actual}" end end defimpl String.Chars, for: Error.Maximum do def to_string(%Error.Maximum{expected: expected, exclusive?: exclusive?}) do "Expected the value to be #{if exclusive?, do: "<", else: "<="} #{expected}" end end defimpl String.Chars, for: Error.MinItems do def to_string(%Error.MinItems{expected: expected, actual: actual}) do "Expected a minimum of #{expected} items but got #{actual}." end end defimpl String.Chars, for: Error.MinLength do def to_string(%Error.MinLength{expected: expected, actual: actual}) do "Expected value to have a minimum length of #{expected} but was #{actual}." end end defimpl String.Chars, for: Error.MinProperties do def to_string(%Error.MinProperties{expected: expected, actual: actual}) do "Expected a minimum of #{expected} properties but got #{actual}" end end defimpl String.Chars, for: Error.Minimum do def to_string(%Error.Minimum{expected: expected, exclusive?: exclusive?}) do "Expected the value to be #{if exclusive?, do: ">", else: ">="} #{expected}" end end defimpl String.Chars, for: Error.MultipleOf do def to_string(%Error.MultipleOf{expected: expected}) do "Expected value to be a multiple of #{expected}." end end defimpl String.Chars, for: Error.Not do def to_string(%Error.Not{}) do "Expected schema not to match but it did." end end defimpl String.Chars, for: Error.OneOf do def to_string(%Error.OneOf{valid_indices: valid_indices}) do if length(valid_indices) > 1 do "Expected exactly one of the schemata to match, but the schemata at the following indexes did: " <> Enum.join(valid_indices, ", ") <> "." else "Expected exactly one of the schemata to match, but none of them did." end end end defimpl String.Chars, for: Error.Pattern do def to_string(%Error.Pattern{expected: expected}) do "Does not match pattern #{inspect(expected)}." end end defimpl String.Chars, for: Error.PropertyNames do def to_string(%Error.PropertyNames{invalid: invalid}) do "Expected the property names to be valid but the following were not: #{invalid |> Map.keys() |> Enum.sort() |> Enum.join(", ")}." end end defimpl String.Chars, for: Error.Required do def to_string(%Error.Required{missing: [missing]}) do "Required property #{missing} was not present." end def to_string(%Error.Required{missing: missing}) do "Required properties #{Enum.join(missing, ", ")} were not present." end end defimpl String.Chars, for: Error.Type do def to_string(%Error.Type{expected: expected, actual: actual}) do "Type mismatch. Expected #{type_names(expected)} but got #{type_names(actual)}." end defp type_names(types) do types |> List.wrap() |> Enum.map_join(", ", &String.capitalize/1) end end defimpl String.Chars, for: Error.UniqueItems do def to_string(%Error.UniqueItems{}) do "Expected items to be unique but they were not." end end defimpl String.Chars, for: Error.Component do # def to_string(%Error.Component{not_a_comp: true}) do # "comp property should not be present or you should set type property to 'component'." # end def to_string(%Error.Component{no_comp_property: true}) do "comp property not found." end def to_string(%Error.Component{actual: actual, expected: expected}) do "The comp property value #{actual} does not match the component #{expected}" end end end
32.547009
142
0.682773
08b0a9839d1be02473c1b3c99d094c4101b12c38
1,248
ex
Elixir
lib/util.ex
andersonmcook/flow_example
af3778c947411e96bfc93a64894ce74e916f248b
[ "MIT" ]
null
null
null
lib/util.ex
andersonmcook/flow_example
af3778c947411e96bfc93a64894ce74e916f248b
[ "MIT" ]
null
null
null
lib/util.ex
andersonmcook/flow_example
af3778c947411e96bfc93a64894ce74e916f248b
[ "MIT" ]
null
null
null
defmodule Util do @moduledoc false @doc """ Keep only .txt files """ def txt?(file) do Path.extname(file) === ".txt" end @doc """ Join path with directory """ def join_path(file, path) do Path.join(path, file) end @doc """ Clean-up words """ def clean(word) do ~r/[^A-zÀ-ÿ'-]/ |> Regex.replace(word, "") |> String.trim() |> String.downcase() end @doc """ Filter out empty strings """ def not_empty?(""), do: false def not_empty?(_), do: true @doc """ Update map, incrementing value at word key """ def word_count(word, acc) do Map.update(acc, word, 1, &(&1 + 1)) end @doc """ Compare tuples via their second value """ def by_count(a, b) do elem(a, 1) > elem(b, 1) end @doc """ Create a new ETS table called :words """ def create_table do :ets.new(:words, []) end @doc """ Update table similarly to word_count/2 """ def update_table(word, table) do :ets.update_counter(table, word, {2, 1}, {word, 0}) table end @doc """ Transfer ownership of table and get all values """ def transfer_and_select(table, parent) do :ets.give_away(table, parent, []) :ets.match_object(table, {:"$1", :"$2"}) end end
17.577465
55
0.581731
08b0c30dd5960c73ed3d699aac476aeea026233b
2,072
ex
Elixir
clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_list_environment_groups_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_list_environment_groups_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_list_environment_groups_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ListEnvironmentGroupsResponse do @moduledoc """ Response for ListEnvironmentGroups. ## Attributes * `environmentGroups` (*type:* `list(GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1EnvironmentGroup.t)`, *default:* `nil`) - EnvironmentGroups in the specified organization. * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Page token that you can include in a ListEnvironmentGroups request to retrieve the next page. If omitted, no subsequent pages exist. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :environmentGroups => list(GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1EnvironmentGroup.t()), :nextPageToken => String.t() } field(:environmentGroups, as: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1EnvironmentGroup, type: :list ) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ListEnvironmentGroupsResponse do def decode(value, options) do GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ListEnvironmentGroupsResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ListEnvironmentGroupsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.533333
195
0.750483
08b0e98da84e3fe435bc61c18994b17f95caef7a
2,267
exs
Elixir
dnd-character/test/dnd_character_test.exs
rapidfireworks/exercism.ex
7739c60db0510099fe8d37fd6bd76eee37623d05
[ "MIT" ]
null
null
null
dnd-character/test/dnd_character_test.exs
rapidfireworks/exercism.ex
7739c60db0510099fe8d37fd6bd76eee37623d05
[ "MIT" ]
null
null
null
dnd-character/test/dnd_character_test.exs
rapidfireworks/exercism.ex
7739c60db0510099fe8d37fd6bd76eee37623d05
[ "MIT" ]
1
2021-03-15T11:02:40.000Z
2021-03-15T11:02:40.000Z
defmodule DndCharacterTest do use ExUnit.Case import DndCharacter, only: [modifier: 1, ability: 0, character: 0] # canonical data version: 1.1.0 describe "ability modifier" do # @tag :pending test "for score 3 is -4" do assert modifier(3) === -4 end # @tag :pending test "for score 4 is -3" do assert modifier(4) === -3 end # @tag :pending test "for score 5 is -3" do assert modifier(5) === -3 end # @tag :pending test "for score 6 is -2" do assert modifier(6) === -2 end # @tag :pending test "for score 7 is -2" do assert modifier(7) === -2 end # @tag :pending test "for score 8 is -1" do assert modifier(8) === -1 end # @tag :pending test "for score 9 is -1" do assert modifier(9) === -1 end # @tag :pending test "for score 10 is 0" do assert modifier(10) === 0 end # @tag :pending test "for score 11 is 0" do assert modifier(11) === 0 end # @tag :pending test "for score 12 is +1" do assert modifier(12) === 1 end # @tag :pending test "for score 13 is +1" do assert modifier(13) === 1 end # @tag :pending test "for score 14 is +2" do assert modifier(14) === 2 end # @tag :pending test "for score 15 is +2" do assert modifier(15) === 2 end # @tag :pending test "for score 16 is +3" do assert modifier(16) === 3 end # @tag :pending test "for score 17 is +3" do assert modifier(17) === 3 end # @tag :pending test "for score 18 is +4" do assert modifier(18) === 4 end end describe "random ability" do # @tag :pending test "is within range" do Enum.each(1..200, fn _ -> assert ability() in 3..18 end) end end describe "random character" do setup do %{character: character()} end # @tag :pending test "has valid hitpoints", %{character: character} do assert character.hitpoints === 10 + modifier(character.constitution) end # @tag :pending test "has each ability only calculated once", %{character: character} do assert character.strength === character.strength end end end
20.061947
76
0.565064
08b0f09554cbaa522094964a2b1cfe7e4f8b39b8
9,619
ex
Elixir
lib/webdavex/client.ex
mugimaru73/webdavex
bdf9fe8bce47de50e5b93d80a3484966b5cced4b
[ "MIT" ]
1
2018-09-09T11:32:48.000Z
2018-09-09T11:32:48.000Z
lib/webdavex/client.ex
mugimaru73/webdavex
bdf9fe8bce47de50e5b93d80a3484966b5cced4b
[ "MIT" ]
null
null
null
lib/webdavex/client.ex
mugimaru73/webdavex
bdf9fe8bce47de50e5b93d80a3484966b5cced4b
[ "MIT" ]
1
2018-11-02T05:53:35.000Z
2018-11-02T05:53:35.000Z
defmodule Webdavex.Client do @moduledoc """ [hackney](https://github.com/benoitc/hackney) based WebDAV client. It is recommended to use `Webdavex` module to define your own client instead of using `Webdavex.Client` directly. With defmodule MyClient use Webdavex, base_url: "http://webdav.host" end you can write MyClient.get("image.png") instead of Webdavex.Config.new(base_url: "http://webdav.host") |> Webdavex.Client.get("image.png") """ alias Webdavex.Config require Logger @spec head(Config.t(), path :: String.t()) :: {:ok, list({String.t(), String.t()})} | {:error, atom} @doc """ Issues a HEAD request to webdav server. Returns response headers if target file exists. It migth be useful to check content type and size of file (Content-Type and Content-Length headers respectively). ### Examples MyClient.head("foo.jpg") {:ok, [ {"Date", "Sun, 09 Sep 2018 18:13:00 GMT"}, {"Content-Type", "image/jpeg"}, {"Content-Length", "870883"}, {"Last-Modified", "Sat, 08 Sep 2018 18:00:51 GMT"}, ]} """ def head(%Config{} = config, path) do case request(:head, path, [], "", config) do {:ok, 200, headers} -> {:ok, headers} error -> wrap_error(error) end end @spec get(Config.t(), path :: String.t()) :: {:ok, binary} | {:error, atom} @doc """ Gets a file from webdav server. ### Examples MyClient.get("foo.png") {:ok, <<binary content>>} """ def get(%Config{} = config, path) do with {:ok, 200, _, ref} <- request(:get, path, [], "", config), {:ok, body} <- :hackney.body(ref) do {:ok, body} else error -> wrap_error(error) end end @spec get_stream(Config.t(), path :: String.t()) :: {:ok, Enumerable.t()} | {:error, atom} @doc """ Same as `get/2`, but returns content reader in form of `Stream.resource/3`. See `Webdavex.Helpers.Hackney.stream_body/1` and `:hackney.stream_body/1`. ### Examples Stream content into a file with {:ok, stream} <- MyClient.get_stream("foo.png") do stream |> Stream.into(File.stream!("/local/path/foo.png", [:write])) |> Stream.run end """ def get_stream(%Config{} = config, path) do case request(:get, path, [], "", config) do {:ok, 200, _headers, ref} -> {:ok, Webdavex.Helpers.Hackney.stream_body(ref)} error -> wrap_error(error) end end @spec put(Config.t(), path :: String.t(), {:file, String.t()} | {:binary, binary} | {:stream, Enumerable.t()}) :: {:ok, :created} | {:ok, :updated} | {:error, atom} @doc """ Uploads local file, `Stream` or binary content to webdav server. Note that webdav specification only allows to create files in already existing folders which means thah you must call `mkcol/2` or `mkcol_recursive/2` manually. ### Examples Upload local file MyClient.put("image.png", {:file, "/home/username/img.png"}) {:ok, :created} Upload custom binary content MyClient.put("file.ext", {:binary, <<42, 42, 42>>}) {:ok, :created} Chunked upload from a `Stream` MyClient.put("file.ext", {:stream, File.stream("/path/to/file.ext")}) {:ok, :created} """ def put(%Config{} = config, path, content) do with {:ok, ref} <- do_put(config, path, content) do case :hackney.start_response(ref) do {:ok, 204, _headers, ref} -> :ok = :hackney.skip_body(ref) {:ok, :updated} {:ok, 201, _headers, ref} -> :ok = :hackney.skip_body(ref) {:ok, :created} {:ok, _status, _headers, ref} = error -> :ok = :hackney.skip_body(ref) wrap_error(error) error -> wrap_error(error) end else error -> wrap_error(error) end end @spec move(Config.t(), source :: String.t(), dest :: String.t(), overwrite :: boolean) :: {:ok, :moved} | {:error, atom} @doc """ Moves a file on webdav server. If overwrite option (3rd argument) is set to false (true by default) will return {:error, :http_412} in case of destination file already exists. ### Examples MyClient.move("imag.png", "image.png") {:ok, :moved} """ def move(%Config{base_url: base_url} = config, source_path, destination_path, overwrite) do dest_header = destination_header(base_url, destination_path) overwrite_header = overwrite_header(overwrite) case request(:move, source_path, [dest_header, overwrite_header], "", config) do {:ok, 204, _, _ref} -> {:ok, :moved} error -> wrap_error(error) end end @spec copy(Config.t(), source :: String.t(), dest :: String.t(), overwrite :: boolean) :: {:ok, :copied} | {:error, atom} @doc """ Copies a file on webdav server. Refer to `move/4` for details. ### Examples MyClient.copy("image.png", "image_copy.png") {:ok, :copied} """ def copy(%Config{base_url: base_url} = config, source_path, dest_path, overwrite) do dest_header = destination_header(base_url, dest_path) overwrite_header = overwrite_header(overwrite) case request(:copy, source_path, [dest_header, overwrite_header], "", config) do {:ok, 204, _, _ref} -> {:ok, :copied} error -> wrap_error(error) end end @spec delete(Config.t(), path :: String.t()) :: {:ok, :deleted} | {:error, atom} @doc """ Deletes file or directory on webdav server. ### Examples MyClient.delete("file.png") {:ok, :deleted} """ def delete(%Config{} = config, path) do case request(:delete, path, [], "", config) do {:ok, 204, _, _} -> {:ok, :deleted} error -> wrap_error(error) end end @spec mkcol(Config.t(), path :: String.t()) :: {:ok, :created} | {:error, atom} @doc """ Creates a folder on wedav server. Note that webdav does not allow to create nested folders (HTTP 409 will be returned). Use `mkcol_recursive/2` to create nested directory structure. ### Examples MyClient.mkcol("foo") {:ok, :created} """ def mkcol(%Config{} = config, path) do case request(:mkcol, path, [], "", config) do {:ok, 201, _, _} -> {:ok, :created} error -> wrap_error(error) end end @spec mkcol_recursive(Config.t(), path :: String.t()) :: {:ok, String.t()} | {:error, atom} @doc """ Creates nested folders for given path or file. Performs sequential `mkcol/2` calls to populate nested structure. ### Examples Create structure for a file. MyClient.mkcol_recursive("foo/bar/baz/file.png") {:ok, :created} "foo", "foo/bar" and "foo/bar/baz" folders will be created. Create structure for a folder. MyClient.mkcol_recursive("foo/bar/") {:ok, :created} Note that trailing slash is required for directory paths. """ def mkcol_recursive(%Config{} = config, path) do path |> Path.dirname() |> String.split("/") |> Enum.reduce_while({:ok, ""}, fn folder, {:ok, prefix} -> new_path = prefix <> "/" <> folder case mkcol(config, new_path) do {:ok, _} -> {:cont, {:ok, new_path}} error -> {:halt, error} end end) end defp do_put(config, path, {:file, file_path}) do case File.read(file_path) do {:ok, content} -> do_put(config, path, {:binary, content}) error -> error end end defp do_put(config, path, {mode, data}) when mode in [:stream, :binary] do with {:ok, ref} <- request(:put, path, [], :stream, config), :ok <- do_send_body(mode, ref, data), :ok <- :hackney.finish_send_body(ref) do {:ok, ref} else error -> wrap_error(error) end end defp do_send_body(:binary, ref, data), do: :hackney.send_body(ref, data) defp do_send_body(:stream, ref, stream) do Enum.reduce_while(stream, :ok, fn part, :ok -> case :hackney.send_body(ref, part) do :ok -> {:cont, :ok} any -> {:halt, any} end end) end defp request(meth, url, headers, body, config) do started_at = now() full_url = full_url(config.base_url, url) headers = config.headers ++ headers case :hackney.request(meth, full_url, headers, body, config.hackney_options) do {:ok, status, _, _} = result -> log_request(meth, full_url, {:ok, status}, started_at) result result -> log_request(meth, full_url, result, started_at) result end end defp log_request(meth, url, result, started_at) do Logger.debug(fn -> meth = meth |> to_string |> String.upcase() "#{meth} #{url} completed with #{inspect(result)} in #{now() - started_at}ms" end) end defp now, do: :erlang.system_time(:millisecond) defp full_url(base_url, url) when is_binary(url), do: full_url(base_url, URI.parse(url)) defp full_url(%URI{path: base_path} = base_url, %URI{} = uri) do base_url |> URI.merge(%{uri | path: Path.join(to_string(base_path), to_string(uri.path))}) |> to_string end defp overwrite_header(true), do: {"Overwrite", "T"} defp overwrite_header(false), do: {"Overwrite", "F"} defp destination_header(base_url, url), do: {"Destination", full_url(base_url, url)} defp wrap_error({:ok, status, _headers}), do: {:error, String.to_atom("http_#{status}")} defp wrap_error({:ok, status, _headers, _ref}), do: {:error, String.to_atom("http_#{status}")} defp wrap_error({:error, reason}), do: {:error, reason} end
28.208211
115
0.598295
08b111358346e9b21789325901e0d5522e1e8240
2,123
ex
Elixir
apps/service_profile/lib/profile/feed/flow.ex
rucker/hindsight
876a5d344c5d8eebbea37684ee07e0a91e4430f0
[ "Apache-2.0" ]
null
null
null
apps/service_profile/lib/profile/feed/flow.ex
rucker/hindsight
876a5d344c5d8eebbea37684ee07e0a91e4430f0
[ "Apache-2.0" ]
null
null
null
apps/service_profile/lib/profile/feed/flow.ex
rucker/hindsight
876a5d344c5d8eebbea37684ee07e0a91e4430f0
[ "Apache-2.0" ]
null
null
null
defmodule Profile.Feed.Flow do use Flow use Properties, otp_app: :service_profile require Logger alias Profile.Feed.Flow.State getter(:window_limit, default: 5) getter(:window_unit, default: :minute) @type init_opts :: [ name: GenServer.name(), dataset_id: String.t(), subset_id: String.t(), from_specs: list(Supervisor.child_spec()), into_specs: list(Supervisor.child_spec()), reducers: list(Profile.Reducer.t()) ] @spec start_link(init_opts) :: GenServer.on_start() def start_link(opts) do Logger.debug(fn -> "#{__MODULE__}(#{inspect(self())}): init with #{inspect(opts)}" end) flow_opts = Keyword.take(opts, [:name]) dataset_id = Keyword.fetch!(opts, :dataset_id) subset_id = Keyword.fetch!(opts, :subset_id) from_specs = Keyword.fetch!(opts, :from_specs) into_specs = Keyword.fetch!(opts, :into_specs) |> Enum.map(fn consumer -> {consumer, []} end) reducers = Keyword.fetch!(opts, :reducers) window = Flow.Window.periodic(window_limit(), window_unit()) {:ok, stats} = Profile.Feed.Store.get_stats(dataset_id, subset_id) reducers = Enum.map(reducers, &Profile.Reducer.init(&1, stats)) {:ok, state} = State.start_link(reducers: reducers) from_specs |> Flow.from_specs() |> Flow.partition(window: window, stages: 1) |> Flow.reduce(fn -> State.get(state) end, &reduce/2) |> Flow.on_trigger(fn acc -> case State.merge(state, acc) do [] -> {[], %{}} changed_reducers -> event = changed_reducers |> Enum.flat_map(&Profile.Reducer.to_event_fields/1) |> Map.new() {[event], %{}} end end) |> Flow.into_specs(into_specs, flow_opts) catch kind, reason -> Logger.error(fn -> "#{__MODULE__}: error - #{kind} - #{inspect(reason)}" end) end defp reduce(event, accumulator) do Logger.debug(fn -> "#{__MODULE__}: event #{inspect(event)}" end) accumulator |> Enum.map(fn reducer -> Profile.Reducer.reduce(reducer, event) end) end end
30.328571
97
0.619878
08b18f61a8bc5ee7d4c8c9d9dbe3ccc00a36ee6c
1,553
ex
Elixir
lib/transhook_web/views/error_helpers.ex
linjunpop/transhook
59000e5a346c6c059d95c5a1f48190f698b4e7a3
[ "0BSD" ]
null
null
null
lib/transhook_web/views/error_helpers.ex
linjunpop/transhook
59000e5a346c6c059d95c5a1f48190f698b4e7a3
[ "0BSD" ]
null
null
null
lib/transhook_web/views/error_helpers.ex
linjunpop/transhook
59000e5a346c6c059d95c5a1f48190f698b4e7a3
[ "0BSD" ]
null
null
null
defmodule TranshookWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn error -> content_tag(:span, translate_error(error), class: "invalid-feedback", phx_feedback_for: input_id(form, field) ) end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # When using gettext, we typically pass the strings we want # to translate as a static argument: # # # Translate "is invalid" in the "errors" domain # dgettext("errors", "is invalid") # # # Translate the number of files with plural rules # dngettext("errors", "1 file", "%{count} files", count) # # Because the error messages we show in our forms and APIs # are defined inside Ecto, we need to translate them dynamically. # This requires us to call the Gettext module passing our gettext # backend as first argument. # # Note we use the "errors" domain, which means translations # should be written to the errors.po file. The :count option is # set by Ecto and indicates we should also apply plural rules. if count = opts[:count] do Gettext.dngettext(TranshookWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(TranshookWeb.Gettext, "errors", msg, opts) end end end
32.354167
78
0.666452
08b1bbcc2fc45538a9fa525d4c96e9cd4954f201
943
exs
Elixir
apps/generic_plug/mix.exs
jfis/ex-gulp
806d305ede7df3c2b42d21c2e7b574987832c8d6
[ "MIT" ]
null
null
null
apps/generic_plug/mix.exs
jfis/ex-gulp
806d305ede7df3c2b42d21c2e7b574987832c8d6
[ "MIT" ]
null
null
null
apps/generic_plug/mix.exs
jfis/ex-gulp
806d305ede7df3c2b42d21c2e7b574987832c8d6
[ "MIT" ]
null
null
null
defmodule GenericPlug.Mixfile do use Mix.Project def project do [app: :generic_plug, version: "0.1.0", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", lockfile: "../../mix.lock", elixir: "~> 1.3", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do [applications: [:logger]] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # To depend on another app inside the umbrella: # # {:myapp, in_umbrella: true} # # Type "mix help deps" for more examples and options defp deps do [{:common, in_umbrella: true}, ] end end
22.452381
77
0.597031
08b1e1c8c5c0d4864e0def860fff220e69cd1cf6
283
ex
Elixir
lib/genstage_importer/repo.ex
kloeckner-i/genstage_importer
a8d8242fa0bc79d83d05212dea667c93990685c7
[ "MIT" ]
4
2019-07-27T13:11:54.000Z
2020-06-19T14:00:21.000Z
lib/genstage_importer/repo.ex
altmer/genstage_importer
a8d8242fa0bc79d83d05212dea667c93990685c7
[ "MIT" ]
null
null
null
lib/genstage_importer/repo.ex
altmer/genstage_importer
a8d8242fa0bc79d83d05212dea667c93990685c7
[ "MIT" ]
2
2018-08-02T11:01:15.000Z
2019-11-15T12:35:40.000Z
defmodule GenstageImporter.Repo do use Ecto.Repo, otp_app: :genstage_importer @doc """ Dynamically loads the repository url from the DATABASE_URL environment variable. """ def init(_, opts) do {:ok, Keyword.put(opts, :url, System.get_env("DATABASE_URL"))} end end
23.583333
66
0.717314
08b206f207c4c7a175e5cf3521c6bb80f5bfc1ce
361
ex
Elixir
lib/ecto_crdt_types/types/state/twopset.ex
ExpressApp/ecto_crdt_types
cf18557cf888b3d50a44640997507cff6caf2b93
[ "MIT" ]
8
2018-09-20T13:05:16.000Z
2021-09-22T08:40:40.000Z
lib/ecto_crdt_types/types/state/twopset.ex
ExpressApp/ecto_crdt_types
cf18557cf888b3d50a44640997507cff6caf2b93
[ "MIT" ]
null
null
null
lib/ecto_crdt_types/types/state/twopset.ex
ExpressApp/ecto_crdt_types
cf18557cf888b3d50a44640997507cff6caf2b93
[ "MIT" ]
null
null
null
defmodule EctoCrdtTypes.Types.State.TWOPSet do @moduledoc """ 2PSet CRDT: two-phased set. Once removed, elements cannot be added again. Also, this is not an observed removed variant. This means elements can be removed before being in the set. """ @crdt_type :state_twopset @crdt_value_type {:array, :string} use EctoCrdtTypes.Types.CRDT end
27.769231
49
0.745152
08b23b6df35644a7db9708607b8530534129484c
3,567
exs
Elixir
test/oli/resources/numbering_test.exs
DevShashi1993/oli-torus
e6e0b66f0973f9790a5785731b22db6fb1c50a73
[ "MIT" ]
45
2020-04-17T15:40:27.000Z
2022-03-25T00:13:30.000Z
test/oli/resources/numbering_test.exs
DevShashi1993/oli-torus
e6e0b66f0973f9790a5785731b22db6fb1c50a73
[ "MIT" ]
944
2020-02-13T02:37:01.000Z
2022-03-31T17:50:07.000Z
test/oli/resources/numbering_test.exs
DevShashi1993/oli-torus
e6e0b66f0973f9790a5785731b22db6fb1c50a73
[ "MIT" ]
23
2020-07-28T03:36:13.000Z
2022-03-17T14:29:02.000Z
defmodule Oli.Resources.NumberingTest do use Oli.DataCase alias Oli.Resources.Numbering alias Oli.Publishing.AuthoringResolver alias Oli.Delivery.Sections alias Oli.Publishing alias Oli.Publishing.DeliveryResolver describe "container numbering" do setup do Seeder.base_project_with_resource2() |> Seeder.create_hierarchy([ %{ title: "Unit 1", children: [ # makes everything a container, so we're just simulating a page here %{title: "Page 1", slug: "page_1", children: []}, %{ title: "Module 2", children: [ %{ title: "Section 1", children: [ # makes everything a container, so we're just simulating a page here %{title: "Page 2", slug: "page_2", children: []} ] }, %{title: "Section 2", children: []}, %{title: "Section 3", children: []} ] }, %{ title: "Module 3", children: [ %{title: "Section 4", children: []}, %{title: "Section 5", children: []}, %{title: "Section 6", children: []} ] } ] }, %{ title: "Unit 2", children: [] } ]) end test "number_tree_from/2 numbers the containers correctly", %{ project: project } do revisions_by_id = AuthoringResolver.all_revisions_in_hierarchy(project.slug) |> Enum.reduce(%{}, fn rev, acc -> Map.put(acc, rev.id, rev) end) # do the numbering, then programatically compare it to the titles of the # containers, which contain the correct numbering and level names # Numbering.number_tree_from(root, AuthoringResolver.all_revisions_in_hierarchy(project.slug)) Numbering.number_full_tree(AuthoringResolver, project.slug) |> Enum.to_list() |> Enum.filter(fn {id, _n} -> !Regex.match?(~r|page|, revisions_by_id[id].slug) && revisions_by_id[id].title != "Root container" end) |> Enum.each(fn {id, n} -> revision = revisions_by_id[id] level = case n.level do 1 -> "Unit" 2 -> "Module" _ -> "Section" end assert Numbering.prefix(n) == revision.title assert revision.title == "#{level} #{n.index}" end) end test "path_from_root_to/2", %{project: project, institution: institution} do # Publish the current state of our test project {:ok, pub1} = Publishing.publish_project(project, "some changes") {:ok, section} = Sections.create_section(%{ title: "1", timezone: "1", registration_open: true, context_id: "1", institution_id: institution.id, base_project_id: project.id }) |> then(fn {:ok, section} -> section end) |> Sections.create_section_resources(pub1) hierarchy = DeliveryResolver.full_hierarchy(section.slug) node = Enum.at( Enum.at(Enum.at(Enum.at(hierarchy.children, 0).children, 1).children, 0).children, 0 ) {:ok, path_nodes} = Numbering.path_from_root_to(hierarchy, node) path_titles = Enum.map(path_nodes, fn n -> n.revision.title end) assert path_titles == ["Root Container", "Unit 1", "Module 2", "Section 1", "Page 2"] end end end
31.566372
100
0.543874
08b25a22ae7cbf11af0e207df40b015865c47661
3,320
exs
Elixir
test/plug/crypto/message_encryptor_test.exs
gjaldon/plug
bfe88530b429c7b9b29b69b737772ef7c6aa2f6b
[ "Apache-2.0" ]
null
null
null
test/plug/crypto/message_encryptor_test.exs
gjaldon/plug
bfe88530b429c7b9b29b69b737772ef7c6aa2f6b
[ "Apache-2.0" ]
null
null
null
test/plug/crypto/message_encryptor_test.exs
gjaldon/plug
bfe88530b429c7b9b29b69b737772ef7c6aa2f6b
[ "Apache-2.0" ]
null
null
null
defmodule Plug.Crypto.MessageEncryptorTest do use ExUnit.Case, async: true alias Plug.Crypto.MessageEncryptor, as: ME @right String.duplicate("abcdefgh", 4) @wrong String.duplicate("12345678", 4) @large String.duplicate(@right, 2) test "it encrypts/decrypts a message" do data = <<0, "hełłoworld", 0>> encrypted = ME.encrypt(<<0, "hełłoworld", 0>>, @right, @right) decrypted = ME.decrypt(encrypted, @wrong, @wrong) assert decrypted == :error decrypted = ME.decrypt(encrypted, @right, @wrong) assert decrypted == :error decrypted = ME.decrypt(encrypted, @wrong, @right) assert decrypted == :error decrypted = ME.decrypt(encrypted, @right, @right) assert decrypted == {:ok, data} # Legacy support for AES256-CBC with HMAC SHA-1 encrypted = ME.encrypt_and_sign(<<0, "hełłoworld", 0>>, @right, @right, :aes_cbc256) decrypted = ME.verify_and_decrypt(encrypted, @wrong, @wrong) assert decrypted == :error decrypted = ME.verify_and_decrypt(encrypted, @right, @wrong) assert decrypted == :error # This can fail depending on the initialization vector # decrypted = ME.verify_and_decrypt(encrypted, @wrong, @right) # assert decrypted == :error decrypted = ME.verify_and_decrypt(encrypted, @right, @right) assert decrypted == {:ok, data} end test "it uses only the first 32 bytes to encrypt/decrypt" do data = <<0, "helloworld", 0>> encrypted = ME.encrypt(<<0, "helloworld", 0>>, @large, @large) decrypted = ME.decrypt(encrypted, @large, @large) assert decrypted == {:ok, data} decrypted = ME.decrypt(encrypted, @right, @large) assert decrypted == {:ok, data} decrypted = ME.decrypt(encrypted, @large, @right) assert decrypted == :error decrypted = ME.decrypt(encrypted, @right, @right) assert decrypted == :error encrypted = ME.encrypt(<<0, "helloworld", 0>>, @right, @large) decrypted = ME.decrypt(encrypted, @large, @large) assert decrypted == {:ok, data} decrypted = ME.decrypt(encrypted, @right, @large) assert decrypted == {:ok, data} decrypted = ME.decrypt(encrypted, @large, @right) assert decrypted == :error decrypted = ME.decrypt(encrypted, @right, @right) assert decrypted == :error # Legacy support for AES256-CBC with HMAC SHA-1 encrypted = ME.encrypt_and_sign(<<0, "helloworld", 0>>, @large, @large, :aes_cbc256) decrypted = ME.verify_and_decrypt(encrypted, @large, @large) assert decrypted == {:ok, data} decrypted = ME.verify_and_decrypt(encrypted, @right, @large) assert decrypted == {:ok, data} decrypted = ME.verify_and_decrypt(encrypted, @large, @right) assert decrypted == :error decrypted = ME.verify_and_decrypt(encrypted, @right, @right) assert decrypted == :error encrypted = ME.encrypt_and_sign(<<0, "helloworld", 0>>, @right, @large, :aes_cbc256) decrypted = ME.verify_and_decrypt(encrypted, @large, @large) assert decrypted == {:ok, data} decrypted = ME.verify_and_decrypt(encrypted, @right, @large) assert decrypted == {:ok, data} decrypted = ME.verify_and_decrypt(encrypted, @large, @right) assert decrypted == :error decrypted = ME.verify_and_decrypt(encrypted, @right, @right) assert decrypted == :error end end
32.23301
88
0.671084
08b2785fb221a59a2c7438ee39ae724de15e6197
311
exs
Elixir
test/test_server.exs
digitalnatives/haphazard
52f0e196bd596662b8bf00dd7f09e20f0a7336b7
[ "MIT" ]
12
2017-02-13T19:35:26.000Z
2020-02-01T15:30:53.000Z
test/test_server.exs
digitalnatives/haphazard
52f0e196bd596662b8bf00dd7f09e20f0a7336b7
[ "MIT" ]
null
null
null
test/test_server.exs
digitalnatives/haphazard
52f0e196bd596662b8bf00dd7f09e20f0a7336b7
[ "MIT" ]
null
null
null
defmodule HaphazardTest.Server do use ExUnit.Case use Plug.Test doctest Haphazard.Server alias Haphazard.Server test "cleanup cache" do Server.store_cache("key", "body", 10000) Server.lookup_request("key") Server.cleanup assert Server.lookup_request("key") == :not_cached end end
19.4375
54
0.720257
08b27c444121c524708334ef5e4a8bdf6119a2d8
217
exs
Elixir
config/test.exs
christopherlai/ex_aws_ssm
62375f4283bc84cc8b8292748ddd93b9a1605d17
[ "MIT" ]
5
2019-03-29T00:18:19.000Z
2020-01-19T05:32:08.000Z
config/test.exs
christopherlai/ex_aws_ssm
62375f4283bc84cc8b8292748ddd93b9a1605d17
[ "MIT" ]
2
2019-08-20T17:19:13.000Z
2020-05-25T19:50:30.000Z
config/test.exs
christopherlai/ex_aws_ssm
62375f4283bc84cc8b8292748ddd93b9a1605d17
[ "MIT" ]
3
2019-02-13T16:56:21.000Z
2020-06-30T16:37:31.000Z
use Mix.Config config :ex_aws, access_key_id: "accesskeyid", secret_access_key: "secretaccesskey", region: "us-east-1" config :ex_aws, ssm: [ host: "localhost", scheme: "http://", port: 4583 ]
15.5
39
0.640553
08b27e677af74d68ad4d987a55471e87eb01b527
1,635
ex
Elixir
web/controllers/parameter_controller.ex
rob05c/tox
f54847ca058ad24b909341ad65d595a4069d2471
[ "Apache-2.0" ]
2
2016-11-16T17:24:21.000Z
2019-02-15T05:38:27.000Z
web/controllers/parameter_controller.ex
rob05c/tox
f54847ca058ad24b909341ad65d595a4069d2471
[ "Apache-2.0" ]
null
null
null
web/controllers/parameter_controller.ex
rob05c/tox
f54847ca058ad24b909341ad65d595a4069d2471
[ "Apache-2.0" ]
null
null
null
defmodule Tox.ParameterController do use Tox.Web, :controller alias Tox.Parameter def index(conn, _params) do parameters = Repo.all(Parameter) render(conn, "index.json", parameters: parameters) end def create(conn, %{"parameter" => parameter_params}) do changeset = Parameter.changeset(%Parameter{}, parameter_params) case Repo.insert(changeset) do {:ok, parameter} -> conn |> put_status(:created) |> put_resp_header("location", parameter_path(conn, :show, parameter)) |> render("show.json", parameter: parameter) {:error, changeset} -> conn |> put_status(:unprocessable_entity) |> render(Tox.ChangesetView, "error.json", changeset: changeset) end end def show(conn, %{"id" => id}) do parameter = Repo.get!(Parameter, id) render(conn, "show.json", parameter: parameter) end def update(conn, %{"id" => id, "parameter" => parameter_params}) do parameter = Repo.get!(Parameter, id) changeset = Parameter.changeset(parameter, parameter_params) case Repo.update(changeset) do {:ok, parameter} -> render(conn, "show.json", parameter: parameter) {:error, changeset} -> conn |> put_status(:unprocessable_entity) |> render(Tox.ChangesetView, "error.json", changeset: changeset) end end def delete(conn, %{"id" => id}) do parameter = Repo.get!(Parameter, id) # Here we use delete! (with a bang) because we expect # it to always work (and if it does not, it will raise). Repo.delete!(parameter) send_resp(conn, :no_content, "") end end
29.196429
78
0.64159
08b2a1fceb0397966b822e15f023298449be9b58
440
exs
Elixir
package.exs
Macu1/erlzk
004f77a5015fac8bda5a044f29457125ab3e3fc4
[ "Apache-2.0" ]
80
2015-01-22T19:18:44.000Z
2022-02-04T16:53:39.000Z
package.exs
Macu1/erlzk
004f77a5015fac8bda5a044f29457125ab3e3fc4
[ "Apache-2.0" ]
15
2015-01-06T12:19:41.000Z
2018-02-07T02:52:55.000Z
package.exs
Macu1/erlzk
004f77a5015fac8bda5a044f29457125ab3e3fc4
[ "Apache-2.0" ]
37
2015-01-07T16:27:31.000Z
2021-09-02T01:43:04.000Z
defmodule Erlzk.MixFile do use Mix.Project def project do [app: :erlzk, version: "0.6.6", description: "A Pure Erlang ZooKeeper Client (no C dependency)", package: package] end def package do [files: ~w(src include rebar.config README.md LICENSE Makefile), licenses: ["Apache 2.0"], maintainers: ["Mega Yu", "Belltoy Zhao"], links: %{"GitHub" => "https://github.com/huaban/erlzk"}] end end
24.444444
69
0.638636
08b2ad6fa9bb657afc0bd4f48c49567d654021fe
1,756
ex
Elixir
clients/chat/lib/google_api/chat/v1/model/action_parameter.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/chat/lib/google_api/chat/v1/model/action_parameter.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/chat/lib/google_api/chat/v1/model/action_parameter.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Chat.V1.Model.ActionParameter do @moduledoc """ List of string parameters to supply when the action method is invoked. For example, consider three snooze buttons: snooze now, snooze 1 day, snooze next week. You might use action method = snooze(), passing the snooze type and snooze time in the list of string parameters. ## Attributes * `key` (*type:* `String.t`, *default:* `nil`) - The name of the parameter for the action script. * `value` (*type:* `String.t`, *default:* `nil`) - The value of the parameter. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :key => String.t(), :value => String.t() } field(:key) field(:value) end defimpl Poison.Decoder, for: GoogleApi.Chat.V1.Model.ActionParameter do def decode(value, options) do GoogleApi.Chat.V1.Model.ActionParameter.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Chat.V1.Model.ActionParameter do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.132075
101
0.720387
08b2af7dd24fd648d5fa354baf33ca49e0b2b12d
661
ex
Elixir
wadm/lib/wadm/lattice_event_listener.ex
wasmCloud/wadm
ccf76739039f14fc40548a00dd209d7ffa5c0c4e
[ "Apache-2.0" ]
2
2022-01-02T12:37:57.000Z
2022-03-02T20:13:03.000Z
wadm/lib/wadm/lattice_event_listener.ex
wasmCloud/wadm
ccf76739039f14fc40548a00dd209d7ffa5c0c4e
[ "Apache-2.0" ]
12
2021-11-28T19:22:20.000Z
2022-01-25T18:41:48.000Z
wadm/lib/wadm/lattice_event_listener.ex
wasmCloud/wadm
ccf76739039f14fc40548a00dd209d7ffa5c0c4e
[ "Apache-2.0" ]
1
2021-11-25T00:42:06.000Z
2021-11-25T00:42:06.000Z
defmodule Wadm.LatticeEventListener do alias Phoenix.PubSub require Logger use Gnat.Server def request(%{topic: topic, body: body}) do lattice_id = topic |> String.split(".") |> List.last() with {:ok, event} <- Jason.decode(body), {:ok, cloud_event} <- Cloudevents.from_map(event) do dispatch_cloud_event(lattice_id, cloud_event) else {:error, e} -> Logger.error("Failed to decode cloud event from message: #{inspect(e)}") end end defp dispatch_cloud_event(lattice_id, cloud_event) do PubSub.broadcast(Wadm.PubSub, "lattice:#{lattice_id}", {:cloud_event, cloud_event}) end end
26.44
87
0.659607
08b2b9a6661d4d7b83d16ed6003ec5a11f17a096
1,298
exs
Elixir
config/dev.exs
kerlak/color_wars_server
a1f069eb110dcae3c519e4b85d64b5d13b9ffc4e
[ "MIT" ]
1
2020-04-21T10:38:14.000Z
2020-04-21T10:38:14.000Z
config/dev.exs
kerlak/color_wars_server
a1f069eb110dcae3c519e4b85d64b5d13b9ffc4e
[ "MIT" ]
null
null
null
config/dev.exs
kerlak/color_wars_server
a1f069eb110dcae3c519e4b85d64b5d13b9ffc4e
[ "MIT" ]
null
null
null
use Mix.Config # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with brunch.io to recompile .js and .css sources. config :color_wars, ColorWarsWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # command from your terminal: # # openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem # # The `http:` config above can be replaced with: # # https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20
34.157895
170
0.737288
08b2ce58e96537eda071656773611ec908214ce8
1,865
ex
Elixir
clients/genomics/lib/google_api/genomics/v1/model/clinical_condition.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/genomics/lib/google_api/genomics/v1/model/clinical_condition.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/genomics/lib/google_api/genomics/v1/model/clinical_condition.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Genomics.V1.Model.ClinicalCondition do @moduledoc """ ## Attributes - conceptId (String): The MedGen concept id associated with this gene. Search for these IDs at http://www.ncbi.nlm.nih.gov/medgen/ Defaults to: `null`. - externalIds (List[ExternalId]): The set of external IDs for this condition. Defaults to: `null`. - names (List[String]): A set of names for the condition. Defaults to: `null`. - omimId (String): The OMIM id for this condition. Search for these IDs at http://omim.org/ Defaults to: `null`. """ defstruct [ :"conceptId", :"externalIds", :"names", :"omimId" ] end defimpl Poison.Decoder, for: GoogleApi.Genomics.V1.Model.ClinicalCondition do import GoogleApi.Genomics.V1.Deserializer def decode(value, options) do value |> deserialize(:"externalIds", :list, GoogleApi.Genomics.V1.Model.ExternalId, options) end end defimpl Poison.Encoder, for: GoogleApi.Genomics.V1.Model.ClinicalCondition do def encode(value, options) do GoogleApi.Genomics.V1.Deserializer.serialize_non_nil(value, options) end end
34.537037
153
0.738338
08b2f63694bc843a4f981935ef892e542c383da8
10,815
ex
Elixir
lib/ecto/adapters/mysql.ex
mbuhot/ecto
e6c4c7df0af055ba4bae8737908b98ae85352d2f
[ "Apache-2.0" ]
null
null
null
lib/ecto/adapters/mysql.ex
mbuhot/ecto
e6c4c7df0af055ba4bae8737908b98ae85352d2f
[ "Apache-2.0" ]
null
null
null
lib/ecto/adapters/mysql.ex
mbuhot/ecto
e6c4c7df0af055ba4bae8737908b98ae85352d2f
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.Adapters.MySQL do @moduledoc """ Adapter module for MySQL. It handles and pools the connections to the MySQL database using `mariaex` and a connection pool, such as `poolboy`. ## Options MySQL options split in different categories described below. All options should be given via the repository configuration. These options are also passed to the module specified in the `:pool` option, so check that module's documentation for more options. ### Compile time options Those options should be set in the config file and require recompilation in order to make an effect. * `:adapter` - The adapter name, in this case, `Ecto.Adapters.MySQL` * `:pool` - The connection pool module, defaults to `DBConnection.Poolboy` * `:pool_timeout` - The default timeout to use on pool calls, defaults to `5000` * `:timeout` - The default timeout to use on queries, defaults to `15000` ### Connection options * `:hostname` - Server hostname * `:port` - Server port (default: 3306) * `:username` - Username * `:password` - User password * `:ssl` - Set to true if ssl should be used (default: false) * `:ssl_opts` - A list of ssl options, see Erlang's `ssl` docs * `:parameters` - Keyword list of connection parameters * `:connect_timeout` - The timeout for establishing new connections (default: 5000) * `:socket_options` - Specifies socket configuration The `:socket_options` are particularly useful when configuring the size of both send and receive buffers. For example, when Ecto starts with a pool of 20 connections, the memory usage may quickly grow from 20MB to 50MB based on the operating system default values for TCP buffers. It is advised to stick with the operating system defaults but they can be tweaked if desired: socket_options: [recbuf: 8192, sndbuf: 8192] We also recommend developers to consult the [Mariaex documentation](https://hexdocs.pm/mariaex/Mariaex.html#start_link/1) for a complete listing of all supported options. ### Storage options * `:charset` - the database encoding (default: "utf8") * `:collation` - the collation order * `:dump_path` - where to place dumped structures ## Limitations There are some limitations when using Ecto with MySQL that one needs to be aware of. ### Engine Since Ecto uses transactions, MySQL users running old versions (5.1 and before) must ensure their tables use the InnoDB engine as the default (MyISAM) does not support transactions. Tables created by Ecto are guaranteed to use InnoDB, regardless of the MySQL version. ### UUIDs MySQL does not support UUID types. Ecto emulates them by using `binary(16)`. ### Read after writes Because MySQL does not support RETURNING clauses in INSERT and UPDATE, it does not support the `:read_after_writes` option of `Ecto.Schema.field/3`. ### DDL Transaction MySQL does not support migrations inside transactions as it automatically commits after some commands like CREATE TABLE. Therefore MySQL migrations does not run inside transactions. ### usec in datetime Old MySQL versions did not support usec in datetime while more recent versions would round or truncate the usec value. Therefore, in case the user decides to use microseconds in datetimes and timestamps with MySQL, be aware of such differences and consult the documentation for your MySQL version. Assuming your version of MySQL supports microsecond precision, you will need to explicitly set it on the relevant columns in your migration. For explicitly declared columns you can add the `size: 6` option. If you're using the `timestamps()` helper you can use `timestamps(size: 6)`. """ # Inherit all behaviour from Ecto.Adapters.SQL use Ecto.Adapters.SQL, :mariaex # And provide a custom storage implementation @behaviour Ecto.Adapter.Storage @behaviour Ecto.Adapter.Structure ## Custom MySQL types @doc false def loaders(:map, type), do: [&json_decode/1, type] def loaders({:map, _}, type), do: [&json_decode/1, type] def loaders(:boolean, type), do: [&bool_decode/1, type] def loaders(:binary_id, type), do: [Ecto.UUID, type] def loaders({:embed, _} = type, _), do: [&json_decode/1, &Ecto.Adapters.SQL.load_embed(type, &1)] def loaders(_, type), do: [type] defp bool_decode(<<0>>), do: {:ok, false} defp bool_decode(<<1>>), do: {:ok, true} defp bool_decode(0), do: {:ok, false} defp bool_decode(1), do: {:ok, true} defp bool_decode(x), do: {:ok, x} defp json_decode(x) when is_binary(x), do: {:ok, Application.get_env(:ecto, :json_library).decode!(x)} defp json_decode(x), do: {:ok, x} ## Storage API @doc false def storage_up(opts) do database = Keyword.fetch!(opts, :database) || raise ":database is nil in repository configuration" charset = opts[:charset] || "utf8" opts = Keyword.put(opts, :skip_database, true) command = ~s(CREATE DATABASE `#{database}` DEFAULT CHARACTER SET = #{charset}) |> concat_if(opts[:collation], &"DEFAULT COLLATE = #{&1}") case run_query(command, opts) do {:ok, _} -> :ok {:error, %{mariadb: %{code: 1007}}} -> {:error, :already_up} {:error, error} -> {:error, Exception.message(error)} end end defp concat_if(content, nil, _fun), do: content defp concat_if(content, value, fun), do: content <> " " <> fun.(value) @doc false def storage_down(opts) do database = Keyword.fetch!(opts, :database) || raise ":database is nil in repository configuration" command = "DROP DATABASE `#{database}`" case run_query(command, opts) do {:ok, _} -> :ok {:error, %{mariadb: %{code: 1008}}} -> {:error, :already_down} {:error, %{mariadb: %{code: 1049}}} -> {:error, :already_down} {:error, error} -> {:error, Exception.message(error)} end end @doc false def supports_ddl_transaction? do true end @doc false def insert(repo, %{source: {prefix, source}} = meta, params, {_, query_params, _} = on_conflict, returning, opts) do key = primary_key!(meta, returning) {fields, values} = :lists.unzip(params) sql = @conn.insert(prefix, source, fields, [fields], on_conflict, []) case Ecto.Adapters.SQL.query(repo, sql, values ++ query_params, opts) do {:ok, %{num_rows: 1, last_insert_id: last_insert_id}} -> {:ok, last_insert_id(key, last_insert_id)} {:ok, %{num_rows: 2, last_insert_id: last_insert_id}} -> {:ok, last_insert_id(key, last_insert_id)} {:error, err} -> case @conn.to_constraints(err) do [] -> raise err constraints -> {:invalid, constraints} end end end defp primary_key!(%{autogenerate_id: {key, :id}}, [key]), do: key defp primary_key!(_, []), do: nil defp primary_key!(%{schema: schema}, returning) do raise ArgumentError, "MySQL does not support :read_after_writes in schemas for non-primary keys. " <> "The following fields in #{inspect schema} are tagged as such: #{inspect returning}" end defp last_insert_id(nil, _last_insert_id), do: [] defp last_insert_id(_key, 0), do: [] defp last_insert_id(key, last_insert_id), do: [{key, last_insert_id}] @doc false def structure_dump(default, config) do table = config[:migration_source] || "schema_migrations" path = config[:dump_path] || Path.join(default, "structure.sql") with {:ok, versions} <- select_versions(table, config), {:ok, contents} <- mysql_dump(config), {:ok, contents} <- append_versions(table, versions, contents) do File.mkdir_p!(Path.dirname(path)) File.write!(path, contents) {:ok, path} end end defp select_versions(table, config) do case run_query(~s[SELECT version FROM `#{table}` ORDER BY version], config) do {:ok, %{rows: rows}} -> {:ok, Enum.map(rows, &hd/1)} {:error, %{mariadb: %{code: 1146}}} -> {:ok, []} {:error, _} = error -> error end end defp mysql_dump(config) do case run_with_cmd("mysqldump", config, ["--no-data", "--routines", config[:database]]) do {output, 0} -> {:ok, output} {output, _} -> {:error, output} end end defp append_versions(_table, [], contents) do {:ok, contents} end defp append_versions(table, versions, contents) do {:ok, contents <> ~s[INSERT INTO `#{table}` (version) VALUES ] <> Enum.map_join(versions, ", ", &"(#{&1})") <> ~s[;\n\n]} end @doc false def structure_load(default, config) do path = config[:dump_path] || Path.join(default, "structure.sql") args = [ "--execute", "SET FOREIGN_KEY_CHECKS = 0; SOURCE #{path}; SET FOREIGN_KEY_CHECKS = 1", "--database", config[:database] ] case run_with_cmd("mysql", config, args) do {_output, 0} -> {:ok, path} {output, _} -> {:error, output} end end ## Helpers defp run_query(sql, opts) do {:ok, _} = Application.ensure_all_started(:mariaex) opts = opts |> Keyword.delete(:name) |> Keyword.put(:pool, DBConnection.Connection) |> Keyword.put(:backoff_type, :stop) {:ok, pid} = Task.Supervisor.start_link task = Task.Supervisor.async_nolink(pid, fn -> {:ok, conn} = Mariaex.start_link(opts) value = Ecto.Adapters.MySQL.Connection.execute(conn, sql, [], opts) GenServer.stop(conn) value end) timeout = Keyword.get(opts, :timeout, 15_000) case Task.yield(task, timeout) || Task.shutdown(task) do {:ok, {:ok, result}} -> {:ok, result} {:ok, {:error, error}} -> {:error, error} {:exit, {%{__struct__: struct} = error, _}} when struct in [Mariaex.Error, DBConnection.Error] -> {:error, error} {:exit, reason} -> {:error, RuntimeError.exception(Exception.format_exit(reason))} nil -> {:error, RuntimeError.exception("command timed out")} end end defp run_with_cmd(cmd, opts, opt_args) do unless System.find_executable(cmd) do raise "could not find executable `#{cmd}` in path, " <> "please guarantee it is available before running ecto commands" end env = if password = opts[:password] do [{"MYSQL_PWD", password}] else [] end host = opts[:hostname] || System.get_env("MYSQL_HOST") || "localhost" port = opts[:port] || System.get_env("MYSQL_TCP_PORT") || "3306" args = ["--user", opts[:username], "--host", host, "--port", to_string(port), "--protocol=tcp"] ++ opt_args System.cmd(cmd, args, env: env, stderr_to_stdout: true) end end
33.482972
111
0.649191
08b312f81c468fdf240a23a00a283fdbb6a5ac06
1,945
ex
Elixir
lib/raxx/response.ex
cryic/raxx
a6e33f5dbd9b9344753b43c5d4eb4cbf838bdddf
[ "Apache-2.0" ]
null
null
null
lib/raxx/response.ex
cryic/raxx
a6e33f5dbd9b9344753b43c5d4eb4cbf838bdddf
[ "Apache-2.0" ]
null
null
null
lib/raxx/response.ex
cryic/raxx
a6e33f5dbd9b9344753b43c5d4eb4cbf838bdddf
[ "Apache-2.0" ]
null
null
null
defmodule Raxx.Response do @moduledoc """ HTTP responses from a Raxx application are encapsulated in a `Raxx.Response` struct. The contents are itemised below: | **status** | The HTTP status code for the response: `1xx, 2xx, 3xx, 4xx, 5xx` | | **headers** | The response headers as a list: `[{"content-type", "text/plain"}` | | **body** | The response body, by default an empty string. | """ @typedoc """ Integer code for server response type """ @type status_code :: integer @typedoc """ Elixir representation for an HTTP response. """ @type t :: %__MODULE__{ status: status_code, headers: Raxx.headers(), body: Raxx.body() } @enforce_keys [:status, :headers, :body] defstruct @enforce_keys # DEBT I never used these, will they be missed? # @doc """ # The response is marked as an interim response. # # https://tools.ietf.org/html/rfc7231#section-6.2 # """ # def informational?(%{status: code}), do: 100 <= code and code < 200 # # @doc """ # The response indicates that client request was received, understood, and accepted. # # https://tools.ietf.org/html/rfc7231#section-6.3 # """ # def success?(%{status: code}), do: 200 <= code and code < 300 # # @doc """ # The response indicates that further action needs to be taken by the client. # # https://tools.ietf.org/html/rfc7231#section-6.4 # """ # def redirect?(%{status: code}), do: 300 <= code and code < 400 # # @doc """ # The response indicates that the client sent an incorrect request. # # https://tools.ietf.org/html/rfc7231#section-6.5 # """ # def client_error?(%{status: code}), do: 400 <= code and code < 500 # # @doc """ # The response indicates that the server is incapable of acting upon the request. # # https://tools.ietf.org/html/rfc7231#section-6.6 # """ # def server_error?(%{status: code}), do: 500 <= code and code < 600 end
29.469697
86
0.632391
08b32209f5d4b63c3f3d4dc8d9d53246821e738e
1,123
exs
Elixir
twitter/config/config.exs
MrCeleryman/elixirtute
797e3cb29a68a54728258329b49ac4ae0787cc76
[ "MIT" ]
null
null
null
twitter/config/config.exs
MrCeleryman/elixirtute
797e3cb29a68a54728258329b49ac4ae0787cc76
[ "MIT" ]
null
null
null
twitter/config/config.exs
MrCeleryman/elixirtute
797e3cb29a68a54728258329b49ac4ae0787cc76
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :tute_tweet, key: :value # # And access this configuration in your application as: # # Application.get_env(:tute_tweet, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
36.225806
73
0.752449
08b32e031e554f4991d579533a1114e1b6f25ec0
19,858
exs
Elixir
test/phoenix_live_view/html_tokenizer_test.exs
feliperenan/phoenix_live_view
af65bb51fe12ea88e7c66808d2b1118e1c491ddd
[ "MIT" ]
null
null
null
test/phoenix_live_view/html_tokenizer_test.exs
feliperenan/phoenix_live_view
af65bb51fe12ea88e7c66808d2b1118e1c491ddd
[ "MIT" ]
null
null
null
test/phoenix_live_view/html_tokenizer_test.exs
feliperenan/phoenix_live_view
af65bb51fe12ea88e7c66808d2b1118e1c491ddd
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveView.HTMLTokenizerTest do use ExUnit.Case, async: true alias Phoenix.LiveView.HTMLTokenizer.ParseError alias Phoenix.LiveView.HTMLTokenizer defp tokenize(text) do HTMLTokenizer.tokenize(text, "nofile", 0, [], [], :text) |> elem(0) |> Enum.reverse() end describe "text" do test "represented as {:text, value}" do assert tokenize("Hello") == [{:text, "Hello", %{line_end: 1, column_end: 6}}] end test "with multiple lines" do tokens = tokenize(""" first second third """) assert tokens == [{:text, "first\nsecond\nthird\n", %{line_end: 4, column_end: 1}}] end test "keep line breaks unchanged" do assert tokenize("first\nsecond\r\nthird") == [ {:text, "first\nsecond\r\nthird", %{line_end: 3, column_end: 6}} ] end end describe "doctype" do test "generated as text" do assert tokenize("<!doctype html>") == [ {:text, "<!doctype html>", %{line_end: 1, column_end: 16}} ] end test "multiple lines" do assert tokenize("<!DOCTYPE\nhtml\n> <br />") == [ {:text, "<!DOCTYPE\nhtml\n> ", %{line_end: 3, column_end: 4}}, {:tag_open, "br", [], %{column: 4, line: 3, self_close: true}} ] end end describe "comment" do test "generated as text" do assert tokenize("Begin<!-- comment -->End") == [ {:text, "Begin<!-- comment -->End", %{line_end: 1, column_end: 25}} ] end test "multiple lines and wrapped by tags" do code = """ <p> <!-- <div> --> </p><br>\ """ assert [ {:tag_open, "p", [], %{line: 1, column: 1}}, {:text, "\n<!--\n<div>\n-->\n", %{line_end: 5, column_end: 1}}, {:tag_close, "p", %{line: 5, column: 1}}, {:tag_open, "br", [], %{line: 5, column: 5}} ] = tokenize(code) end test "adds comment_start and comment_end" do first_part = """ <p> <!-- <div> """ {first_tokens, cont} = HTMLTokenizer.tokenize(first_part, "nofile", 0, [], [], :text) second_part = """ </div> --> </p> <div> <p>Hello</p> </div> """ {tokens, :text} = HTMLTokenizer.tokenize(second_part, "nofile", 0, [], first_tokens, cont) assert Enum.reverse(tokens) == [ {:tag_open, "p", [], %{column: 1, line: 1}}, {:text, "\n<!--\n<div>\n", %{column_end: 1, context: [:comment_start], line_end: 4}}, {:text, "</div>\n-->\n", %{column_end: 1, context: [:comment_end], line_end: 3}}, {:tag_close, "p", %{column: 1, line: 3}}, {:text, "\n", %{column_end: 1, line_end: 4}}, {:tag_open, "div", [], %{column: 1, line: 4}}, {:text, "\n ", %{column_end: 3, line_end: 5}}, {:tag_open, "p", [], %{column: 3, line: 5}}, {:text, "Hello", %{column_end: 11, line_end: 5}}, {:tag_close, "p", %{column: 11, line: 5}}, {:text, "\n", %{column_end: 1, line_end: 6}}, {:tag_close, "div", %{column: 1, line: 6}}, {:text, "\n", %{column_end: 1, line_end: 7}} ] end test "two comments in a row" do first_part = """ <p> <!-- <%= "Hello" %> """ {first_tokens, cont} = HTMLTokenizer.tokenize(first_part, "nofile", 0, [], [], :text) second_part = """ --> <!-- <p><%= "World"</p> """ {second_tokens, cont} = HTMLTokenizer.tokenize(second_part, "nofile", 0, [], first_tokens, cont) third_part = """ --> <div> <p>Hi</p> </p> """ {tokens, :text} = HTMLTokenizer.tokenize(third_part, "nofile", 0, [], second_tokens, cont) assert Enum.reverse(tokens) == [ {:tag_open, "p", [], %{column: 1, line: 1}}, {:text, "\n<!--\n<%= \"Hello\" %>\n", %{column_end: 1, context: [:comment_start], line_end: 4}}, {:text, "-->\n<!--\n<p><%= \"World\"</p>\n", %{column_end: 1, context: [:comment_end, :comment_start], line_end: 4}}, {:text, "-->\n", %{column_end: 1, line_end: 2, context: [:comment_end]}}, {:tag_open, "div", [], %{column: 1, line: 2}}, {:text, "\n ", %{column_end: 3, line_end: 3}}, {:tag_open, "p", [], %{column: 3, line: 3}}, {:text, "Hi", %{column_end: 8, line_end: 3}}, {:tag_close, "p", %{column: 8, line: 3}}, {:text, "\n", %{column_end: 1, line_end: 4}}, {:tag_close, "p", %{column: 1, line: 4}}, {:text, "\n", %{column_end: 1, line_end: 5}} ] end end describe "opening tag" do test "represented as {:tag_open, name, attrs, meta}" do tokens = tokenize("<div>") assert [{:tag_open, "div", [], %{}}] = tokens end test "with space after name" do tokens = tokenize("<div >") assert [{:tag_open, "div", [], %{}}] = tokens end test "with line break after name" do tokens = tokenize("<div\n>") assert [{:tag_open, "div", [], %{}}] = tokens end test "self close" do tokens = tokenize("<div/>") assert [{:tag_open, "div", [], %{self_close: true}}] = tokens end test "compute line and column" do tokens = tokenize(""" <div> <span> <p/><br>\ """) assert [ {:tag_open, "div", [], %{line: 1, column: 1}}, {:text, _, %{line_end: 2, column_end: 3}}, {:tag_open, "span", [], %{line: 2, column: 3}}, {:text, _, %{line_end: 4, column_end: 1}}, {:tag_open, "p", [], %{column: 1, line: 4, self_close: true}}, {:tag_open, "br", [], %{column: 5, line: 4}} ] = tokens end test "raise on missing/incomplete tag name" do assert_raise ParseError, "nofile:2:4: expected tag name", fn -> tokenize(""" <div> <>\ """) end assert_raise ParseError, "nofile:1:2: expected tag name", fn -> tokenize("<") end assert_raise ParseError, ~r"nofile:1:5: expected closing `>` or `/>`", fn -> tokenize("<foo") end end end describe "attributes" do test "represented as a list of {name, tuple | nil}, where tuple is the {type, value}" do attrs = tokenize_attrs(~S(<div class="panel" style={@style} hidden>)) assert [ {"class", {:string, "panel", %{}}}, {"style", {:expr, "@style", %{}}}, {"hidden", nil} ] = attrs end test "accepts space between the name and `=`" do attrs = tokenize_attrs(~S(<div class ="panel">)) assert [{"class", {:string, "panel", %{}}}] = attrs end test "accepts line breaks between the name and `=`" do attrs = tokenize_attrs("<div class\n=\"panel\">") assert [{"class", {:string, "panel", %{}}}] = attrs attrs = tokenize_attrs("<div class\r\n=\"panel\">") assert [{"class", {:string, "panel", %{}}}] = attrs end test "accepts space between `=` and the value" do attrs = tokenize_attrs(~S(<div class= "panel">)) assert [{"class", {:string, "panel", %{}}}] = attrs end test "accepts line breaks between `=` and the value" do attrs = tokenize_attrs("<div class=\n\"panel\">") assert [{"class", {:string, "panel", %{}}}] = attrs attrs = tokenize_attrs("<div class=\r\n\"panel\">") assert [{"class", {:string, "panel", %{}}}] = attrs end test "raise on missing value" do message = ~r"nofile:2:9: invalid attribute value after `=`" assert_raise ParseError, message, fn -> tokenize(""" <div class=>\ """) end message = ~r"nofile:1:13: invalid attribute value after `=`" assert_raise ParseError, message, fn -> tokenize(~S(<div class= >)) end message = ~r"nofile:1:12: invalid attribute value after `=`" assert_raise ParseError, message, fn -> tokenize("<div class=") end end test "raise on missing attribute name" do assert_raise ParseError, "nofile:2:8: expected attribute name", fn -> tokenize(""" <div> <div ="panel">\ """) end assert_raise ParseError, "nofile:1:6: expected attribute name", fn -> tokenize(~S(<div = >)) end assert_raise ParseError, "nofile:1:6: expected attribute name", fn -> tokenize(~S(<div / >)) end end test "raise on attribute names with quotes" do assert_raise ParseError, "nofile:1:5: invalid character in attribute name: '", fn -> tokenize(~S(<div'>)) end assert_raise ParseError, "nofile:1:5: invalid character in attribute name: \"", fn -> tokenize(~S(<div">)) end assert_raise ParseError, "nofile:1:10: invalid character in attribute name: '", fn -> tokenize(~S(<div attr'>)) end assert_raise ParseError, "nofile:1:20: invalid character in attribute name: \"", fn -> tokenize(~S(<div class={"test"}">)) end end end describe "boolean attributes" do test "represented as {name, nil}" do attrs = tokenize_attrs("<div hidden>") assert [{"hidden", nil}] = attrs end test "multiple attributes" do attrs = tokenize_attrs("<div hidden selected>") assert [{"hidden", nil}, {"selected", nil}] = attrs end test "with space after" do attrs = tokenize_attrs("<div hidden >") assert [{"hidden", nil}] = attrs end test "in self close tag" do attrs = tokenize_attrs("<div hidden/>") assert [{"hidden", nil}] = attrs end test "in self close tag with space after" do attrs = tokenize_attrs("<div hidden />") assert [{"hidden", nil}] = attrs end end describe "attributes as double quoted string" do test "value is represented as {:string, value, meta}}" do attrs = tokenize_attrs(~S(<div class="panel">)) assert [{"class", {:string, "panel", %{delimiter: ?"}}}] = attrs end test "multiple attributes" do attrs = tokenize_attrs(~S(<div class="panel" style="margin: 0px;">)) assert [ {"class", {:string, "panel", %{delimiter: ?"}}}, {"style", {:string, "margin: 0px;", %{delimiter: ?"}}} ] = attrs end test "value containing single quotes" do attrs = tokenize_attrs(~S(<div title="i'd love to!">)) assert [{"title", {:string, "i'd love to!", %{delimiter: ?"}}}] = attrs end test "value containing line breaks" do tokens = tokenize(""" <div title="first second third"><span>\ """) assert [ {:tag_open, "div", [{"title", {:string, "first\n second\nthird", _meta}}], %{}}, {:tag_open, "span", [], %{line: 3, column: 8}} ] = tokens end test "raise on incomplete attribute value (EOF)" do assert_raise ParseError, ~r"nofile:2:15: expected closing `\"` for attribute value", fn -> tokenize(""" <div class="panel\ """) end end end describe "attributes as single quoted string" do test "value is represented as {:string, value, meta}}" do attrs = tokenize_attrs(~S(<div class='panel'>)) assert [{"class", {:string, "panel", %{delimiter: ?'}}}] = attrs end test "multiple attributes" do attrs = tokenize_attrs(~S(<div class='panel' style='margin: 0px;'>)) assert [ {"class", {:string, "panel", %{delimiter: ?'}}}, {"style", {:string, "margin: 0px;", %{delimiter: ?'}}} ] = attrs end test "value containing double quotes" do attrs = tokenize_attrs(~S(<div title='Say "hi!"'>)) assert [{"title", {:string, ~S(Say "hi!"), %{delimiter: ?'}}}] = attrs end test "value containing line breaks" do tokens = tokenize(""" <div title='first second third'><span>\ """) assert [ {:tag_open, "div", [{"title", {:string, "first\n second\nthird", _meta}}], %{}}, {:tag_open, "span", [], %{line: 3, column: 8}} ] = tokens end test "raise on incomplete attribute value (EOF)" do assert_raise ParseError, ~r"nofile:2:15: expected closing `\'` for attribute value", fn -> tokenize(""" <div class='panel\ """) end end end describe "attributes as expressions" do test "value is represented as {:expr, value, meta}" do attrs = tokenize_attrs(~S(<div class={@class}>)) assert [{"class", {:expr, "@class", %{line: 1, column: 13}}}] = attrs end test "multiple attributes" do attrs = tokenize_attrs(~S(<div class={@class} style={@style}>)) assert [ {"class", {:expr, "@class", %{}}}, {"style", {:expr, "@style", %{}}} ] = attrs end test "double quoted strings inside expression" do attrs = tokenize_attrs(~S(<div class={"text"}>)) assert [{"class", {:expr, ~S("text"), %{}}}] = attrs end test "value containing curly braces" do attrs = tokenize_attrs(~S(<div class={ [{:active, @active}] }>)) assert [{"class", {:expr, " [{:active, @active}] ", %{}}}] = attrs end test "ignore escaped curly braces inside elixir strings" do attrs = tokenize_attrs(~S(<div class={"\{hi"}>)) assert [{"class", {:expr, ~S("\{hi"), %{}}}] = attrs attrs = tokenize_attrs(~S(<div class={"hi\}"}>)) assert [{"class", {:expr, ~S("hi\}"), %{}}}] = attrs end test "compute line and columns" do attrs = tokenize_attrs(""" <div class={@class} style={ @style } title={@title} >\ """) assert [ {"class", {:expr, _, %{line: 2, column: 10}}}, {"style", {:expr, _, %{line: 3, column: 12}}}, {"title", {:expr, _, %{line: 6, column: 10}}} ] = attrs end test "raise on incomplete attribute expression (EOF)" do assert_raise ParseError, "nofile:2:15: expected closing `}` for expression", fn -> tokenize(""" <div class={panel\ """) end end end describe "root attributes" do test "represented as {:root, value, meta}" do attrs = tokenize_attrs("<div {@attrs}>") assert [{:root, {:expr, "@attrs", %{}}}] = attrs end test "with space after" do attrs = tokenize_attrs("<div {@attrs} >") assert [{:root, {:expr, "@attrs", %{}}}] = attrs end test "with line break after" do attrs = tokenize_attrs("<div {@attrs}\n>") assert [{:root, {:expr, "@attrs", %{}}}] = attrs end test "in self close tag" do attrs = tokenize_attrs("<div {@attrs}/>") assert [{:root, {:expr, "@attrs", %{}}}] = attrs end test "in self close tag with space after" do attrs = tokenize_attrs("<div {@attrs} />") assert [{:root, {:expr, "@attrs", %{}}}] = attrs end test "multiple values among other attributes" do attrs = tokenize_attrs("<div class={@class} {@attrs1} hidden {@attrs2}/>") assert [ {"class", {:expr, "@class", %{}}}, {:root, {:expr, "@attrs1", %{}}}, {"hidden", nil}, {:root, {:expr, "@attrs2", %{}}} ] = attrs end test "compute line and columns" do attrs = tokenize_attrs(""" <div {@root1} { @root2 } {@root3} >\ """) assert [ {:root, {:expr, "@root1", %{line: 2, column: 4}}}, {:root, {:expr, "\n @root2\n ", %{line: 3, column: 6}}}, {:root, {:expr, "@root3", %{line: 6, column: 4}}} ] = attrs end test "raise on incomplete expression (EOF)" do assert_raise ParseError, "nofile:2:10: expected closing `}` for expression", fn -> tokenize(""" <div {@attrs\ """) end end end describe "closing tag" do test "represented as {:tag_close, name, meta}" do tokens = tokenize("</div>") assert [{:tag_close, "div", %{}}] = tokens end test "compute line and columns" do tokens = tokenize(""" <div> </div><br>\ """) assert [ {:tag_open, "div", [], _meta}, {:text, "\n", %{column_end: 1, line_end: 2}}, {:tag_close, "div", %{line: 2, column: 1}}, {:tag_open, "br", [], %{line: 2, column: 7}} ] = tokens end test "raise on missing closing `>`" do assert_raise ParseError, "nofile:2:6: expected closing `>`", fn -> tokenize(""" <div> </div text\ """) end end test "raise on missing tag name" do assert_raise ParseError, "nofile:2:5: expected tag name", fn -> tokenize(""" <div> </>\ """) end end end describe "script" do test "self-closing" do assert tokenize(""" <script src="foo.js" /> """) == [ {:tag_open, "script", [{"src", {:string, "foo.js", %{delimiter: 34}}}], %{column: 1, line: 1, self_close: true}}, {:text, "\n", %{column_end: 1, line_end: 2}} ] end test "traverses until </script>" do assert tokenize(""" <script> a = "<a>Link</a>" </script> """) == [ {:tag_open, "script", [], %{column: 1, line: 1}}, {:text, "\n a = \"<a>Link</a>\"\n", %{column_end: 1, line_end: 3}}, {:tag_close, "script", %{column: 1, line: 3}}, {:text, "\n", %{column_end: 1, line_end: 4}} ] end end describe "style" do test "self-closing" do assert tokenize(""" <style src="foo.js" /> """) == [ {:tag_open, "style", [{"src", {:string, "foo.js", %{delimiter: 34}}}], %{column: 1, line: 1, self_close: true}}, {:text, "\n", %{column_end: 1, line_end: 2}} ] end test "traverses until </style>" do assert tokenize(""" <style> a = "<a>Link</a>" </style> """) == [ {:tag_open, "style", [], %{column: 1, line: 1}}, {:text, "\n a = \"<a>Link</a>\"\n", %{column_end: 1, line_end: 3}}, {:tag_close, "style", %{column: 1, line: 3}}, {:text, "\n", %{column_end: 1, line_end: 4}} ] end end test "mixing text and tags" do tokens = tokenize(""" text before <div> text </div> text after """) assert [ {:text, "text before\n", %{line_end: 2, column_end: 1}}, {:tag_open, "div", [], %{}}, {:text, "\n text\n", %{line_end: 4, column_end: 1}}, {:tag_close, "div", %{line: 4, column: 1}}, {:text, "\ntext after\n", %{line_end: 6, column_end: 1}} ] = tokens end defp tokenize_attrs(code) do [{:tag_open, "div", attrs, %{}}] = tokenize(code) attrs end end
28.613833
96
0.485799
08b335a4b52c98cf9f4c07f74dd977e481e477b7
1,901
ex
Elixir
clients/storage/lib/google_api/storage/v1/model/objects.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/storage/lib/google_api/storage/v1/model/objects.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/storage/lib/google_api/storage/v1/model/objects.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Storage.V1.Model.Objects do @moduledoc """ A list of objects. ## Attributes - items ([Object]): The list of items. Defaults to: `null`. - kind (String.t): The kind of item this is. For lists of objects, this is always storage#objects. Defaults to: `null`. - nextPageToken (String.t): The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results. Defaults to: `null`. - prefixes ([String.t]): The list of prefixes of objects matching-but-not-listed up to and including the requested delimiter. Defaults to: `null`. """ defstruct [ :items, :kind, :nextPageToken, :prefixes ] end defimpl Poison.Decoder, for: GoogleApi.Storage.V1.Model.Objects do import GoogleApi.Storage.V1.Deserializer def decode(value, options) do value |> deserialize(:items, :list, GoogleApi.Storage.V1.Model.Object, options) end end defimpl Poison.Encoder, for: GoogleApi.Storage.V1.Model.Objects do def encode(value, options) do GoogleApi.Storage.V1.Deserializer.serialize_non_nil(value, options) end end
35.867925
193
0.740663
08b33e28595b8270f883df589722c482828c3084
1,924
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/sites_list_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/sites_list_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/sites_list_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DFAReporting.V33.Model.SitesListResponse do @moduledoc """ Site List Response ## Attributes * `kind` (*type:* `String.t`, *default:* `dfareporting#sitesListResponse`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#sitesListResponse". * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Pagination token to be used for the next list operation. * `sites` (*type:* `list(GoogleApi.DFAReporting.V33.Model.Site.t)`, *default:* `nil`) - Site collection. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :kind => String.t(), :nextPageToken => String.t(), :sites => list(GoogleApi.DFAReporting.V33.Model.Site.t()) } field(:kind) field(:nextPageToken) field(:sites, as: GoogleApi.DFAReporting.V33.Model.Site, type: :list) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.SitesListResponse do def decode(value, options) do GoogleApi.DFAReporting.V33.Model.SitesListResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.SitesListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.301887
180
0.725572
08b352259acbc5cd59c9a19dacf18ad2e6b1fb30
7,373
ex
Elixir
clients/android_management/lib/google_api/android_management/v1/model/application_policy.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/android_management/lib/google_api/android_management/v1/model/application_policy.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/android_management/lib/google_api/android_management/v1/model/application_policy.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.AndroidManagement.V1.Model.ApplicationPolicy do @moduledoc """ Policy for an individual app. ## Attributes * `accessibleTrackIds` (*type:* `list(String.t)`, *default:* `nil`) - List of the app’s track IDs that a device belonging to the enterprise can access. If the list contains multiple track IDs, devices receive the latest version among all accessible tracks. If the list contains no track IDs, devices only have access to the app’s production track. More details about each track are available in AppTrackInfo. * `alwaysOnVpnLockdownExemption` (*type:* `String.t`, *default:* `nil`) - Specifies whether the app is allowed networking when the VPN is not connected and alwaysOnVpnPackage.lockdownEnabled is enabled. If set to VPN_LOCKDOWN_ENFORCED, the app is not allowed networking, and if set to VPN_LOCKDOWN_EXEMPTION, the app is allowed networking. Only supported on devices running Android 10 and above. If this is not supported by the device, the device will contain a NonComplianceDetail with non_compliance_reason set to API_LEVEL and a fieldPath. If this is not applicable to the app, the device will contain a NonComplianceDetail with non_compliance_reason set to UNSUPPORTED and a fieldPath. The fieldPath is set to applications[i].alwaysOnVpnLockdownExemption, where i is the index of the package in the applications policy. * `autoUpdateMode` (*type:* `String.t`, *default:* `nil`) - Controls the auto-update mode for the app. * `connectedWorkAndPersonalApp` (*type:* `String.t`, *default:* `nil`) - Controls whether the app can communicate with itself across a device’s work and personal profiles, subject to user consent. * `defaultPermissionPolicy` (*type:* `String.t`, *default:* `nil`) - The default policy for all permissions requested by the app. If specified, this overrides the policy-level default_permission_policy which applies to all apps. It does not override the permission_grants which applies to all apps. * `delegatedScopes` (*type:* `list(String.t)`, *default:* `nil`) - The scopes delegated to the app from Android Device Policy. * `disabled` (*type:* `boolean()`, *default:* `nil`) - Whether the app is disabled. When disabled, the app data is still preserved. * `extensionConfig` (*type:* `GoogleApi.AndroidManagement.V1.Model.ExtensionConfig.t`, *default:* `nil`) - Configuration to enable this app as an extension app, with the capability of interacting with Android Device Policy offline.This field can be set for at most one app. * `installType` (*type:* `String.t`, *default:* `nil`) - The type of installation to perform. * `lockTaskAllowed` (*type:* `boolean()`, *default:* `nil`) - Whether the app is allowed to lock itself in full-screen mode. DEPRECATED. Use InstallType KIOSK or kioskCustomLauncherEnabled to to configure a dedicated device. * `managedConfiguration` (*type:* `map()`, *default:* `nil`) - Managed configuration applied to the app. The format for the configuration is dictated by the ManagedProperty values supported by the app. Each field name in the managed configuration must match the key field of the ManagedProperty. The field value must be compatible with the type of the ManagedProperty: *type* *JSON value* BOOL true or false STRING string INTEGER number CHOICE string MULTISELECT array of strings HIDDEN string BUNDLE_ARRAY array of objects * `managedConfigurationTemplate` (*type:* `GoogleApi.AndroidManagement.V1.Model.ManagedConfigurationTemplate.t`, *default:* `nil`) - The managed configurations template for the app, saved from the managed configurations iframe. This field is ignored if managed_configuration is set. * `minimumVersionCode` (*type:* `integer()`, *default:* `nil`) - The minimum version of the app that runs on the device. If set, the device attempts to update the app to at least this version code. If the app is not up-to-date, the device will contain a NonComplianceDetail with non_compliance_reason set to APP_NOT_UPDATED. The app must already be published to Google Play with a version code greater than or equal to this value. At most 20 apps may specify a minimum version code per policy. * `packageName` (*type:* `String.t`, *default:* `nil`) - The package name of the app. For example, com.google.android.youtube for the YouTube app. * `permissionGrants` (*type:* `list(GoogleApi.AndroidManagement.V1.Model.PermissionGrant.t)`, *default:* `nil`) - Explicit permission grants or denials for the app. These values override the default_permission_policy and permission_grants which apply to all apps. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :accessibleTrackIds => list(String.t()) | nil, :alwaysOnVpnLockdownExemption => String.t() | nil, :autoUpdateMode => String.t() | nil, :connectedWorkAndPersonalApp => String.t() | nil, :defaultPermissionPolicy => String.t() | nil, :delegatedScopes => list(String.t()) | nil, :disabled => boolean() | nil, :extensionConfig => GoogleApi.AndroidManagement.V1.Model.ExtensionConfig.t() | nil, :installType => String.t() | nil, :lockTaskAllowed => boolean() | nil, :managedConfiguration => map() | nil, :managedConfigurationTemplate => GoogleApi.AndroidManagement.V1.Model.ManagedConfigurationTemplate.t() | nil, :minimumVersionCode => integer() | nil, :packageName => String.t() | nil, :permissionGrants => list(GoogleApi.AndroidManagement.V1.Model.PermissionGrant.t()) | nil } field(:accessibleTrackIds, type: :list) field(:alwaysOnVpnLockdownExemption) field(:autoUpdateMode) field(:connectedWorkAndPersonalApp) field(:defaultPermissionPolicy) field(:delegatedScopes, type: :list) field(:disabled) field(:extensionConfig, as: GoogleApi.AndroidManagement.V1.Model.ExtensionConfig) field(:installType) field(:lockTaskAllowed) field(:managedConfiguration, type: :map) field(:managedConfigurationTemplate, as: GoogleApi.AndroidManagement.V1.Model.ManagedConfigurationTemplate ) field(:minimumVersionCode) field(:packageName) field(:permissionGrants, as: GoogleApi.AndroidManagement.V1.Model.PermissionGrant, type: :list) end defimpl Poison.Decoder, for: GoogleApi.AndroidManagement.V1.Model.ApplicationPolicy do def decode(value, options) do GoogleApi.AndroidManagement.V1.Model.ApplicationPolicy.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AndroidManagement.V1.Model.ApplicationPolicy do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
77.610526
827
0.746508
08b3616864f46e9411efa1b793e8813f7987deff
982
exs
Elixir
config/test.exs
frunox/discuss
d19367eceb8c68ebef4e565981ceef256b5cb04e
[ "MIT" ]
null
null
null
config/test.exs
frunox/discuss
d19367eceb8c68ebef4e565981ceef256b5cb04e
[ "MIT" ]
null
null
null
config/test.exs
frunox/discuss
d19367eceb8c68ebef4e565981ceef256b5cb04e
[ "MIT" ]
null
null
null
import Config # Configure your database # # The MIX_TEST_PARTITION environment variable can be used # to provide built-in test partitioning in CI environment. # Run `mix help test` for more information. config :discuss, Discuss.Repo, username: "postgres", password: "postgres", database: "discuss_test#{System.get_env("MIX_TEST_PARTITION")}", hostname: "localhost", pool: Ecto.Adapters.SQL.Sandbox, pool_size: 10 # We don't run a server during test. If one is required, # you can enable the server option below. config :discuss, DiscussWeb.Endpoint, http: [ip: {127, 0, 0, 1}, port: 4002], secret_key_base: "LCIP5mPqXlXnZvRvekHSXSqtldprUBGGx2Nn4lajIePRHa047WT1WdXmn57Ajsle", server: false # In test we don't send emails. config :discuss, Discuss.Mailer, adapter: Swoosh.Adapters.Test # Print only warnings and errors during test config :logger, level: :warn # Initialize plugs at runtime for faster test compilation config :phoenix, :plug_init_mode, :runtime
31.677419
86
0.761711
08b3721a82d1243e31a3ae3e008425c9633d0f8f
1,999
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/commitment_list_warning_data.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/compute/lib/google_api/compute/v1/model/commitment_list_warning_data.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/compute/lib/google_api/compute/v1/model/commitment_list_warning_data.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Compute.V1.Model.CommitmentListWarningData do @moduledoc """ ## Attributes * `key` (*type:* `String.t`, *default:* `nil`) - [Output Only] A key that provides more detail on the warning being returned. For example, for warnings where there are no results in a list request for a particular zone, this key might be scope and the key value might be the zone name. Other examples might be a key indicating a deprecated resource and a suggested replacement, or a warning about invalid network settings (for example, if an instance attempts to perform IP forwarding but is not enabled for IP forwarding). * `value` (*type:* `String.t`, *default:* `nil`) - [Output Only] A warning data value corresponding to the key. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :key => String.t() | nil, :value => String.t() | nil } field(:key) field(:value) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.CommitmentListWarningData do def decode(value, options) do GoogleApi.Compute.V1.Model.CommitmentListWarningData.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.CommitmentListWarningData do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.98
527
0.738369