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
sequence
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
sequence
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
sequence
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
737eab0734ad01b42abeea59f43122c249cfcb7b
1,373
ex
Elixir
lib/banchan_web/plugs/ensure_role_plug.ex
riamaria/banchan
c4f8bd9374acaf0a8bb2c501e2ae1eb78f96579f
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
lib/banchan_web/plugs/ensure_role_plug.ex
riamaria/banchan
c4f8bd9374acaf0a8bb2c501e2ae1eb78f96579f
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
lib/banchan_web/plugs/ensure_role_plug.ex
riamaria/banchan
c4f8bd9374acaf0a8bb2c501e2ae1eb78f96579f
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
defmodule BanchanWeb.EnsureRolePlug do @moduledoc """ This plug ensures that a user has a particular role before accessing a given route. ## Example Let's suppose we have three roles: :admin, :manager and :user. If you want a user to have at least manager role, so admins and managers are authorised to access a given route plug BanchanWeb.EnsureRolePlug, [:admin, :manager] If you want to give access only to an admin: plug BanchanWeb.EnsureRolePlug, :admin """ import Plug.Conn alias Banchan.Accounts alias Banchan.Accounts.User alias Phoenix.Controller alias Plug.Conn @doc false @spec init(any()) :: any() def init(config), do: config @doc false @spec call(Conn.t(), atom() | [atom()]) :: Conn.t() def call(conn, roles) do user_token = get_session(conn, :user_token) (user_token && Accounts.get_user_by_session_token(user_token)) |> has_role?(roles) |> maybe_halt(conn) end defp has_role?(user, roles) when is_list(roles), do: Enum.any?(roles, &has_role?(user, &1)) defp has_role?(%User{roles: roles}, role), do: Enum.member?(roles, role) defp maybe_halt(true, conn), do: conn defp maybe_halt(_any, conn) do conn |> Controller.put_flash(:error, "Unauthorised") |> Controller.redirect(to: signed_in_path(conn)) |> halt() end defp signed_in_path(_conn), do: "/" end
26.921569
113
0.689731
737eaf7c132b85c557613546db9e4f2ae9150e8d
15,108
ex
Elixir
lib/helios/event_journal/adapters/memory.ex
exponentially/helios
3a7b66bd95a8c53c500272eb8a269a73e6de6d8a
[ "Apache-2.0" ]
12
2018-09-20T21:33:07.000Z
2020-01-14T19:31:11.000Z
lib/helios/event_journal/adapters/memory.ex
exponentially/helios
3a7b66bd95a8c53c500272eb8a269a73e6de6d8a
[ "Apache-2.0" ]
null
null
null
lib/helios/event_journal/adapters/memory.ex
exponentially/helios
3a7b66bd95a8c53c500272eb8a269a73e6de6d8a
[ "Apache-2.0" ]
null
null
null
defmodule Helios.EventJournal.Adapter.Memory do @moduledoc """ Simple memory event journal adapter. Events are kept in ETS table """ use GenServer require Logger # alias Helios.EventJournal.Messages.EventData alias Helios.EventJournal.Messages.ReadStreamEventsResponse alias Helios.EventJournal.Messages.ReadAllEventsResponse alias Helios.EventJournal.Messages.PersistedEvent alias Helios.EventJournal.Messages.Position alias Helios.EventJournal.Messages.StreamMetadataResponse @behaviour Helios.EventJournal.Adapter @max_event_no 9_223_372_036_854_775_807 @streams "Streams" @events "Events" @all "$all" @impl true def start_link(module, config, opts \\ []) do opts = Keyword.put(opts, :name, module) GenServer.start_link(__MODULE__, {module, config}, opts) end @impl Helios.EventJournal.Adapter def append_to_stream(server, stream, events, expexted_version) do GenServer.call(server, {:append_to_stream, stream, events, expexted_version}) end @impl Helios.EventJournal.Adapter def read_event(server, stream, event_number, _resolve_links \\ false) do # fun = # :ets.fun2ms(fn {idx, stream_id, sequence_number, event_id, event_type, data, metadata, # created} # when stream_id == stream and sequence_number == event_number -> # {idx, stream_id, sequence_number, event_id, event_type, data, metadata, created} # end) meta = get_stream_metadata(server, stream) fun = [ {{:"$1", :"$2", :"$3", :"$4", :"$5", :"$6", :"$7", :"$8"}, [{:andalso, {:==, :"$2", {:const, stream}}, {:==, :"$3", {:const, event_number}}}], [{{:"$1", :"$2", :"$3", :"$4", :"$5", :"$6", :"$7", :"$8"}}]} ] res = :ets.select(events(server), fun) case {res, meta} do {[head | _], _} -> to_persisted(head) {[], {:ok, %{is_deleted: true}}} -> {:error, :stream_deleted} {[], {:ok, %{is_deleted: false}}} -> {:error, :no_stream} {[], {:error, error}} -> {:error, error} end end @impl Helios.EventJournal.Adapter def read_stream_events_forward( server, stream, event_number, max_events, _resolve_links \\ false ) do # TODO: read stream metadata and check if $maxAge, or similar metadata is set there # so we can skeep events that should be scavaged later # fun = # :ets.fun2ms(fn {idx, stream_id, sequence_number, event_id, event_type, data, metadata, # created} # when stream_id == stream and sequence_number >= event_number and sequence_number <= max_events -> # {idx, stream_id, sequence_number, event_id, event_type, data, metadata, created} # end) event_number = if event_number < 0, do: 0, else: event_number last_event_number = event_number + max_events fun = [ {{:"$1", :"$2", :"$3", :"$4", :"$5", :"$6", :"$7", :"$8"}, [ {:andalso, {:andalso, {:==, :"$2", {:const, stream}}, {:>=, :"$3", {:const, event_number}}}, {:<, :"$3", {:const, last_event_number}}} ], [{{:"$1", :"$2", :"$3", :"$4", :"$5", :"$6", :"$7", :"$8"}}]} ] persisted_events = server |> events() |> :ets.select(fun) |> Enum.map(&elem(to_persisted(&1), 1)) last_event_number = get_stream_event_number(server, stream) last_commit_position = get_idx(server) case List.last(persisted_events) do nil -> {:ok, %ReadStreamEventsResponse{ events: persisted_events, next_event_number: -1, last_event_number: last_event_number, is_end_of_stream: true, last_commit_position: last_commit_position }} event -> {:ok, %ReadStreamEventsResponse{ events: persisted_events, next_event_number: if( last_event_number > event.event_number, do: event.event_number + 1, else: event.event_number ), last_event_number: last_event_number, is_end_of_stream: true, last_commit_position: last_commit_position }} end end @impl Helios.EventJournal.Adapter def read_stream_events_backward( server, stream, event_number, max_events, _resolve_links \\ false ) do # fun = # :ets.fun2ms(fn {idx, stream_id, sequence_number, event_id, event_type, data, metadata, # created} # when stream_id == stream and sequence_number <= event_number and sequence_number >= max_events -> # {idx, stream_id, sequence_number, event_id, event_type, data, metadata, created} # end) last_event_number = event_number - max_events fun = [ {{:"$1", :"$2", :"$3", :"$4", :"$5", :"$6", :"$7", :"$8"}, [ {:andalso, {:andalso, {:==, :"$2", {:const, stream}}, {:"=<", :"$3", {:const, event_number}}}, {:>, :"$3", {:const, last_event_number}}} ], [{{:"$1", :"$2", :"$3", :"$4", :"$5", :"$6", :"$7", :"$8"}}]} ] persisted_events = server |> events() |> :ets.select(fun) |> Enum.map(&elem(to_persisted(&1), 1)) |> Enum.reverse() last_event_number = get_stream_event_number(server, stream) last_commit_position = get_idx(server) case List.last(persisted_events) do nil -> {:ok, %ReadStreamEventsResponse{ events: persisted_events, next_event_number: -1, last_event_number: last_event_number, is_end_of_stream: TRUE, last_commit_position: last_commit_position }} event -> {:ok, %ReadStreamEventsResponse{ events: persisted_events, next_event_number: if( last_event_number > event.event_number, do: event.event_number + 1, else: event.event_number ), last_event_number: last_event_number, is_end_of_stream: true, last_commit_position: last_commit_position }} end end @impl Helios.EventJournal.Adapter def read_all_events_forward(server, {commit_position, _}, max_events, _resolve_links \\ false) do last_commit_position = get_idx(server) commit_position = if commit_position <= -1 do last_commit_position + 1 else commit_position end from_position = commit_position until_position = commit_position + max_events fun = [ {{:"$1", :"$2", :"$3", :"$4", :"$5", :"$6", :"$7", :"$8"}, [ {:andalso, {:andalso, {:>=, :"$1", {:const, from_position}}}, {:<, :"$1", {:const, until_position}}} ], [{{:"$1", :"$2", :"$3", :"$4", :"$5", :"$6", :"$7", :"$8"}}]} ] persisted_events = server |> events() |> :ets.select(fun) |> Enum.map(&elem(to_persisted(&1), 1)) case List.last(persisted_events) do nil -> {:ok, %ReadAllEventsResponse{ commit_position: -1, prepare_position: -1, events: [], next_commit_position: -1, next_prepare_position: -1 }} event -> pos = event.position.commit_position next_pos = if( last_commit_position > pos, do: pos + 1, else: pos ) {:ok, %ReadAllEventsResponse{ commit_position: pos, prepare_position: pos, events: persisted_events, next_commit_position: next_pos, next_prepare_position: next_pos }} end end @impl Helios.EventJournal.Adapter def read_all_events_backward(server, {commit_position, _}, max_events, _resolve_links \\ false) do last_commit_position = get_idx(server) commit_position = if commit_position < 0 or commit_position >= last_commit_position do last_commit_position else commit_position end from_position = commit_position - max_events until_position = commit_position fun = [ {{:"$1", :"$2", :"$3", :"$4", :"$5", :"$6", :"$7", :"$8"}, [ {:andalso, {:andalso, {:>=, :"$1", {:const, from_position}}}, {:<, :"$1", {:const, until_position}}} ], [{{:"$1", :"$2", :"$3", :"$4", :"$5", :"$6", :"$7", :"$8"}}]} ] persisted_events = server |> events() |> :ets.select(fun) |> Enum.map(&elem(to_persisted(&1), 1)) case List.last(persisted_events) do nil -> {:ok, %ReadAllEventsResponse{ commit_position: -1, prepare_position: -1, events: [], next_commit_position: -1, next_prepare_position: -1 }} event -> pos = event.position.commit_position next_pos = if( last_commit_position > pos, do: pos + 1, else: pos ) {:ok, %ReadAllEventsResponse{ commit_position: pos, prepare_position: pos, events: persisted_events, next_commit_position: next_pos, next_prepare_position: next_pos }} end end @impl Helios.EventJournal.Adapter def delete_stream(server, stream, expected_version, hard_delete?) do GenServer.call(server, {:delete_stream, stream, expected_version, hard_delete?}) end @impl Helios.EventJournal.Adapter def set_stream_metadata(server, stream, metadata, expexted_version) do GenServer.call(server, {:set_stream_metadata, stream, metadata, expexted_version}) end @impl Helios.EventJournal.Adapter def get_stream_metadata(server, stream) do case :ets.lookup(streams(server), stream) do [{^stream, sequence_no, meta} | _] -> {:ok, sequence_no} {:ok, StreamMetadataResponse.new( stream, false, sequence_no, meta || %{} )} [] -> {:error, :no_stream} end end # SERVER @impl GenServer def init({module, _}) do :ets.new(streams(module), [:set, :protected, :named_table]) :ets.new(events(module), [:ordered_set, :protected, :named_table]) {:ok, %{module: module}} end @impl GenServer def handle_call({:append_to_stream, stream, events, expected_ver}, _, s) do do_append_to_stream( stream, events, expected_ver, get_idx(s.module), get_stream_event_number(s.module, stream), s ) end def handle_call({:delete_stream, stream, expected_version, hard_delete?}, _, s) do # :ets.fun2ms(fn # {idx, stream_id, sequence_number, event_id, event_type, data, metadata, created} when stream_id == stream -> # {idx} # end) last_event_number = get_stream_event_number(s.module, stream) if expected_version == last_event_number do fun = [ {{:"$1", :"$2", :"$3", :"$4", :"$5", :"$6", :"$7", :"$8"}, [{:==, :"$2", {:const, stream}}], [{{:"$1"}}]} ] persisted = s.module |> events() |> :ets.select(fun) persisted |> Enum.each(fn {idx} -> :ets.delete(events(s.module), idx) end) case {List.last(persisted), last_event_number} do {nil, num} when num > -1 and num < @max_event_no -> {:reply, {:ok, :no_stream}, s} {nil, num} when num == @max_event_no -> {:reply, {:error, :stream_deleted}, s} {idx, _num} -> if hard_delete? do {:ok, sm} = get_stream_metadata(s.module, stream) :ets.insert(streams(s.module), {stream, @max_event_no, sm.metadata}) end pos = %Position{commit_position: idx, prepare_position: idx} {:reply, {:ok, pos}, s} end else {:reply, {:error, :wrong_expected_version}, s} end end def handle_call({:set_stream_metadata, stream, metadata, expexted_version}, _from, s) do event_number = get_stream_event_number(s.module, stream) :ets.insert(streams(s.module), {stream, event_number, metadata}) {:reply, {:ok, expexted_version + 1}, s} end defp do_append_to_stream( _stream, _events, _expexted_version, _last_event_number, stream_event_number, s ) when stream_event_number == @max_event_no do {:reply, {:error, :stream_deleted}, s} end defp do_append_to_stream( _stream, _events, expexted_version, _last_event_number, stream_event_number, s ) when expexted_version != stream_event_number do {:reply, {:error, :wrong_expected_version}, s} end defp do_append_to_stream( stream, events, expexted_version, last_event_number, stream_event_number, s ) when expexted_version < 0 or expexted_version == stream_event_number do {last_event_number, stream_event_number} = Enum.reduce(events, {last_event_number, stream_event_number}, fn event, {idx, event_number} -> idx = idx + 1 stream_id = stream event_number = event_number + 1 event_id = event.id event_type = event.type data = event.data metadata = event.metadata || %{} created = DateTime.utc_now() true = :ets.insert( events(s.module), {idx, stream_id, event_number, event_id, event_type, data, metadata, created} ) {idx, event_number} end) :ets.insert(streams(s.module), {@all, last_event_number, %{}}) case get_stream_metadata(s.module, stream) do {:ok, r} -> :ets.insert(streams(s.module), {stream, stream_event_number, r.metadata}) _ -> :ets.insert(streams(s.module), {stream, stream_event_number, %{}}) end {:reply, {:ok, stream_event_number}, s} end defp streams(module) do Module.concat(module, @streams) end @spec events(module) :: module defp events(module) do Module.concat(module, @events) end defp get_idx(module) do case :ets.lookup(streams(module), @all) do [] -> -1 [{@all, event_number, _} | _] -> event_number end end defp get_stream_event_number(module, stream) do case :ets.lookup(streams(module), stream) do [] -> -1 [{^stream, event_number, _} | _] -> event_number end end defp to_persisted({idx, stream_id, event_number, event_id, event_type, data, metadata, created}) do response = %PersistedEvent{ stream_id: stream_id, event_number: event_number, event_id: event_id, event_type: event_type, data: data, metadata: metadata, position: %Position{ commit_position: idx, prepare_position: idx }, created: created } {:ok, response} end end
28.722433
120
0.567977
737ed516a4e83437740758f4baae5731f74f7232
2,122
ex
Elixir
lib/wechat_pay/client.ex
linjunpop/wechat_pay
8db9a5882e87ed0ac899b806f556540423028a1c
[ "MIT" ]
55
2016-10-19T09:01:39.000Z
2019-03-23T12:40:21.000Z
lib/wechat_pay/client.ex
linjunpop/wechat_pay
8db9a5882e87ed0ac899b806f556540423028a1c
[ "MIT" ]
11
2017-05-19T05:08:53.000Z
2019-03-22T11:54:30.000Z
lib/wechat_pay/client.ex
linjunpop/wechat_pay
8db9a5882e87ed0ac899b806f556540423028a1c
[ "MIT" ]
9
2017-01-05T04:17:21.000Z
2019-02-18T03:52:05.000Z
defmodule WechatPay.Client do @moduledoc """ API client. """ alias WechatPay.Client @enforce_keys [:app_id, :mch_id, :api_key] defstruct api_host: "https://api.mch.weixin.qq.com/", app_id: nil, mch_id: nil, api_key: nil, sign_type: :md5, ssl: nil @type t :: %Client{ api_host: String.t(), app_id: String.t(), mch_id: String.t(), api_key: String.t(), sign_type: :md5 | :sha256, ssl: [ {:ca_cert, String.t() | nil}, {:cert, String.t()}, {:key, String.t()} ] } @sign_types [:md5, :sha256] @doc """ Build a new client from options. ## Example iex>WechatPay.Client.new(app_id: "APP_ID", mch_id: "MCH_ID", api_key: "API_KEY", sign_type: :sha256) {:ok, %WechatPay.Client{ api_host: "https://api.mch.weixin.qq.com/", api_key: "API_KEY", app_id: "APP_ID", mch_id: "MCH_ID", sign_type: :sha256, ssl: nil }} """ @spec new(Enum.t()) :: {:ok, Client.t()} | {:error, binary()} def new(opts) do attrs = Enum.into(opts, %{}) with :ok <- validate_opts(attrs), client = struct(Client, attrs) do {:ok, client} end end @enforce_keys |> Enum.each(fn key -> defp unquote(:"validate_#{key}")(%{unquote(key) => value}) when not is_nil(value) do :ok end defp unquote(:"validate_#{key}")(_) do {:error, "please set `#{unquote(key)}`"} end end) defp validate_sign_type(%{sign_type: sign_type}) when sign_type in @sign_types do :ok end defp validate_sign_type(%{sign_type: sign_type}) do {:error, "`#{sign_type}` is invalid for `sign_type`, available options: `:md5` and `:sha256`."} end defp validate_sign_type(_) do :ok end defp validate_opts(attrs) when is_map(attrs) do with :ok <- validate_app_id(attrs), :ok <- validate_mch_id(attrs), :ok <- validate_api_key(attrs), :ok <- validate_sign_type(attrs) do :ok end end end
23.577778
106
0.549482
737ed9e03a302429eb94ef70ebec94d89cb82d06
10,167
ex
Elixir
deps/plug_cowboy/lib/plug/cowboy.ex
rpillar/Top5_Elixir
9c450d2e9b291108ff1465dc066dfe442dbca822
[ "MIT" ]
null
null
null
deps/plug_cowboy/lib/plug/cowboy.ex
rpillar/Top5_Elixir
9c450d2e9b291108ff1465dc066dfe442dbca822
[ "MIT" ]
null
null
null
deps/plug_cowboy/lib/plug/cowboy.ex
rpillar/Top5_Elixir
9c450d2e9b291108ff1465dc066dfe442dbca822
[ "MIT" ]
null
null
null
defmodule Plug.Cowboy do @moduledoc """ Adapter interface to the Cowboy2 webserver. ## Options * `:ip` - the ip to bind the server to. Must be either a tuple in the format `{a, b, c, d}` with each value in `0..255` for IPv4, or a tuple in the format `{a, b, c, d, e, f, g, h}` with each value in `0..65535` for IPv6, or a tuple in the format `{:local, path}` for a unix socket at the given `path`. * `:port` - the port to run the server. Defaults to 4000 (http) and 4040 (https). Must be 0 when `:ip` is a `{:local, path}` tuple. * `:dispatch` - manually configure Cowboy's dispatch. If this option is used, the given plug won't be initialized nor dispatched to (and doing so becomes the user's responsibility). * `:ref` - the reference name to be used. Defaults to `plug.HTTP` (http) and `plug.HTTPS` (https). This is the value that needs to be given on shutdown. * `:compress` - Cowboy will attempt to compress the response body. Defaults to false. * `:timeout` - Time in ms with no requests before Cowboy closes the connection. Defaults to 5000ms. * `:protocol_options` - Specifies remaining protocol options, see [Cowboy docs](https://ninenines.eu/docs/en/cowboy/2.5/manual/cowboy_http/). * `:transport_options` - A keyword list specifying transport options, see [ranch docs](https://ninenines.eu/docs/en/ranch/1.6/manual/ranch/). By default `:num_acceptors` will be set to `100` and `:max_connections` to `16_384`. All other options are given as `:socket_opts` to the underlying transport. When running on HTTPS, any SSL configuration should be given directly to the adapter. See `https/3` for an example and read `Plug.SSL.configure/1` to understand about our SSL defaults. When using a unix socket, OTP 21+ is required for `Plug.Static` and `Plug.Conn.send_file/3` to behave correctly. """ require Logger @doc false def start(_type, _args) do Logger.add_translator({Plug.Cowboy.Translator, :translate}) Supervisor.start_link([], strategy: :one_for_one) end # Made public with @doc false for testing. @doc false def args(scheme, plug, plug_opts, cowboy_options) do {cowboy_options, non_keyword_options} = Enum.split_with(cowboy_options, &match?({_, _}, &1)) cowboy_options |> set_compress() |> normalize_cowboy_options(scheme) |> to_args(scheme, plug, plug_opts, non_keyword_options) end @doc """ Runs cowboy under http. ## Example # Starts a new interface Plug.Cowboy.http MyPlug, [], port: 80 # The interface above can be shutdown with Plug.Cowboy.shutdown MyPlug.HTTP """ @spec http(module(), Keyword.t(), Keyword.t()) :: {:ok, pid} | {:error, :eaddrinuse} | {:error, term} def http(plug, opts, cowboy_options \\ []) do run(:http, plug, opts, cowboy_options) end @doc """ Runs cowboy under https. Besides the options described in the module documentation, this modules sets defaults and accepts all options defined in `Plug.SSL.configure/2`. ## Example # Starts a new interface Plug.Cowboy.https MyPlug, [], port: 443, password: "SECRET", otp_app: :my_app, keyfile: "priv/ssl/key.pem", certfile: "priv/ssl/cert.pem", dhfile: "priv/ssl/dhparam.pem" # The interface above can be shutdown with Plug.Cowboy.shutdown MyPlug.HTTPS """ @spec https(module(), Keyword.t(), Keyword.t()) :: {:ok, pid} | {:error, :eaddrinuse} | {:error, term} def https(plug, opts, cowboy_options \\ []) do Application.ensure_all_started(:ssl) run(:https, plug, opts, cowboy_options) end @doc """ Shutdowns the given reference. """ def shutdown(ref) do :cowboy.stop_listener(ref) end @transport_options [ :connection_type, :handshake_timeout, :max_connections, :logger, :num_acceptors, :shutdown, :socket, :socket_opts, # Special cases supported by plug but not ranch :acceptors ] @doc """ A function for starting a Cowboy2 server under Elixir v1.5 supervisors. It expects three options: * `:scheme` - either `:http` or `:https` * `:plug` - such as MyPlug or {MyPlug, plug_opts} * `:options` - the server options as specified in the module documentation ## Examples Assuming your Plug module is named `MyApp` you can add it to your supervision tree by using this function: children = [ {Plug.Cowboy, scheme: :http, plug: MyApp, options: [port: 4040]} ] Supervisor.start_link(children, strategy: :one_for_one) """ def child_spec(opts) do scheme = Keyword.fetch!(opts, :scheme) cowboy_opts = Keyword.get(opts, :options, []) {plug, plug_opts} = case Keyword.fetch!(opts, :plug) do {_, _} = tuple -> tuple plug -> {plug, []} end cowboy_args = args(scheme, plug, plug_opts, cowboy_opts) [ref, transport_opts, proto_opts] = cowboy_args {ranch_module, cowboy_protocol, transport_opts} = case scheme do :http -> {:ranch_tcp, :cowboy_clear, transport_opts} :https -> %{socket_opts: socket_opts} = transport_opts socket_opts = socket_opts |> Keyword.put_new(:next_protocols_advertised, ["h2", "http/1.1"]) |> Keyword.put_new(:alpn_preferred_protocols, ["h2", "http/1.1"]) {:ranch_ssl, :cowboy_tls, %{transport_opts | socket_opts: socket_opts}} end {id, start, restart, shutdown, type, modules} = :ranch.child_spec(ref, ranch_module, transport_opts, cowboy_protocol, proto_opts) %{id: id, start: start, restart: restart, shutdown: shutdown, type: type, modules: modules} end ## Helpers @protocol_options [:timeout, :compress, :stream_handlers] defp run(scheme, plug, opts, cowboy_options) do case Application.ensure_all_started(:cowboy) do {:ok, _} -> nil {:error, {:cowboy, _}} -> raise "could not start the Cowboy application. Please ensure it is listed as a dependency in your mix.exs" end start = case scheme do :http -> :start_clear :https -> :start_tls other -> :erlang.error({:badarg, [other]}) end apply(:cowboy, start, args(scheme, plug, opts, cowboy_options)) end @default_stream_handlers [Plug.Cowboy.Stream] defp set_compress(cowboy_options) do compress = Keyword.get(cowboy_options, :compress) stream_handlers = Keyword.get(cowboy_options, :stream_handlers) case {compress, stream_handlers} do {true, nil} -> Keyword.put_new(cowboy_options, :stream_handlers, [ :cowboy_compress_h | @default_stream_handlers ]) {true, _} -> raise "cannot set both compress and stream_handlers at once. " <> "If you wish to set compress, please add `:cowboy_compress_h` to your stream handlers." _ -> cowboy_options end end defp normalize_cowboy_options(cowboy_options, :http) do Keyword.put_new(cowboy_options, :port, 4000) end defp normalize_cowboy_options(cowboy_options, :https) do cowboy_options |> Keyword.put_new(:port, 4040) |> Plug.SSL.configure() |> case do {:ok, options} -> options {:error, message} -> fail(message) end end defp to_args(opts, scheme, plug, plug_opts, non_keyword_opts) do opts = Keyword.delete(opts, :otp_app) {ref, opts} = Keyword.pop(opts, :ref) {dispatch, opts} = Keyword.pop(opts, :dispatch) {protocol_options, opts} = Keyword.pop(opts, :protocol_options, []) dispatch = :cowboy_router.compile(dispatch || dispatch_for(plug, plug_opts)) {extra_options, opts} = Keyword.split(opts, @protocol_options) extra_options = Keyword.put_new(extra_options, :stream_handlers, @default_stream_handlers) protocol_and_extra_options = :maps.from_list(protocol_options ++ extra_options) protocol_options = Map.merge(%{env: %{dispatch: dispatch}}, protocol_and_extra_options) {transport_options, socket_options} = Keyword.pop(opts, :transport_options, []) option_keys = Keyword.keys(socket_options) for opt <- @transport_options, opt in option_keys do option_deprecation_warning(opt) end {num_acceptors, socket_options} = Keyword.pop(socket_options, :num_acceptors, 100) {num_acceptors, socket_options} = Keyword.pop(socket_options, :acceptors, num_acceptors) {max_connections, socket_options} = Keyword.pop(socket_options, :max_connections, 16_384) socket_options = non_keyword_opts ++ socket_options transport_options = transport_options |> Keyword.put_new(:num_acceptors, num_acceptors) |> Keyword.put_new(:max_connections, max_connections) |> Keyword.update( :socket_opts, socket_options, &(&1 ++ socket_options) ) |> Map.new() [ref || build_ref(plug, scheme), transport_options, protocol_options] end defp build_ref(plug, scheme) do Module.concat(plug, scheme |> to_string |> String.upcase()) end defp dispatch_for(plug, opts) do opts = plug.init(opts) [{:_, [{:_, Plug.Cowboy.Handler, {plug, opts}}]}] end defp fail(message) do raise ArgumentError, "could not start Cowboy2 adapter, " <> message end defp option_deprecation_warning(:acceptors), do: option_deprecation_warning(:acceptors, :num_acceptors) defp option_deprecation_warning(option), do: option_deprecation_warning(option, option) defp option_deprecation_warning(option, expected_option) do warning = "using :#{option} in options is deprecated. Please pass " <> ":#{expected_option} to the :transport_options keyword list instead" IO.warn(warning) end end
32.482428
115
0.643749
737edcf5aae122ab2cd41d09310dc132306f7a10
1,118
ex
Elixir
lib/phoenix_react_starter/application.ex
devin-henslee/phoenix-react-starter
ec1a3b971b4e4c8db960a66fddb67da02811e4ab
[ "MIT" ]
null
null
null
lib/phoenix_react_starter/application.ex
devin-henslee/phoenix-react-starter
ec1a3b971b4e4c8db960a66fddb67da02811e4ab
[ "MIT" ]
null
null
null
lib/phoenix_react_starter/application.ex
devin-henslee/phoenix-react-starter
ec1a3b971b4e4c8db960a66fddb67da02811e4ab
[ "MIT" ]
null
null
null
defmodule PhoenixReactStarter.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do children = [ # Start the Ecto repository PhoenixReactStarter.Repo, # Start the Telemetry supervisor PhoenixReactStarterWeb.Telemetry, # Start the PubSub system {Phoenix.PubSub, name: PhoenixReactStarter.PubSub}, # Start the Endpoint (http/https) PhoenixReactStarterWeb.Endpoint # Start a worker by calling: PhoenixReactStarter.Worker.start_link(arg) # {PhoenixReactStarter.Worker, arg} ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: PhoenixReactStarter.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do PhoenixReactStarterWeb.Endpoint.config_change(changed, removed) :ok end end
31.942857
77
0.730769
737f23160df9908fe8556ec2d3e0cef2cf1930e8
2,006
ex
Elixir
clients/content/lib/google_api/content/v21/model/shopping_ads_program_status.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v21/model/shopping_ads_program_status.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v21/model/shopping_ads_program_status.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.Content.V21.Model.ShoppingAdsProgramStatus do @moduledoc """ Response message for GetShoppingAdsProgramStatus. ## Attributes * `globalState` (*type:* `String.t`, *default:* `nil`) - State of the program. `ENABLED` if there are offers for at least one region. * `regionStatuses` (*type:* `list(GoogleApi.Content.V21.Model.ShoppingAdsProgramStatusRegionStatus.t)`, *default:* `nil`) - Status of the program in each region. Regions with the same status and review eligibility are grouped together in `regionCodes`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :globalState => String.t() | nil, :regionStatuses => list(GoogleApi.Content.V21.Model.ShoppingAdsProgramStatusRegionStatus.t()) | nil } field(:globalState) field(:regionStatuses, as: GoogleApi.Content.V21.Model.ShoppingAdsProgramStatusRegionStatus, type: :list ) end defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.ShoppingAdsProgramStatus do def decode(value, options) do GoogleApi.Content.V21.Model.ShoppingAdsProgramStatus.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.ShoppingAdsProgramStatus do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.472727
256
0.743769
737f480e74b4acceb04a09340b26eb1dcbf47112
1,548
ex
Elixir
lib/hound.ex
manukall/hound
5a96b714b5ae0b64f9cbee3ee4955d209895b92e
[ "MIT" ]
null
null
null
lib/hound.ex
manukall/hound
5a96b714b5ae0b64f9cbee3ee4955d209895b92e
[ "MIT" ]
null
null
null
lib/hound.ex
manukall/hound
5a96b714b5ae0b64f9cbee3ee4955d209895b92e
[ "MIT" ]
null
null
null
defmodule Hound do use Application # See http://elixir-lang.org/docs/stable/Application.Behaviour.html # for more information on OTP Applications @doc false def start(_type, _args) do Hound.Supervisor.start_link end @doc false def driver_info do Hound.ConnectionServer.driver_info end @doc false def configs do Hound.ConnectionServer.configs end @doc """ Starts a Hound session. Use this in your test case's setup block to start a Hound session for each test case. defmodule HoundTest do use ExUnit.Case use Hound.Helpers setup do Hound.start_session :ok end teardown do :ok = Hound.end_session end test "the truth", meta do navigate_to("http://example.com/guestbook.html") find_element(:name, "message") |> fill_field("Happy Birthday ~!") |> submit_element() assert page_title() == "Thank you" end end """ def start_session do Hound.SessionServer.session_for_pid(self) end @doc """ Ends a Hound session. If you have multiple sessions, all of those sessions are killed. For an example, take a look at the documentation for `start_session`. """ def end_session(pid) do Hound.SessionServer.destroy_sessions_for_pid(pid) end def end_session do Hound.SessionServer.destroy_sessions_for_pid(self) end @doc false def current_session_id do Hound.SessionServer.current_session_id(self) end end
20.103896
88
0.660853
737f485c28a605a5273fc5038cd200bbddec04dd
1,185
ex
Elixir
lib/oli/delivery/student/summary.ex
DevShashi1993/oli-torus
e6e0b66f0973f9790a5785731b22db6fb1c50a73
[ "MIT" ]
45
2020-04-17T15:40:27.000Z
2022-03-25T00:13:30.000Z
lib/oli/delivery/student/summary.ex
DevShashi1993/oli-torus
e6e0b66f0973f9790a5785731b22db6fb1c50a73
[ "MIT" ]
944
2020-02-13T02:37:01.000Z
2022-03-31T17:50:07.000Z
lib/oli/delivery/student/summary.ex
DevShashi1993/oli-torus
e6e0b66f0973f9790a5785731b22db6fb1c50a73
[ "MIT" ]
23
2020-07-28T03:36:13.000Z
2022-03-17T14:29:02.000Z
defmodule Oli.Delivery.Student.Summary do alias Oli.Delivery.Sections alias Oli.Delivery.Attempts.Core, as: Attempts alias Oli.Publishing.DeliveryResolver alias Oli.Repo defstruct [:title, :description, :access_map, :hierarchy, :updates] def get_summary(section_slug, user) do with {:ok, section} <- Sections.get_section_by(slug: section_slug) |> Repo.preload([:base_project, :root_section_resource]) |> Oli.Utils.trap_nil(), resource_accesses <- Attempts.get_user_resource_accesses_for_context(section.slug, user.id), hierarchy <- DeliveryResolver.full_hierarchy(section.slug), updates <- Sections.check_for_available_publication_updates(section) do access_map = Enum.reduce(resource_accesses, %{}, fn ra, acc -> Map.put_new(acc, ra.resource_id, ra) end) {:ok, %Oli.Delivery.Student.Summary{ title: section.title, description: section.base_project.description, access_map: access_map, hierarchy: hierarchy, updates: updates }} else _ -> {:error, :not_found} end end end
32.027027
82
0.650633
737f51c9a899c89a101a4525ff035646056a8c09
848
exs
Elixir
wabanex/test/wabanex_web/schema_test.exs
shonorio/nlwt_elixir
029b731c747e4b4954bc0197881b325fb80b4ab6
[ "MIT" ]
null
null
null
wabanex/test/wabanex_web/schema_test.exs
shonorio/nlwt_elixir
029b731c747e4b4954bc0197881b325fb80b4ab6
[ "MIT" ]
null
null
null
wabanex/test/wabanex_web/schema_test.exs
shonorio/nlwt_elixir
029b731c747e4b4954bc0197881b325fb80b4ab6
[ "MIT" ]
null
null
null
defmodule WabanexWeb.SchemaTest do use WabanexWeb.ConnCase, async: true alias Wabanex.User alias Wabanex.Users.Create describe "users queries" do test "when a valid id is given, returns the user", %{conn: conn} do params = %{name: "John Doe", email: "[email protected]", password: "123456"} {:ok, %User{id: user_id}} = Create.call(params) query = """ { getUser(id: "#{user_id}") { name email } } """ response = conn |> post("/api/graphql", %{query: query}) |> json_response(:ok) assert response == %{ "data" => %{ "getUser" => %{ "email" => "[email protected]", "name" => "John Doe" } } } end end end
22.315789
76
0.454009
737f707b32d822dc9b573107c0ac0414393b49d6
1,207
ex
Elixir
lib/okr_app/objectives/store/cycle_store.ex
sb8244/okr_app_pub
933872107bd13390a0a5ea119d7997d4cb5ea7db
[ "MIT" ]
12
2019-05-10T21:48:06.000Z
2021-11-07T14:04:30.000Z
lib/okr_app/objectives/store/cycle_store.ex
sb8244/okr_app_pub
933872107bd13390a0a5ea119d7997d4cb5ea7db
[ "MIT" ]
2
2019-05-14T19:07:10.000Z
2019-05-20T21:06:27.000Z
lib/okr_app/objectives/store/cycle_store.ex
sb8244/okr_app_pub
933872107bd13390a0a5ea119d7997d4cb5ea7db
[ "MIT" ]
3
2019-05-19T18:24:20.000Z
2019-10-31T20:29:12.000Z
defmodule OkrApp.Objectives.CycleStore do import Ecto.Query alias OkrApp.Repo alias OkrApp.Objectives.Cycle def all(params = %{}, opts \\ []) do params = Enum.map(params, fn {k, v} -> {to_string(k), v} end) |> Enum.into(%{}) clean_params = Map.drop(params, ["active", "present_or_future"]) OkrApp.Query.ListQuery.get_query(Cycle, clean_params, opts) |> append_list_query(:present_or_future, Map.has_key?(params, "present_or_future"), Map.get(params, "present_or_future")) |> append_list_query(:active, Map.has_key?(params, "active"), Map.get(params, "active")) |> Repo.all() end def create(params, user: user) do Cycle.changeset(params, user: user) |> Repo.insert() end defp append_list_query(query, _, false, _), do: query defp append_list_query(query, :present_or_future, true, val) when val == true or val == "true" do now = DateTime.utc_now() query |> where(^dynamic([c], c.ends_at >= ^now)) end defp append_list_query(query, :active, true, val) when val == true or val == "true" do now = DateTime.utc_now() query |> where(^dynamic([c], c.starts_at <= ^now)) |> where(^dynamic([c], c.ends_at >= ^now)) end end
30.948718
125
0.655344
737f8352aa414ee9574ca835c054660c6186e7b1
14,655
exs
Elixir
components/notifications-service/server/test/formatters/servicenow_test.exs
fossabot/automate-1
16910c3ebd75ee0aa25e527bfce3e1378306f42d
[ "Apache-2.0" ]
191
2019-04-16T15:04:53.000Z
2022-03-21T14:10:44.000Z
components/notifications-service/server/test/formatters/servicenow_test.exs
fossabot/automate-1
16910c3ebd75ee0aa25e527bfce3e1378306f42d
[ "Apache-2.0" ]
4,882
2019-04-16T16:16:01.000Z
2022-03-31T15:39:35.000Z
components/notifications-service/server/test/formatters/servicenow_test.exs
fossabot/automate-1
16910c3ebd75ee0aa25e527bfce3e1378306f42d
[ "Apache-2.0" ]
114
2019-04-16T15:21:27.000Z
2022-03-26T09:50:08.000Z
defmodule Notifications.Formatters.ServiceNow.Test do use ExUnit.Case, async: false doctest Notifications.Formatters.ServiceNow alias Notifications.Formatters.ServiceNow describe "#format" do test "that a populated CCR notification creates the correct webhook paylaod" do exception_backtrace = [ "/Users/aleff/projects/chef/lib/chef/mixin/why_run.rb:240:in `run'", "/Users/aleff/projects/chef/lib/chef/mixin/why_run.rb:321:in `block in run'", "/Users/aleff/projects/chef/lib/chef/mixin/why_run.rb:320:in `each'", "/Users/aleff/projects/chef/lib/chef/mixin/why_run.rb:320:in `run'", "/Users/aleff/projects/chef/lib/chef/provider.rb:155:in `process_resource_requirements'", "/Users/aleff/projects/chef/lib/chef/provider.rb:133:in `run_action'", "/Users/aleff/projects/chef/lib/chef/resource.rb:591:in `run_action'", "/Users/aleff/projects/chef/lib/chef/runner.rb:69:in `run_action'", "/Users/aleff/projects/chef/lib/chef/runner.rb:97:in `block (2 levels) in converge'", "/Users/aleff/projects/chef/lib/chef/runner.rb:97:in `each'", "/Users/aleff/projects/chef/lib/chef/runner.rb:97:in `block in converge'", "/Users/aleff/projects/chef/lib/chef/resource_collection/resource_list.rb:94:in `block in execute_each_resource'", "/Users/aleff/projects/chef/lib/chef/resource_collection/stepable_iterator.rb:116:in `call'", "/Users/aleff/projects/chef/lib/chef/resource_collection/stepable_iterator.rb:116:in `call_iterator_block'", "/Users/aleff/projects/chef/lib/chef/resource_collection/stepable_iterator.rb:85:in `step'", "/Users/aleff/projects/chef/lib/chef/resource_collection/stepable_iterator.rb:104:in `iterate'", "/Users/aleff/projects/chef/lib/chef/resource_collection/stepable_iterator.rb:55:in `each_with_index'", "/Users/aleff/projects/chef/lib/chef/resource_collection/resource_list.rb:92:in `execute_each_resource'", "/Users/aleff/projects/chef/lib/chef/runner.rb:96:in `converge'", "/Users/aleff/projects/chef/lib/chef/client.rb:669:in `block in converge'", "/Users/aleff/projects/chef/lib/chef/client.rb:664:in `catch'", "/Users/aleff/projects/chef/lib/chef/client.rb:664:in `converge'", "/Users/aleff/projects/chef/lib/chef/client.rb:703:in `converge_and_save'", "/Users/aleff/projects/chef/lib/chef/client.rb:283:in `run'", "/Users/aleff/projects/chef/lib/chef/application.rb:286:in `block in fork_chef_client'", "/Users/aleff/projects/chef/lib/chef/application.rb:274:in `fork'", "/Users/aleff/projects/chef/lib/chef/application.rb:274:in `fork_chef_client'", "/Users/aleff/projects/chef/lib/chef/application.rb:239:in `block in run_chef_client'", "/Users/aleff/projects/chef/lib/chef/local_mode.rb:44:in `with_server_connectivity'", "/Users/aleff/projects/chef/lib/chef/application.rb:227:in `run_chef_client'", "/Users/aleff/projects/chef/lib/chef/application/client.rb:456:in `sleep_then_run_chef_client'", "/Users/aleff/projects/chef/lib/chef/application/client.rb:443:in `block in interval_run_chef_client'", "/Users/aleff/projects/chef/lib/chef/application/client.rb:442:in `loop'", "/Users/aleff/projects/chef/lib/chef/application/client.rb:442:in `interval_run_chef_client'", "/Users/aleff/projects/chef/lib/chef/application/client.rb:426:in `run_application'", "/Users/aleff/projects/chef/lib/chef/application.rb:59:in `run'", "/Users/aleff/projects/chef/bin/chef-client:26:in `<top (required)>'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/bin/chef-client:22:in `load'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/bin/chef-client:22:in `<top (required)>'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/cli/exec.rb:63:in `load'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/cli/exec.rb:63:in `kernel_load'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/cli/exec.rb:24:in `run'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/cli.rb:304:in `exec'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/cli.rb:11:in `start'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/exe/bundle:27:in `block in <top (required)>'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/friendly_errors.rb:98:in `with_friendly_errors'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/exe/bundle:19:in `<top (required)>'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/bin/bundle:22:in `load'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/bin/bundle:22:in `<main>'" ] notification = %Notifications.CCRFailure{ run_id: "", node_name: "insights.chef.co", node_url: "chef-server.insights.co", run_url: "https://localhost/nodes/0271e125-97dd-498a-b026-8448ee60aafe/runs/ba6acb91-1eaa-4c84-8d68-f19ee641e606", cookbook: "test-cookbook", recipe: "", time: %Notifications.TimeInfo{start_time: "2016-06-28T20:05:29.000000Z", end_time: "2016-06-28T20:05:30.000000Z"}, timestamp: "2016-06-28T20:05:31.000000Z", exception: %Notifications.ExceptionInfo{class: "", title: "Error executing action `create` on resource 'file[/failed/file/resource]'", msg: "file[/failed/file/resource] (insights-test::default line 26) had an error: Chef::Exceptions::EnclosingDirectoryDoesNotExist: Parent directory /failed/file does not exist.", backtrace: exception_backtrace}} expected = %{automate_failure_url: "https://localhost/nodes/0271e125-97dd-498a-b026-8448ee60aafe/runs/ba6acb91-1eaa-4c84-8d68-f19ee641e606", automate_fqdn: "http://localhost", cookbook: "test-cookbook", end_time_utc: "2016-06-28T20:05:30.000000Z", exception_message: "file[/failed/file/resource] (insights-test::default line 26) had an error: Chef::Exceptions::EnclosingDirectoryDoesNotExist: Parent directory /failed/file does not exist.", exception_title: "Error executing action `create` on resource 'file[/failed/file/resource]'", failure_snippet: "Chef client run failure on [chef-server.insights.co] insights.chef.co : https://localhost/nodes/0271e125-97dd-498a-b026-8448ee60aafe/runs/ba6acb91-1eaa-4c84-8d68-f19ee641e606\nError executing action `create` on resource 'file[/failed/file/resource]'\nfile[/failed/file/resource] (insights-test::default line 26) had an error: Chef::Exceptions::EnclosingDirectoryDoesNotExist: Parent directory /failed/file does not exist. \n", node_name: "insights.chef.co", start_time_utc: "2016-06-28T20:05:29.000000Z", type: "converge_failure", timestamp_utc: "2016-06-28T20:05:31.000000Z", exception_backtrace: exception_backtrace } assert expected == ServiceNow.format(notification) end test "that a populated CCR notification with no failed resources creates the correct webhook payload" do exception_backtrace = [ "/Users/aleff/projects/chef/lib/chef/mixin/why_run.rb:240:in `run'", "/Users/aleff/projects/chef/lib/chef/mixin/why_run.rb:321:in `block in run'", "/Users/aleff/projects/chef/lib/chef/mixin/why_run.rb:320:in `each'", "/Users/aleff/projects/chef/lib/chef/mixin/why_run.rb:320:in `run'", "/Users/aleff/projects/chef/lib/chef/provider.rb:155:in `process_resource_requirements'", "/Users/aleff/projects/chef/lib/chef/provider.rb:133:in `run_action'", "/Users/aleff/projects/chef/lib/chef/resource.rb:591:in `run_action'", "/Users/aleff/projects/chef/lib/chef/runner.rb:69:in `run_action'", "/Users/aleff/projects/chef/lib/chef/runner.rb:97:in `block (2 levels) in converge'", "/Users/aleff/projects/chef/lib/chef/runner.rb:97:in `each'", "/Users/aleff/projects/chef/lib/chef/runner.rb:97:in `block in converge'", "/Users/aleff/projects/chef/lib/chef/resource_collection/resource_list.rb:94:in `block in execute_each_resource'", "/Users/aleff/projects/chef/lib/chef/resource_collection/stepable_iterator.rb:116:in `call'", "/Users/aleff/projects/chef/lib/chef/resource_collection/stepable_iterator.rb:116:in `call_iterator_block'", "/Users/aleff/projects/chef/lib/chef/resource_collection/stepable_iterator.rb:85:in `step'", "/Users/aleff/projects/chef/lib/chef/resource_collection/stepable_iterator.rb:104:in `iterate'", "/Users/aleff/projects/chef/lib/chef/resource_collection/stepable_iterator.rb:55:in `each_with_index'", "/Users/aleff/projects/chef/lib/chef/resource_collection/resource_list.rb:92:in `execute_each_resource'", "/Users/aleff/projects/chef/lib/chef/runner.rb:96:in `converge'", "/Users/aleff/projects/chef/lib/chef/client.rb:669:in `block in converge'", "/Users/aleff/projects/chef/lib/chef/client.rb:664:in `catch'", "/Users/aleff/projects/chef/lib/chef/client.rb:664:in `converge'", "/Users/aleff/projects/chef/lib/chef/client.rb:703:in `converge_and_save'", "/Users/aleff/projects/chef/lib/chef/client.rb:283:in `run'", "/Users/aleff/projects/chef/lib/chef/application.rb:286:in `block in fork_chef_client'", "/Users/aleff/projects/chef/lib/chef/application.rb:274:in `fork'", "/Users/aleff/projects/chef/lib/chef/application.rb:274:in `fork_chef_client'", "/Users/aleff/projects/chef/lib/chef/application.rb:239:in `block in run_chef_client'", "/Users/aleff/projects/chef/lib/chef/local_mode.rb:44:in `with_server_connectivity'", "/Users/aleff/projects/chef/lib/chef/application.rb:227:in `run_chef_client'", "/Users/aleff/projects/chef/lib/chef/application/client.rb:456:in `sleep_then_run_chef_client'", "/Users/aleff/projects/chef/lib/chef/application/client.rb:443:in `block in interval_run_chef_client'", "/Users/aleff/projects/chef/lib/chef/application/client.rb:442:in `loop'", "/Users/aleff/projects/chef/lib/chef/application/client.rb:442:in `interval_run_chef_client'", "/Users/aleff/projects/chef/lib/chef/application/client.rb:426:in `run_application'", "/Users/aleff/projects/chef/lib/chef/application.rb:59:in `run'", "/Users/aleff/projects/chef/bin/chef-client:26:in `<top (required)>'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/bin/chef-client:22:in `load'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/bin/chef-client:22:in `<top (required)>'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/cli/exec.rb:63:in `load'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/cli/exec.rb:63:in `kernel_load'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/cli/exec.rb:24:in `run'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/cli.rb:304:in `exec'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/cli.rb:11:in `start'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/exe/bundle:27:in `block in <top (required)>'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/lib/bundler/friendly_errors.rb:98:in `with_friendly_errors'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/gems/bundler-1.12.5/exe/bundle:19:in `<top (required)>'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/bin/bundle:22:in `load'", "/Users/aleff/.chefdk/gem/ruby/2.1.0/bin/bundle:22:in `<main>'" ] notification = %Notifications.CCRFailure{ run_id: "", node_name: "insights.chef.co", node_url: "chef-server.insights.co", run_url: "https://localhost/nodes/0271e125-97dd-498a-b026-8448ee60aafe/runs/ba6acb91-1eaa-4c84-8d68-f19ee641e606", cookbook: "", recipe: "", time: %Notifications.TimeInfo{start_time: "2016-06-28T20:05:29.000000Z", end_time: "2016-06-28T20:05:30.000000Z"}, timestamp: "2016-06-28T20:05:31.000000Z", exception: %Notifications.ExceptionInfo{class: "RuntimeError", title: "", msg: "", backtrace: exception_backtrace}} expected = %{automate_failure_url: "https://localhost/nodes/0271e125-97dd-498a-b026-8448ee60aafe/runs/ba6acb91-1eaa-4c84-8d68-f19ee641e606", automate_fqdn: "http://localhost", cookbook: "", end_time_utc: "2016-06-28T20:05:30.000000Z", exception_message: "", exception_title: "", failure_snippet: "Chef client run failure on [chef-server.insights.co] insights.chef.co : https://localhost/nodes/0271e125-97dd-498a-b026-8448ee60aafe/runs/ba6acb91-1eaa-4c84-8d68-f19ee641e606\n\n \n", node_name: "insights.chef.co", start_time_utc: "2016-06-28T20:05:29.000000Z", type: "converge_failure", timestamp_utc: "2016-06-28T20:05:31.000000Z", exception_backtrace: exception_backtrace } assert expected == ServiceNow.format(notification) end end end
79.216216
454
0.671307
737fe147fc009aa1029d91a59cce2295c61a8af0
529
exs
Elixir
config/test.exs
w0rd-driven/scratch_phoenix
465e01af6e7d649bfb308edf91247e9d6c6a5876
[ "MIT" ]
null
null
null
config/test.exs
w0rd-driven/scratch_phoenix
465e01af6e7d649bfb308edf91247e9d6c6a5876
[ "MIT" ]
null
null
null
config/test.exs
w0rd-driven/scratch_phoenix
465e01af6e7d649bfb308edf91247e9d6c6a5876
[ "MIT" ]
null
null
null
use Mix.Config # We don't run a server during test. If one is required, # you can enable the server option below. config :scratch_phoenix, ScratchPhoenix.Endpoint, http: [port: 4001], server: false # Print only warnings and errors during test config :logger, level: :warn # Configure your database config :scratch_phoenix, ScratchPhoenix.Repo, adapter: Ecto.Adapters.Postgres, username: "postgres", password: "postgres", database: "scratch_phoenix_test", hostname: "localhost", pool: Ecto.Adapters.SQL.Sandbox
26.45
56
0.752363
73801b8ddca4dabed4a64dc2a283a1c766d2c5f8
1,123
ex
Elixir
test/support/channel_case.ex
integratedb/core
0b4a7a38d014e5ae973a1fa807c137834dfdf9cb
[ "MIT" ]
13
2021-01-28T14:45:43.000Z
2021-11-04T21:54:19.000Z
test/support/channel_case.ex
integratedb/integrate
0b4a7a38d014e5ae973a1fa807c137834dfdf9cb
[ "MIT" ]
null
null
null
test/support/channel_case.ex
integratedb/integrate
0b4a7a38d014e5ae973a1fa807c137834dfdf9cb
[ "MIT" ]
null
null
null
defmodule IntegrateWeb.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use IntegrateWeb.ChannelCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with channels import Phoenix.ChannelTest import IntegrateWeb.ChannelCase # The default endpoint for testing @endpoint IntegrateWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Integrate.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Integrate.Repo, {:shared, self()}) end :ok end end
27.390244
71
0.730187
738037568eb9db5b471217f29bd54bc421ef8acb
11,304
ex
Elixir
lib/elixir/lib/record.ex
ekosz/elixir
62e375bc711b4072e1b68de776e96cc31f571d45
[ "Apache-2.0" ]
1
2017-10-29T16:37:08.000Z
2017-10-29T16:37:08.000Z
lib/elixir/lib/record.ex
ekosz/elixir
62e375bc711b4072e1b68de776e96cc31f571d45
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/record.ex
ekosz/elixir
62e375bc711b4072e1b68de776e96cc31f571d45
[ "Apache-2.0" ]
null
null
null
defmodule Record do @moduledoc """ Functions to define and interact with Erlang records """ @doc """ Extract record information from an Erlang file and return the fields as a list of tuples. ## Examples defrecord FileInfo, Record.extract(:file_info, from_lib: "kernel/include/file.hrl") """ def extract(name, opts) do Record.Extractor.retrieve(name, opts) end @doc """ Implements the access macro used by records. It returns a quoted expression that represents the access given by the keywords. """ def access(caller, atom, fields, keyword) do unless is_orddict(keyword) do raise "expected contents inside brackets to be a Keyword" end in_match = caller.in_match? has_underscore_value = Keyword.key?(keyword, :_) underscore_value = Keyword.get(keyword, :_, { :_, 0, nil }) keyword = Keyword.delete keyword, :_ iterator = fn({field, default}, each_keyword) -> new_fields = case Keyword.key?(each_keyword, field) do true -> Keyword.get(each_keyword, field) false -> case in_match or has_underscore_value do true -> underscore_value false -> Macro.escape(default) end end { new_fields, Keyword.delete(each_keyword, field) } end { match, remaining } = :lists.mapfoldl(iterator, keyword, fields) case remaining do [] -> { :{}, caller.line, [atom|match] } _ -> keys = lc { key, _ } inlist remaining, do: key raise "record #{inspect atom} does not have the keys: #{inspect keys}" end end defp is_orddict(list) when is_list(list), do: :lists.all(is_orddict_tuple(&1), list) defp is_orddict(_), do: false defp is_orddict_tuple({ x, _ }) when is_atom(x), do: true defp is_orddict_tuple(_), do: false @doc """ Main entry point for records definition. This is invoked directly by `Kernel.defrecord`. Returns the quoted expression of a module given by name. """ def defrecord(name, values, opts) do moduledoc = Keyword.get(opts, :moduledoc, false) block = Keyword.get(opts, :do) definition = Keyword.get(opts, :definition, Record.Definition) quote do defmodule unquote(name) do @moduledoc unquote(moduledoc) Record.define_functions(__ENV__, unquote(values), unquote(definition)) unquote(block) end end end @doc false # Private endpoint that defines the functions for the Record. def define_functions(env, values, definition) do # Escape the values so they are valid syntax nodes values = Macro.escape(values) contents = [ reflection(values), getters_and_setters(values, 1, [], definition), initializers(values), converters(values) ] Module.eval_quoted env, contents end # Define __record__/1 and __record__/2 as reflection functions # that returns the record names and fields. # # Note that fields are *not* keywords. They are in the same # order as given as parameter and reflects the order of the # fields in the tuple. # # ## Examples # # defrecord FileInfo, atime: nil, mtime: nil # # FileInfo.__record__(:name) #=> FileInfo # FileInfo.__record__(:fields) #=> [atime: nil, mtime: nil] # defp reflection(values) do quote do def __access__(caller, args), do: Record.access(caller, __MODULE__, __record__(:fields), args) def __record__(kind, _), do: __record__(kind) def __record__(:name), do: __MODULE__ def __record__(:fields), do: unquote(values) end end # Define initializers methods. For a declaration like: # # defrecord FileInfo, atime: nil, mtime: nil # # It will define three methods: # # def new() do # new([]) # end # # def new([]) do # { FileInfo, nil, nil } # end # # def new(opts) do # { FileInfo, Keyword.get(opts, :atime), Keyword.get(opts, :mtime) } # end # defp initializers(values) do defaults = lc value inlist values, do: elem(value, 2) # For each value, define a piece of code that will receive # an ordered dict of options (opts) and it will try to fetch # the given key from the ordered dict, falling back to the # default value if one does not exist. selective = lc { k, v } inlist values do quote do: Keyword.get(opts, unquote(k), unquote(v)) end quote do def new(), do: new([]) def new([]), do: { __MODULE__, unquote_splicing(defaults) } def new(opts) when is_list(opts), do: { __MODULE__, unquote_splicing(selective) } def new(tuple) when is_tuple(tuple), do: setelem(tuple, 1, __MODULE__) end end # Define converters method(s). For a declaration like: # # defrecord FileInfo, atime: nil, mtime: nil # # It will define one method, to_keywords, which will return a Keyword # # [atime: nil, mtime: nil] # defp converters(values) do sorted = lc { k, _ } inlist values do index = find_index(values, k, 1) { k, quote(do: :erlang.element(unquote(index + 1), record)) } end quote do def to_keywords(record) do unquote(:orddict.from_list(sorted)) end end end defp find_index([{ k, _ }|_], k, i), do: i defp find_index([{ _, _ }|t], k, i), do: find_index(t, k, i + 1) # Implement getters and setters for each attribute. # For a declaration like: # # defrecord FileInfo, atime: nil, mtime: nil # # It will define four methods: # # def :atime.(record) do # elem(record, 2) # end # # def :atime.(record, value) do # setelem(record, 2, value) # end # # def :mtime.(record) do # elem(record, 3) # end # # def :mtime.(record, value) do # setelem(record, value, 3) # end # # `element` and `setelement` will simply get and set values # from the record tuple. Notice that `:atime.(record)` is just # a dynamic way to say `atime(record)`. We need to use this # syntax as `unquote(key)(record)` wouldn't be valid (as Elixir # allows you to parenthesis just on specific cases as `foo()` # and `foo.bar()`) defp getters_and_setters([{ key, default }|t], i, acc, definition) do i = i + 1 functions = definition.functions_for(key, default, i) getters_and_setters(t, i, [functions | acc], definition) end defp getters_and_setters([], _i, acc, _), do: acc end defmodule Record.Extractor do @moduledoc false # Retrieve a record definition from an Erlang file using # the same lookup as the *include* attribute from Erlang modules. def retrieve(name, from: string) do file = to_char_list(string) case Erlang.code.where_is_file(file) do :non_existing -> realfile = file realfile -> nil end retrieve_record(name, realfile) end # Retrieve a record definition from an Erlang file using # the same lookup as the *include_lib* attribute from Erlang modules. def retrieve(name, from_lib: file) do [app|path] = Erlang.filename.split(to_char_list(file)) case Erlang.code.lib_dir(to_char_list(app)) do { :error, _ } -> raise ArgumentError, "Lib file #{to_binary(file)} could not be found" libpath -> retrieve_record name, Erlang.filename.join([libpath|path]) end end # Retrieve the record with the given name from the given file defp retrieve_record(name, file) do records = retrieve_from_file(file) if record = List.keyfind(records, name, 1) do parse_record(record) else raise ArgumentError, "No record #{name} found at #{to_binary(file)}" end end # Parse the given file and retrieve all existent records. defp retrieve_from_file(file) do lc { :attribute, _, :record, record } inlist read_file(file), do: record end # Read a file and return its abstract syntax form that also # includes record and other preprocessor modules. This is done # by using Erlang's epp_dodger. defp read_file(file) do case Erlang.epp_dodger.quick_parse_file(file) do { :ok, form } -> form other -> raise "Error parsing file #{to_binary(file)}, got: #{inspect(other)}" end end # Parse a tuple with name and fields and returns a # list of second order tuples where the first element # is the field and the second is its default value. defp parse_record({ _name, fields }) do cons = List.foldr fields, { nil, 0 }, fn f, acc -> { :cons, 0, parse_field(f), acc } end { :value, list, _ } = Erlang.erl_eval.expr(cons, []) list end defp parse_field({ :typed_record_field, record_field, _type }) do parse_field(record_field) end defp parse_field({ :record_field, _, key }) do { :tuple, 0, [key, {:atom, 0, :nil}] } end defp parse_field({ :record_field, _, key, value }) do { :tuple, 0, [key, value] } end end defmodule Record.Definition do @moduledoc false # Main entry point. It defines both default functions # via `default_for` and extensions via `extension_for`. def functions_for(key, default, i) do [ default_for(key, default, i), extension_for(key, default, i) ] end # Skip the __exception__ for defexception. def default_for(:__exception__, _default, _i) do nil end # Define the default functions for each field. def default_for(key, _default, i) do bin_update = "update_" <> atom_to_binary(key) update = binary_to_atom(bin_update) quote do def unquote(key).(record) do :erlang.element(unquote(i), record) end def unquote(key).(value, record) do :erlang.setelement(unquote(i), record, value) end def unquote(update).(function, record) do current = :erlang.element(unquote(i), record) :erlang.setelement(unquote(i), record, function.(current)) end end end # Define extensions based on the default type. def extension_for(key, default, i) when is_list(default) do bin_key = atom_to_binary(key) prepend = :"prepend_#{bin_key}" merge = :"merge_#{bin_key}" quote do def unquote(prepend).(value, record) do current = :erlang.element(unquote(i), record) :erlang.setelement(unquote(i), record, value ++ current) end def unquote(merge).(value, record) do current = :erlang.element(unquote(i), record) :erlang.setelement(unquote(i), record, Keyword.merge(current, value)) end end end def extension_for(key, default, i) when is_number(default) do bin_key = atom_to_binary(key) increment = :"increment_#{bin_key}" quote do def unquote(increment).(value // 1, record) do current = :erlang.element(unquote(i), record) :erlang.setelement(unquote(i), record, current + value) end end end def extension_for(key, default, i) when is_boolean(default) do bin_key = atom_to_binary(key) toggle = :"toggle_#{bin_key}" quote do def unquote(toggle).(value // false, record) do current = :erlang.element(unquote(i), record) :erlang.setelement(unquote(i), record, not current) end end end def extension_for(_, _, _), do: nil end
29.361039
100
0.642516
73804189e178573c6286daa1f3ef3b2ce7dbf6e9
5,744
ex
Elixir
lib/beam_notify.ex
nerves-networking/beam_notify
e821f0341d18c398ed8d49785a6350e789d0dc25
[ "Apache-2.0" ]
9
2021-01-20T00:45:10.000Z
2021-07-14T21:39:06.000Z
lib/beam_notify.ex
nerves-networking/beam_notify
e821f0341d18c398ed8d49785a6350e789d0dc25
[ "Apache-2.0" ]
3
2021-10-11T18:48:48.000Z
2022-01-24T15:40:28.000Z
lib/beam_notify.ex
nerves-networking/beam_notify
e821f0341d18c398ed8d49785a6350e789d0dc25
[ "Apache-2.0" ]
null
null
null
defmodule BEAMNotify do use GenServer require Logger @moduledoc """ Send a message to the BEAM from a shell script """ @typedoc """ Callback for dispatching notifications BEAMNotify calls the dispatcher function whenever a message comes in. The first parameter is the list of arguments passed to `$BEAM_NOTIFY`. The second argument is a map containing environment variables. Whether or not the map is populated depends on the options to `start_link/1`. """ @type dispatcher() :: ([String.t()], %{String.t() => String.t()} -> :ok) @typedoc """ BEAMNotify takes the following options * `:name` - a unique name for this notifier. This is required if you expect to run multiple BEAMNotify GenServers at a time. * `:dispatcher` - a function to call when a notification comes in * `:path` - the path to use for the named socket. A path in the system temporary directory is the default. * `:mode` - the permissions to apply to the socket. Should be an octal number eg: 0o660 for read/write owner/group, no access to everyone else * `:report_env` - set to `true` to report environment variables in addition to commandline argument. Defaults to `false` * `:recbuf` - receive buffer size. If you're sending a particular large amount of data and getting errors from `:erlang.binary_to_term(data)`, try making this bigger. Defaults to 8192. """ @type options() :: [ name: binary() | atom(), path: Path.t(), mode: non_neg_integer(), dispatcher: dispatcher(), report_env: boolean(), recbuf: non_neg_integer() ] @doc """ Start the BEAMNotify message receiver """ @spec start_link(options()) :: GenServer.on_start() def start_link(options) do name = options |> name_from_options() |> gen_server_name() GenServer.start_link(__MODULE__, options, name: name) end @doc """ Return the OS environment needed to call `$BEAM_NOTIFY` This returns a map that can be passed directly to `System.cmd/3` via its `:env` option. This function can be passed different things based on what's convenient. 1. If you're setting up `child_spec`'s for a supervision tree and need the environment to pass in another `child_spec`, call this with the same options that you'd pass to `start_link/1`. This is a very common use. 2. If you called `start_link/1` manually and have the pid, call it with the pid. 3. If you only have the name that was passed to `start_link/1`, then call it with the name. The name alone is insufficient for returning the `$BEAM_NOTIFY_OPTIONS` environment variable, so the `BEAMNotify` GenServer must be running. If you're in a chicken-and-egg situation where you're setting up a supervision tree, but it hasn't been started yet, see option 1. """ @spec env(pid() | binary() | atom() | keyword()) :: Enumerable.t() def env(options) when is_list(options) do options_to_env(options) end def env(pid) when is_pid(pid) do GenServer.call(pid, :env) end def env(name) when is_binary(name) or is_atom(name) do GenServer.call(gen_server_name(name), :env) end @doc """ Return the path to `beam_notify` """ @spec bin_path() :: Path.t() def bin_path() do Application.app_dir(:beam_notify, ["priv", "beam_notify"]) end @impl GenServer def init(options) do socket_path = socket_path(options) dispatcher = Keyword.get(options, :dispatcher, &null_dispatcher/2) recbuf = Keyword.get(options, :recbuf, 8192) mode = Keyword.get(options, :mode) # Blindly try to remove an old file just in case it exists from a previous run _ = File.rm(socket_path) _ = File.mkdir_p(Path.dirname(socket_path)) {:ok, socket} = :gen_udp.open(0, [ :local, :binary, {:active, true}, {:ip, {:local, socket_path}}, {:recbuf, recbuf} ]) if mode, do: File.chmod!(socket_path, mode) state = %{ socket_path: socket_path, socket: socket, options: options, dispatcher: dispatcher } {:ok, state} end @impl GenServer def handle_call(:env, _from, state) do {:reply, options_to_env(state.options), state} end @impl GenServer def handle_info({:udp, socket, _, 0, data}, %{socket: socket} = state) do {args, env} = :erlang.binary_to_term(data) state.dispatcher.(args, env) {:noreply, state} end @impl GenServer def terminate(_reason, state) do # Try to clean up _ = File.rm(state.socket_path) end defp gen_server_name(name) do Module.concat(__MODULE__, name) end defp name_from_options(options) do Keyword.get(options, :name, :unnamed) end defp null_dispatcher(args, env) do Logger.warn("beam_notify called with no dispatcher: #{inspect(args)}, #{inspect(env)}") end defp options_to_env(options) do bn_options = options_to_cmdline(options) |> Enum.map(&quote_string/1) |> Enum.join(" ") %{"BEAM_NOTIFY" => bin_path(), "BEAM_NOTIFY_OPTIONS" => bn_options} end defp options_to_cmdline(options) do ["-p", socket_path(options)] ++ report_env_arg(options) end defp report_env_arg(options) do if Keyword.get(options, :report_env) do ["-e"] else [] end end defp quote_string(s) do if String.contains?(s, " ") do "\"" <> s <> "\"" else s end end defp socket_path(options) do case Keyword.get(options, :path) do nil -> safe_name = name_from_options(options) |> :erlang.phash2() |> Integer.to_string() name = "beam_notify-" <> safe_name Path.join(System.tmp_dir!(), name) path -> path end end end
29.15736
91
0.660341
738079639a7fce11ab570798d9eceb327d9b8ea3
6,066
ex
Elixir
lib/flashfeed/news/crawler.ex
alexiob/flashfeed-elixir
72e83c47f556072d26f4a3f195026c2e5b4cd442
[ "MIT" ]
4
2020-02-27T14:29:20.000Z
2021-04-03T19:08:50.000Z
lib/flashfeed/news/crawler.ex
alexiob/flashfeed-elixir
72e83c47f556072d26f4a3f195026c2e5b4cd442
[ "MIT" ]
6
2020-02-17T21:35:04.000Z
2021-09-02T06:46:46.000Z
lib/flashfeed/news/crawler.ex
alexiob/flashfeed-elixir
72e83c47f556072d26f4a3f195026c2e5b4cd442
[ "MIT" ]
null
null
null
defmodule Flashfeed.News.Crawler do @moduledoc false use GenServer require Logger alias Flashfeed.News.Crawler.Utilities alias Flashfeed.News.Sources @fetch_feed_task_timeout 10_000 @crawler_engine_module_signature "Elixir.Flashfeed.News.Crawler.Engine." @topic_entity_feeds "entity_feeds" def start_link(_) do GenServer.start_link(__MODULE__, nil, name: __MODULE__) end @impl true def init(_) do state = init_state(%{}) Logger.debug("Flashfeed.News.Crawler.init") {:ok, state, {:continue, :crawl}} end @doc """ This is public so it can be used in tests. Is this the proper approach? """ def init_state(state) do entities = Sources.load() state |> Map.put(:entities, entities) |> Map.put(:entity_feeds_last_update, nil) |> Map.put(:entity_feeds, %{}) |> Map.put(:crawler_engines, retrieve_crawler_engines()) end @doc """ Updates the `entity_feeds` state entry with the latest news feeds, if any. """ def update(state) do state |> crawl_entities() end def subscribe do Logger.debug("Flashfeed.News.Crawler.subscribe: #{inspect(self())}") Phoenix.PubSub.subscribe(Flashfeed.PubSub, @topic_entity_feeds) end # CLIENT FUNCTIONS @doc """ List available feeds """ def entity_feeds do GenServer.call(__MODULE__, {:entity_feeds}) end @doc """ Get last time the feeds where updated """ def entity_feeds_last_update do GenServer.call(__MODULE__, {:entity_feeds_last_update}) end @doc """ Gets the feed """ def feed(%{outlet: _, source: _, country: _, region: _, name: _, format: format} = entry_fields) do entity_key = Utilities.entity_key(entry_fields) GenServer.call(__MODULE__, {:feed, entity_key, format}) end # MESSAGE HANDLERS @impl true def handle_continue(:crawl, state) do {:noreply, crawl(state)} end @impl true def handle_call({:entity_feeds}, _from, state) do {:reply, state.entity_feeds, state} end @impl true def handle_call({:entity_feeds_last_update}, _from, state) do {:reply, state.entity_feeds_last_update, state} end @impl true def handle_call({:feed, entity_key, format}, _from, state) do {reply, state} = case Map.get(state.entity_feeds, entity_key, nil) do nil -> {{:error, :unknown_key}, state} feed -> {feed_to_format(feed, format), state} end {:reply, reply, state} end @impl true def handle_info(:crawl, state) do {:noreply, crawl(state)} end # Public, for testing purposes @doc """ Supported formats are: * :amazon_alexa """ def feed_to_format(feed, format) do case format do :amazon_alexa -> {:ok, feed_to_amazon_alexa(feed)} :google_assistant -> {:ok, feed_to_google_assistant(feed)} _ -> {:error, "unknown '#{format}' feed format "} end end defp feed_to_amazon_alexa(feed) do feed_entry = %{ "uid" => feed.uuid, "updateDate" => feed.update_date, "titleText" => feed.title_text, "mainText" => feed.main_text, "streamUrl" => feed.url, "redirectionUrl" => feed.redirection_url } [feed_entry] end defp feed_to_google_assistant(_feed) do throw("not implemented") end # PRIVATE FUNCTIONS defp crawl(state) do state |> update() |> notify_updated_feeds() |> schedule_update() end defp schedule_update(state) do Process.send_after( self(), :crawl, Application.get_env(:flashfeed, :crawler_every_seconds, 3600) * 1000 ) state end defp entity_crawler(entity, state) do Task.async(fn -> # Logger.debug( # "Flashfeed.News.Crawler.crawl: entity '#{entity.name}-#{entity.country}-#{entity.region}'" # ) crawler = Map.get(state.crawler_engines, entity.crawler, nil) if crawler do case crawler.fetch(entity) do {:ok, new_entity_feeds} -> entity_feeds = crawler.update(state.entity_feeds, new_entity_feeds) {:ok, entity_feeds} {:error, reason} -> {:error, "Flashfeed.News.Crawler.crawl: entity '#{entity.name}' crawler engine '#{ entity.crawler }' errored as #{inspect(reason)}"} end else {:error, "Flashfeed.News.Crawler.crawl: entity '#{entity.name}' has an unknown crawler engine named '#{ entity.crawler }'"} end end) end defp crawl_entities(state) do Logger.info("Flashfeed.News.Crawler.crawl_entities: started at #{DateTime.utc_now()}") entity_feeds = Enum.map(state.entities, fn entity -> entity_crawler(entity, state) end) |> Enum.map(fn task -> Task.await(task, @fetch_feed_task_timeout) end) feeds = Keyword.get_values(entity_feeds, :ok) errors = Keyword.get_values(entity_feeds, :error) Enum.each(errors, fn error -> Logger.error(error) end) entity_feeds = case length(feeds) do 0 -> Map.get(state, :entity_feeds, %{}) _ -> Enum.reduce(feeds, %{}, fn feed, acc -> Map.merge(acc, feed) end) end %{state | entity_feeds: entity_feeds, entity_feeds_last_update: NaiveDateTime.local_now()} end defp notify_updated_feeds(state) do Phoenix.PubSub.broadcast( Flashfeed.PubSub, @topic_entity_feeds, %{event: :feeds_update, state: state} ) state end # Scans all modules in search for the ones starting with the given prefix. # The engine name is the lowercase version of the last module name part. defp retrieve_crawler_engines do with {:ok, modules_list} <- :application.get_key(:flashfeed, :modules) do modules_list |> Enum.filter(fn module -> module |> to_string |> String.starts_with?(@crawler_engine_module_signature) end) |> Enum.reduce(%{}, fn module, acc -> Map.put(acc, Module.split(module) |> List.last() |> String.downcase(), module) end) end end end
24.658537
103
0.639466
738079be8a194310d92ab4160b1a5a7adc208446
1,696
ex
Elixir
clients/translate/lib/google_api/translate/v3/model/detect_language_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/translate/lib/google_api/translate/v3/model/detect_language_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/translate/lib/google_api/translate/v3/model/detect_language_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.Translate.V3.Model.DetectLanguageResponse do @moduledoc """ The response message for language detection. ## Attributes * `languages` (*type:* `list(GoogleApi.Translate.V3.Model.DetectedLanguage.t)`, *default:* `nil`) - The most probable language detected by the Translation API. For each request, the Translation API will always return only one result. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :languages => list(GoogleApi.Translate.V3.Model.DetectedLanguage.t()) } field(:languages, as: GoogleApi.Translate.V3.Model.DetectedLanguage, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Translate.V3.Model.DetectLanguageResponse do def decode(value, options) do GoogleApi.Translate.V3.Model.DetectLanguageResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Translate.V3.Model.DetectLanguageResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.085106
237
0.756486
7380920336ea0229329c1c9078d03a264f0870a2
20,869
ex
Elixir
lib/clickhousex/codec/binary/extractor.ex
sofakingworld/clickhousex
0c067499a2638dfb08e6949cfa916fec968159d1
[ "Apache-2.0" ]
null
null
null
lib/clickhousex/codec/binary/extractor.ex
sofakingworld/clickhousex
0c067499a2638dfb08e6949cfa916fec968159d1
[ "Apache-2.0" ]
null
null
null
lib/clickhousex/codec/binary/extractor.ex
sofakingworld/clickhousex
0c067499a2638dfb08e6949cfa916fec968159d1
[ "Apache-2.0" ]
1
2020-08-14T18:44:50.000Z
2020-08-14T18:44:50.000Z
defmodule Clickhousex.Codec.Binary.Extractor do @moduledoc """ Allows modules that `use` this module to create efficient extractor functions that speak clickhouse's binary protocol. To define extractors, annotate a function with the `extract` attribute like this: @extract length: :varint def extract_length(<<data::binary>>, length, other_param) do do_something_with_length(data, length, other_param) end def do_something_with_length(_data, length, other_param) do {other_param, length} end In the above example, a function named `extract_length/2` will be created, which, when passed a binary, will extract the length varint from it, and call the function above, passing the unparsed part of the binary and the extracted length varint to it. Usage looks like this {:ok, binary_from_network} = :gen_tcp.recv(conn, 0) {:this_is_passed_along, length} = extract_length(binary_from_network, :this_is_passed_along) If there isn't enough data to parse, a resume tuple is returned. The second element of the tuple is a function that when called with more data, picks up the parse operation where it left off. {:resume, resume_fn} = extract_length(<<>>, :this_is_passed_along) {:ok, data} = :gen_tcp.recv(conn, 0) {:this_is_passed_along, length} = resume_fn.(data) # Performance All functions generated by this module take advantage of binary optimizations, resuse match contexts and won't create sub-binaries. # Completeness The following extractors are implemented: 1. Variable length integers `:varint` 1. Signed integers: `:i8`, `:i16`, `:i32`, `i64` 1. Unsigned integers: `:u8`, `:u16`, `:u32`, `:u64` 1. Floats: `:f32`, `:f64` 1. Strings: `:string` 1. Booleans: `:boolean` 1. Dates: `:date`, `:datetime` 1. Lists of the above scalar types `{:list, scalar}` 1. Nullable instances of all the above `{:nullable, scalar}` or `{:list, {:nullable, scalar}}` """ defmacro __using__(_) do quote do use Bitwise Module.register_attribute(__MODULE__, :extract, accumulate: true) Module.register_attribute(__MODULE__, :extractors, accumulate: true) @on_definition {unquote(__MODULE__), :on_definition} @before_compile unquote(__MODULE__) end end @doc false defmacro __before_compile__(env) do for {name, visibility, args, [extractors]} <- Module.get_attribute(env.module, :extractors), {arg_name, arg_type} <- extractors do [_ | non_binary_args] = args extractor_args = reject_argument(non_binary_args, arg_name) landing_call = quote do unquote(name)(rest, unquote_splicing(non_binary_args)) end extractor_fn_name = unique_name(name) jump_functions = build_jump_fn(name, extractor_fn_name, extractor_args) |> rewrite_visibility(visibility) |> collapse_blocks() extractors = arg_type |> build_extractor(arg_name, extractor_fn_name, landing_call, args) |> rewrite_visibility(visibility) quote do unquote_splicing(jump_functions) unquote(extractors) end end |> collapse_blocks() end @doc false def on_definition(env, visibility, name, args, _guards, _body) do extractors = Module.get_attribute(env.module, :extract) Module.delete_attribute(env.module, :extract) Module.put_attribute(env.module, :extractors, {name, visibility, args, extractors}) end defp build_jump_fn(base_fn_name, extractor_fn_name, extractor_args) do quote do def unquote(base_fn_name)(<<>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_fn_name)(&1, unquote_splicing(extractor_args))} end def unquote(base_fn_name)(<<rest::binary>>, unquote_splicing(extractor_args)) do unquote(extractor_fn_name)(rest, unquote_splicing(extractor_args)) end end end defp build_extractor(:varint, arg_name, extractor_name, landing_call, [_ | non_binary_args]) do extractor_args = reject_argument(non_binary_args, arg_name) int_variable = Macro.var(arg_name, nil) quote do def unquote(extractor_name)(<<>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_name)(&1, unquote_splicing(extractor_args))} end def unquote(extractor_name)( <<0::size(1), unquote(int_variable)::size(7), rest::binary>>, unquote_splicing(extractor_args) ) do unquote(landing_call) end def unquote(extractor_name)( <<1::size(1), a::size(7), 0::size(1), b::size(7), rest::binary>>, unquote_splicing(extractor_args) ) do unquote(int_variable) = b <<< 7 ||| a unquote(landing_call) end def unquote(extractor_name)( <<1::size(1), a::size(7), 1::size(1), b::size(7), 0::size(1), c::size(7), rest::binary>>, unquote_splicing(extractor_args) ) do unquote(int_variable) = c <<< 14 ||| b <<< 7 ||| a unquote(landing_call) end def unquote(extractor_name)( <<1::size(1), a::size(7), 1::size(1), b::size(7), 1::size(1), c::size(7), 0::size(1), d::size(7), rest::binary>>, unquote_splicing(extractor_args) ) do unquote(int_variable) = d <<< 21 ||| c <<< 14 ||| b <<< 7 ||| a unquote(landing_call) end def unquote(extractor_name)( <<1::size(1), a::size(7), 1::size(1), b::size(7), 1::size(1), c::size(7), 1::size(1), d::size(7), 0::size(1), e::size(7), rest::binary>>, unquote_splicing(extractor_args) ) do unquote(int_variable) = e <<< 28 ||| d <<< 21 ||| c <<< 14 ||| b <<< 7 ||| a unquote(landing_call) end def unquote(extractor_name)( <<1::size(1), a::size(7), 1::size(1), b::size(7), 1::size(1), c::size(7), 1::size(1), d::size(7), 1::size(1), e::size(7), 0::size(1), f::size(7), rest::binary>>, unquote_splicing(extractor_args) ) do unquote(int_variable) = f <<< 35 ||| e <<< 28 ||| d <<< 21 ||| c <<< 14 ||| b <<< 7 ||| a unquote(landing_call) end def unquote(extractor_name)( <<1::size(1), a::size(7), 1::size(1), b::size(7), 1::size(1), c::size(7), 1::size(1), d::size(7), 1::size(1), e::size(7), 1::size(1), f::size(7), 0::size(1), g::size(7), rest::binary>>, unquote_splicing(extractor_args) ) do unquote(int_variable) = g <<< 42 ||| f <<< 35 ||| e <<< 28 ||| d <<< 21 ||| c <<< 14 ||| b <<< 7 ||| a unquote(landing_call) end def unquote(extractor_name)( <<1::size(1), a::size(7), 1::size(1), b::size(7), 1::size(1), c::size(7), 1::size(1), d::size(7), 1::size(1), e::size(7), 1::size(1), f::size(7), 1::size(1), g::size(7), 0::size(1), h::size(7), rest::binary>>, unquote_splicing(extractor_args) ) do unquote(int_variable) = h <<< 49 ||| g <<< 42 ||| f <<< 35 ||| e <<< 28 ||| d <<< 21 ||| c <<< 14 ||| b <<< 7 ||| a unquote(landing_call) end def unquote(extractor_name)( <<1::size(1), a::size(7), 1::size(1), b::size(7), 1::size(1), c::size(7), 1::size(1), d::size(7), 1::size(1), e::size(7), 1::size(1), f::size(7), 1::size(1), g::size(7), 1::size(1), h::size(7), 0::size(1), i::size(7), rest::binary>>, unquote_splicing(extractor_args) ) do unquote(int_variable) = i <<< 56 ||| h <<< 49 ||| g <<< 42 ||| f <<< 35 ||| e <<< 28 ||| d <<< 21 ||| c <<< 14 ||| b <<< 7 ||| a unquote(landing_call) end def unquote(extractor_name)( <<1::size(1), a::size(7), 1::size(1), b::size(7), 1::size(1), c::size(7), 1::size(1), d::size(7), 1::size(1), e::size(7), 1::size(1), f::size(7), 1::size(1), g::size(7), 1::size(1), h::size(7), 1::size(1), i::size(7), 0::size(1), j::size(7), rest::binary>>, unquote_splicing(extractor_args) ) do unquote(int_variable) = j <<< 63 ||| i <<< 56 ||| h <<< 49 ||| g <<< 42 ||| f <<< 35 ||| e <<< 28 ||| d <<< 21 ||| c <<< 14 ||| b <<< 7 ||| a unquote(landing_call) end def unquote(extractor_name)(<<rest::binary>>, unquote_splicing(extractor_args)) do {:resume, fn more_data -> unquote(extractor_name)(rest <> more_data, unquote_splicing(extractor_args)) end} end end end @int_extractors [ {:i64, :signed, 64}, {:u64, :unsigned, 64}, {:i32, :signed, 32}, {:u32, :unsigned, 32}, {:i16, :signed, 16}, {:u16, :unsigned, 16}, {:i8, :signed, 8}, {:u8, :unsigned, 8} ] for {type_name, signed, width} <- @int_extractors do defp build_extractor(unquote(type_name), arg_name, extractor_name, landing_call, [_ | args]) do extractor_args = reject_argument(args, arg_name) value_variable = Macro.var(arg_name, nil) width = unquote(width) signedness = Macro.var(unquote(signed), nil) match = quote do <<unquote(value_variable)::little-unquote(signedness)-size(unquote(width)), rest::binary>> end quote do def unquote(extractor_name)(unquote(match), unquote_splicing(extractor_args)) do unquote(landing_call) end def unquote(extractor_name)(<<>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_name)(&1, unquote_splicing(extractor_args))} end def unquote(extractor_name)(<<data::binary>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_name)(data <> &1, unquote_splicing(extractor_args))} end end end end # Float extractors for width <- [32, 64], type_name = :"f#{width}" do defp build_extractor(unquote(type_name), arg_name, extractor_name, landing_call, [_ | args]) do extractor_args = reject_argument(args, arg_name) value_variable = Macro.var(arg_name, nil) width = unquote(width) quote do def unquote(extractor_name)( <<unquote(value_variable)::little-signed-float-size(unquote(width)), rest::binary>>, unquote_splicing(extractor_args) ) do unquote(landing_call) end def unquote(extractor_name)(<<>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_name)(&1, unquote_splicing(extractor_args))} end def unquote(extractor_name)(<<rest::binary>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_name)(rest <> &1, unquote_splicing(extractor_args))} end end end end defp build_extractor(:boolean, arg_name, extractor_name, landing_call, [_ | args]) do extractor_args = reject_argument(args, arg_name) value_variable = Macro.var(arg_name, nil) quote do def unquote(extractor_name)(<<1, rest::binary>>, unquote_splicing(extractor_args)) do unquote(value_variable) = true unquote(landing_call) end def unquote(extractor_name)(<<0, rest::binary>>, unquote_splicing(extractor_args)) do unquote(value_variable) = false unquote(landing_call) end def unquote(extractor_name)(<<>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_name)(&1, unquote_splicing(extractor_args))} end end end defp build_extractor(:date, arg_name, extractor_name, landing_call, [_ | args]) do extractor_args = reject_argument(args, arg_name) value_variable = Macro.var(arg_name, nil) quote do def unquote(extractor_name)( <<days_since_epoch::little-unsigned-size(16), rest::binary>>, unquote_splicing(extractor_args) ) do {:ok, date} = Date.new(1970, 01, 01) unquote(value_variable) = Date.add(date, days_since_epoch) unquote(landing_call) end def unquote(extractor_name)(<<>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_name)(&1, unquote_splicing(extractor_args))} end def unquote(extractor_name)(<<rest::binary>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_name)(rest <> &1, unquote_splicing(extractor_args))} end end end defp build_extractor(:datetime, arg_name, extractor_name, landing_call, [_ | args]) do extractor_args = reject_argument(args, arg_name) value_variable = Macro.var(arg_name, nil) quote do def unquote(extractor_name)( <<seconds_since_epoch::little-unsigned-size(32), rest::binary>>, unquote_splicing(extractor_args) ) do {:ok, date_time} = NaiveDateTime.new(1970, 1, 1, 0, 0, 0) unquote(value_variable) = NaiveDateTime.add(date_time, seconds_since_epoch) unquote(landing_call) end def unquote(extractor_name)(<<>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_name)(&1, unquote_splicing(extractor_args))} end def unquote(extractor_name)(<<rest::binary>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_name)(rest <> &1, unquote_splicing(extractor_args))} end end end defp build_extractor({:nullable, type}, arg_name, extractor_name, landing_call, [_ | non_binary_args] = args) do extractor_args = reject_argument(non_binary_args, arg_name) value_variable = Macro.var(arg_name, nil) value_extractor_name = :"#{extractor_name}_value" value_extractors = type |> build_extractor(arg_name, value_extractor_name, landing_call, args) |> collapse_blocks() quote do unquote_splicing(value_extractors) def unquote(extractor_name)(<<>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_name)(&1, unquote_splicing(extractor_args))} end def unquote(extractor_name)(<<0, rest::binary>>, unquote_splicing(extractor_args)) do unquote(value_extractor_name)(rest, unquote_splicing(extractor_args)) end def unquote(extractor_name)(<<1, rest::binary>>, unquote_splicing(extractor_args)) do unquote(value_variable) = nil unquote(landing_call) end end end defp build_extractor(:string, arg_name, extractor_name, landing_call, [binary_arg | non_binary_args]) do extractor_args = reject_argument(non_binary_args, arg_name) length_variable_name = unique_name("string_length") length_variable = Macro.var(length_variable_name, nil) length_extractor_name = :"#{extractor_name}_length" length_extractor_args = extractor_args length_landing_call = quote do unquote(extractor_name)(rest, unquote_splicing(extractor_args), unquote(length_variable)) end length_extractors = build_extractor( :varint, length_variable_name, length_extractor_name, length_landing_call, [binary_arg | length_extractor_args] ++ [length_variable] ) |> collapse_blocks() value_arg = Macro.var(arg_name, nil) # The string extractor call chain looks like this: # top_level function -> length_extractor -> value_extractor quote do # Size exctractors unquote_splicing(length_extractors) # Value extractors # Empty string optimization, prevents concatenating large data to an empty string and # reallocating the large data def unquote(extractor_name)(<<>>, unquote_splicing(extractor_args), unquote(length_variable)) do {:resume, &unquote(extractor_name)(&1, unquote_splicing(extractor_args), unquote(length_variable))} end def unquote(extractor_name)(<<rest::binary>>, unquote_splicing(extractor_args), unquote(length_variable)) do case rest do <<unquote(value_arg)::binary-size(unquote(length_variable)), rest::binary>> -> unquote(landing_call) _ -> {:resume, &unquote(extractor_name)(rest <> &1, unquote_splicing(extractor_args), unquote(length_variable))} end end # Starts the size extractor chain def unquote(extractor_name)(<<b::binary>>, unquote_splicing(extractor_args)) do unquote(length_extractor_name)(b, unquote_splicing(extractor_args)) end end end defp build_extractor({:array, item_type}, arg_name, extractor_name, landing_call, args) do build_extractor({:list, item_type}, arg_name, extractor_name, landing_call, args) end defp build_extractor({:list, item_type}, arg_name, extractor_name, landing_call, [binary_arg | non_binary_args]) do extractor_args = reject_argument(non_binary_args, arg_name) length_extractor_name = :"#{extractor_name}_list_length" length_name = :length |> unique_name() length_variable = length_name |> Macro.var(nil) length_extractor_args = [binary_arg | extractor_args] ++ [length_variable] list_extractor_name = unique_name("#{extractor_name}_list") item_name = :item |> unique_name() item_variable = Macro.var(item_name, nil) item_accumulator_variable = Macro.var(arg_name, nil) count_variable = Macro.var(:"#{extractor_name}_count", nil) item_extractor_name = unique_name("#{extractor_name}_item") item_extractor_call_args = extractor_args ++ [count_variable, item_accumulator_variable] item_extractor_args = [binary_arg] ++ item_extractor_call_args list_extractor_args = extractor_args length_landing_call = quote do unquote(item_extractor_name)(rest, unquote_splicing(extractor_args), unquote(length_variable), []) end list_landing_call = quote do unquote(list_extractor_name)( rest, unquote_splicing(list_extractor_args), unquote(count_variable) - 1, unquote(item_variable), unquote(item_accumulator_variable) ) end item_extractors = item_type |> build_extractor(item_name, item_extractor_name, list_landing_call, item_extractor_args) |> collapse_blocks length_extractors = :varint |> build_extractor(length_name, length_extractor_name, length_landing_call, length_extractor_args) |> collapse_blocks() quote do def unquote(extractor_name)(<<>>, unquote_splicing(extractor_args)) do {:resume, &unquote(extractor_name)(&1, unquote_splicing(extractor_args))} end # Starts the chain by calling the length extractor def unquote(extractor_name)(<<rest::binary>>, unquote_splicing(extractor_args)) do unquote(length_extractor_name)(rest, unquote_splicing(extractor_args)) end unquote_splicing(length_extractors) unquote_splicing(item_extractors) # This clause matches when we've extracted all items (remaining count is 0) def unquote(list_extractor_name)( <<rest::binary>>, unquote_splicing(list_extractor_args), 0, unquote(item_variable), unquote(item_accumulator_variable) ) do unquote(item_accumulator_variable) = Enum.reverse([unquote(item_variable) | unquote(item_accumulator_variable)]) unquote(landing_call) end # This matches when there's more work to do. It accumulates the extracted item # and calls the item extractor again def unquote(list_extractor_name)( <<rest::binary>>, unquote_splicing(list_extractor_args), unquote(count_variable), unquote(item_variable), unquote(item_accumulator_variable) ) do unquote(item_accumulator_variable) = [unquote(item_variable) | unquote(item_accumulator_variable)] unquote(item_extractor_name)(rest, unquote_splicing(item_extractor_call_args)) end end end # Helper functions defp rewrite_visibility(ast, :def) do ast end defp rewrite_visibility(ast, :defp) do Macro.prewalk(ast, fn {:def, context, rest} -> {:defp, context, rest} other -> other end) end defp collapse_blocks({:__block__, _, defs}) do defs end defp collapse_blocks(ast) when is_list(ast) do Enum.reduce(ast, [], fn {:__block__, _context, clauses}, acc -> acc ++ clauses _, acc -> acc end) |> Enum.reverse() end defp collapse_blocks(ast) do [ast] end defp reject_argument(args, arg_name) do Enum.reject(args, fn {^arg_name, _, _} -> true _ -> false end) end defp unique_name(base_name) do unique = System.unique_integer([:positive, :monotonic]) :"#{base_name}_#{unique}" end end
35.857388
133
0.636926
73809368c36f5e60057ae8ac3a9ecc1077125377
4,188
exs
Elixir
test/swoosh/adapters/gmail_test.exs
ntodd/swoosh
e2cc97b695543f9ef29c02d0c50dd692107762b0
[ "MIT" ]
null
null
null
test/swoosh/adapters/gmail_test.exs
ntodd/swoosh
e2cc97b695543f9ef29c02d0c50dd692107762b0
[ "MIT" ]
null
null
null
test/swoosh/adapters/gmail_test.exs
ntodd/swoosh
e2cc97b695543f9ef29c02d0c50dd692107762b0
[ "MIT" ]
null
null
null
defmodule Swoosh.Adapters.GmailTest do use Swoosh.AdapterCase, async: true import Swoosh.Email alias Swoosh.Adapters.Gmail @success_response """ { "id": "234jkasdfl", "threadId": "12312adfsx", "labelIds": ["SENT"] } """ setup do bypass = Bypass.open() config = [base_url: "http://localhost:#{bypass.port}", access_token: "test_token"] valid_email = new() |> from("[email protected]") |> to("[email protected]") |> subject("Hello, Avengers!") |> html_body("<h1>Hello</h1>") {:ok, bypass: bypass, valid_email: valid_email, config: config} end test "a sent email results in :ok", %{bypass: bypass, config: config, valid_email: email} do Bypass.expect(bypass, fn conn -> conn = parse(conn) boundary = Mail.Message.get_boundary(conn.body_params) body_params = ~s""" To: "" <[email protected]>\r Subject: Hello, Avengers!\r MIME-Version: 1.0\r From: "" <[email protected]>\r Content-Type: multipart/alternative; boundary="#{boundary}"\r \r --#{boundary}\r Content-Type: text/html\r Content-Transfer-Encoding: quoted-printable\r \r <h1>Hello</h1>\r --#{boundary}--\ """ |> Mail.Parsers.RFC2822.parse() assert body_params == conn.body_params assert "/users/me/messages/send" == conn.request_path assert "POST" == conn.method Plug.Conn.resp(conn, 200, @success_response) end) assert Gmail.deliver(email, config) == {:ok, %{id: "234jkasdfl", thread_id: "12312adfsx", labels: ["SENT"]}} end test "deliver/1 with all fields returns :ok", %{ bypass: bypass, config: config } do email = new() |> from({"T Stark", "[email protected]"}) |> to("[email protected]") |> to({"Steve Rogers", "[email protected]"}) |> subject("Hello, Avengers!") |> html_body("<h1>Hello</h1>") |> cc("[email protected]") |> bcc({"Clinton Francis Barton", "[email protected]"}) |> bcc("[email protected]") |> bcc({"Bruce Banner", "[email protected]"}) |> reply_to("[email protected]") |> html_body("<h1>Hello</h1>") |> text_body("Hello") |> header("X-Avengers", "Assemble") Bypass.expect(bypass, fn conn -> conn = parse(conn) boundary = Mail.Message.get_boundary(conn.body_params) body_params = ~s""" Bcc: "Bruce Banner" <[email protected]>, "" <[email protected]>, "Clinton Francis Barton" <[email protected]>\r To: "Steve Rogers" <[email protected]>, "" <[email protected]>\r Subject: Hello, Avengers!\r Reply-To: "" <[email protected]>\r MIME-Version: 1.0\r From: "T Stark" <[email protected]>\r Content-Type: multipart/alternative; boundary="#{boundary}"\r Cc: "" <[email protected]>\r X-Avengers: Assemble\r \r --#{boundary}\r Content-Type: text/plain\r Content-Transfer-Encoding: quoted-printable\r \r Hello\r \r --#{boundary}\r Content-Type: text/html\r Content-Transfer-Encoding: quoted-printable\r \r <h1>Hello</h1>\r --#{boundary}--\ """ |> Mail.Parsers.RFC2822.parse() assert body_params == conn.body_params assert "/users/me/messages/send" == conn.request_path assert "POST" == conn.method Plug.Conn.resp(conn, 200, @success_response) end) assert Gmail.deliver(email, config) == {:ok, %{id: "234jkasdfl", thread_id: "12312adfsx", labels: ["SENT"]}} end defmodule GMailer do use Swoosh.Mailer, otp_app: :swoosh_test, adapter: Swoosh.Adapters.Gmail end test "deliver/1 without :access_token raises exception", %{config: config, valid_email: email} do assert_raise( ArgumentError, fn -> config = Keyword.delete(config, :access_token) GMailer.deliver(email, config) end ) end end
30.347826
136
0.591213
7380970a1948ca9c8b466d9e6ded16ced533dff2
1,038
ex
Elixir
test/support/factories.ex
chrislaskey/assoc
7bee95e7f5bc6222cd7c2a63e3f955d0db89b2b7
[ "MIT" ]
6
2019-01-31T23:31:42.000Z
2020-10-06T20:05:34.000Z
test/support/factories.ex
chrislaskey/assoc
7bee95e7f5bc6222cd7c2a63e3f955d0db89b2b7
[ "MIT" ]
2
2021-11-09T14:35:51.000Z
2021-11-09T18:04:15.000Z
test/support/factories.ex
chrislaskey/assoc
7bee95e7f5bc6222cd7c2a63e3f955d0db89b2b7
[ "MIT" ]
2
2019-01-31T23:53:33.000Z
2021-11-05T21:47:26.000Z
defmodule Assoc.Test.Factories do alias Assoc.Test.Address alias Assoc.Test.Repo alias Assoc.Test.Role alias Assoc.Test.Tag alias Assoc.Test.User # Factories def insert_address!(params \\ %{}) do default_params = %{ address: "test address" } params = Map.merge(default_params, params) %Address{} |> Address.changeset(params) |> Repo.insert!() end def insert_tag!(params \\ %{}) do default_params = %{ name: "test tag" } params = Map.merge(default_params, params) %Tag{} |> Tag.changeset(params) |> Repo.insert!() end def insert_role!(params \\ %{}) do default_params = %{ name: "test role" } params = Map.merge(default_params, params) %Role{} |> Role.changeset(params) |> Repo.insert!() end def insert_user!(params \\ %{}) do default_params = %{ email: "[email protected]" } params = Map.merge(default_params, params) %User{} |> User.changeset(params) |> Repo.insert!() end end
17.896552
46
0.600193
7380aaeb69d93704ebdc095b570ccf83b9e14352
201
exs
Elixir
test/test_helper.exs
maartenvanvliet/dolla
3620cb4613fa63363014cd78207ddbb055e0818d
[ "BSD-3-Clause" ]
7
2016-06-28T08:36:31.000Z
2020-02-13T02:39:16.000Z
test/test_helper.exs
maartenvanvliet/dolla
3620cb4613fa63363014cd78207ddbb055e0818d
[ "BSD-3-Clause" ]
null
null
null
test/test_helper.exs
maartenvanvliet/dolla
3620cb4613fa63363014cd78207ddbb055e0818d
[ "BSD-3-Clause" ]
3
2017-02-22T22:40:04.000Z
2020-02-11T09:44:34.000Z
ExUnit.start() Application.ensure_all_started(:bypass) defmodule DollaTest.Fixtures do def receipt_with_iaps do {:ok, file} = File.read("test/fixtures/receipt_with_iaps.json") file end end
22.333333
67
0.761194
7380cc8616febcc529f32a8bd086358d066d066e
216
exs
Elixir
farmbot_core/priv/logger/migrations/20190711221214_add_message_hash_to_logs_table.exs
adamswsk/farmbot_os
d177d3b74888c1e7bcbf8f8595818708ee97f73b
[ "MIT" ]
1
2021-08-23T13:36:14.000Z
2021-08-23T13:36:14.000Z
farmbot_core/priv/logger/migrations/20190711221214_add_message_hash_to_logs_table.exs
adamswsk/farmbot_os
d177d3b74888c1e7bcbf8f8595818708ee97f73b
[ "MIT" ]
null
null
null
farmbot_core/priv/logger/migrations/20190711221214_add_message_hash_to_logs_table.exs
adamswsk/farmbot_os
d177d3b74888c1e7bcbf8f8595818708ee97f73b
[ "MIT" ]
null
null
null
defmodule FarmbotCore.Logger.Repo.Migrations.AddMessageHashToLogsTable do use Ecto.Migration def change do alter table("logs") do add(:hash, :binary) add(:duplicates, :integer) end end end
19.636364
73
0.703704
7380ea00df371d87adaa4a0a2be8ba082af2f09c
4,815
ex
Elixir
lib/mix/tasks/firmware.ex
petermm/nerves
173b0a424177f45f77db4206406d9c98f1d73e95
[ "Apache-2.0" ]
null
null
null
lib/mix/tasks/firmware.ex
petermm/nerves
173b0a424177f45f77db4206406d9c98f1d73e95
[ "Apache-2.0" ]
null
null
null
lib/mix/tasks/firmware.ex
petermm/nerves
173b0a424177f45f77db4206406d9c98f1d73e95
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Firmware do use Mix.Task import Mix.Nerves.Utils @shortdoc "Build a firmware bundle" @moduledoc """ Build a firmware image for the selected target platform. This task builds the project, combines the generated OTP release with a Nerves system image, and creates a `.fw` file that may be written to an SDCard or sent to a device. ## Command line options * `--verbose` - produce detailed output about release assembly ## Environment variables * `NERVES_SYSTEM` - may be set to a local directory to specify the Nerves system image that is used * `NERVES_TOOLCHAIN` - may be set to a local directory to specify the Nerves toolchain (C/C++ crosscompiler) that is used """ @switches [verbose: :boolean] @impl true def run(args) do preflight() debug_info("Nerves Firmware Assembler") {opts, _, _} = OptionParser.parse(args, switches: @switches) system_path = check_nerves_system_is_set!() check_nerves_toolchain_is_set!() rel_config = File.cwd!() |> Path.join("rel/config.exs") unless File.exists?(rel_config) do Mix.raise(""" You are missing a release config file. Run nerves.release.init task first """) end Mix.Task.run("compile", []) Mix.Nerves.IO.shell_info("Building OTP Release...") clean_release(opts) build_release(opts) build_firmware(system_path) end @doc false def result({_, 0}), do: nil def result({result, _}), do: Mix.raise(""" Nerves encountered an error. #{inspect(result)} """) defp clean_release(opts) do verbosity = if opts[:verbose], do: "--verbose", else: "--silent" try do Mix.Task.run("release.clean", [verbosity, "--implode", "--no-confirm"]) catch :exit, _ -> :noop end end defp build_release(opts) do verbosity = if opts[:verbose], do: "--verbose", else: "--quiet" Mix.Task.run("release", [verbosity, "--no-tar"]) end defp build_firmware(system_path) do config = Mix.Project.config() otp_app = config[:app] images_path = (config[:images_path] || Path.join([Mix.Project.build_path(), "nerves", "images"])) |> Path.expand() unless File.exists?(images_path) do File.mkdir_p(images_path) end firmware_config = Application.get_env(:nerves, :firmware) rootfs_priorities = Nerves.Env.package(:nerves_system_br) |> rootfs_priorities() rel2fw_path = Path.join(system_path, "scripts/rel2fw.sh") cmd = "bash" args = [rel2fw_path] if firmware_config[:rootfs_additions] do Mix.shell().error( "The :rootfs_additions configuration option has been deprecated. Please use :rootfs_overlay instead." ) end rootfs_overlay = case firmware_config[:rootfs_overlay] || firmware_config[:rootfs_additions] do nil -> [] overlays when is_list(overlays) -> Enum.map(overlays, fn overlay -> ["-a", Path.join(File.cwd!(), overlay)] end) |> List.flatten() overlay -> ["-a", Path.join(File.cwd!(), overlay)] end fwup_conf = case firmware_config[:fwup_conf] do nil -> [] fwup_conf -> ["-c", Path.join(File.cwd!(), fwup_conf)] end fw = ["-f", "#{images_path}/#{otp_app}.fw"] release_path = Path.join(Mix.Project.build_path(), "rel/#{otp_app}") output = [release_path] args = args ++ fwup_conf ++ rootfs_overlay ++ fw ++ rootfs_priorities ++ output env = standard_fwup_variables(config) set_provisioning(firmware_config[:provisioning]) shell(cmd, args, env: env) |> result end defp standard_fwup_variables(config) do # Assuming the fwup.conf file respects these variable like the official # systems do, this will set the .fw metadata to what's in the mix.exs. [ {"NERVES_FW_VERSION", config[:version]}, {"NERVES_FW_PRODUCT", config[:name] || to_string(config[:app])}, {"NERVES_FW_DESCRIPTION", config[:description]}, {"NERVES_FW_AUTHOR", config[:author]} ] end # Need to check min version for nerves_system_br to check if passing the # rootfs priorities option is supported. This was added in the 1.7.1 release # https://github.com/nerves-project/nerves_system_br/releases/tag/v1.7.1 defp rootfs_priorities(%Nerves.Package{app: :nerves_system_br, version: vsn}) do case Version.compare(vsn, "1.7.1") do r when r in [:gt, :eq] -> rootfs_priorities_file = Path.join([Mix.Project.build_path(), "nerves", "rootfs.priorities"]) if File.exists?(rootfs_priorities_file) do ["-p", rootfs_priorities_file] else [] end _ -> [] end end defp rootfs_priorities(_), do: [] end
27.672414
109
0.641329
7380ec8d3e7979a8c1e1999fc4075530f1e90eb8
79
ex
Elixir
lib/retroflect_web/views/user_confirmation_view.ex
gaslight/retroflect
d98a52dbe4ef14dd50ef06970fba9c673e456647
[ "MIT" ]
3
2021-10-04T15:03:09.000Z
2021-10-05T00:42:19.000Z
lib/retroflect_web/views/user_confirmation_view.ex
gaslight/retroflect
d98a52dbe4ef14dd50ef06970fba9c673e456647
[ "MIT" ]
29
2021-10-04T12:56:21.000Z
2021-10-20T17:38:12.000Z
lib/retroflect_web/views/user_confirmation_view.ex
gaslight/retroflect
d98a52dbe4ef14dd50ef06970fba9c673e456647
[ "MIT" ]
null
null
null
defmodule RetroflectWeb.UserConfirmationView do use RetroflectWeb, :view end
19.75
47
0.848101
7381499e6966773202f2dac40e7baabdb117fd80
1,812
ex
Elixir
server/lib/domsegserver_web/controllers/user_reset_password_controller.ex
arpieb/domseg
0c7165d69181e59902730c6e7ac41e8e849edd70
[ "Apache-2.0" ]
null
null
null
server/lib/domsegserver_web/controllers/user_reset_password_controller.ex
arpieb/domseg
0c7165d69181e59902730c6e7ac41e8e849edd70
[ "Apache-2.0" ]
9
2021-12-09T18:19:21.000Z
2022-01-09T03:45:33.000Z
server/lib/domsegserver_web/controllers/user_reset_password_controller.ex
arpieb/domseg
0c7165d69181e59902730c6e7ac41e8e849edd70
[ "Apache-2.0" ]
null
null
null
defmodule DOMSegServerWeb.UserResetPasswordController do use DOMSegServerWeb, :controller alias DOMSegServer.Accounts plug :get_user_by_reset_password_token when action in [:edit, :update] def new(conn, _params) do render(conn, "new.html") end def create(conn, %{"user" => %{"email" => email}}) do if user = Accounts.get_user_by_email(email) do Accounts.deliver_user_reset_password_instructions( user, &Routes.user_reset_password_url(conn, :edit, &1) ) end # In order to prevent user enumeration attacks, regardless of the outcome, show an impartial success/error message. conn |> put_flash( :info, "If your email is in our system, you will receive instructions to reset your password shortly." ) |> redirect(to: "/") end def edit(conn, _params) do render(conn, "edit.html", changeset: Accounts.change_user_password(conn.assigns.user)) end # Do not log in the user after reset password to avoid a # leaked token giving the user access to the account. def update(conn, %{"user" => user_params}) do case Accounts.reset_user_password(conn.assigns.user, user_params) do {:ok, _} -> conn |> put_flash(:info, "Password reset successfully.") |> redirect(to: Routes.user_session_path(conn, :new)) {:error, changeset} -> render(conn, "edit.html", changeset: changeset) end end defp get_user_by_reset_password_token(conn, _opts) do %{"token" => token} = conn.params if user = Accounts.get_user_by_reset_password_token(token) do conn |> assign(:user, user) |> assign(:token, token) else conn |> put_flash(:error, "Reset password link is invalid or it has expired.") |> redirect(to: "/") |> halt() end end end
30.2
119
0.66777
73814a0814fd1bdfe5b095d1aac5a031ed0c04ab
21,403
ex
Elixir
lib/phoenix_live_view/html_tokenizer.ex
feliperenan/phoenix_live_view
af65bb51fe12ea88e7c66808d2b1118e1c491ddd
[ "MIT" ]
null
null
null
lib/phoenix_live_view/html_tokenizer.ex
feliperenan/phoenix_live_view
af65bb51fe12ea88e7c66808d2b1118e1c491ddd
[ "MIT" ]
null
null
null
lib/phoenix_live_view/html_tokenizer.ex
feliperenan/phoenix_live_view
af65bb51fe12ea88e7c66808d2b1118e1c491ddd
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveView.HTMLTokenizer do @moduledoc false @space_chars '\s\t\f' @quote_chars '"\'' @stop_chars '>/=\r\n' ++ @quote_chars ++ @space_chars defmodule ParseError do @moduledoc false defexception [:file, :line, :column, :description] @impl true def message(exception) do location = exception.file |> Path.relative_to_cwd() |> format_file_line_column(exception.line, exception.column) "#{location} #{exception.description}" end # Use Exception.format_file_line_column/4 instead when support # for Elixir < v1.11 is removed. def format_file_line_column(file, line, column, suffix \\ "") do cond do is_nil(file) -> "" is_nil(line) or line == 0 -> "#{file}:#{suffix}" is_nil(column) or column == 0 -> "#{file}:#{line}:#{suffix}" true -> "#{file}:#{line}:#{column}:#{suffix}" end end end def finalize(_tokens, file, {:comment, line, column}) do message = "expected closing `-->` for comment" raise ParseError, file: file, line: line, column: column, description: message end def finalize(tokens, _file, _cont) do tokens |> strip_text_token_fully() |> Enum.reverse() |> strip_text_token_fully() end @doc """ Tokenize the given text according to the given params. * `text` - The content to be tokenized. * `file` - Can be either a file or a string "nofile". * `indentation` - An integer that indicates the current indentation. * `meta` - A keyword list with `:line` and `:column`. Both must be integers. * `tokens` - A list of tokens. * `cont` - An atom that is `:text`, `:style`, or `:script`, or a tuple {:comment, line, column}. ### Examples iex> alias Phoenix.LiveView.HTMLTokenizer iex> HTMLTokenizer.tokenize("<section><div/></section>", "nofile", 0, [line: 1, column: 1], [], :text) {[ {:tag_close, "section", %{column: 16, line: 1}}, {:tag_open, "div", [], %{column: 10, line: 1, self_close: true}}, {:tag_open, "section", [], %{column: 1, line: 1}} ], :text} """ def tokenize(text, file, indentation, meta, tokens, cont) do line = Keyword.get(meta, :line, 1) column = Keyword.get(meta, :column, 1) state = %{file: file, column_offset: indentation + 1, braces: [], context: []} case cont do :text -> handle_text(text, line, column, [], tokens, state) :style -> handle_style(text, line, column, [], tokens, state) :script -> handle_script(text, line, column, [], tokens, state) {:comment, _, _} -> handle_comment(text, line, column, [], tokens, state) end end ## handle_text defp handle_text("\r\n" <> rest, line, _column, buffer, acc, state) do handle_text(rest, line + 1, state.column_offset, ["\r\n" | buffer], acc, state) end defp handle_text("\n" <> rest, line, _column, buffer, acc, state) do handle_text(rest, line + 1, state.column_offset, ["\n" | buffer], acc, state) end defp handle_text("<!doctype" <> rest, line, column, buffer, acc, state) do handle_doctype(rest, line, column + 9, ["<!doctype" | buffer], acc, state) end defp handle_text("<!DOCTYPE" <> rest, line, column, buffer, acc, state) do handle_doctype(rest, line, column + 9, ["<!DOCTYPE" | buffer], acc, state) end defp handle_text("<!--" <> rest, line, column, buffer, acc, state) do state = update_in(state.context, &[:comment_start | &1]) handle_comment(rest, line, column + 4, ["<!--" | buffer], acc, state) end defp handle_text("</" <> rest, line, column, buffer, acc, state) do text_to_acc = text_to_acc(buffer, acc, line, column, state.context) handle_tag_close(rest, line, column + 2, text_to_acc, %{state | context: []}) end defp handle_text("<" <> rest, line, column, buffer, acc, state) do text_to_acc = text_to_acc(buffer, acc, line, column, state.context) handle_tag_open(rest, line, column + 1, text_to_acc, %{state | context: []}) end defp handle_text(<<c::utf8, rest::binary>>, line, column, buffer, acc, state) do handle_text(rest, line, column + 1, [char_or_bin(c) | buffer], acc, state) end defp handle_text(<<>>, line, column, buffer, acc, _state) do ok(text_to_acc(buffer, acc, line, column, []), :text) end ## handle_doctype defp handle_doctype(<<?>, rest::binary>>, line, column, buffer, acc, state) do handle_text(rest, line, column + 1, [?> | buffer], acc, state) end defp handle_doctype("\r\n" <> rest, line, _column, buffer, acc, state) do handle_doctype(rest, line + 1, state.column_offset, ["\r\n" | buffer], acc, state) end defp handle_doctype("\n" <> rest, line, _column, buffer, acc, state) do handle_doctype(rest, line + 1, state.column_offset, ["\n" | buffer], acc, state) end defp handle_doctype(<<c::utf8, rest::binary>>, line, column, buffer, acc, state) do handle_doctype(rest, line, column + 1, [char_or_bin(c) | buffer], acc, state) end ## handle_script defp handle_script("</script>" <> rest, line, column, buffer, acc, state) do acc = [ {:tag_close, "script", %{line: line, column: column}} | text_to_acc(buffer, acc, line, column, []) ] handle_text(rest, line, column + 9, [], acc, state) end defp handle_script("\r\n" <> rest, line, _column, buffer, acc, state) do handle_script(rest, line + 1, state.column_offset, ["\r\n" | buffer], acc, state) end defp handle_script("\n" <> rest, line, _column, buffer, acc, state) do handle_script(rest, line + 1, state.column_offset, ["\n" | buffer], acc, state) end defp handle_script(<<c::utf8, rest::binary>>, line, column, buffer, acc, state) do handle_script(rest, line, column + 1, [char_or_bin(c) | buffer], acc, state) end defp handle_script(<<>>, line, column, buffer, acc, _state) do ok(text_to_acc(buffer, acc, line, column, []), :script) end ## handle_style defp handle_style("</style>" <> rest, line, column, buffer, acc, state) do acc = [ {:tag_close, "style", %{line: line, column: column}} | text_to_acc(buffer, acc, line, column, []) ] handle_text(rest, line, column + 9, [], acc, state) end defp handle_style("\r\n" <> rest, line, _column, buffer, acc, state) do handle_style(rest, line + 1, state.column_offset, ["\r\n" | buffer], acc, state) end defp handle_style("\n" <> rest, line, _column, buffer, acc, state) do handle_style(rest, line + 1, state.column_offset, ["\n" | buffer], acc, state) end defp handle_style(<<c::utf8, rest::binary>>, line, column, buffer, acc, state) do handle_style(rest, line, column + 1, [char_or_bin(c) | buffer], acc, state) end defp handle_style(<<>>, line, column, buffer, acc, _state) do ok(text_to_acc(buffer, acc, line, column, []), :style) end ## handle_comment defp handle_comment("\r\n" <> rest, line, _column, buffer, acc, state) do handle_comment(rest, line + 1, state.column_offset, ["\r\n" | buffer], acc, state) end defp handle_comment("\n" <> rest, line, _column, buffer, acc, state) do handle_comment(rest, line + 1, state.column_offset, ["\n" | buffer], acc, state) end defp handle_comment("-->" <> rest, line, column, buffer, acc, state) do state = update_in(state.context, &[:comment_end | &1]) handle_text(rest, line, column + 3, ["-->" | buffer], acc, state) end defp handle_comment(<<c::utf8, rest::binary>>, line, column, buffer, acc, state) do handle_comment(rest, line, column + 1, [char_or_bin(c) | buffer], acc, state) end defp handle_comment(<<>>, line, column, buffer, acc, state) do ok(text_to_acc(buffer, acc, line, column, state.context), {:comment, line, column}) end ## handle_tag_open defp handle_tag_open(text, line, column, acc, state) do case handle_tag_name(text, column, []) do {:ok, name, new_column, rest} -> acc = if strip_tag?(name), do: strip_text_token_partially(acc), else: acc acc = [{:tag_open, name, [], %{line: line, column: column - 1}} | acc] handle_maybe_tag_open_end(rest, line, new_column, acc, state) {:error, message} -> raise ParseError, file: state.file, line: line, column: column, description: message end end ## handle_tag_close defp handle_tag_close(text, line, column, acc, state) do case handle_tag_name(text, column, []) do {:ok, name, new_column, ">" <> rest} -> acc = [{:tag_close, name, %{line: line, column: column - 2}} | acc] rest = if strip_tag?(name), do: String.trim_leading(rest), else: rest handle_text(rest, line, new_column + 1, [], acc, state) {:ok, _, new_column, _} -> message = "expected closing `>`" raise ParseError, file: state.file, line: line, column: new_column, description: message {:error, message} -> raise ParseError, file: state.file, line: line, column: column, description: message end end ## handle_tag_name defp handle_tag_name(<<c::utf8, _rest::binary>> = text, column, buffer) when c in @stop_chars do done_tag_name(text, column, buffer) end defp handle_tag_name(<<c::utf8, rest::binary>>, column, buffer) do handle_tag_name(rest, column + 1, [char_or_bin(c) | buffer]) end defp handle_tag_name(<<>>, column, buffer) do done_tag_name(<<>>, column, buffer) end defp done_tag_name(_text, _column, []) do {:error, "expected tag name"} end defp done_tag_name(text, column, buffer) do {:ok, buffer_to_string(buffer), column, text} end ## handle_maybe_tag_open_end defp handle_maybe_tag_open_end("\r\n" <> rest, line, _column, acc, state) do handle_maybe_tag_open_end(rest, line + 1, state.column_offset, acc, state) end defp handle_maybe_tag_open_end("\n" <> rest, line, _column, acc, state) do handle_maybe_tag_open_end(rest, line + 1, state.column_offset, acc, state) end defp handle_maybe_tag_open_end(<<c::utf8, rest::binary>>, line, column, acc, state) when c in @space_chars do handle_maybe_tag_open_end(rest, line, column + 1, acc, state) end defp handle_maybe_tag_open_end("/>" <> rest, line, column, acc, state) do acc = reverse_attrs(acc) handle_text(rest, line, column + 2, [], put_self_close(acc), state) end defp handle_maybe_tag_open_end(">" <> rest, line, column, acc, state) do case reverse_attrs(acc) do [{:tag_open, "script", _, _} | _] = acc -> handle_script(rest, line, column + 1, [], acc, state) [{:tag_open, "style", _, _} | _] = acc -> handle_style(rest, line, column + 1, [], acc, state) acc -> handle_text(rest, line, column + 1, [], acc, state) end end defp handle_maybe_tag_open_end("{" <> rest, line, column, acc, state) do handle_root_attribute(rest, line, column + 1, acc, state) end defp handle_maybe_tag_open_end(<<>>, line, column, _acc, state) do message = ~S""" expected closing `>` or `/>` Make sure the tag is properly closed. This may happen if there is an EEx interpolation inside a tag, which is not supported. For instance, instead of <div id="<%= @id %>">Content</div> do <div id={@id}>Content</div> If @id is nil or false, then no attribute is sent at all. Inside {...} you can place any Elixir expression. If you want to interpolate in the middle of an attribute value, instead of <a class="foo bar <%= @class %>">Text</a> you can pass an Elixir string with interpolation: <a class={"foo bar #{@class}"}>Text</a> """ raise ParseError, file: state.file, line: line, column: column, description: message end defp handle_maybe_tag_open_end(text, line, column, acc, state) do handle_attribute(text, line, column, acc, state) end ## handle_attribute defp handle_attribute(text, line, column, acc, state) do case handle_attr_name(text, column, []) do {:ok, name, new_column, rest} -> acc = put_attr(acc, name) handle_maybe_attr_value(rest, line, new_column, acc, state) {:error, message, column} -> raise ParseError, file: state.file, line: line, column: column, description: message end end ## handle_root_attribute defp handle_root_attribute(text, line, column, acc, state) do case handle_interpolation(text, line, column, [], state) do {:ok, value, new_line, new_column, rest, state} -> acc = put_attr(acc, :root, {:expr, value, %{line: line, column: column}}) handle_maybe_tag_open_end(rest, new_line, new_column, acc, state) {:error, message, line, column} -> raise ParseError, file: state.file, line: line, column: column, description: message end end ## handle_attr_name defp handle_attr_name(<<c::utf8, _rest::binary>>, column, _buffer) when c in @quote_chars do {:error, "invalid character in attribute name: #{<<c>>}", column} end defp handle_attr_name(<<c::utf8, _rest::binary>>, column, []) when c in @stop_chars do {:error, "expected attribute name", column} end defp handle_attr_name(<<c::utf8, _rest::binary>> = text, column, buffer) when c in @stop_chars do {:ok, buffer_to_string(buffer), column, text} end defp handle_attr_name(<<c::utf8, rest::binary>>, column, buffer) do handle_attr_name(rest, column + 1, [char_or_bin(c) | buffer]) end ## handle_maybe_attr_value defp handle_maybe_attr_value("\r\n" <> rest, line, _column, acc, state) do handle_maybe_attr_value(rest, line + 1, state.column_offset, acc, state) end defp handle_maybe_attr_value("\n" <> rest, line, _column, acc, state) do handle_maybe_attr_value(rest, line + 1, state.column_offset, acc, state) end defp handle_maybe_attr_value(<<c::utf8, rest::binary>>, line, column, acc, state) when c in @space_chars do handle_maybe_attr_value(rest, line, column + 1, acc, state) end defp handle_maybe_attr_value("=" <> rest, line, column, acc, state) do handle_attr_value_begin(rest, line, column + 1, acc, state) end defp handle_maybe_attr_value(text, line, column, acc, state) do handle_maybe_tag_open_end(text, line, column, acc, state) end ## handle_attr_value_begin defp handle_attr_value_begin("\r\n" <> rest, line, _column, acc, state) do handle_attr_value_begin(rest, line + 1, state.column_offset, acc, state) end defp handle_attr_value_begin("\n" <> rest, line, _column, acc, state) do handle_attr_value_begin(rest, line + 1, state.column_offset, acc, state) end defp handle_attr_value_begin(<<c::utf8, rest::binary>>, line, column, acc, state) when c in @space_chars do handle_attr_value_begin(rest, line, column + 1, acc, state) end defp handle_attr_value_begin("\"" <> rest, line, column, acc, state) do handle_attr_value_quote(rest, ?", line, column + 1, [], acc, state) end defp handle_attr_value_begin("'" <> rest, line, column, acc, state) do handle_attr_value_quote(rest, ?', line, column + 1, [], acc, state) end defp handle_attr_value_begin("{" <> rest, line, column, acc, state) do handle_attr_value_as_expr(rest, line, column + 1, acc, state) end defp handle_attr_value_begin(_text, line, column, _acc, state) do message = "invalid attribute value after `=`. Expected either a value between quotes " <> "(such as \"value\" or \'value\') or an Elixir expression between curly brackets (such as `{expr}`)" raise ParseError, file: state.file, line: line, column: column, description: message end ## handle_attr_value_quote defp handle_attr_value_quote("\r\n" <> rest, delim, line, _column, buffer, acc, state) do column = state.column_offset handle_attr_value_quote(rest, delim, line + 1, column, ["\r\n" | buffer], acc, state) end defp handle_attr_value_quote("\n" <> rest, delim, line, _column, buffer, acc, state) do column = state.column_offset handle_attr_value_quote(rest, delim, line + 1, column, ["\n" | buffer], acc, state) end defp handle_attr_value_quote(<<delim, rest::binary>>, delim, line, column, buffer, acc, state) do value = buffer_to_string(buffer) acc = put_attr_value(acc, {:string, value, %{delimiter: delim}}) handle_maybe_tag_open_end(rest, line, column + 1, acc, state) end defp handle_attr_value_quote(<<c::utf8, rest::binary>>, delim, line, column, buffer, acc, state) do handle_attr_value_quote(rest, delim, line, column + 1, [char_or_bin(c) | buffer], acc, state) end defp handle_attr_value_quote(<<>>, delim, line, column, _buffer, _acc, state) do message = """ expected closing `#{<<delim>>}` for attribute value Make sure the attribute is properly closed. This may also happen if there is an EEx interpolation inside a tag, which is not supported. Instead of <div <%= @some_attributes %>> </div> do <div {@some_attributes}> </div> Where @some_attributes must be a keyword list or a map. """ raise ParseError, file: state.file, line: line, column: column, description: message end ## handle_attr_value_as_expr defp handle_attr_value_as_expr(text, line, column, acc, %{braces: []} = state) do case handle_interpolation(text, line, column, [], state) do {:ok, value, new_line, new_column, rest, state} -> acc = put_attr_value(acc, {:expr, value, %{line: line, column: column}}) handle_maybe_tag_open_end(rest, new_line, new_column, acc, state) {:error, message, line, column} -> raise ParseError, file: state.file, line: line, column: column, description: message end end ## handle_interpolation defp handle_interpolation("\r\n" <> rest, line, _column, buffer, state) do handle_interpolation(rest, line + 1, state.column_offset, ["\r\n" | buffer], state) end defp handle_interpolation("\n" <> rest, line, _column, buffer, state) do handle_interpolation(rest, line + 1, state.column_offset, ["\n" | buffer], state) end defp handle_interpolation("}" <> rest, line, column, buffer, %{braces: []} = state) do value = buffer_to_string(buffer) {:ok, value, line, column + 1, rest, state} end defp handle_interpolation(~S(\}) <> rest, line, column, buffer, state) do handle_interpolation(rest, line, column + 2, [~S(\}) | buffer], state) end defp handle_interpolation(~S(\{) <> rest, line, column, buffer, state) do handle_interpolation(rest, line, column + 2, [~S(\{) | buffer], state) end defp handle_interpolation("}" <> rest, line, column, buffer, state) do {_pos, state} = pop_brace(state) handle_interpolation(rest, line, column + 1, ["}" | buffer], state) end defp handle_interpolation("{" <> rest, line, column, buffer, state) do state = push_brace(state, {line, column}) handle_interpolation(rest, line, column + 1, ["{" | buffer], state) end defp handle_interpolation(<<c::utf8, rest::binary>>, line, column, buffer, state) do handle_interpolation(rest, line, column + 1, [char_or_bin(c) | buffer], state) end defp handle_interpolation(<<>>, line, column, _buffer, _state) do {:error, "expected closing `}` for expression", line, column} end ## helpers @compile {:inline, ok: 2, char_or_bin: 1} defp ok(acc, cont), do: {acc, cont} defp char_or_bin(c) when c <= 127, do: c defp char_or_bin(c), do: <<c::utf8>> defp buffer_to_string(buffer) do IO.iodata_to_binary(Enum.reverse(buffer)) end defp text_to_acc(buffer, acc, line, column, context) defp text_to_acc([], acc, _line, _column, _context), do: acc defp text_to_acc(buffer, acc, line, column, context) do meta = %{line_end: line, column_end: column} meta = if context = get_context(context) do Map.put(meta, :context, context) else meta end [{:text, buffer_to_string(buffer), meta} | acc] end defp get_context([]), do: nil defp get_context(context), do: Enum.reverse(context) defp put_attr([{:tag_open, name, attrs, meta} | acc], attr, value \\ nil) do attrs = [{attr, value} | attrs] [{:tag_open, name, attrs, meta} | acc] end defp put_attr_value([{:tag_open, name, [{attr, _value} | attrs], meta} | acc], value) do attrs = [{attr, value} | attrs] [{:tag_open, name, attrs, meta} | acc] end defp reverse_attrs([{:tag_open, name, attrs, meta} | acc]) do attrs = Enum.reverse(attrs) [{:tag_open, name, attrs, meta} | acc] end defp put_self_close([{:tag_open, name, attrs, meta} | acc]) do meta = Map.put(meta, :self_close, true) [{:tag_open, name, attrs, meta} | acc] end defp push_brace(state, pos) do %{state | braces: [pos | state.braces]} end defp pop_brace(%{braces: [pos | braces]} = state) do {pos, %{state | braces: braces}} end # Strip space before slots defp strip_tag?(":" <> _), do: true defp strip_tag?(_), do: false defp strip_text_token_fully(tokens) do with [{:text, text, _} | rest] <- tokens, "" <- String.trim_leading(text) do strip_text_token_fully(rest) else _ -> tokens end end defp strip_text_token_partially(tokens) do with [{:text, text, _meta} | rest] <- tokens, "" <- String.trim_leading(text) do strip_text_token_partially(rest) else _ -> tokens end end end
34.135566
108
0.647573
738159920c15aed06b86f7beef7345bfceb70149
654
ex
Elixir
slackbot/lib/slackbot.ex
enilsen16/elixir
b4d1d45858a25e4beb39e07de8685f3d93d6a520
[ "MIT" ]
null
null
null
slackbot/lib/slackbot.ex
enilsen16/elixir
b4d1d45858a25e4beb39e07de8685f3d93d6a520
[ "MIT" ]
null
null
null
slackbot/lib/slackbot.ex
enilsen16/elixir
b4d1d45858a25e4beb39e07de8685f3d93d6a520
[ "MIT" ]
null
null
null
defmodule Slackbot do use Application # See http://elixir-lang.org/docs/stable/elixir/Application.html # for more information on OTP Applications def start(_type, _args) do import Supervisor.Spec, warn: false # Define workers and child supervisors to be supervised children = [ # Starts a worker by calling: Slackbot.Worker.start_link(arg1, arg2, arg3) worker(Slackbot.Bot, [[]]), ] # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Slackbot.Supervisor] Supervisor.start_link(children, opts) end end
31.142857
80
0.714067
73815ba2fee4e7a6d4473ed4edf83a348a96a238
3,824
ex
Elixir
apps/kv_rest_api/lib/kv_rest_api/web/business/client.ex
WhiteRookPL/production-debugging-workshop.ex
26e81d14ba39c33764ddaee5d6d65a6061f4e823
[ "MIT" ]
5
2017-05-03T08:05:54.000Z
2022-03-11T04:11:00.000Z
apps/kv_rest_api/lib/kv_rest_api/web/business/client.ex
WhiteRookPL/production-debugging-workshop.ex
26e81d14ba39c33764ddaee5d6d65a6061f4e823
[ "MIT" ]
null
null
null
apps/kv_rest_api/lib/kv_rest_api/web/business/client.ex
WhiteRookPL/production-debugging-workshop.ex
26e81d14ba39c33764ddaee5d6d65a6061f4e823
[ "MIT" ]
null
null
null
defmodule KV.RestAPI.Web.Client do # Public API. @doc """ Client operation responsible for listing all buckets. """ def buckets() do response = command("BUCKETS") |> String.split("\r\n") case response do [ "OK" ] -> [] [ buckets | _tail ] -> String.split(buckets, ",") |> Enum.map(&decode/1) end end @doc """ Client operation responsible for creating new `bucket`. """ def create(bucket) do case command("CREATE #{bucket}") do "OK" -> :ok _ -> :error end end @doc """ Client operation responsible for creating new `key` in the `bucket` with provided `value`. """ def create(bucket, key, value) do case command(["PUT #{bucket} #{key} " | Base.encode64(to_string(value))]) do "OK" -> :ok _ -> :error end end @doc """ Client operation responsible for creating new `key` in the `bucket` with provided `value` and ttl. """ def create(bucket, key, value, ttl) do case command(["PUTX #{bucket} #{key} ", Base.encode64(to_string(value)), " #{ttl}"]) do "OK" -> :ok _ -> :error end end @doc """ Client operation responsible for getting value for `key` in `bucket`. If `key` does not exist in the `bucket` returns `nil` as a value. """ def get(bucket, key) do response = command("GET #{bucket} #{key}") |> String.split("\r\n") case response do [ "OK" ] -> nil [ value | _tail ] -> value end end @doc """ Client operation responsible for deleting a `bucket`. """ def delete(bucket) do case command("DELETE #{bucket}") do "OK" -> :ok "NOT_FOUND" -> :not_found end end @doc """ Client operation responsible for deleting a `key` in `bucket`. """ def delete(bucket, key) do case command("DELETE #{bucket} #{key}") do "OK" -> :ok _ -> :error end end @doc """ Client operation responsible for listing keys in `bucket`. """ def keys(bucket) do response = command("KEYS #{bucket}") |> String.split("\r\n") case response do [ "OK" ] -> [] [ keys | _tail ] -> String.split(keys, ",") |> Enum.map(&decode/1) end end @doc """ Client operation responsible for calculating average for a `bucket`. """ def avg(bucket) do [ id | _tail ] = command("AVG #{bucket}") |> String.split("\r\n") id end @doc """ Client operation responsible for calculating sum for a `bucket`. """ def sum(bucket) do [ id | _tail ] = command("SUM #{bucket}") |> String.split("\r\n") id end @doc """ Client operation responsible for calculating word count for a `key` in the `bucket`. """ def word_count(bucket, key) do [ id | _tail ] = command("WORDCOUNT #{bucket} #{key}") |> String.split("\r\n") case id do "NOT_FOUND" -> :not_found _ -> id end end @doc """ Client operation responsible for getting result of aggregation job identified by `id`. """ def result(id) do response = command("RESULT #{id}") |> String.split("\r\n") case response do [ "JOB NOT FOUND" ] -> :not_found [ "INVALID JOB ID"] -> :error [ result | _tail ] -> result end end # Private API. defp decode(name) do String.replace(name, "%2C", ",") end defp kv_server_open() do {:ok, socket} = :gen_tcp.connect('127.0.0.1', 4040, [:binary, active: false]) socket end defp kv_server_send(socket, what) do :gen_tcp.send(socket, what) end defp kv_server_recv(socket) do {:ok, message} = :gen_tcp.recv(socket, 0) message end defp command(command) do socket = kv_server_open() kv_server_send(socket, [command, ?\r, ?\n]) response = String.trim(kv_server_recv(socket)) :gen_tcp.close(socket) response end end
22.362573
100
0.583159
738168e431745e1ab3bc3f6caf54f31556564502
234
exs
Elixir
test/liquex/filter_test.exs
univers-agency/liquex
1a12e56be21da064d092b76fa3cce9bcb192103c
[ "MIT" ]
19
2020-02-29T01:37:11.000Z
2022-03-15T06:45:20.000Z
test/liquex/filter_test.exs
univers-agency/liquex
1a12e56be21da064d092b76fa3cce9bcb192103c
[ "MIT" ]
19
2020-09-02T19:35:08.000Z
2022-03-31T21:42:16.000Z
test/liquex/filter_test.exs
univers-agency/liquex
1a12e56be21da064d092b76fa3cce9bcb192103c
[ "MIT" ]
4
2020-10-20T08:22:43.000Z
2022-01-19T17:21:32.000Z
defmodule Liquex.FilterTest do @moduledoc false use ExUnit.Case, async: true alias Liquex.Filter doctest Liquex.Filter test "apply" do assert 5 == Filter.apply(-5, {:filter, ["abs", {:arguments, []}]}, %{}) end end
18
75
0.653846
73816e7b2a89787b560414a5f65d19f6c38ec1e1
1,051
ex
Elixir
elixir/phoenix_demo/lib/phoenix_demo/application.ex
gilmoreg/learn
0c4f34387f0d2235ecd88ac62fb86a51f87eb5c2
[ "MIT" ]
null
null
null
elixir/phoenix_demo/lib/phoenix_demo/application.ex
gilmoreg/learn
0c4f34387f0d2235ecd88ac62fb86a51f87eb5c2
[ "MIT" ]
null
null
null
elixir/phoenix_demo/lib/phoenix_demo/application.ex
gilmoreg/learn
0c4f34387f0d2235ecd88ac62fb86a51f87eb5c2
[ "MIT" ]
null
null
null
defmodule PhoenixDemo.Application do use Application # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications def start(_type, _args) do import Supervisor.Spec # Define workers and child supervisors to be supervised children = [ # Start the Ecto repository supervisor(PhoenixDemo.Repo, []), # Start the endpoint when the application starts supervisor(PhoenixDemoWeb.Endpoint, []), # Start your own worker by calling: PhoenixDemo.Worker.start_link(arg1, arg2, arg3) # worker(PhoenixDemo.Worker, [arg1, arg2, arg3]), ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: PhoenixDemo.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do PhoenixDemoWeb.Endpoint.config_change(changed, removed) :ok end end
32.84375
89
0.721218
73817b3e775972521fbf3ec97ddf073727cc412a
552
ex
Elixir
lib/myApi_web/views/changeset_view.ex
alex2chan/Phoenix-JWT-Auth-API
5313b41bb590db4c12bdc16f624c11a035d4d692
[ "MIT" ]
40
2018-05-20T21:30:30.000Z
2021-09-10T07:25:44.000Z
lib/myApi_web/views/changeset_view.ex
alex2chan/Phoenix-JWT-Auth-API
5313b41bb590db4c12bdc16f624c11a035d4d692
[ "MIT" ]
3
2020-09-07T10:53:53.000Z
2022-02-12T21:45:34.000Z
lib/myApi_web/views/changeset_view.ex
alex2chan/Phoenix-JWT-Auth-API
5313b41bb590db4c12bdc16f624c11a035d4d692
[ "MIT" ]
15
2018-06-07T08:16:20.000Z
2020-04-12T07:38:05.000Z
defmodule MyApiWeb.ChangesetView do use MyApiWeb, :view @doc """ Traverses and translates changeset errors. See `Ecto.Changeset.traverse_errors/2` and `MyApiWeb.ErrorHelpers.translate_error/1` for more details. """ def translate_errors(changeset) do Ecto.Changeset.traverse_errors(changeset, &translate_error/1) end def render("error.json", %{changeset: changeset}) do # When encoded, the changeset returns its errors # as a JSON object. So we just pass it forward. %{errors: translate_errors(changeset)} end end
27.6
65
0.735507
73818f7b03533448cdd1f52b45ec22fc761d9a8f
2,849
ex
Elixir
deps/distillery/lib/mix/lib/releases/logger.ex
renatoalmeidaoliveira/Merlin
92a0e318872190cdfa07ced85ee54cc69cad5c14
[ "Apache-2.0" ]
null
null
null
deps/distillery/lib/mix/lib/releases/logger.ex
renatoalmeidaoliveira/Merlin
92a0e318872190cdfa07ced85ee54cc69cad5c14
[ "Apache-2.0" ]
null
null
null
deps/distillery/lib/mix/lib/releases/logger.ex
renatoalmeidaoliveira/Merlin
92a0e318872190cdfa07ced85ee54cc69cad5c14
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Releases.Logger do @moduledoc """ This is the logger implementation for Distillery. It is necessary to use because the process-based Logger in Elixir will drop messages when errors occur which kill the runtime, making debugging more difficult. We also colorize and format messages here. """ @type verbosity :: :silent | :quiet | :normal | :verbose @doc """ Configure the logging verbosity of the release logger. Valid verbosity settings are: - silent - no output except errors - quiet - no output except warnings/errors - normal - no debug output (default) - verbose - all output """ @spec configure(verbosity) :: :ok def configure(verbosity) when is_atom(verbosity) do Application.put_env(:mix, :release_logger_verbosity, verbosity) end @debug_color IO.ANSI.cyan @info_color IO.ANSI.bright <> IO.ANSI.cyan @success_color IO.ANSI.bright <> IO.ANSI.green @warn_color IO.ANSI.yellow @error_color IO.ANSI.red @doc "Print a debug message in cyan" @spec debug(String.t) :: :ok def debug(message), do: log(:debug, colorize("==> #{message}", @debug_color)) @doc "Print an unformatted debug message in cyan" @spec debug(String.t, :plain) :: :ok def debug(message, :plain), do: log(:debug, colorize(message, @debug_color)) @doc "Print an informational message in bright cyan" @spec info(String.t) :: :ok def info(message), do: log(:info, colorize("==> #{message}", @info_color)) @doc "Print a success message in bright green" @spec success(String.t) :: :ok def success(message), do: log(:warn, colorize("==> #{message}", @success_color)) @doc "Print a warning message in yellow" @spec warn(String.t) :: :ok def warn(message) do case Application.get_env(:distillery, :warnings_as_errors) do true -> error(message) exit({:shutdown, 1}) _ -> log(:warn, colorize("==> #{message}", @warn_color)) end end @doc "Print a notice in yellow" @spec notice(String.t) :: :ok def notice(message), do: log(:notice, colorize(message, @warn_color)) @doc "Print an error message in red" @spec error(String.t) :: :ok def error(message), do: log(:error, colorize("==> #{message}", @error_color)) defp log(level, message), do: log(level, Application.get_env(:mix, :release_logger_verbosity, :normal), message) defp log(_, :verbose, message), do: IO.puts message defp log(:error, :silent, message), do: IO.puts message defp log(_level, :silent, _message), do: :ok defp log(:debug, :quiet, _message), do: :ok defp log(:debug, :normal, _message), do: :ok defp log(:info, :quiet, _message), do: :ok defp log(_level, _verbosity, message), do: IO.puts message defp colorize(message, color), do: IO.ANSI.format([color, message, IO.ANSI.reset]) end
37.486842
90
0.67006
7381bab1a9167347febcac0e4098c2df0561056f
2,544
ex
Elixir
lib/koans/14_enums.ex
themichaelyang/elixir-koans-solutions
35f6857bb62b22f3a21da21af753cdb484f884a8
[ "MIT" ]
null
null
null
lib/koans/14_enums.ex
themichaelyang/elixir-koans-solutions
35f6857bb62b22f3a21da21af753cdb484f884a8
[ "MIT" ]
null
null
null
lib/koans/14_enums.ex
themichaelyang/elixir-koans-solutions
35f6857bb62b22f3a21da21af753cdb484f884a8
[ "MIT" ]
null
null
null
defmodule Enums do use Koans @intro "Enums" koan "Knowing how many elements are in a list is important for book-keeping" do assert Enum.count([1, 2, 3]) == 3 end koan "Depending on the type, it counts pairs" do assert Enum.count(%{a: :foo, b: :bar}) == 2 end def less_than_five?(n), do: n < 5 koan "Elements can have a lot in common" do assert Enum.all?([1, 2, 3], &less_than_five?/1) == true assert Enum.all?([4, 6, 8], &less_than_five?/1) == false end def even?(n), do: rem(n, 2) == 0 koan "Sometimes you just want to know if there are any elements fulfilling a condition" do assert Enum.any?([1, 2, 3], &even?/1) == true assert Enum.any?([1, 3, 5], &even?/1) == false end koan "Sometimes you just want to know if an element is part of the party" do input = [1, 2, 3] assert Enum.member?(input, 1) == true assert Enum.member?(input, 30) == false end def multiply_by_ten(n), do: 10 * n koan "Map converts each element of a list by running some function with it" do assert Enum.map([1, 2, 3], &multiply_by_ten/1) == [10, 20, 30] end def odd?(n), do: rem(n, 2) == 1 koan "Filter allows you to only keep what you really care about" do assert Enum.filter([1, 2, 3], &odd?/1) == [1, 3] end koan "Reject will help you throw out unwanted cruft" do assert Enum.reject([1, 2, 3], &odd?/1) == [2] end koan "You three there, follow me!" do assert Enum.take([1, 2, 3, 4, 5], 3) == [1, 2, 3] end koan "You can ask for a lot, but Enum won't hand you more than you give" do assert Enum.take([1, 2, 3, 4, 5], 10) == [1, 2, 3, 4, 5] end koan "Just like taking, you can also drop elements" do assert Enum.drop([-1, 0, 1, 2, 3], 2) == [1, 2, 3] end koan "Zip-up in pairs!" do letters = [:a, :b, :c] numbers = [1, 2, 3] assert Enum.zip(letters, numbers) == [a: 1, b: 2, c: 3] end koan "When you want to find that one pesky element" do assert Enum.find([1, 2, 3, 4], &even?/1) == 2 end def divisible_by_five?(n), do: rem(n, 5) == 0 koan "...but you don't quite find it..." do assert Enum.find([1, 2, 3], &divisible_by_five?/1) == :nil end koan "...you can settle for a consolation prize" do assert Enum.find([1, 2, 3], :no_such_element, &divisible_by_five?/1) == :no_such_element end koan "Collapse an entire list of elements down to a single one by repeating a function." do assert Enum.reduce([1, 2, 3], 0, fn element, accumulator -> element + accumulator end) == 6 end end
29.581395
95
0.61478
7381ce0c0cf5ee763e6e596af72c27efcf386149
7,997
ex
Elixir
lib/requiem/quic/nif.ex
5ebec/requiem
dee0638c9c68e13b194fd8e45c9e4fd1b4e3207a
[ "MIT" ]
37
2021-01-06T05:47:49.000Z
2022-03-24T11:07:00.000Z
lib/requiem/quic/nif.ex
5ebec/requiem
dee0638c9c68e13b194fd8e45c9e4fd1b4e3207a
[ "MIT" ]
null
null
null
lib/requiem/quic/nif.ex
5ebec/requiem
dee0638c9c68e13b194fd8e45c9e4fd1b4e3207a
[ "MIT" ]
2
2021-01-06T06:28:44.000Z
2022-03-07T10:04:34.000Z
defmodule Requiem.QUIC.NIF do use Rustler, otp_app: :requiem, crate: "requiem_nif", mode: :release @spec config_new() :: {:ok, integer} | {:error, :system_error | :not_found} def config_new(), do: error() @spec config_destroy(integer) :: :ok | {:error, :system_error | :not_found} def config_destroy(_ptr), do: error() @spec config_load_cert_chain_from_pem_file(integer, binary) :: :ok | {:error, :system_error | :not_found} def config_load_cert_chain_from_pem_file(_ptr, _file), do: error() @spec config_load_priv_key_from_pem_file(integer, binary) :: :ok | {:error, :system_error | :not_found} def config_load_priv_key_from_pem_file(_ptr, _file), do: error() @spec config_load_verify_locations_from_file(integer, binary) :: :ok | {:error, :system_error | :not_found} def config_load_verify_locations_from_file(_ptr, _file), do: error() @spec config_load_verify_locations_from_directory(integer, binary) :: :ok | {:error, :system_error | :not_found} def config_load_verify_locations_from_directory(_ptr, _dir), do: error() @spec config_verify_peer(integer, boolean) :: :ok | {:error, :system_error | :not_found} def config_verify_peer(_ptr, _verify), do: error() @spec config_grease(integer, boolean) :: :ok | {:error, :system_error | :not_found} def config_grease(_ptr, _grease), do: error() @spec config_enable_early_data(integer) :: :ok | {:error, :system_error | :not_found} def config_enable_early_data(_ptr), do: error() @spec config_set_application_protos(integer, binary) :: :ok | {:error, :system_error | :not_found} def config_set_application_protos(_ptr, _protos), do: error() @spec config_set_max_idle_timeout(integer, non_neg_integer) :: :ok | {:error, :system_error | :not_found} def config_set_max_idle_timeout(_ptr, _v), do: error() @spec config_set_max_udp_payload_size(integer, non_neg_integer) :: :ok | {:error, :system_error | :not_found} def config_set_max_udp_payload_size(_ptr, _v), do: error() @spec config_set_initial_max_data(integer, non_neg_integer) :: :ok | {:error, :system_error | :not_found} def config_set_initial_max_data(_ptr, _v), do: error() @spec config_set_initial_max_stream_data_bidi_local(integer, non_neg_integer) :: :ok | {:error, :system_error | :not_found} def config_set_initial_max_stream_data_bidi_local(_ptr, _v), do: error() @spec config_set_initial_max_stream_data_bidi_remote(integer, non_neg_integer) :: :ok | {:error, :system_error | :not_found} def config_set_initial_max_stream_data_bidi_remote(_ptr, _v), do: error() @spec config_set_initial_max_stream_data_uni(integer, non_neg_integer) :: :ok | {:error, :system_error | :not_found} def config_set_initial_max_stream_data_uni(_ptr, _v), do: error() @spec config_set_initial_max_streams_bidi(integer, non_neg_integer) :: :ok | {:error, :system_error | :not_found} def config_set_initial_max_streams_bidi(_ptr, _v), do: error() @spec config_set_initial_max_streams_uni(integer, non_neg_integer) :: :ok | {:error, :system_error | :not_found} def config_set_initial_max_streams_uni(_ptr, _v), do: error() @spec config_set_ack_delay_exponent(integer, non_neg_integer) :: :ok | {:error, :system_error | :not_found} def config_set_ack_delay_exponent(_ptr, _v), do: error() @spec config_set_max_ack_delay(integer, non_neg_integer) :: :ok | {:error, :system_error | :not_found} def config_set_max_ack_delay(_ptr, _v), do: error() @spec config_set_disable_active_migration(integer, boolean) :: :ok | {:error, :system_error | :not_found} def config_set_disable_active_migration(_ptr, _v), do: error() @spec config_set_cc_algorithm_name(integer, binary) :: :ok | {:error, :system_error | :not_found} def config_set_cc_algorithm_name(_ptr, _name), do: error() @spec config_enable_hystart(integer, boolean) :: :ok | {:error, :system_error | :not_found} def config_enable_hystart(_ptr, _v), do: error() @spec config_enable_dgram(integer, boolean, non_neg_integer, non_neg_integer) :: :ok | {:error, :system_error | :not_found} def config_enable_dgram(_ptr, _enabled, _recv_queue_len, _send_queue_len), do: error() @spec connection_accept(integer, binary, binary, term, pid, non_neg_integer) :: {:ok, integer} | {:error, :system_error | :not_found} def connection_accept(_config_ptr, _scid, _odcid, _peer, _sender_pid, _stream_buf_size), do: error() @spec connection_destroy(integer) :: :ok | {:error, :system_error | :not_found} def connection_destroy(_conn_ptr), do: error() @spec connection_close(integer, boolean, non_neg_integer, binary) :: {:ok, non_neg_integer} | {:error, :system_error | :already_closed} def connection_close(_conn, _app, _err, _reason), do: error() @spec connection_is_closed(integer) :: boolean def connection_is_closed(_conn), do: error() @spec connection_on_packet(pid, integer, binary) :: {:ok, non_neg_integer} | {:error, :system_error | :already_closed} def connection_on_packet(_pid, _conn, _packet), do: error() @spec connection_on_timeout(integer) :: {:ok, non_neg_integer} | {:error, :system_error | :already_closed} def connection_on_timeout(_conn), do: error() @spec connection_stream_send(integer, non_neg_integer, binary, boolean) :: {:ok, non_neg_integer} | {:error, :system_error | :already_closed} def connection_stream_send(_conn, _stream_id, _data, _fin), do: error() @spec connection_dgram_send(integer, binary) :: {:ok, non_neg_integer} | {:error, :system_error | :already_closed} def connection_dgram_send(_conn, _data), do: error() @spec packet_builder_new() :: {:ok, integer} | {:error, :system_error} def packet_builder_new(), do: error() @spec packet_builder_destroy(integer) :: :ok | {:error, :system_error} def packet_builder_destroy(_builder), do: error() @spec packet_builder_build_negotiate_version(integer, binary, binary) :: {:ok, binary} | {:error, :system_error} def packet_builder_build_negotiate_version(_builder, _scid, _dcid), do: error() @spec packet_builder_build_retry(integer, binary, binary, binary, binary, non_neg_integer) :: {:ok, binary} | {:error, :system_error} def packet_builder_build_retry(_builder, _scid, _dcid, _new_scid, _token, _version), do: error() @spec cpu_num() :: integer | {:error, :system_error | :not_found} def cpu_num(), do: error() @spec socket_sender_get(integer, non_neg_integer) :: {:ok, integer} | {:error, :system_error | :not_found} def socket_sender_get(_socket_ptr, _idx), do: error() @spec socket_sender_send(integer, term, binary) :: :ok | {:error, :system_error | :not_found} def socket_sender_send(_socket_ptr, _addr, _packet), do: error() @spec socket_sender_destroy(integer) :: :ok | {:error, :system_error | :not_found} def socket_sender_destroy(_socket_ptr), do: error() @spec socket_new(integer, non_neg_integer, non_neg_integer) :: {:ok, integer} | {:error, :system_error | :socket_error} def socket_new(_num_node, _read_timeout, _write_timeout), do: error() @spec socket_start(integer, binary, pid, [pid]) :: :ok | {:error, :system_error | :not_found} def socket_start(_ptr, _address, _pid, _target_pids), do: error() @spec socket_destroy(integer) :: :ok | {:error, :system_error | :not_found} def socket_destroy(_ptr), do: error() @spec socket_address_parts(term) :: {:ok, binary, non_neg_integer} def socket_address_parts(_address), do: error() @spec socket_address_from_string(binary) :: {:ok, term} | {:error, :bad_format} def socket_address_from_string(_address), do: error() defp error(), do: :erlang.nif_error(:nif_not_loaded) end
42.994624
98
0.700888
7381d71a07be3e05d5fd37b03e7f48a95563171c
1,743
ex
Elixir
lib/inch_ex/reporter/local.ex
AndrewDryga/inch_ex
59997ce05b60902c9b482409b09da7697b267c17
[ "MIT" ]
null
null
null
lib/inch_ex/reporter/local.ex
AndrewDryga/inch_ex
59997ce05b60902c9b482409b09da7697b267c17
[ "MIT" ]
null
null
null
lib/inch_ex/reporter/local.ex
AndrewDryga/inch_ex
59997ce05b60902c9b482409b09da7697b267c17
[ "MIT" ]
1
2022-03-17T18:34:45.000Z
2022-03-17T18:34:45.000Z
defmodule InchEx.Reporter.Local do @cli_api_end_point 'https://inch-ci.org/api/v1/cli' @doc """ Runs inch locally, if installed. If you want to force usage of a particular inch installation, set INCH_PATH environment variable: export INCH_PATH=/home/rrrene/projects/inch Otherwise, InchEx will take whatever `inch` command it finds. If it does not find any, it sends the data to the open API at inch-ci.org (or the endpoint defined in the INCH_CLI_API environment variable) to perform the analysis and reports the findings back. Returns a tuple `{:ok, _}` if successful, `{:error, _}` otherwise. """ def run(filename, args \\ []) do if local_inch?() do local_inch(args ++ ["--language=elixir", "--read-from-dump=#{filename}"]) else data = File.read!(filename) case :httpc.request(:post, {inch_cli_api_endpoint(), [], 'application/json', data}, [], []) do {:ok, {_, _, body}} -> InchEx.Reporter.handle_success(body) {:error, {:failed_connect, _, _}} -> InchEx.Reporter.handle_error "Connect failed." _ -> InchEx.Reporter.handle_error "InchEx failed." end end end defp inch_cli_api_endpoint do case System.get_env("INCH_CLI_API") do nil -> @cli_api_end_point url -> to_char_list url end end defp inch_cmd do case System.get_env("INCH_PATH") do nil -> System.find_executable("inch") dir -> Path.join([dir, "bin", "inch"]) end end defp local_inch? do !is_nil(inch_cmd()) end defp local_inch(args) do case System.cmd(inch_cmd(), args) do {output, 0} -> InchEx.Reporter.handle_success(output) {output, _} -> InchEx.Reporter.handle_error(output) end end end
31.690909
100
0.658635
7381e4f9d66d9273cf9a83333f4096b8f6d29cbf
11,007
ex
Elixir
debian/manpage.xml.ex
rzr/neheglqt
b80cbb859ec76e80c74ac646b94fafa44259431d
[ "Linux-OpenIB" ]
1
2021-02-06T01:34:45.000Z
2021-02-06T01:34:45.000Z
debian/manpage.xml.ex
rzr/neheglqt
b80cbb859ec76e80c74ac646b94fafa44259431d
[ "Linux-OpenIB" ]
null
null
null
debian/manpage.xml.ex
rzr/neheglqt
b80cbb859ec76e80c74ac646b94fafa44259431d
[ "Linux-OpenIB" ]
null
null
null
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [ <!-- `xsltproc -''-nonet \ -''-param man.charmap.use.subset "0" \ -''-param make.year.ranges "1" \ -''-param make.single.year.ranges "1" \ /usr/share/xml/docbook/stylesheet/docbook-xsl/manpages/docbook.xsl \ manpage.xml' A manual page <package>.<section> will be generated. You may view the manual page with: nroff -man <package>.<section> | less'. A typical entry in a Makefile or Makefile.am is: DB2MAN = /usr/share/sgml/docbook/stylesheet/xsl/docbook-xsl/manpages/docbook.xsl XP = xsltproc -''-nonet -''-param man.charmap.use.subset "0" manpage.1: manpage.xml $(XP) $(DB2MAN) $< The xsltproc binary is found in the xsltproc package. The XSL files are in docbook-xsl. A description of the parameters you can use can be found in the docbook-xsl-doc-* packages. Please remember that if you create the nroff version in one of the debian/rules file targets (such as build), you will need to include xsltproc and docbook-xsl in your Build-Depends control field. Alternatively use the xmlto command/package. That will also automatically pull in xsltproc and docbook-xsl. Notes for using docbook2x: docbook2x-man does not automatically create the AUTHOR(S) and COPYRIGHT sections. In this case, please add them manually as <refsect1> ... </refsect1>. To disable the automatic creation of the AUTHOR(S) and COPYRIGHT sections read /usr/share/doc/docbook-xsl/doc/manpages/authors.html. This file can be found in the docbook-xsl-doc-html package. Validation can be done using: `xmllint -''-noout -''-valid manpage.xml` General documentation about man-pages and man-page-formatting: man(1), man(7), http://www.tldp.org/HOWTO/Man-Page/ --> <!-- Fill in your name for FIRSTNAME and SURNAME. --> <!ENTITY dhfirstname "FIRSTNAME"> <!ENTITY dhsurname "SURNAME"> <!-- dhusername could also be set to "&dhfirstname; &dhsurname;". --> <!ENTITY dhusername "Philippe Coval"> <!ENTITY dhemail "[email protected]"> <!-- SECTION should be 1-8, maybe w/ subsection other parameters are allowed: see man(7), man(1) and http://www.tldp.org/HOWTO/Man-Page/q2.html. --> <!ENTITY dhsection "SECTION"> <!-- TITLE should be something like "User commands" or similar (see http://www.tldp.org/HOWTO/Man-Page/q2.html). --> <!ENTITY dhtitle "neheglqt User Manual"> <!ENTITY dhucpackage "NEHEGLQT"> <!ENTITY dhpackage "neheglqt"> ]> <refentry> <refentryinfo> <title>&dhtitle;</title> <productname>&dhpackage;</productname> <authorgroup> <author> <firstname>&dhfirstname;</firstname> <surname>&dhsurname;</surname> <contrib>Wrote this manpage for the Debian system.</contrib> <address> <email>&dhemail;</email> </address> </author> </authorgroup> <copyright> <year>2007</year> <holder>&dhusername;</holder> </copyright> <legalnotice> <para>This manual page was written for the Debian system (and may be used by others).</para> <para>Permission is granted to copy, distribute and/or modify this document under the terms of the GNU General Public License, Version 2 or (at your option) any later version published by the Free Software Foundation.</para> <para>On Debian systems, the complete text of the GNU General Public License can be found in <filename>/usr/share/common-licenses/GPL</filename>.</para> </legalnotice> </refentryinfo> <refmeta> <refentrytitle>&dhucpackage;</refentrytitle> <manvolnum>&dhsection;</manvolnum> </refmeta> <refnamediv> <refname>&dhpackage;</refname> <refpurpose>program to do something</refpurpose> </refnamediv> <refsynopsisdiv> <cmdsynopsis> <command>&dhpackage;</command> <!-- These are several examples, how syntaxes could look --> <arg choice="plain"><option>-e <replaceable>this</replaceable></option></arg> <arg choice="opt"><option>--example=<parameter>that</parameter></option></arg> <arg choice="opt"> <group choice="req"> <arg choice="plain"><option>-e</option></arg> <arg choice="plain"><option>--example</option></arg> </group> <replaceable class="option">this</replaceable> </arg> <arg choice="opt"> <group choice="req"> <arg choice="plain"><option>-e</option></arg> <arg choice="plain"><option>--example</option></arg> </group> <group choice="req"> <arg choice="plain"><replaceable>this</replaceable></arg> <arg choice="plain"><replaceable>that</replaceable></arg> </group> </arg> </cmdsynopsis> <cmdsynopsis> <command>&dhpackage;</command> <!-- Normally the help and version options make the programs stop right after outputting the requested information. --> <group choice="opt"> <arg choice="plain"> <group choice="req"> <arg choice="plain"><option>-h</option></arg> <arg choice="plain"><option>--help</option></arg> </group> </arg> <arg choice="plain"> <group choice="req"> <arg choice="plain"><option>-v</option></arg> <arg choice="plain"><option>--version</option></arg> </group> </arg> </group> </cmdsynopsis> </refsynopsisdiv> <refsect1 id="description"> <title>DESCRIPTION</title> <para>This manual page documents briefly the <command>&dhpackage;</command> and <command>bar</command> commands.</para> <para>This manual page was written for the Debian distribution because the original program does not have a manual page. Instead, it has documentation in the GNU <citerefentry> <refentrytitle>info</refentrytitle> <manvolnum>1</manvolnum> </citerefentry> format; see below.</para> <para><command>&dhpackage;</command> is a program that...</para> </refsect1> <refsect1 id="options"> <title>OPTIONS</title> <para>The program follows the usual GNU command line syntax, with long options starting with two dashes (`-'). A summary of options is included below. For a complete description, see the <citerefentry> <refentrytitle>info</refentrytitle> <manvolnum>1</manvolnum> </citerefentry> files.</para> <variablelist> <!-- Use the variablelist.term.separator and the variablelist.term.break.after parameters to control the term elements. --> <varlistentry> <term><option>-e <replaceable>this</replaceable></option></term> <term><option>--example=<replaceable>that</replaceable></option></term> <listitem> <para>Does this and that.</para> </listitem> </varlistentry> <varlistentry> <term><option>-h</option></term> <term><option>--help</option></term> <listitem> <para>Show summary of options.</para> </listitem> </varlistentry> <varlistentry> <term><option>-v</option></term> <term><option>--version</option></term> <listitem> <para>Show version of program.</para> </listitem> </varlistentry> </variablelist> </refsect1> <refsect1 id="files"> <title>FILES</title> <variablelist> <varlistentry> <term><filename>/etc/foo.conf</filename></term> <listitem> <para>The system-wide configuration file to control the behaviour of <application>&dhpackage;</application>. See <citerefentry> <refentrytitle>foo.conf</refentrytitle> <manvolnum>5</manvolnum> </citerefentry> for further details.</para> </listitem> </varlistentry> <varlistentry> <term><filename>${HOME}/.foo.conf</filename></term> <listitem> <para>The per-user configuration file to control the behaviour of <application>&dhpackage;</application>. See <citerefentry> <refentrytitle>foo.conf</refentrytitle> <manvolnum>5</manvolnum> </citerefentry> for further details.</para> </listitem> </varlistentry> </variablelist> </refsect1> <refsect1 id="environment"> <title>ENVIONMENT</title> <variablelist> <varlistentry> <term><envar>FOO_CONF</envar></term> <listitem> <para>If used, the defined file is used as configuration file (see also <xref linkend="files"/>).</para> </listitem> </varlistentry> </variablelist> </refsect1> <refsect1 id="diagnostics"> <title>DIAGNOSTICS</title> <para>The following diagnostics may be issued on <filename class="devicefile">stderr</filename>:</para> <variablelist> <varlistentry> <term><errortext>Bad configuration file. Exiting.</errortext></term> <listitem> <para>The configuration file seems to contain a broken configuration line. Use the <option>--verbose</option> option, to get more info. </para> </listitem> </varlistentry> </variablelist> <para><command>&dhpackage;</command> provides some return codes, that can be used in scripts:</para> <segmentedlist> <segtitle>Code</segtitle> <segtitle>Diagnostic</segtitle> <seglistitem> <seg><errorcode>0</errorcode></seg> <seg>Program exited successfully.</seg> </seglistitem> <seglistitem> <seg><errorcode>1</errorcode></seg> <seg>The configuration file seems to be broken.</seg> </seglistitem> </segmentedlist> </refsect1> <refsect1 id="bugs"> <!-- Or use this section to tell about upstream BTS. --> <title>BUGS</title> <para>The program is currently limited to only work with the <package>foobar</package> library.</para> <para>The upstreams <acronym>BTS</acronym> can be found at <ulink url="http://bugzilla.foo.tld"/>.</para> </refsect1> <refsect1 id="see_also"> <title>SEE ALSO</title> <!-- In alpabetical order. --> <para><citerefentry> <refentrytitle>bar</refentrytitle> <manvolnum>1</manvolnum> </citerefentry>, <citerefentry> <refentrytitle>baz</refentrytitle> <manvolnum>1</manvolnum> </citerefentry>, <citerefentry> <refentrytitle>foo.conf</refentrytitle> <manvolnum>5</manvolnum> </citerefentry></para> <para>The programs are documented fully by <citetitle>The Rise and Fall of a Fooish Bar</citetitle> available via the <citerefentry> <refentrytitle>info</refentrytitle> <manvolnum>1</manvolnum> </citerefentry> system.</para> </refsect1> </refentry>
37.695205
84
0.632143
7381ebfcbc33a489ec26f6bd63757a51c290cd75
570
ex
Elixir
web/router.ex
mskog/Upfeed
34fad85cbf7c0c7b0a7d0238c312b29edb61b1d1
[ "MIT" ]
null
null
null
web/router.ex
mskog/Upfeed
34fad85cbf7c0c7b0a7d0238c312b29edb61b1d1
[ "MIT" ]
null
null
null
web/router.ex
mskog/Upfeed
34fad85cbf7c0c7b0a7d0238c312b29edb61b1d1
[ "MIT" ]
null
null
null
defmodule Upfeed.Router do use Upfeed.Web, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug :accepts, ["json"] end scope "/", Upfeed do pipe_through :browser # Use the default browser stack get "/:feed", FeedEntryController, :index get "/:feed/:file", FeedEntryController, :show end # Other scopes may use custom stacks. # scope "/api", Upfeed do # pipe_through :api # end end
20.357143
57
0.673684
738201aee3261571099884c778b61092fd06308b
4,714
exs
Elixir
test/indulgences_test.exs
TrsNium/Indulgences
9492e49508551eb30c030016f5422475184e90f7
[ "MIT" ]
5
2019-09-09T08:51:25.000Z
2020-01-01T06:28:21.000Z
test/indulgences_test.exs
TrsNium/Indulgences
9492e49508551eb30c030016f5422475184e90f7
[ "MIT" ]
10
2020-05-19T20:28:34.000Z
2022-03-23T21:39:11.000Z
test/indulgences_test.exs
TrsNium/Indulgences
9492e49508551eb30c030016f5422475184e90f7
[ "MIT" ]
null
null
null
defmodule IndulgencesTest do use ExUnit.Case doctest Indulgences test "basic scenario execute engine " do test_scenario = Indulgences.Scenario.new( "test_scenario", fn -> Indulgences.Http.new("Test Local Request") |> Indulgences.Http.get("https://localhost") |> Indulgences.Http.set_header("hoge", "huga") |> Indulgences.Http.check(fn %HTTPoison.Response{} = response -> Indulgences.Http.is_status(response, 404) end) end ) IO.puts(inspect(Indulgences.Scenario.Executer.execute_scenario(test_scenario))) end test "flexible scenario execute engine " do test_scenario = Indulgences.Scenario.new( "test_scenario", fn -> Indulgences.Http.new("Test Local Request") |> Indulgences.Http.get("http://localhost") |> Indulgences.Http.set_header("hoge", "huga") |> Indulgences.Http.check(fn %HTTPoison.Response{} = response, %{} = state -> Indulgences.Http.is_status(response, 200) state |> Map.put(:body, response.body) end) |> Indulgences.Http.new("Test Google Request") |> Indulgences.Http.get("http://www.google.com") |> Indulgences.Http.set_header( "huga", fn state -> Map.get(state, :body) end ) end ) IO.puts(inspect(Indulgences.Scenario.Executer.execute_scenario(test_scenario))) end test "execute scenario with activation" do Indulgences.Report.clear() Indulgences.Scenario.new( "test_scenario", fn -> Indulgences.Http.new("Test Local Request") |> Indulgences.Http.get("http://localhost") |> Indulgences.Http.set_header("header", "value") |> Indulgences.Http.check(fn %HTTPoison.Response{} = response, %{} = state -> Indulgences.Http.is_status(response, 200) state |> Map.put(:body, response.body) end) Indulgences.Http.new("Test Local Request2") |> Indulgences.Http.get("http://localhost") |> Indulgences.Http.set_header("header-body", fn state -> Map.get(state, :body) end) |> Indulgences.Http.check(fn %HTTPoison.Response{} = response -> Indulgences.Http.is_status(response, 200) end) end ) |> Indulgences.Scenario.inject(fn -> Indulgences.Activation.constant_users_per_sec(100, 3) end) |> Indulgences.Simulation.start() end test "execute scenario with distributed activation" do Indulgences.Report.clear() simulation_configure = Indulgences.Simulation.Config.new(%{Node.self() => 1}) Indulgences.Scenario.new( "test_scenario", fn -> Indulgences.Http.new("Test Local Request") |> Indulgences.Http.get("http://localhost") |> Indulgences.Http.set_header("header", "value") |> Indulgences.Http.check(fn %HTTPoison.Response{} = response, %{} = state -> Indulgences.Http.is_status(response, 200) state |> Map.put(:body, response.body) end) Indulgences.Http.new("Test Local Request2") |> Indulgences.Http.get("http://localhost") |> Indulgences.Http.set_header("header-body", fn state -> Map.get(state, :body) end) |> Indulgences.Http.check(fn %HTTPoison.Response{} = response -> Indulgences.Http.is_status(response, 200) end) end ) |> Indulgences.Scenario.inject(fn -> Indulgences.Activation.constant_users_per_sec(100, 10) end) |> Indulgences.Simulation.start(simulation_configure) end test "request_option update headers" do test_request_option = %Indulgences.Http{headers: [{"hoge", "huga"}]} desired1 = %Indulgences.Http{headers: [{"hoge", "hugahuga"}]} desired2 = %Indulgences.Http{headers: [{"hoge", "huga"}, {"huga", "hoge"}]} assert Indulgences.Http.update_header(test_request_option, "hoge", "hugahuga") == desired1 assert Indulgences.Http.update_header(test_request_option, "huga", "hoge") == desired2 end test "request_option_evaluter evalute option" do alias Indulgences.Http.Evaluter alias Indulgences.Http state = %{url: "test_url", value: "test_value"} request_option = %Http{} |> Map.put(:url, fn state -> Map.get(state, :url) end) |> Map.put(:headers, [{"key", fn state -> Map.get(state, :value) end}]) desired_request_option = %Http{url: "test_url", headers: [{"key", "test_value"}]} evaluted_request_option = Evaluter.evalute_http(request_option, state) assert evaluted_request_option == desired_request_option end end
34.15942
94
0.627068
738202a7e25f405b50e7444b2007dacc39598659
1,626
exs
Elixir
test/fake_server/request_test.exs
JacksonIsaac/fake_server
a646287b252d1ce4da4b61eac50e897a6423b7ed
[ "Apache-2.0" ]
null
null
null
test/fake_server/request_test.exs
JacksonIsaac/fake_server
a646287b252d1ce4da4b61eac50e897a6423b7ed
[ "Apache-2.0" ]
null
null
null
test/fake_server/request_test.exs
JacksonIsaac/fake_server
a646287b252d1ce4da4b61eac50e897a6423b7ed
[ "Apache-2.0" ]
null
null
null
defmodule FakeServer.RequestTest do use ExUnit.Case @cowboy_req { :http_req, :some_port, :ranch_tcp, :keepalive, :some_pid, "POST", :"HTTP/1.1", {{127, 0, 0, 1}, 52683}, "127.0.0.1", :undefined, 6455, "/", :undefined, "a=b", :undefined, [], [{"host", "127.0.0.1:6455"}, {"user-agent", "hackney/1.10.1"}, {"content-type", "application/octet-stream"}, {"content-length", "14"}], [], :undefined, [], :waiting, "{\"test\": true}", :undefined, false, :waiting, [], "", :undefined } describe "#from_cowboy_req" do test "creates a struct with the http method of cowboy_req object" do request = FakeServer.Request.from_cowboy_req(@cowboy_req) assert request.method == "POST" end test "creates a struct with the http body of cowboy_req object" do request = FakeServer.Request.from_cowboy_req(@cowboy_req) assert request.body == "{\"test\": true}" end test "creates a struct with the http headers of cowboy_req object" do request = FakeServer.Request.from_cowboy_req(@cowboy_req) assert request.headers == %{"user-agent" => "hackney/1.10.1", "host" => "127.0.0.1:6455", "content-length" => "14", "content-type" => "application/octet-stream"} end test "creates a struct with the http query_string of cowboy_req object" do request = FakeServer.Request.from_cowboy_req(@cowboy_req) assert request.query_string == "a=b" end test "creates a struct with the http query of cowboy_req object" do request = FakeServer.Request.from_cowboy_req(@cowboy_req) assert request.query == %{"a" => "b"} end end end
40.65
167
0.652522
7382703b57c5d31c660e87482477d6e9a324b861
6,742
ex
Elixir
lib/tentacat/gists.ex
hi-rustin/tentacat
be0b4a671f90faab2598b6d58a691d506f46cfb5
[ "MIT" ]
432
2015-01-19T20:38:35.000Z
2022-01-11T14:32:28.000Z
lib/tentacat/gists.ex
hi-rustin/tentacat
be0b4a671f90faab2598b6d58a691d506f46cfb5
[ "MIT" ]
183
2015-01-19T08:55:29.000Z
2022-03-01T20:26:03.000Z
lib/tentacat/gists.ex
hi-rustin/tentacat
be0b4a671f90faab2598b6d58a691d506f46cfb5
[ "MIT" ]
189
2015-01-04T14:56:59.000Z
2021-12-14T20:48:18.000Z
defmodule Tentacat.Gists do import Tentacat, [:except, :delete, 2] alias Tentacat.Client @doc """ List current user's gists. ## Examples Tentacat.Gists.list_mine(client) More info at: https://developer.github.com/v3/gists/#list-a-users-gists """ @spec list_mine(Client.t(), Keyword.t()) :: Tentacat.response() def list_mine(client, params \\ [], options \\ []) do get("gists", client, params, options) end @doc """ List users gists. ## Example Tentacat.Gists.list_users(client, "steve") Tentacat.Gists.list_users("steve") More info at: https://developer.github.com/v3/gists/#list-a-users-gists """ @spec list_users(Client.t(), binary, Keyword.t(), Keyword.t()) :: Tentacat.response() def list_users(client \\ %Client{}, owner, params \\ [], options \\ []) do get("users/#{owner}/gists", client, params, options) end @doc """ List all public gists. ## Example Tentacat.Gists.list_public Tentacat.Gists.list_public(client) More info at: https://developer.github.com/v3/gists/#list-all-public-gists """ @spec list_public(Client.t(), Keyword.t(), Keyword.t()) :: Tentacat.response() def list_public(client \\ %Client{}, params \\ [], options \\ []) do get("gists/public", client, params, Keyword.merge([pagination: :none], options)) end @doc """ List starred gists. ## Example Tentacat.Gists.list_starred(client) More info at: https://developer.github.com/v3/gists/#list-starred-gists """ @spec list_starred(Client.t(), Keyword.t(), Keyword.t()) :: Tentacat.response() def list_starred(client, params \\ [], options \\ []) do get("gists/starred", client, params, Keyword.merge([pagination: :none], options)) end @doc """ Get a single gist. ## Example Tentacat.Gists.gist_get("fe771b85eeeff878d177b0c0f3840afd") Tentacat.Gists.gist_get(client, "fe771b85eeeff878d177b0c0f3840afd") More info at: https://developer.github.com/v3/gists/#get-a-single-gist """ @spec gist_get(Client.t(), binary) :: Tentacat.response() def gist_get(client \\ %Client{}, gist_id) do get("gists/#{gist_id}", client) end @doc """ Get a specific revision of a gist. ## Example Tentacat.Gists.get_revision("fe771b85eeeff878d177b0c0f3840afd", "0ba06a873509677ab40b8ed5575f249a55c6fc41") Tentacat.Gists.get_revision(client, "fe771b85eeeff878d177b0c0f3840afd", "0ba06a873509677ab40b8ed5575f249a55c6fc41") More info at: https://developer.github.com/v3/gists/#get-a-specific-revision-of-a-gist """ @spec get_revision(Client.t(), binary, binary) :: Tentacat.response() def get_revision(client \\ %Client{}, gist_id, sha) do get("gists/#{gist_id}/#{sha}", client) end @doc """ Create a new gist for the authenticated user. Gist body example: ```elixir %{ "files" => %{ "hello.rb" => %{"content" => "puts 'Hello World'"}, "hello.py" => %{"content" => "print 'Hello World'"} }, "description" => "Hello World Examples", "public" => false } ``` ## Example Tentacat.Gists.create(client, body) More info at: https://developer.github.com/v3/gists/#create-a-gist """ @spec create(Client.t(), map) :: Tentacat.response() def create(client, body) when is_map(body) do post("gists", client, body) end @doc """ Edit a gist. Gist body example: ```elixir %{ "description" => "Hello World Examples", "files" => %{ "hello_world_ruby.txt" => %{ "content" => "Run `ruby hello.rb` or `python hello.py` to print Hello World", "filename" => "hello.md" }, "hello_world_python.txt" => nil, "new_file.txt" => %{ "content" => "This is a new placeholder file." } } } ``` ## Example Tentacat.Gists.edit(client, "fe771b85eeeff878d177b0c0f3840afd", body) More info at: https://developer.github.com/v3/gists/#edit-a-gist """ @spec edit(Client.t(), binary, map) :: Tentacat.response() def edit(client, gist_id, body) when is_map(body) do patch("gists/#{gist_id}", client, body) end @doc """ List forks. ## Example Tentacat.Gists.list_forks("fe771b85eeeff878d177b0c0f3840afd") Tentacat.Gists.list_forks(client, "fe771b85eeeff878d177b0c0f3840afd") More info at: https://developer.github.com/v3/gists/#list-gist-forks """ @spec list_forks(Client.t(), binary, Keyword.t()) :: Tentacat.response() def list_forks(client \\ %Client{}, gist_id, params \\ []) do get("gists/#{gist_id}/forks", client, params) end @doc """ Fork a gist. ## Example Tentacat.Gists.fork(client, "fe771b85eeeff878d177b0c0f3840afd") More info: https://developer.github.com/v3/gists/#fork-a-gist """ @spec fork(Client.t(), binary) :: Tentacat.response() def fork(client, gist_id) do post("gists/#{gist_id}/forks", client, %{}) end @doc """ Star a gist. ## Example Tentacat.Gists.star(client, "fe771b85eeeff878d177b0c0f3840afd") More info: https://developer.github.com/v3/gists/#star-a-gist """ @spec star(Client.t(), binary) :: Tentacat.response() def star(client, gist_id) do put("gists/#{gist_id}/star", client) end @doc """ Unstar a gist. ## Example Tentacat.Gists.unstar(client, "fe771b85eeeff878d177b0c0f3840afd") More info: https://developer.github.com/v3/gists/#unstar-a-gist """ @spec unstar(Client.t(), binary) :: Tentacat.response() def unstar(client, gist_id) do Tentacat.delete("gists/#{gist_id}/star", client) end @doc """ Check if a gist is starred. ## Example Tentacat.Gists.check_if_starred(client, "") More info: https://developer.github.com/v3/gists/#check-if-a-gist-is-starred """ @spec check_if_starred(Client.t(), binary) :: Tentacat.response() def check_if_starred(client, gist_id) do get("gists/#{gist_id}/star", client) end @doc """ List gist commits. ## Example Tentacat.Gists.list_commits("fe771b85eeeff878d177b0c0f3840afd") Tentacat.Gists.list_commits(client, "fe771b85eeeff878d177b0c0f3840afd") More info at: https://developer.github.com/v3/gists/#list-gist-commits """ @spec list_commits(Client.t(), binary) :: Tentacat.response() def list_commits(client \\ %Client{}, gist_id) do get("gists/#{gist_id}/commits", client) end @doc """ Deleting a gist requires admin access. If OAuth is used, the gist scope is required. ## Example Tentacat.Gists.delete(client, "fe771b85eeeff878d177b0c0f3840afd") More info at: https://developer.github.com/v3/gists/#delete-a-gist """ @spec delete(Client.t(), binary) :: Tentacat.response() def delete(client, gist_id) do Tentacat.delete("gists/#{gist_id}", client) end end
26.543307
121
0.65752
7382753611c712023db75d9e164ac1fd5b031ba8
1,722
ex
Elixir
lib/wechat/server_message/xml_parser.ex
feng19/wechat
431c22818c60cd01fc5c676aa060feb303d0c444
[ "Apache-2.0" ]
7
2021-01-22T04:07:29.000Z
2021-12-14T14:01:30.000Z
lib/wechat/server_message/xml_parser.ex
feng19/wechat
431c22818c60cd01fc5c676aa060feb303d0c444
[ "Apache-2.0" ]
1
2021-03-17T15:44:26.000Z
2021-03-17T15:44:26.000Z
lib/wechat/server_message/xml_parser.ex
feng19/wechat
431c22818c60cd01fc5c676aa060feb303d0c444
[ "Apache-2.0" ]
2
2021-03-17T14:35:56.000Z
2021-08-10T07:44:10.000Z
if Code.ensure_loaded?(Saxy) do defmodule WeChat.ServerMessage.XmlParser do @moduledoc "XML Parser" @behaviour Saxy.Handler @spec parse(xml :: String.t()) :: {:ok, map()} def parse(xml) do Saxy.parse_string(xml, __MODULE__, []) end @impl true def handle_event(:start_document, _prolog, stack) do {:ok, stack} end def handle_event(:start_element, {element, _attributes}, stack) do {:ok, [{element, []} | stack]} end def handle_event(:characters, chars, [{element, content} | stack] = old) do case String.trim(chars) do "" -> {:ok, old} chars -> {:ok, [{element, [chars | content]} | stack]} end end def handle_event(:end_element, tag_name, stack) do [{^tag_name, content} | stack] = stack current = {tag_name, Enum.reverse(content)} case stack do [] -> {:ok, [current]} [{parent_tag_name, parent_content} | rest] -> parent = {parent_tag_name, [current | parent_content]} {:ok, [parent | rest]} end end def handle_event(:end_document, _data, stack) do state = stack |> stack_to_map() |> Map.get("xml") {:ok, state} end defp stack_to_map(stack) do Map.new(stack, fn {name, []} -> {name, ""} {name, [content]} when is_binary(content) -> {name, content} {name, content} -> with [{"item", _}] <- Enum.uniq_by(content, &elem(&1, 0)) do content = Enum.map(content, &(&1 |> elem(1) |> stack_to_map())) {name, content} else _ -> {name, stack_to_map(content)} end end) end end end
25.701493
79
0.543554
7382c5c061736a230e6f8db46556e75bb57f2f40
484
ex
Elixir
lib/authex/plugs/unauthorized_plug.ex
notproperlycut/authex
1361ddbde275d711c76d7897481a5d47d7ca1732
[ "MIT" ]
null
null
null
lib/authex/plugs/unauthorized_plug.ex
notproperlycut/authex
1361ddbde275d711c76d7897481a5d47d7ca1732
[ "MIT" ]
null
null
null
lib/authex/plugs/unauthorized_plug.ex
notproperlycut/authex
1361ddbde275d711c76d7897481a5d47d7ca1732
[ "MIT" ]
null
null
null
defmodule Authex.UnauthorizedPlug do @moduledoc """ A plug to mark the status as unauthorized. This plug is the default used when authentication fails with `Authex.AuthenticationPlug`. It will put a `401` status into the conn with the body `"Unauthorized"`. """ @behaviour Plug import Plug.Conn @impl Plug def init(opts \\ []) do opts end @impl Plug def call(conn, _options) do conn |> send_resp(401, "Not Authorized") |> halt() end end
19.36
91
0.67562
7382d797da648828cc099d4f73c17e755fafcb15
1,617
exs
Elixir
test/honeydew/queue/ecto_poll_queue_integration_test.exs
kianmeng/honeydew
7c0e825c70ef4b72c82d02ca95491e7365d6b2e8
[ "MIT" ]
717
2015-06-15T19:30:54.000Z
2022-03-22T06:10:09.000Z
test/honeydew/queue/ecto_poll_queue_integration_test.exs
kianmeng/honeydew
7c0e825c70ef4b72c82d02ca95491e7365d6b2e8
[ "MIT" ]
106
2015-06-25T05:38:05.000Z
2021-12-08T23:17:19.000Z
test/honeydew/queue/ecto_poll_queue_integration_test.exs
kianmeng/honeydew
7c0e825c70ef4b72c82d02ca95491e7365d6b2e8
[ "MIT" ]
60
2015-06-07T00:48:37.000Z
2022-03-06T08:20:23.000Z
defmodule Honeydew.EctoPollQueueIntegrationTest do alias Mix.Shell.IO, as: Output use ExUnit.Case, async: false @moduletag timeout: 4 * 60 * 1_000 @examples_root "./examples/ecto_poll_queue" # Postgres test "ecto poll queue external project test: Postgres" do announce_test("Postgres (unprefixed)") :ok = mix("deps.get", "postgres", prefixed: false) :ok = mix("test", "postgres", prefixed: false) end test "ecto poll queue external project test: Postgres (prefixed)" do announce_test("Postgres (prefixed)") :ok = mix("deps.get", "postgres", prefixed: true) :ok = mix("test", "postgres", prefixed: true) end # Cockroach test "ecto poll queue external project test: Cockroach" do announce_test("CockroachDB (unprefixed)") :ok = mix("deps.get", "cockroach", prefixed: false) :ok = mix("test", "cockroach", prefixed: false) end defp announce_test(message) do Output.info( "\n#{IO.ANSI.underline()}[ECTO POLL QUEUE INTEGRATION] #{message}#{IO.ANSI.reset()}" ) end defp mix(task, database, opts) when is_binary(task), do: mix([task], database, opts) defp mix(task, database, prefixed: prefixed_tables) do environment = [{"MIX_ENV", database}] |> add_prefixed_tables_env(prefixed_tables) {_, exit_code} = System.cmd("mix", task, cd: @examples_root, into: IO.stream(:stdio, 1), env: environment) if exit_code == 0 do :ok else {:error, exit_code} end end defp add_prefixed_tables_env(env, true), do: env ++ [{"prefixed_tables", "true"}] defp add_prefixed_tables_env(env, false), do: env end
31.705882
95
0.673469
7382efaa3bc90c7dcd9f54204b6d860c4e85e510
919
ex
Elixir
lib/ash/registry/dsl.ex
ash-project/ash
63c240ebbdda6efc2ba8b24547f143cb8bd8c57e
[ "MIT" ]
528
2019-12-08T01:51:54.000Z
2022-03-30T10:09:45.000Z
lib/ash/registry/dsl.ex
ash-project/ash
63c240ebbdda6efc2ba8b24547f143cb8bd8c57e
[ "MIT" ]
278
2019-12-04T15:25:06.000Z
2022-03-31T03:40:51.000Z
lib/ash/registry/dsl.ex
ash-project/ash
63c240ebbdda6efc2ba8b24547f143cb8bd8c57e
[ "MIT" ]
53
2020-08-17T22:08:09.000Z
2022-03-24T01:58:59.000Z
defmodule Ash.Registry.Dsl do @entry %Ash.Dsl.Entity{ name: :entry, describe: "A reference to an ash module (typically a resource)", target: Ash.Registry.Entry, args: [:entry], examples: [ "entry MyApp.User" ], schema: [ entry: [ type: :atom, required: true, doc: "The referenced module" ] ] } @entries %Ash.Dsl.Section{ name: :entries, describe: "List the entries present in this registry", examples: [ """ entries do entry MyApp.User entry MyApp.Post entry MyApp.Comment end """ ], entities: [ @entry ] } @sections [@entries] @moduledoc """ A small DSL for declaring an `Ash.Registry`. # Table of Contents #{Ash.Dsl.Extension.doc_index(@sections)} #{Ash.Dsl.Extension.doc(@sections)} """ use Ash.Dsl.Extension, sections: @sections end
18.755102
68
0.572361
7383194dea07a579a4e8e5019ca7a6eaf23871d9
2,148
exs
Elixir
config/prod.exs
arpieb/aggit
048a4f25da9aa1d0d41f350b67f9b034a6e65aa3
[ "Apache-2.0" ]
null
null
null
config/prod.exs
arpieb/aggit
048a4f25da9aa1d0d41f350b67f9b034a6e65aa3
[ "Apache-2.0" ]
null
null
null
config/prod.exs
arpieb/aggit
048a4f25da9aa1d0d41f350b67f9b034a6e65aa3
[ "Apache-2.0" ]
null
null
null
use Mix.Config # For production, we configure the host to read the PORT # from the system environment. Therefore, you will need # to set PORT=80 before running your server. # # You should also configure the url host to something # meaningful, we use this information when generating URLs. # # Finally, we also include the path to a manifest # containing the digested version of static files. This # manifest is generated by the mix phoenix.digest task # which you typically run after static files are built. config :aggit, Aggit.Endpoint, http: [port: {:system, "PORT"}], url: [host: "example.com", port: 80], cache_static_manifest: "priv/static/manifest.json" # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :aggit, Aggit.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [port: 443, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH")] # # Where those two env variables return an absolute path to # the key and cert in disk or a relative path inside priv, # for example "priv/ssl/server.key". # # We also recommend setting `force_ssl`, ensuring no data is # ever sent via http, always redirecting to https: # # config :aggit, Aggit.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # ## Using releases # # If you are doing OTP releases, you need to instruct Phoenix # to start the server for all endpoints: # # config :phoenix, :serve_endpoints, true # # Alternatively, you can configure exactly which server to # start per endpoint: # # config :aggit, Aggit.Endpoint, server: true # # You will also need to set the application root to `.` in order # for the new static assets to be served after a hot upgrade: # # config :aggit, Aggit.Endpoint, root: "." # Finally import the config/prod.secret.exs # which should be versioned separately. import_config "prod.secret.exs"
32.545455
67
0.709497
73833028b18a49c3e092d2af20766e8c62eafff5
575
ex
Elixir
lib/hap/services/faucet.ex
petermm/hap
550433a78bccd586ab6a7d8bf85765bfae58b13b
[ "MIT" ]
40
2019-10-26T01:58:42.000Z
2022-03-09T18:18:39.000Z
lib/hap/services/faucet.ex
petermm/hap
550433a78bccd586ab6a7d8bf85765bfae58b13b
[ "MIT" ]
11
2021-04-02T14:55:02.000Z
2021-11-05T13:49:55.000Z
lib/hap/services/faucet.ex
petermm/hap
550433a78bccd586ab6a7d8bf85765bfae58b13b
[ "MIT" ]
6
2020-05-18T09:34:14.000Z
2021-11-04T11:14:15.000Z
defmodule HAP.Services.Faucet do @moduledoc """ Struct representing an instance of the `public.hap.service.faucet` service """ defstruct active: nil, name: nil, fault: nil defimpl HAP.ServiceSource do def compile(value) do HAP.Service.ensure_required!(__MODULE__, "active", value.active) %HAP.Service{ type: "D7", characteristics: [ {HAP.Characteristics.Active, value.active}, {HAP.Characteristics.Name, value.name}, {HAP.Characteristics.StatusFault, value.fault} ] } end end end
25
76
0.645217
7383501ff7c17ddb3edf5d1c546c768786e14c2d
1,672
ex
Elixir
clients/replica_pool/lib/google_api/replica_pool/v1beta1/model/replicas_delete_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/replica_pool/lib/google_api/replica_pool/v1beta1/model/replicas_delete_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/replica_pool/lib/google_api/replica_pool/v1beta1/model/replicas_delete_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "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.ReplicaPool.V1beta1.Model.ReplicasDeleteRequest do @moduledoc """ ## Attributes * `abandonInstance` (*type:* `boolean()`, *default:* `nil`) - Whether the instance resource represented by this replica should be deleted or abandoned. If abandoned, the replica will be deleted but the virtual machine instance will remain. By default, this is set to false and the instance will be deleted along with the replica. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :abandonInstance => boolean() } field(:abandonInstance) end defimpl Poison.Decoder, for: GoogleApi.ReplicaPool.V1beta1.Model.ReplicasDeleteRequest do def decode(value, options) do GoogleApi.ReplicaPool.V1beta1.Model.ReplicasDeleteRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ReplicaPool.V1beta1.Model.ReplicasDeleteRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.574468
333
0.757775
738352afa7b08da11f1a6645da58bd469193fb65
16,193
ex
Elixir
lib/ash/elixir_sense/plugin.ex
joshprice/ash
e452c4091918a88d51063000f7dc44b2f54f5f96
[ "MIT" ]
null
null
null
lib/ash/elixir_sense/plugin.ex
joshprice/ash
e452c4091918a88d51063000f7dc44b2f54f5f96
[ "MIT" ]
null
null
null
lib/ash/elixir_sense/plugin.ex
joshprice/ash
e452c4091918a88d51063000f7dc44b2f54f5f96
[ "MIT" ]
null
null
null
if Code.ensure_loaded?(ElixirSense.Plugin) do defmodule Ash.ElixirSense.Plugin do @moduledoc false @behaviour ElixirSense.Plugin use ElixirSense.Providers.Suggestion.GenericReducer alias Ash.ElixirSense.Resource alias Ash.ElixirSense.Types alias ElixirSense.Providers.Suggestion.Matcher def suggestions(hint, {_, function_call, arg_index, info}, _chain, opts) do option = info.option || get_option(opts.cursor_context.text_before) if option do get_suggestions(hint, opts, [function_call], {:value, option}) else get_suggestions(hint, opts, [function_call], {:arg, arg_index}) end end def suggestions(hint, opts) do option = get_section_option(opts.cursor_context.text_before) if option do get_suggestions(hint, opts, [], {:value, option}) else get_suggestions(hint, opts) end end def get_suggestions(hint, opts, opt_path \\ [], type \\ nil) do with true <- Enum.any?(opts.env.attributes, &(&1.name == :ash_is)), dsl_mod when not is_nil(dsl_mod) <- Enum.find(opts.env.requires, &ash_extension?/1) do extension_kinds = List.flatten(dsl_mod.module_info[:attributes][:ash_extension_kinds] || []) extensions = default_extensions(dsl_mod) ++ parse_extensions(opts, extension_kinds) scopes_to_lines = Enum.reduce(opts.buffer_metadata.lines_to_env, %{}, fn {line, env}, acc -> line = line - 1 Map.update(acc, env.scope_id, line, fn existing -> if existing < line do existing else line end end) end) scope_path = get_scope_path(opts, scopes_to_lines, nil, opt_path) case get_constructors(extensions, scope_path, hint, type) do [] -> :ignore constructors -> suggestions = case find_option(constructors, type) do {key, config} -> option_values(key, config, hint, opts) _ -> # Check for an edge case where we are editing the first argument of a constructor with {:value, option} <- type, entity when not is_nil(entity) <- find_building_entity(constructors, option), [arg | _] <- entity.args, config when not is_nil(config) <- entity.schema[arg] do option_values(arg, config, hint, opts) else _ -> hint = case type do {:value, val} when not is_nil(val) -> to_string(val) _ -> nil end Enum.map(constructors, fn {key, config} -> option_suggestions(key, config, type) %{__struct__: Ash.Dsl.Entity} = entity -> entity_suggestions(entity) %{__struct__: Ash.Dsl.Section} = section -> section_suggestions(section) end) |> filter_matches(hint) end end {:override, List.flatten(suggestions)} end else _ -> :ignore end end defp filter_matches(hints, match) do if match do Enum.filter(hints, fn %{label: label} -> Matcher.match?(label, match) end) else hints end end defp find_building_entity(constructors, option) do Enum.find(constructors, fn %{__struct__: Ash.Dsl.Entity, name: ^option} -> true _ -> false end) end defp find_option(constructors, {:value, option}) do Enum.find_value(constructors, fn {^option, _} = opt -> opt %{__struct__: Ash.Dsl.Entity, name: ^option, args: [arg | _], schema: schema} -> {arg, schema[arg]} _ -> false end) end defp find_option(constructors, {:arg, arg_index}) do Enum.find(constructors, fn {_option, config} -> config[:arg_index] == arg_index _ -> false end) end defp find_option(_, _), do: nil defp section_suggestions(section) do snippet = Map.get(section, :snippet) snippet = if snippet && snippet != "" do snippet else "$0" end %{ type: :generic, kind: :function, label: to_string(section.name), snippet: "#{section.name} do\n #{snippet}\nend", detail: "Dsl Section", documentation: Map.get(section, :docs) || "" } end defp entity_suggestions(entity) do snippet = Map.get(entity, :snippet) snippet = if snippet && snippet != "" do snippet else "$0" end %{ type: :generic, kind: :function, label: to_string(entity.name), snippet: "#{entity.name} #{args(entity)}do\n #{snippet}\nend", detail: "Dsl Entity", documentation: Map.get(entity, :docs) || "" } end defp option_suggestions(key, config, type) do snippet = if config[:snippet] && config[:snippet] != "" do config[:snippet] else default_snippet(config) end snippet = case type do :option -> "#{key}: #{snippet}" {:arg, _} -> "#{key}: #{snippet}" _ -> "#{key} #{snippet}" end %{ type: :generic, kind: :function, label: to_string(key), snippet: snippet, detail: "Option", documentation: config[:doc] } end defp get_option(text) when is_binary(text) do case Regex.named_captures(~r/\s(?<option>[^\s]*):[[:blank:]]*$/, text) do %{"option" => option} when option != "" -> try do String.to_existing_atom(option) rescue _ -> nil end _ -> nil end end defp get_option(_), do: nil defp get_section_option(text) when is_binary(text) do case Regex.named_captures(~r/\n[[:blank:]]+(?<option>[^\s]*)[[:blank:]]*$/, text) do %{"option" => option} when option != "" -> try do String.to_existing_atom(option) rescue _ -> nil end _ -> nil end end defp get_section_option(_), do: nil defp option_values(key, config, hint, opts) do case config[:type] do :boolean -> enum_suggestion([true, false], hint, "boolean") {:one_of, values} -> enum_suggestion(values, hint, to_string(key)) {:in, values} -> enum_suggestion(values, hint, to_string(key)) :ash_type -> builtin_types = Types.find_builtin_types(hint, opts.cursor_context) custom_types = Types.find_custom_types(hint, opts.module_store) builtin_types ++ custom_types :ash_resource -> Resource.find_resources(hint) {:ash_behaviour, behaviour, builtins} -> Resource.find_ash_behaviour_impls(behaviour, builtins, hint, opts.module_store) {:behaviour, behaviour} -> Resource.find_ash_behaviour_impls(behaviour, nil, hint, opts.module_store) {:ash_behaviour, behaviour} -> Resource.find_ash_behaviour_impls(behaviour, nil, hint, opts.module_store) _ -> [] end end defp enum_suggestion(values, hint, label) do Enum.flat_map(values, fn v -> inspected = inspect(v) if Matcher.match?(inspected, hint) do [ %{ type: :generic, kind: :type_parameter, label: label, insert_text: inspect(v), snippet: inspect(v), documentation: inspect(v), priority: 0 } ] else [] end end) end defp default_snippet(config) do cond do config[:type] == :boolean && config[:default] in [true, false] -> "#{to_string(!config[:default])}" config[:type] == :string -> "\"$0\"" match?({:list, {:in, _list}}, config[:type]) -> if config[:default] do inspect(config[:default]) else "$0" end match?({:list, _}, config[:type]) -> "[$0]" match?({:in, _}, config[:type]) -> if config[:default] do inspect(config[:default]) else {:in, list} = config[:type] inspect(Enum.at(list, 0)) end match?({:one_of, _}, config[:type]) -> if config[:default] do inspect(config[:default]) else {:one_of, list} = config[:type] inspect(Enum.at(list, 0)) end config[:type] == :atom -> ":$0" config[:type] == :mfa -> "{${1:module}, :${2:function}, [${3:args}]}" config[:type] == :keyword_list -> "[$0]" true -> "$0" end end defp args(entity) do case entity.args || [] do [] -> "" args -> args |> Enum.with_index() |> Enum.map(fn {arg, index} -> "${#{index + 1}:#{arg}}" end) |> Enum.intersperse(", ") |> Enum.join() |> Kernel.<>(" ") end end defp get_constructors(extensions, [], hint, _type) do Enum.flat_map( extensions, fn extension -> try do Enum.filter(extension.sections(), fn section -> Matcher.match?(to_string(section.name), hint) end) rescue _ -> [] end end ) end defp get_constructors(extensions, [first | rest], hint, type) do Enum.flat_map( extensions, fn extension -> try do Enum.flat_map(extension.sections(), fn section -> if section.name == first do do_find_constructors(section, rest, hint, type) else [] end end) rescue _ -> [] end end ) end defp do_find_constructors(entity_or_section, path, hint, type, recursives \\ []) defp do_find_constructors(%{__struct__: Ash.Dsl.Entity} = entity, [], hint, type, recursives) do case type do {:value, _value} -> entity.schema ++ Enum.flat_map(entity.entities || [], &elem(&1, 1)) ++ Enum.uniq(recursives ++ List.wrap(recursive_for(entity))) {:arg, arg_index} -> if arg_index >= Enum.count(entity.args || []) do find_opt_hints(entity, hint) ++ find_entity_hints(entity, hint, recursives) else Enum.map(entity.schema, fn {key, value} -> arg_index = Enum.find_index(entity.args || [], &(&1 == key)) if arg_index do {key, Keyword.put(value, :arg_index, arg_index)} else {key, value} end end) ++ Enum.uniq( recursives ++ List.wrap(recursive_for(entity)) ) end _ -> find_opt_hints(entity, hint) ++ find_entity_hints(entity, hint, recursives) end end defp do_find_constructors(section, [], hint, _type, recursives) do find_opt_hints(section, hint) ++ find_entity_hints(section, hint, []) ++ Enum.filter(section.sections, fn section -> Matcher.match?(to_string(section.name), hint) end) ++ recursives end defp do_find_constructors( %{__struct__: Ash.Dsl.Entity} = entity, [next | rest], hint, type, recursives ) do entity.entities |> Kernel.||([]) |> Enum.flat_map(&elem(&1, 1)) |> Enum.concat(recursives) |> Enum.concat(List.wrap(recursive_for(entity))) |> Enum.filter(&(&1.name == next)) |> Enum.flat_map( &do_find_constructors( &1, rest, hint, type, Enum.uniq(recursives ++ List.wrap(recursive_for(entity))) ) ) |> Enum.uniq() end defp do_find_constructors(section, [first | rest], hint, type, recursives) do Enum.flat_map(section.entities, fn entity -> if entity.name == first do do_find_constructors(entity, rest, hint, type) else [] end end) ++ Enum.flat_map(section.sections, fn section -> if section.name == first do do_find_constructors(section, rest, hint, type) else [] end end) ++ recursives end defp recursive_for(entity) do if entity.recursive_as do entity end end defp find_opt_hints(%{__struct__: Ash.Dsl.Entity} = entity, hint) do Enum.flat_map(entity.schema, fn {key, value} -> if Matcher.match?(to_string(key), hint) do arg_index = Enum.find_index(entity.args || [], &(&1 == key)) if arg_index do [{key, Keyword.put(value, :arg_index, arg_index)}] else [{key, value}] end else [] end end) end defp find_opt_hints(section, hint) do Enum.filter(section.schema, fn {key, _value} -> Matcher.match?(to_string(key), hint) end) end defp find_entity_hints(%{__struct__: Ash.Dsl.Entity} = entity, hint, recursives) do entity.entities |> Keyword.values() |> Enum.concat(recursives) |> Enum.concat(List.wrap(recursive_for(entity))) |> List.flatten() |> Enum.filter(fn entity -> Matcher.match?(to_string(entity.name), hint) end) end defp find_entity_hints(section, hint, _recursives) do Enum.filter(section.entities, fn entity -> Matcher.match?(to_string(entity.name), hint) end) end defp get_scope_path(opts, scopes_to_lines, env, path) do env = env || opts.env with earliest_line when not is_nil(earliest_line) <- scopes_to_lines[env.scope_id], [%{func: func}] when func != :defmodule <- opts.buffer_metadata.calls[earliest_line], next_env when not is_nil(next_env) <- opts.buffer_metadata.lines_to_env[earliest_line] do get_scope_path(opts, scopes_to_lines, next_env, [func | path]) else _ -> path end end defp ash_extension?(module) do true in List.wrap(module.module_info()[:attributes][:ash_dsl]) rescue _ -> false end defp default_extensions(dsl_mod) do dsl_mod.module_info[:attributes][:ash_default_extensions] |> List.wrap() |> List.flatten() end defp parse_extensions(opts, extension_kinds) do Enum.flat_map([:extensions | extension_kinds], fn extension_kind -> case Regex.named_captures( ~r/#{extension_kind}:\s+?(?<extensions>(\[[^\]]*\])|([^\s]*))?[\,\s$]/, opts.cursor_context.text_before ) do %{"extensions" => extensions} when extensions != "" -> extensions |> String.replace("[", "") |> String.replace("]", "") |> String.split(",") |> Enum.map(&String.trim/1) _ -> [] end end) |> Enum.uniq() |> Enum.map(&Module.concat([&1])) |> Enum.filter(&Code.ensure_loaded?/1) end end end
27.260943
100
0.509788
7383a3e428b54345bab96f38313d4d8d72ae503f
2,279
ex
Elixir
clients/dataflow/lib/google_api/dataflow/v1b3/model/source_fork.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/source_fork.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/dataflow/lib/google_api/dataflow/v1b3/model/source_fork.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "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.Dataflow.V1b3.Model.SourceFork do @moduledoc """ DEPRECATED in favor of DynamicSourceSplit. ## Attributes * `primary` (*type:* `GoogleApi.Dataflow.V1b3.Model.SourceSplitShard.t`, *default:* `nil`) - DEPRECATED * `primarySource` (*type:* `GoogleApi.Dataflow.V1b3.Model.DerivedSource.t`, *default:* `nil`) - DEPRECATED * `residual` (*type:* `GoogleApi.Dataflow.V1b3.Model.SourceSplitShard.t`, *default:* `nil`) - DEPRECATED * `residualSource` (*type:* `GoogleApi.Dataflow.V1b3.Model.DerivedSource.t`, *default:* `nil`) - DEPRECATED """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :primary => GoogleApi.Dataflow.V1b3.Model.SourceSplitShard.t(), :primarySource => GoogleApi.Dataflow.V1b3.Model.DerivedSource.t(), :residual => GoogleApi.Dataflow.V1b3.Model.SourceSplitShard.t(), :residualSource => GoogleApi.Dataflow.V1b3.Model.DerivedSource.t() } field(:primary, as: GoogleApi.Dataflow.V1b3.Model.SourceSplitShard) field(:primarySource, as: GoogleApi.Dataflow.V1b3.Model.DerivedSource) field(:residual, as: GoogleApi.Dataflow.V1b3.Model.SourceSplitShard) field(:residualSource, as: GoogleApi.Dataflow.V1b3.Model.DerivedSource) end defimpl Poison.Decoder, for: GoogleApi.Dataflow.V1b3.Model.SourceFork do def decode(value, options) do GoogleApi.Dataflow.V1b3.Model.SourceFork.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dataflow.V1b3.Model.SourceFork do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.696429
111
0.738482
7383aa6a913de364c7c7e8f9ac4d8e7f5033ea6e
10,348
ex
Elixir
lib/http_structured_field/parser.ex
cogini/http_structured_field
4d55b9a58d730f7a14fc8856ff84e332ac3cbf42
[ "Apache-2.0" ]
null
null
null
lib/http_structured_field/parser.ex
cogini/http_structured_field
4d55b9a58d730f7a14fc8856ff84e332ac3cbf42
[ "Apache-2.0" ]
null
null
null
lib/http_structured_field/parser.ex
cogini/http_structured_field
4d55b9a58d730f7a14fc8856ff84e332ac3cbf42
[ "Apache-2.0" ]
null
null
null
defmodule HttpStructuredField.Parser do @moduledoc """ Parse structured fields. """ import NimbleParsec # sf-integer = ["-"] 1*15DIGIT # Convert charlist into integer defp process_integer(_rest, acc, context, _line, _offset) do case Integer.parse(to_string(Enum.reverse(acc))) do {value, ""} -> {[value], context} :error -> {:error, "Invalid integer"} end end sf_integer = optional(ascii_char([?-])) |> ascii_string([?0..?9], min: 1, max: 15) |> label("integer") # |> concat(basic_integer) |> label("integer") |> post_traverse(:process_integer) |> unwrap_and_tag(:integer) # sf-decimal = ["-"] 1*12DIGIT "." 1*3DIGIT # Convert charlist into float defp process_decimal(_rest, acc, context, _line, _offset) do case Float.parse(to_string(Enum.reverse(acc))) do {value, ""} -> {[value], context} :error -> {:error, "Invalid decimal"} end end sf_decimal = optional(ascii_char([?-])) |> ascii_string([?0..?9], min: 1, max: 12) |> ascii_char([?.]) |> ascii_string([?0..?9], min: 1, max: 3) |> label("decimal") |> post_traverse(:process_decimal) |> unwrap_and_tag(:decimal) sf_boolean = ignore(ascii_char([63])) # ? |> choice([ ascii_char([?0]) |> replace(false), ascii_char([?1]) |> replace(true) ]) |> label("boolean") |> unwrap_and_tag(:boolean) # sf-string = DQUOTE *chr DQUOTE # chr = unescaped / escaped # unescaped = %x20-21 / %x23-5B / %x5D-7E # escaped = "\" ( DQUOTE / "\" ) # Convert charlist to string defp process_string(_rest, acc, context, _line, _offset) do {[IO.iodata_to_binary(Enum.reverse(acc))], context} end sf_string = ignore(ascii_char([?"])) |> repeat( lookahead_not(ascii_char([?"])) |> choice([ ~S(\") |> string() |> replace(?"), ~S(\\) |> string() |> replace(0x5C), # Printable ASCII utf8_string([0x20..0x21, 0x23..0x5B, 0x5D..0x7E], min: 1) ]) ) |> ignore(ascii_char([?"])) |> label("string") |> post_traverse(:process_string) |> unwrap_and_tag(:string) # sf-token = ( ALPHA / "*" ) *( tchar / ":" / "/" ) # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" # / DIGIT / ALPHA # ; any VCHAR, except delimiters # VCHAR = %x21-7E ; visible (printing) characters # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z alpha = ascii_char([0x41..0x5A, 0x61..0x7A]) |> label("ALPHA") # DIGIT = %x30-39 ; 0-9 digit = ascii_char([0x30..0x39]) |> label("DIGIT") # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" # / DIGIT / ALPHA tchar = choice([ ascii_char([ ?!, ?#, # $ 0x24, # %, 0x25, # & 0x26, # ' 0x27, # * 0x2A, # + 0x2B, # - 0x2D, # . 0x2E, # ^ 0x5E, # _ 0x5F, # ` 0x60, # | 0x7C, # ~ 0x7E ]), digit, alpha ]) |> label("tchar") sf_token = choice([alpha, ascii_char([?*])]) |> optional(repeat(choice([tchar, ascii_char([?:, ?/])]))) |> label("token") |> post_traverse(:process_string) |> unwrap_and_tag(:token) # sf-binary = ":" *(base64) ":" # base64 = ALPHA / DIGIT / "+" / "/" / "=" base64 = choice([ alpha, digit, ascii_char([ # + 0x2B, ?/, ?= ]) ]) |> label("base64") # Convert base64 to binary defp process_base64(_rest, acc, context, _line, _offset) do value = acc |> Enum.reverse() |> IO.iodata_to_binary() case Base.decode64(value) do {:ok, binary} -> {[binary], context} :error -> {:error, "Invalid base64"} end end sf_binary = ignore(ascii_char([?:])) |> repeat(lookahead_not(ascii_char([?:])) |> concat(base64)) |> ignore(ascii_char([?:])) |> label("binary") |> post_traverse(:process_base64) |> unwrap_and_tag(:binary) # sf-item = bare-item parameters # bare-item = sf-integer / sf-decimal / sf-string / sf-token / # sf-binary / sf-boolean bare_item = choice([ sf_token, sf_boolean, sf_binary, sf_string, sf_decimal, sf_integer ]) |> label("bare-item") # parameters = *( ";" *SP parameter ) # parameter = param-key [ "=" param-value ] # param-key = key # key = ( lcalpha / "*" ) # *( lcalpha / DIGIT / "_" / "-" / "." / "*" ) # lcalpha = %x61-7A ; a-z # param-value = bare-item lcalpha = ascii_char([?a..?z]) |> label("lcalpha") key = choice([lcalpha, ascii_char([?*])]) |> optional( repeat( choice([ lcalpha, digit, ascii_char([ # _ 0x5F, # - 0x2D, # . 0x2E, # * 0x2A ]) ]) ) ) |> label("key") |> post_traverse(:process_string) param_value = bare_item |> label("param-value") # Space sp = ascii_char([0x20]) |> label("SP") defp process_parameter(_rest, [value], context, _line, _offset) do {[{value, {:boolean, true}}], context} end defp process_parameter(_rest, acc, context, _line, _offset) do value = acc |> Enum.reverse() |> List.to_tuple() {[value], context} end parameter = ignore(ascii_char([?;])) |> ignore(optional(repeat(sp))) |> concat(key) |> optional( ignore(ascii_char([?=])) |> concat(param_value) ) |> label("parameter") |> post_traverse(:process_parameter) parameters = repeat(parameter) |> label("parameters") # If there are parameters, make a 3-tuple like {tag, value, params} defp process_parameters(_rest, [_value] = acc, context, _line, _offset) do {acc, context} end defp process_parameters(_rest, acc, context, _line, _offset) do case Enum.reverse(acc) do [{tag, value}, {:parameters, []}] -> {[{tag, value}], context} [{tag, value}, {:parameters, params}] -> {[{tag, value, params}], context} end end sf_item = bare_item |> optional(parameters |> tag(:parameters)) |> label("sf-item") |> post_traverse(:process_parameters) # OWS = *( SP / HTAB ) ; optional whitespace # HTAB = %x09 ; horizontal tab ows = ascii_char([0x20, 0x09]) |> label("OWS") # inner-list = "(" *SP [ sf-item *( 1*SP sf-item ) *SP ] ")" parameters inner_list = ignore(ascii_char([?(])) |> ignore(optional(repeat(sp))) |> optional(sf_item) |> optional(repeat(ignore(repeat(sp)) |> concat(sf_item))) |> ignore(optional(repeat(sp))) |> ignore(ascii_char([?)])) |> label("inner-list") |> tag(:inner_list) |> optional(parameters |> tag(:parameters)) |> post_traverse(:process_parameters) list_member = choice([sf_item, inner_list]) sf_list = list_member |> optional( repeat( ignore(optional(ows)) |> ignore(ascii_char([?,])) |> ignore(optional(ows)) |> concat(list_member) ) ) # sf-dictionary = dict-member *( OWS "," OWS dict-member ) # dict-member = member-key ( parameters / ( "=" member-value )) # member-key = key # member-value = sf-item / inner-list # Simple boolean value defp process_dict_member(_rest, [key], context, _line, _offset) do {[{key, {:boolean, true}}], context} end defp process_dict_member(_rest, acc, context, _line, _offset) do case Enum.reverse(acc) do # key is simple boolean, but with parameters [key, {:parameters, []}] -> {[{key, {:boolean, true}}], context} [key, {:parameters, params}] -> {[{key, {:boolean, true}, params}], context} # {[{key, {:boolean, true, params}}], context} # key = inner-list [key, {:inner_list, value}] -> {[{key, value}], context} # key = inner-list, where inner-list has params [key, {:inner_list, value, params}] -> {[{key, value, params}], context} # key = item value [key, {tag, _value} = item] when is_atom(tag) -> {[{key, item}], context} # key = item value, where item has params [key, {tag, _value, _params} = item] when is_atom(tag) -> {[{key, item}], context} end end member_value = choice([sf_item, inner_list |> unwrap_and_tag(:inner_list)]) |> label("member-value") dict_member = key |> choice([ ignore(ascii_char([?=])) |> concat(member_value), parameters |> tag(:parameters) ]) |> post_traverse(:process_dict_member) sf_dictionary = dict_member |> optional( repeat( ignore(optional(ows)) |> ignore(ascii_char([?,])) |> ignore(optional(ows)) |> concat(dict_member) ) ) defparsec(:parsec_parse_list, sf_list) defparsec(:parsec_parse_dict, sf_dictionary) @doc """ Parse Structured Field. By default, assumes that input is a single Item or a List. For Dictionaries, set the `type: :dict` option. Returns a tagged tuple with the result or an error if parsing failed. If the item has paramerters, then the tuple also contains a list of parameters. Parmeters and dictionary members are represented as lists of tuples where the name is the first tuple element. """ @spec parse(binary(), Keyword.t()) :: {:ok, HttpStructuredField.item() | list()} | {:error, term()} def parse(input, opts \\ []) def parse("", _opts), do: {:ok, []} def parse(input, opts) do type = opts[:type] || :list result = case type do :list -> parsec_parse_list(input) :dict -> parsec_parse_dict(input) end case result do {:ok, [value], _, _, _, _} -> {:ok, value} {:ok, values, _, _, _, _} -> {:ok, values} {:error, reason, _, _, _, _} -> {:error, reason} end end end
24.121212
101
0.523773
7383bb0e4131d64f811576615d27051adabe1732
571
exs
Elixir
config/nightly.exs
elarkham/animu
0f0c7b0b34168e69255943bdede60e03df057a44
[ "MIT" ]
1
2018-01-02T06:59:08.000Z
2018-01-02T06:59:08.000Z
config/nightly.exs
elarkham/Animu
0f0c7b0b34168e69255943bdede60e03df057a44
[ "MIT" ]
null
null
null
config/nightly.exs
elarkham/Animu
0f0c7b0b34168e69255943bdede60e03df057a44
[ "MIT" ]
null
null
null
import Config ############# # ANIMU # ############# # Configure HTTP Endpoint config :animu, Animu.Web.Endpoint, http: [port: {:system, "PORT"}], url: [host: {:system, "HOST"}, port: {:system, "PORT"}], server: true, root: ".", version: Mix.Project.config[:version] # Configure file paths for nightly config :animu, input_root: "/mnt/charon/videos/anime/animu", output_root: "/mnt/hydra/animu" ############## # Elixir # ############## # Nightly should print debug information config :logger, level: :debug import_config "nightly.secret.exs"
19.689655
58
0.607706
7383c96724b2e2c757b17f8eff7f298a11647b72
435
ex
Elixir
apps/api_web/lib/api_web/plugs/require_user.ex
fjlanasa/api
c39bc393aea572bfb81754b2ea1adf9dda9ce24a
[ "MIT" ]
62
2019-01-17T12:34:39.000Z
2022-03-20T21:49:47.000Z
apps/api_web/lib/api_web/plugs/require_user.ex
fjlanasa/api
c39bc393aea572bfb81754b2ea1adf9dda9ce24a
[ "MIT" ]
375
2019-02-13T15:30:50.000Z
2022-03-30T18:50:41.000Z
apps/api_web/lib/api_web/plugs/require_user.ex
fjlanasa/api
c39bc393aea572bfb81754b2ea1adf9dda9ce24a
[ "MIT" ]
14
2019-01-16T19:35:57.000Z
2022-02-26T18:55:54.000Z
defmodule ApiWeb.Plugs.RequireUser do @moduledoc """ Requires a user to be assigned to the Conn. """ import Plug.Conn import Phoenix.Controller, only: [redirect: 2] def init(opts), do: opts def call(conn, _) do case conn.assigns[:user] do %ApiAccounts.User{} -> conn nil -> conn |> redirect(to: ApiWeb.Router.Helpers.session_path(conn, :new)) |> halt() end end end
20.714286
71
0.609195
73842b1dce8f90a742af64b1aa919c35228bd5dd
985
exs
Elixir
apps/core/test/pubsub/cache/users_test.exs
michaeljguarino/forge
50ee583ecb4aad5dee4ef08fce29a8eaed1a0824
[ "Apache-2.0" ]
null
null
null
apps/core/test/pubsub/cache/users_test.exs
michaeljguarino/forge
50ee583ecb4aad5dee4ef08fce29a8eaed1a0824
[ "Apache-2.0" ]
2
2019-12-13T23:55:50.000Z
2019-12-17T05:49:58.000Z
apps/core/test/pubsub/cache/users_test.exs
michaeljguarino/chartmart
a34c949cc29d6a1ab91c04c5e4f797e6f0daabfc
[ "Apache-2.0" ]
null
null
null
defmodule Core.PubSub.Consumers.Cache.UsersTest do use Core.SchemaCase, async: true alias Core.PubSub alias Core.PubSub.Consumers.Cache describe "UserUpdated" do test "it will overwrite the login cache" do user = insert(:user) event = %PubSub.UserUpdated{item: user} Cache.handle_event(event) found = Core.Cache.get({:login, user.id}) assert found.id == user.id end end describe "CacheUser" do test "it will overwrite the login cache" do user = insert(:user) event = %PubSub.CacheUser{item: user} Cache.handle_event(event) found = Core.Cache.get({:login, user.id}) assert found.id == user.id end end describe "EmailConfirmed" do test "it will overwrite the login cache" do user = insert(:user) event = %PubSub.EmailConfirmed{item: user} Cache.handle_event(event) found = Core.Cache.get({:login, user.id}) assert found.id == user.id end end end
23.452381
50
0.650761
7384320a6987e7a1b360e78590fe9385a4f8ec7f
13,818
ex
Elixir
lib/oban/testing.ex
wjdix/oban
b68bcf02d2942c6ef7a98f8ea6ec80912beea47c
[ "Apache-2.0" ]
null
null
null
lib/oban/testing.ex
wjdix/oban
b68bcf02d2942c6ef7a98f8ea6ec80912beea47c
[ "Apache-2.0" ]
null
null
null
lib/oban/testing.ex
wjdix/oban
b68bcf02d2942c6ef7a98f8ea6ec80912beea47c
[ "Apache-2.0" ]
null
null
null
defmodule Oban.Testing do @moduledoc """ This module simplifies making assertions about enqueued jobs during testing. Assertions may be made on any property of a job, but you'll typically want to check by `args`, `queue` or `worker`. If you're using namespacing through PostgreSQL schemas, also called "prefixes" in Ecto, you should use the `prefix` option when doing assertions about enqueued jobs during testing. By default the `prefix` option is `public`. ## Using in Tests The most convenient way to use `Oban.Testing` is to `use` the module: use Oban.Testing, repo: MyApp.Repo That will define three helper functions, `assert_enqueued/1,2`, `refute_enqueued/1,2` and `all_enqueued/1`. The functions can then be used to make assertions on the jobs that have been inserted in the database while testing. Some small examples: ```elixir # Assert that a job was already enqueued assert_enqueued worker: MyWorker, args: %{id: 1} # Assert that a job was enqueued or will be enqueued in the next 100ms assert_enqueued [worker: MyWorker, args: %{id: 1}], 100 # Refute that a job was already enqueued refute_enqueued queue: "special", args: %{id: 2} # Refute that a job was already enqueued or would be enqueued in the next 100ms refute_enqueued queue: "special", args: %{id: 2}, 100 # Make assertions on a list of all jobs matching some options assert [%{args: %{"id" => 1}}] = all_enqueued(worker: MyWorker) ``` Note that the final example, using `all_enqueued/1`, returns a raw list of matching jobs and does not make an assertion by itself. This makes it possible to test using pattern matching at the expense of being more verbose. ## Example Given a simple module that enqueues a job: ```elixir defmodule MyApp.Business do def work(args) do args |> Oban.Job.new(worker: MyApp.Worker, queue: :special) |> Oban.insert!() end end ``` The behaviour can be exercised in your test code: defmodule MyApp.BusinessTest do use ExUnit.Case, async: true use Oban.Testing, repo: MyApp.Repo alias MyApp.Business test "jobs are enqueued with provided arguments" do Business.work(%{id: 1, message: "Hello!"}) assert_enqueued worker: MyApp.Worker, args: %{id: 1, message: "Hello!"} end end ## Matching Scheduled Jobs and Timestamps In order to assert a job has been scheduled at a certain time, you will need to match against the `scheduled_at` attribute of the enqueued job. in_an_hour = DateTime.add(DateTime.utc_now(), 3600, :second) assert_enqueued worker: MyApp.Worker, scheduled_at: in_an_hour By default, Oban will apply a 1 second delta to all timestamp fields of jobs, so that small deviations between the actual value and the expected one are ignored. You may configure this delta by passing a tuple of value and a `delta` option (in seconds) to corresponding keyword: assert_enqueued worker: MyApp.Worker, scheduled_at: {in_an_hour, delta: 10} ## Adding to Case Templates To include helpers in all of your tests you can add it to your case template: ```elixir defmodule MyApp.DataCase do use ExUnit.CaseTemplate using do quote do use Oban.Testing, repo: MyApp.Repo import Ecto import Ecto.Changeset import Ecto.Query import MyApp.DataCase alias MyApp.Repo end end end ``` """ @moduledoc since: "0.3.0" import ExUnit.Assertions, only: [assert: 2, refute: 2] import Ecto.Query, only: [limit: 2, order_by: 2, select: 2, where: 2, where: 3] alias Ecto.Changeset alias Oban.{Job, Repo, Worker} @wait_interval 10 @doc false defmacro __using__(repo: repo) do quote do alias Oban.Testing import Oban.Testing, only: [perform_job: 2, perform_job: 3] def all_enqueued(opts) do Testing.all_enqueued(unquote(repo), opts) end def assert_enqueued(opts, timeout \\ :none) do if timeout == :none do Testing.assert_enqueued(unquote(repo), opts) else Testing.assert_enqueued(unquote(repo), opts, timeout) end end def refute_enqueued(opts, timeout \\ :none) do if timeout == :none do Testing.refute_enqueued(unquote(repo), opts) else Testing.refute_enqueued(unquote(repo), opts, timeout) end end end end @doc """ Construct a job and execute it with a worker module. This reduces boiler plate when constructing jobs for unit tests and checks for common pitfalls. For example, it automatically converts `args` to string keys before calling `perform/1`, ensuring that perform clauses aren't erroneously trying to match atom keys. The helper makes the following assertions: * That the worker implements the `Oban.Worker` behaviour * That the options provided build a valid job * That the return is valid, e.g. `:ok`, `{:ok, value}`, `{:error, value}` etc. If all of the assertions pass then the function returns the result of `perform/1` for you to make additional assertions on. ## Examples Successfully execute a job with some string arguments: assert :ok = perform_job(MyWorker, %{"id" => 1}) Successfully execute a job and assert that it returns an error tuple: assert {:error, _} = perform_job(MyWorker, %{"bad" => "arg"}) Execute a job with the args keys automatically stringified: assert :ok = perform_job(MyWorker, %{id: 1}) Exercise custom attempt handling within a worker by passing options: assert :ok = perform_job(MyWorker, %{}, attempt: 42) Cause a test failure because the provided worker isn't real: assert :ok = perform_job(Vorker, %{"id" => 1}) """ @doc since: "2.0.0" @spec perform_job(worker :: Worker.t(), args :: Job.args(), opts :: [Job.option()]) :: Worker.result() def perform_job(worker, args, opts \\ []) when is_atom(worker) and is_map(args) do assert_valid_worker(worker) changeset = args |> worker.new(opts) |> Changeset.update_change(:args, &json_encode_decode/1) assert_valid_changeset(changeset) result = changeset |> Changeset.apply_action!(:insert) |> worker.perform() assert_valid_result(result) result end @doc """ Retrieve all currently enqueued jobs matching a set of options. Only jobs matching all of the provided arguments will be returned. Additionally, jobs are returned in descending order where the most recently enqueued job will be listed first. ## Examples Assert based on only _some_ of a job's args: assert [%{args: %{"id" => 1}}] = all_enqueued(worker: MyWorker) Assert that exactly one job was inserted for a queue: assert [%Oban.Job{}] = all_enqueued(queue: :alpha) """ @doc since: "0.6.0" @spec all_enqueued(repo :: module(), opts :: Keyword.t()) :: [Job.t()] def all_enqueued(repo, [_ | _] = opts) do {prefix, opts} = extract_prefix(opts) Repo.all( %{prefix: prefix, repo: repo}, opts |> base_query() |> order_by(desc: :id) ) end @doc """ Assert that a job with particular options has been enqueued. Only values for the provided arguments will be checked. For example, an assertion made on `worker: "MyWorker"` will match _any_ jobs for that worker, regardless of the queue or args. """ @doc since: "0.3.0" @spec assert_enqueued(repo :: module(), opts :: Keyword.t()) :: true def assert_enqueued(repo, [_ | _] = opts) do error_message = """ Expected a job matching: #{inspect(Map.new(opts), pretty: true)} to be enqueued. Instead found: #{inspect(available_jobs(repo, opts), pretty: true)} """ assert get_job(repo, opts), error_message end @doc """ Assert that a job with particular options is or will be enqueued within a timeout period. See `assert_enqueued/2` for additional details. ## Examples Assert that a job will be enqueued in the next 100ms: assert_enqueued [worker: MyWorker], 100 """ @doc since: "1.2.0" @spec assert_enqueued(repo :: module(), opts :: Keyword.t(), timeout :: pos_integer()) :: true def assert_enqueued(repo, [_ | _] = opts, timeout) when timeout > 0 do error_message = """ Expected a job matching: #{inspect(Map.new(opts), pretty: true)} to be enqueued within #{timeout}ms """ assert wait_for_job(repo, opts, timeout), error_message end @doc """ Refute that a job with particular options has been enqueued. See `assert_enqueued/2` for additional details. """ @doc since: "0.3.0" @spec refute_enqueued(repo :: module(), opts :: Keyword.t()) :: false def refute_enqueued(repo, [_ | _] = opts) do error_message = """ Expected no jobs matching: #{inspect(opts, pretty: true)} to be enqueued """ refute get_job(repo, opts), error_message end @doc """ Refute that a job with particular options is or will be enqueued within a timeout period. The minimum refute timeout is 10ms. See `assert_enqueued/2` for additional details. ## Examples Refute that a job will not be enqueued in the next 100ms: refute_enqueued [worker: MyWorker], 100 """ @doc since: "1.2.0" @spec refute_enqueued(repo :: module(), opts :: Keyword.t(), timeout :: pos_integer()) :: false def refute_enqueued(repo, [_ | _] = opts, timeout) when timeout >= 10 do error_message = """ Expected no jobs matching: #{inspect(opts, pretty: true)} to be enqueued within #{timeout}ms """ refute wait_for_job(repo, opts, timeout), error_message end # Perform Helpers defp assert_valid_worker(worker) do assert Code.ensure_loaded?(worker) and implements_worker?(worker), """ Expected worker to be a module that implements the Oban.Worker behaviour, got: #{inspect(worker)} """ end defp implements_worker?(worker) do :attributes |> worker.__info__() |> Keyword.get_values(:behaviour) |> List.flatten() |> Enum.member?(Oban.Worker) end defp assert_valid_changeset(changeset) do assert changeset.valid?, """ Expected args and opts to build a valid job, got validation errors: #{traverse_errors(changeset)} """ end defp traverse_errors(changeset) do traverser = fn {message, opts} -> Enum.reduce(opts, message, fn {key, value}, acc -> String.replace(acc, "%{#{key}}", to_string(value)) end) end changeset |> Changeset.traverse_errors(traverser) |> Enum.map(fn {key, val} -> "#{key}: #{val}" end) |> Enum.join("\n") end defp json_encode_decode(map) do map |> Jason.encode!() |> Jason.decode!() end defp assert_valid_result(result) do valid? = case result do :ok -> true {:ok, _value} -> true {:error, _value} -> true {:discard, _value} -> true {:snooze, snooze} when is_integer(snooze) -> true :discard -> true _ -> false end assert valid?, """ Expected result to be one of - `:ok` - `:discard` - `{:ok, value}` - `{:error, reason}` - `{:discard, reason}` - `{:snooze, duration} Instead received: #{inspect(result, pretty: true)} """ end # Enqueued Helpers defp get_job(repo, opts) do {prefix, opts} = extract_prefix(opts) Repo.one( %{prefix: prefix, repo: repo}, opts |> base_query() |> limit(1) |> select([:id]) ) end defp wait_for_job(repo, opts, timeout) when timeout > 0 do case get_job(repo, opts) do nil -> Process.sleep(@wait_interval) wait_for_job(repo, opts, timeout - @wait_interval) job -> job end end defp wait_for_job(_repo, _opts, _timeout), do: nil defp available_jobs(repo, opts) do {prefix, opts} = extract_prefix(opts) fields = Keyword.keys(opts) %{prefix: prefix, repo: repo} |> Repo.all([] |> base_query() |> select(^fields)) |> Enum.map(&Map.take(&1, fields)) end defp base_query(opts) do {fields, field_opts} = Enum.map_reduce(opts, [], &extract_field_opts/2) fields_with_opts = fields |> normalize_fields() |> Enum.map(fn {key, value} -> {key, value, Keyword.get(field_opts, key, [])} end) Job |> where([j], j.state in ["available", "scheduled"]) |> apply_where_clauses(fields_with_opts) end defp extract_prefix(opts) do Keyword.pop(opts, :prefix, "public") end defp extract_field_opts({key, {value, field_opts}}, field_opts_acc) do {{key, value}, [{key, field_opts} | field_opts_acc]} end defp extract_field_opts({key, value}, field_opts_acc) do {{key, value}, field_opts_acc} end defp normalize_fields(fields) do args = Keyword.get(fields, :args, %{}) keys = Keyword.keys(fields) args |> Job.new(fields) |> Changeset.apply_changes() |> Map.from_struct() |> Map.take(keys) |> Keyword.new() end @timestamp_fields ~W(attempted_at completed_at inserted_at scheduled_at)a @timestamp_default_delta_seconds 1 defp apply_where_clauses(query, []), do: query defp apply_where_clauses(query, [{key, value, opts} | rest]) when key in @timestamp_fields do delta = Keyword.get(opts, :delta, @timestamp_default_delta_seconds) window_start = DateTime.add(value, -delta, :second) window_end = DateTime.add(value, delta, :second) query |> where([j], fragment("? BETWEEN ? AND ?", field(j, ^key), ^window_start, ^window_end)) |> apply_where_clauses(rest) end defp apply_where_clauses(query, [{key, value, _opts} | rest]) do query |> where(^[{key, value}]) |> apply_where_clauses(rest) end end
27.802817
97
0.658344
7384bd1ae141645f79508ca40fa46cfa54570968
2,894
exs
Elixir
test/kino/vega_lite_test.exs
BrooklinJazz/kino
5ce878691798259c592b4298097e72353e23880c
[ "Apache-2.0" ]
84
2021-07-17T09:19:45.000Z
2022-03-21T20:43:21.000Z
test/kino/vega_lite_test.exs
BrooklinJazz/kino
5ce878691798259c592b4298097e72353e23880c
[ "Apache-2.0" ]
48
2021-07-21T11:59:20.000Z
2022-03-31T16:34:16.000Z
test/kino/vega_lite_test.exs
BrooklinJazz/kino
5ce878691798259c592b4298097e72353e23880c
[ "Apache-2.0" ]
11
2021-09-05T16:30:23.000Z
2022-02-19T02:06:48.000Z
defmodule Kino.VegaLiteTest do use Kino.LivebookCase, async: true import KinoTest.JS.Live alias VegaLite, as: Vl test "sends current data after initial connection" do widget = start_widget() Kino.VegaLite.push(widget, %{x: 1, y: 1}) data = connect(widget) assert %{spec: %{}, datasets: [[nil, [%{x: 1, y: 1}]]]} = data end test "does not send data outside of the specified window" do widget = start_widget() Kino.VegaLite.push(widget, %{x: 1, y: 1}, window: 1) Kino.VegaLite.push(widget, %{x: 2, y: 2}, window: 1) data = connect(widget) assert %{spec: %{}, datasets: [[nil, [%{x: 2, y: 2}]]]} = data end test "push/3 sends data point message to the client" do widget = start_widget() Kino.VegaLite.push(widget, %{x: 1, y: 1}) assert_broadcast_event(widget, "push", %{data: [%{x: 1, y: 1}], dataset: nil, window: nil}) end test "push/3 allows for specifying the dataset" do widget = start_widget() Kino.VegaLite.push(widget, %{x: 1, y: 1}, dataset: "points") assert_broadcast_event(widget, "push", %{ data: [%{x: 1, y: 1}], dataset: "points", window: nil }) end test "push/3 converts keyword list to map" do widget = start_widget() Kino.VegaLite.push(widget, x: 1, y: 1) assert_broadcast_event(widget, "push", %{data: [%{x: 1, y: 1}], dataset: nil, window: nil}) end test "push/3 raises if an invalid data type is given" do widget = start_widget() assert_raise Protocol.UndefinedError, ~r/"invalid"/, fn -> Kino.VegaLite.push(widget, "invalid") end end test "push_many/3 sends multiple datapoints" do widget = start_widget() points = [%{x: 1, y: 1}, %{x: 2, y: 2}] Kino.VegaLite.push_many(widget, points) assert_broadcast_event(widget, "push", %{data: ^points, dataset: nil, window: nil}) end test "push_many/3 raises if an invalid data type is given" do widget = start_widget() assert_raise Protocol.UndefinedError, ~r/"invalid"/, fn -> Kino.VegaLite.push_many(widget, ["invalid"]) end end test "clear/2 pushes empty data" do widget = start_widget() Kino.VegaLite.clear(widget) assert_broadcast_event(widget, "push", %{data: [], dataset: nil, window: 0}) end test "periodically/4 evaluates the given callback in background until stopped" do widget = start_widget() parent = self() Kino.VegaLite.periodically(widget, 1, 1, fn n -> send(parent, {:ping, n}) if n < 2 do {:cont, n + 1} else :halt end end) assert_receive {:ping, 1} assert_receive {:ping, 2} refute_receive {:ping, 3}, 5 end defp start_widget() do Vl.new() |> Vl.mark(:point) |> Vl.encode_field(:x, "x", type: :quantitative) |> Vl.encode_field(:y, "y", type: :quantitative) |> Kino.VegaLite.new() end end
25.385965
95
0.620594
7384ed520a8b5542499a9670f5adb5e02623c532
77
ex
Elixir
testData/org/elixir_lang/reference/module/suffix/reference.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/reference/module/suffix/reference.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/reference/module/suffix/reference.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
defmodule Prefix.Usage do alias Prefix.Suffix Suffix<caret> @a 1 end
9.625
25
0.714286
738516d01028c6f71ba66ebd662305759fd98829
1,932
ex
Elixir
clients/private_ca/lib/google_api/private_ca/v1/model/key_version_spec.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/private_ca/lib/google_api/private_ca/v1/model/key_version_spec.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/private_ca/lib/google_api/private_ca/v1/model/key_version_spec.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.PrivateCA.V1.Model.KeyVersionSpec do @moduledoc """ A Cloud KMS key configuration that a CertificateAuthority will use. ## Attributes * `algorithm` (*type:* `String.t`, *default:* `nil`) - The algorithm to use for creating a managed Cloud KMS key for a for a simplified experience. All managed keys will be have their ProtectionLevel as `HSM`. * `cloudKmsKeyVersion` (*type:* `String.t`, *default:* `nil`) - The resource name for an existing Cloud KMS CryptoKeyVersion in the format `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*`. This option enables full flexibility in the key's capabilities and properties. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :algorithm => String.t() | nil, :cloudKmsKeyVersion => String.t() | nil } field(:algorithm) field(:cloudKmsKeyVersion) end defimpl Poison.Decoder, for: GoogleApi.PrivateCA.V1.Model.KeyVersionSpec do def decode(value, options) do GoogleApi.PrivateCA.V1.Model.KeyVersionSpec.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.PrivateCA.V1.Model.KeyVersionSpec do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.64
291
0.739648
73851ae44dbadeccda02ba366bccd1e8b1ceaaa0
3,788
ex
Elixir
lib/teiserver/agents/battlejoin_agent_server.ex
badosu/teiserver
19b623aeb7c2ab28756405f7486e92b714777c54
[ "MIT" ]
6
2021-02-08T10:42:53.000Z
2021-04-25T12:12:03.000Z
lib/teiserver/agents/battlejoin_agent_server.ex
Jazcash/teiserver
fec14784901cb2965d8c1350fe84107c57451877
[ "MIT" ]
14
2021-08-01T02:36:14.000Z
2022-01-30T21:15:03.000Z
lib/teiserver/agents/battlejoin_agent_server.ex
Jazcash/teiserver
fec14784901cb2965d8c1350fe84107c57451877
[ "MIT" ]
7
2021-05-13T12:55:28.000Z
2022-01-14T06:39:06.000Z
defmodule Teiserver.Agents.BattlejoinAgentServer do use GenServer alias Teiserver.Agents.AgentLib alias Teiserver.Battle.Lobby require Logger @tick_period 7000 @leave_chance 0.5 def handle_info(:startup, state) do socket = AgentLib.get_socket() AgentLib.login(socket, %{ name: "Battlejoin_#{state.number}", email: "Battlejoin_#{state.number}@agent_email", extra_data: %{} }) :timer.send_interval(@tick_period, self(), :tick) {:noreply, %{state | socket: socket}} end def handle_info(:tick, state) do new_state = case state.stage do :no_battle -> join_battle(state, Lobby.list_lobby_ids()) :waiting -> state :in_battle -> if :rand.uniform() <= @leave_chance do leave_battle(state) else state end end {:noreply, new_state} end def handle_info({:ssl, _socket, data}, state) do new_state = data |> AgentLib.translate |> Enum.reduce(state, fn data, acc -> handle_msg(data, acc) end) {:noreply, new_state} end defp handle_msg(nil, state), do: state defp handle_msg(%{"cmd" => "s.lobby.join", "result" => "waiting_for_host"}, state) do %{state | stage: :waiting} end defp handle_msg(%{"cmd" => "s.lobby.join", "result" => "failure"}, state) do %{state | stage: :no_battle, lobby_id: nil} end defp handle_msg(%{"cmd" => "s.lobby.join_response", "result" => "failure"}, state) do %{state | stage: :no_battle, lobby_id: nil} end defp handle_msg(%{"cmd" => "s.lobby.join_response", "result" => "approve"}, state) do %{state | stage: :in_battle} end defp handle_msg(%{"cmd" => "s.lobby.join_response", "result" => "reject"}, state) do %{state | stage: :no_battle, lobby_id: nil} end defp handle_msg(%{"cmd" => "s.lobby.leave", "result" => "success"}, state) do %{state | lobby_id: nil} end defp handle_msg(%{"cmd" => "s.lobby.request_status"}, state) do update_battlestatus(state) end defp handle_msg(%{"cmd" => "s.communication.direct_message"}, state), do: state defp handle_msg(%{"cmd" => "s.lobby.announce"}, state), do: state defp handle_msg(%{"cmd" => "s.lobby.message"}, state), do: state defp update_battlestatus(state) do data = if Enum.random([true, false]) do %{ player: true, ready: Enum.random([true, false]), sync: 1, team_number: Enum.random(0..15), ally_team_number: Enum.random([0, 1]), side: Enum.random([0, 1, 2]), team_colour: Enum.random(0..9322660) } else %{ player: false } end AgentLib._send(state.socket, Map.put(data, :cmd, "c.lobby.update_status")) state end defp join_battle(state, []), do: state defp join_battle(state, lobby_ids) do lobby_id = Enum.random(lobby_ids) case Lobby.get_battle!(lobby_id) do nil -> %{state | lobby_id: nil, stage: :no_battle} battle -> cmd = %{ cmd: "c.lobby.join", lobby_id: lobby_id, password: battle.password } AgentLib._send(state.socket, cmd) AgentLib.post_agent_update(state.id, "opened battle") %{state | lobby_id: lobby_id, stage: :waiting} end end defp leave_battle(state) do AgentLib._send(state.socket, %{cmd: "c.lobby.leave"}) AgentLib.post_agent_update(state.id, "left battle") %{state | lobby_id: nil, stage: :no_battle} end # Startup def start_link(opts \\ []) do GenServer.start_link(__MODULE__, opts[:data], opts) end def init(opts) do send(self(), :startup) {:ok, %{ id: opts.id, number: opts.number, lobby_id: nil, stage: :no_battle, socket: nil }} end end
26.305556
87
0.606389
73851fefc160622bc0a8ec26158c43f07cee3eb1
152
ex
Elixir
socket_gallows/lib/socket_gallows_web/controllers/page_controller.ex
wronfim/hangman_game
c4dc4b9f122e773fe87ac4dc88206b792c1b239e
[ "MIT" ]
2
2020-01-20T20:15:20.000Z
2020-02-27T11:08:42.000Z
learning/gnome/game/socket_gallows/lib/socket_gallows_web/controllers/page_controller.ex
Mdlkxzmcp/various_elixir
c87527b7118a0c74a042073c04d2228025888ddf
[ "MIT" ]
null
null
null
learning/gnome/game/socket_gallows/lib/socket_gallows_web/controllers/page_controller.ex
Mdlkxzmcp/various_elixir
c87527b7118a0c74a042073c04d2228025888ddf
[ "MIT" ]
null
null
null
defmodule SocketGallowsWeb.PageController do use SocketGallowsWeb, :controller def index(conn, _params) do render conn, "index.html" end end
19
44
0.763158
73853745ffe36b094c8afbf9f8e05445b36d97f6
13,433
ex
Elixir
clients/drive/lib/google_api/drive/v3/api/changes.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/drive/lib/google_api/drive/v3/api/changes.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/drive/lib/google_api/drive/v3/api/changes.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "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.Drive.V3.Api.Changes do @moduledoc """ API calls for all endpoints tagged `Changes`. """ alias GoogleApi.Drive.V3.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Gets the starting pageToken for listing future changes. ## Parameters * `connection` (*type:* `GoogleApi.Drive.V3.Connection.t`) - Connection to server * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - 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` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:driveId` (*type:* `String.t`) - The ID of the shared drive for which the starting pageToken for listing future changes from that shared drive is returned. * `:supportsAllDrives` (*type:* `boolean()`) - Deprecated - Whether the requesting application supports both My Drives and shared drives. This parameter will only be effective until June 1, 2020. Afterwards all applications are assumed to support shared drives. * `:supportsTeamDrives` (*type:* `boolean()`) - Deprecated use supportsAllDrives instead. * `:teamDriveId` (*type:* `String.t`) - Deprecated use driveId instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Drive.V3.Model.StartPageToken{}}` on success * `{:error, info}` on failure """ @spec drive_changes_get_start_page_token(Tesla.Env.client(), keyword(), keyword()) :: {:ok, GoogleApi.Drive.V3.Model.StartPageToken.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def drive_changes_get_start_page_token(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :driveId => :query, :supportsAllDrives => :query, :supportsTeamDrives => :query, :teamDriveId => :query } request = Request.new() |> Request.method(:get) |> Request.url("/drive/v3/changes/startPageToken", %{}) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Drive.V3.Model.StartPageToken{}]) end @doc """ Lists the changes for a user or shared drive. ## Parameters * `connection` (*type:* `GoogleApi.Drive.V3.Connection.t`) - Connection to server * `page_token` (*type:* `String.t`) - The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response or to the response from the getStartPageToken method. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - 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` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:driveId` (*type:* `String.t`) - The shared drive from which changes are returned. If specified the change IDs will be reflective of the shared drive; use the combined drive ID and change ID as an identifier. * `:includeCorpusRemovals` (*type:* `boolean()`) - Whether changes should include the file resource if the file is still accessible by the user at the time of the request, even when a file was removed from the list of changes and there will be no further change entries for this file. * `:includeItemsFromAllDrives` (*type:* `boolean()`) - Deprecated - Whether both My Drive and shared drive items should be included in results. This parameter will only be effective until June 1, 2020. Afterwards shared drive items are included in the results. * `:includeRemoved` (*type:* `boolean()`) - Whether to include changes indicating that items have been removed from the list of changes, for example by deletion or loss of access. * `:includeTeamDriveItems` (*type:* `boolean()`) - Deprecated use includeItemsFromAllDrives instead. * `:pageSize` (*type:* `integer()`) - The maximum number of changes to return per page. * `:restrictToMyDrive` (*type:* `boolean()`) - Whether to restrict the results to changes inside the My Drive hierarchy. This omits changes to files such as those in the Application Data folder or shared files which have not been added to My Drive. * `:spaces` (*type:* `String.t`) - A comma-separated list of spaces to query within the user corpus. Supported values are 'drive', 'appDataFolder' and 'photos'. * `:supportsAllDrives` (*type:* `boolean()`) - Deprecated - Whether the requesting application supports both My Drives and shared drives. This parameter will only be effective until June 1, 2020. Afterwards all applications are assumed to support shared drives. * `:supportsTeamDrives` (*type:* `boolean()`) - Deprecated use supportsAllDrives instead. * `:teamDriveId` (*type:* `String.t`) - Deprecated use driveId instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Drive.V3.Model.ChangeList{}}` on success * `{:error, info}` on failure """ @spec drive_changes_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Drive.V3.Model.ChangeList.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def drive_changes_list(connection, page_token, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :driveId => :query, :includeCorpusRemovals => :query, :includeItemsFromAllDrives => :query, :includeRemoved => :query, :includeTeamDriveItems => :query, :pageSize => :query, :restrictToMyDrive => :query, :spaces => :query, :supportsAllDrives => :query, :supportsTeamDrives => :query, :teamDriveId => :query } request = Request.new() |> Request.method(:get) |> Request.url("/drive/v3/changes", %{}) |> Request.add_param(:query, :pageToken, page_token) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Drive.V3.Model.ChangeList{}]) end @doc """ Subscribes to changes for a user. ## Parameters * `connection` (*type:* `GoogleApi.Drive.V3.Connection.t`) - Connection to server * `page_token` (*type:* `String.t`) - The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response or to the response from the getStartPageToken method. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - 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` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:driveId` (*type:* `String.t`) - The shared drive from which changes are returned. If specified the change IDs will be reflective of the shared drive; use the combined drive ID and change ID as an identifier. * `:includeCorpusRemovals` (*type:* `boolean()`) - Whether changes should include the file resource if the file is still accessible by the user at the time of the request, even when a file was removed from the list of changes and there will be no further change entries for this file. * `:includeItemsFromAllDrives` (*type:* `boolean()`) - Deprecated - Whether both My Drive and shared drive items should be included in results. This parameter will only be effective until June 1, 2020. Afterwards shared drive items are included in the results. * `:includeRemoved` (*type:* `boolean()`) - Whether to include changes indicating that items have been removed from the list of changes, for example by deletion or loss of access. * `:includeTeamDriveItems` (*type:* `boolean()`) - Deprecated use includeItemsFromAllDrives instead. * `:pageSize` (*type:* `integer()`) - The maximum number of changes to return per page. * `:restrictToMyDrive` (*type:* `boolean()`) - Whether to restrict the results to changes inside the My Drive hierarchy. This omits changes to files such as those in the Application Data folder or shared files which have not been added to My Drive. * `:spaces` (*type:* `String.t`) - A comma-separated list of spaces to query within the user corpus. Supported values are 'drive', 'appDataFolder' and 'photos'. * `:supportsAllDrives` (*type:* `boolean()`) - Deprecated - Whether the requesting application supports both My Drives and shared drives. This parameter will only be effective until June 1, 2020. Afterwards all applications are assumed to support shared drives. * `:supportsTeamDrives` (*type:* `boolean()`) - Deprecated use supportsAllDrives instead. * `:teamDriveId` (*type:* `String.t`) - Deprecated use driveId instead. * `:resource` (*type:* `GoogleApi.Drive.V3.Model.Channel.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Drive.V3.Model.Channel{}}` on success * `{:error, info}` on failure """ @spec drive_changes_watch(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Drive.V3.Model.Channel.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def drive_changes_watch(connection, page_token, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :driveId => :query, :includeCorpusRemovals => :query, :includeItemsFromAllDrives => :query, :includeRemoved => :query, :includeTeamDriveItems => :query, :pageSize => :query, :restrictToMyDrive => :query, :spaces => :query, :supportsAllDrives => :query, :supportsTeamDrives => :query, :teamDriveId => :query, :resource => :body } request = Request.new() |> Request.method(:post) |> Request.url("/drive/v3/changes/watch", %{}) |> Request.add_param(:query, :pageToken, page_token) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Drive.V3.Model.Channel{}]) end end
59.438053
292
0.670587
73856ba8d3c455210ba6e259191550772f701724
1,824
exs
Elixir
test/onesky/resources/translation_test.exs
ahtung/onesky.ex
bd3a150d67e25e1ef6d4b7bc33a593b49a65f37f
[ "Apache-2.0" ]
6
2018-11-22T14:44:26.000Z
2020-01-20T14:33:26.000Z
test/onesky/resources/translation_test.exs
dunyakirkali/onesky.ex
f28fc94722c3b13ff82ee307d2a1cc42db4b6df2
[ "Apache-2.0" ]
24
2021-01-13T16:45:34.000Z
2022-03-24T04:07:33.000Z
test/onesky/resources/translation_test.exs
dunyakirkali/onesky.ex
f28fc94722c3b13ff82ee307d2a1cc42db4b6df2
[ "Apache-2.0" ]
null
null
null
defmodule TranslationTest do use ExUnit.Case, async: true use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney doctest Onesky.Translation test "export_files" do use_cassette "translation#export_files" do params = [locale: "zh-TW", source_file_name: "string.po"] {:ok, %Tesla.Env{} = env} = Onesky.client() |> Onesky.Translation.export_files(322_974, params) assert env.status == 200 end end test "export_multilingual_files" do use_cassette "translation#export_multilingual_files" do params = [source_file_name: "app.json"] {:ok, %Tesla.Env{} = env} = Onesky.client() |> Onesky.Translation.export_multilingual_files(322_974, params) assert env.status == 200 end end test "get_appstore_description" do use_cassette "translation#app_store" do locale = [locale: "en"] {:ok, %Tesla.Env{} = env} = Onesky.client() |> Onesky.Translation.get_appstore_description(322_974, locale) assert env.status == 200 assert env.body["meta"]["status"] == 200 assert env.body["data"]["APP_NAME"] == "ABN AMRO Grip" assert env.body["data"]["TITLE"] == nil assert env.body["data"]["DESCRIPTION"] == nil end end test "get_translation_status" do use_cassette "translation#status" do file = [file_name: "Localizable.strings", locale: "nl-NL"] {:ok, %Tesla.Env{} = env} = Onesky.client() |> Onesky.Translation.get_translation_status(314_254, file) assert env.status == 200 assert env.body["meta"]["status"] == 200 assert env.body["data"]["file_name"] == "Localizable.strings" assert env.body["data"]["progress"] == "100.0%" assert env.body["data"]["string_count"] == 534 assert env.body["data"]["word_count"] == 2478 end end end
28.5
88
0.643092
73858f826241140c3f5329b7fab2245fd1bf574a
228
exs
Elixir
test/phoenix_component_folders_web/controllers/page_controller_test.exs
kimlindholm/phoenix_component_folders
2d07f4966fe473063183e97009955b82a93b181f
[ "MIT" ]
30
2017-05-05T09:30:06.000Z
2021-03-29T15:08:02.000Z
test/phoenix_component_folders_web/controllers/page_controller_test.exs
kimlindholm/phoenix_component_folders
2d07f4966fe473063183e97009955b82a93b181f
[ "MIT" ]
4
2017-05-01T18:53:57.000Z
2020-11-22T06:46:55.000Z
test/phoenix_component_folders_web/controllers/page_controller_test.exs
kimlindholm/phoenix_component_folders
2d07f4966fe473063183e97009955b82a93b181f
[ "MIT" ]
7
2017-11-09T06:34:07.000Z
2021-03-01T20:14:18.000Z
defmodule PhoenixComponentFoldersWeb.PageControllerTest do use PhoenixComponentFoldersWeb.ConnCase test "GET /", %{conn: conn} do conn = get(conn, "/") assert html_response(conn, 200) =~ "Latest comments" end end
25.333333
58
0.72807
7385b14d0a03d4a0966c09aeec200b419aa68ddb
6,232
ex
Elixir
lib/chat_api_web/controllers/google_controller.ex
hakerspeak/hakerspeak.com
efd9e75f4854fdd19fc1873300deae0b160fb629
[ "MIT" ]
null
null
null
lib/chat_api_web/controllers/google_controller.ex
hakerspeak/hakerspeak.com
efd9e75f4854fdd19fc1873300deae0b160fb629
[ "MIT" ]
null
null
null
lib/chat_api_web/controllers/google_controller.ex
hakerspeak/hakerspeak.com
efd9e75f4854fdd19fc1873300deae0b160fb629
[ "MIT" ]
null
null
null
defmodule ChatApiWeb.GoogleController do use ChatApiWeb, :controller require Logger alias ChatApi.Google alias ChatApi.Google.GoogleAuthorization @spec callback(Plug.Conn.t(), map()) :: Plug.Conn.t() @doc """ This action is reached via `/api/google/oauth` is the the callback URL that Google's OAuth2 provider will redirect the user back to with a `code` that will be used to request an access token. The access token will then be used to access protected resources on behalf of the user. """ def callback(conn, %{"code" => code} = params) do with %{account_id: account_id, id: user_id} <- conn.assigns.current_user do type = case Map.get(params, "state") do state when state in ["personal", "support", "sheets"] -> state _ -> nil end client = Google.Auth.get_access_token!(code: code, redirect_uri: get_redirect_uri(type)) Logger.debug("Gmail access token: #{inspect(client.token)}") scope = client.token.other_params["scope"] || params["scope"] || "" inbox_id = Map.get(params, "inbox_id") client_type = cond do String.contains?(scope, "spreadsheets") -> "sheets" String.contains?(scope, "gmail") -> "gmail" true -> raise "Unrecognized scope: #{scope}" end case Google.create_or_update_authorization(account_id, %{ account_id: account_id, inbox_id: inbox_id, user_id: user_id, access_token: client.token.access_token, refresh_token: client.token.refresh_token, token_type: client.token.token_type, expires_at: client.token.expires_at, scope: scope, client: client_type, type: type }) do {:ok, auth} -> if should_enable_gmail_sync?(auth), do: enqueue_enabling_gmail_sync(account_id) json(conn, %{data: %{ok: true}}) error -> Logger.error("Error saving sheets auth: #{inspect(error)}") json(conn, %{data: %{ok: false}}) end end end @spec authorization(Plug.Conn.t(), map()) :: Plug.Conn.t() def authorization(conn, %{"client" => _} = params) do with %{account_id: account_id} <- conn.assigns.current_user do filters = Map.new(params, fn {key, value} -> {String.to_atom(key), value} end) # filters = # case Map.get(formatted, :type) do # "personal" -> %{client: client, type: "personal"} # "support" -> %{client: client, type: "support"} # "sheets" -> %{client: client, type: "sheets"} # _ -> %{client: client} # end case Google.get_authorization_by_account(account_id, filters) do nil -> json(conn, %{data: nil}) auth -> json(conn, %{ data: %{ id: auth.id, created_at: auth.inserted_at, updated_at: auth.updated_at, account_id: auth.account_id, inbox_id: auth.inbox_id, user_id: auth.user_id, scope: auth.scope } }) end end end @spec index(Plug.Conn.t(), map()) :: Plug.Conn.t() def index(conn, %{"client" => client} = params) do scope = case client do "sheets" -> "https://www.googleapis.com/auth/spreadsheets" "gmail" -> "https://www.googleapis.com/auth/gmail.modify" _ -> raise "Unrecognized client: #{client}" end redirect(conn, external: Google.Auth.authorize_url!( scope: scope, prompt: "consent", access_type: "offline", state: get_auth_state(params), redirect_uri: get_redirect_uri(params) ) ) end @spec auth(Plug.Conn.t(), map()) :: Plug.Conn.t() def auth(conn, %{"client" => client} = params) do scope = case client do "sheets" -> "https://www.googleapis.com/auth/spreadsheets" "gmail" -> "https://www.googleapis.com/auth/gmail.modify" _ -> raise "Unrecognized client: #{client}" end url = Google.Auth.authorize_url!( scope: scope, prompt: "consent", access_type: "offline", state: get_auth_state(params), redirect_uri: get_redirect_uri(params) ) json(conn, %{data: %{url: url}}) end @spec delete(Plug.Conn.t(), map()) :: Plug.Conn.t() def delete(conn, %{"id" => id}) do with %{account_id: _account_id} <- conn.assigns.current_user, %GoogleAuthorization{} = auth <- Google.get_google_authorization!(id), {:ok, %GoogleAuthorization{}} <- Google.delete_google_authorization(auth) do send_resp(conn, :no_content, "") end end defp get_auth_state(params) do case params do %{"state" => state} -> state %{"type" => type, "inbox_id" => inbox_id} when is_binary(type) and is_binary(inbox_id) -> "#{type}:#{inbox_id}" %{"type" => type} -> type _ -> nil end end @spec get_redirect_uri(map() | binary()) :: String.t() | nil defp get_redirect_uri(type) when is_binary(type) do default_redirect_uri = System.get_env("Hakerspeak_GOOGLE_REDIRECT_URI") case type do "support" -> System.get_env("Hakerspeak_SUPPORT_GMAIL_REDIRECT_URI", default_redirect_uri) "personal" -> System.get_env("Hakerspeak_PERSONAL_GMAIL_REDIRECT_URI", default_redirect_uri) _ -> default_redirect_uri end end defp get_redirect_uri(params) when is_map(params), do: params |> Map.get("type") |> get_redirect_uri() defp get_redirect_uri(_), do: System.get_env("Hakerspeak_GOOGLE_REDIRECT_URI") @spec should_enable_gmail_sync?(GoogleAuthorization.t()) :: boolean() defp should_enable_gmail_sync?(%GoogleAuthorization{client: "gmail", type: "support"}), do: true defp should_enable_gmail_sync?(_), do: false @spec enqueue_enabling_gmail_sync(binary()) :: {:ok, Oban.Job.t()} | {:error, Ecto.Changeset.t()} defp enqueue_enabling_gmail_sync(account_id) do %{account_id: account_id} |> ChatApi.Workers.EnableGmailInboxSync.new() |> Oban.insert() end end
31.795918
98
0.60077
7385c679466fc71bb8835aa0b6a490368ce25bd2
1,260
ex
Elixir
lib/conduit_web/controllers/article_controller.ex
rudyyazdi/conduit
8defa60962482fb81f5093ea5d58b71a160db3c4
[ "MIT" ]
298
2017-06-05T14:28:23.000Z
2022-03-30T16:53:44.000Z
lib/conduit_web/controllers/article_controller.ex
rudyyazdi/conduit
8defa60962482fb81f5093ea5d58b71a160db3c4
[ "MIT" ]
28
2017-07-21T01:06:47.000Z
2021-03-07T12:32:56.000Z
lib/conduit_web/controllers/article_controller.ex
rudyyazdi/conduit
8defa60962482fb81f5093ea5d58b71a160db3c4
[ "MIT" ]
77
2017-08-14T20:12:03.000Z
2021-12-08T22:24:59.000Z
defmodule ConduitWeb.ArticleController do use ConduitWeb, :controller alias Conduit.Blog alias Conduit.Blog.Projections.Article plug(Guardian.Plug.EnsureAuthenticated when action in [:create, :feed]) action_fallback(ConduitWeb.FallbackController) def index(conn, params) do user = Guardian.Plug.current_resource(conn) author = Blog.get_author(user) {articles, total_count} = Blog.list_articles(params, author) render(conn, "index.json", articles: articles, total_count: total_count) end def feed(conn, params) do user = Guardian.Plug.current_resource(conn) author = Blog.get_author(user) {articles, total_count} = Blog.feed_articles(params, author) render(conn, "index.json", articles: articles, total_count: total_count) end def show(conn, %{"slug" => slug}) do article = Blog.article_by_slug!(slug) render(conn, "show.json", article: article) end def create(conn, %{"article" => article_params}) do user = Guardian.Plug.current_resource(conn) author = Blog.get_author!(user.uuid) with {:ok, %Article{} = article} <- Blog.publish_article(author, article_params) do conn |> put_status(:created) |> render("show.json", article: article) end end end
28
87
0.707143
7385caa625a23c9938a3c5c247a3411a8a42d9fc
874
exs
Elixir
mix.exs
mbresson/Relev-de-notes-AN
00f79d36ad0de64635cf9c35e979aa4f7e0931e2
[ "MIT" ]
null
null
null
mix.exs
mbresson/Relev-de-notes-AN
00f79d36ad0de64635cf9c35e979aa4f7e0931e2
[ "MIT" ]
null
null
null
mix.exs
mbresson/Relev-de-notes-AN
00f79d36ad0de64635cf9c35e979aa4f7e0931e2
[ "MIT" ]
null
null
null
defmodule ReleveDeNotesAN.Mixfile do use Mix.Project def project do [app: :releve_de_notes_an, escript: escript_config, version: "0.1.0", 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, :httpoison]] 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"} # # Type "mix help deps" for more examples and options defp deps do [ {:sweet_xml, "~> 0.6.3" }, {:httpoison, "~> 0.10.0" } ] end defp escript_config do [ main_module: ReleveDeNotesAN.CLI ] end end
21.317073
77
0.608696
7385d5bd0ea3c43598d924a19628c26418845443
158
exs
Elixir
apps/re/priv/repo/migrations/20190111153747_remove_messages_and_channels.exs
ruby2elixir/emcasa-backend
70d7f4f233555417941ffa6ada84cf8740c21dd2
[ "MIT" ]
4
2019-11-01T16:29:31.000Z
2020-10-10T21:20:12.000Z
apps/re/priv/repo/migrations/20190111153747_remove_messages_and_channels.exs
caspg/backend
34df9dc14ab8ed75de4578fefa2e087580c7e867
[ "MIT" ]
null
null
null
apps/re/priv/repo/migrations/20190111153747_remove_messages_and_channels.exs
caspg/backend
34df9dc14ab8ed75de4578fefa2e087580c7e867
[ "MIT" ]
5
2019-11-04T21:25:45.000Z
2020-02-13T23:49:36.000Z
defmodule Re.Repo.Migrations.RemoveMessagesAndChannels do use Ecto.Migration def change do drop table(:messages) drop table(:channels) end end
17.555556
57
0.753165
738625098138a5b183eda31ae558dda00db8892f
3,971
ex
Elixir
lib/ex_admin/paginate.ex
augnustin/ex_admin
218d0094de8186808924dcca6157875a7bb382c9
[ "MIT" ]
2
2019-12-21T12:59:19.000Z
2020-04-01T15:27:12.000Z
lib/ex_admin/paginate.ex
augnustin/ex_admin
218d0094de8186808924dcca6157875a7bb382c9
[ "MIT" ]
null
null
null
lib/ex_admin/paginate.ex
augnustin/ex_admin
218d0094de8186808924dcca6157875a7bb382c9
[ "MIT" ]
1
2020-02-29T22:13:24.000Z
2020-02-29T22:13:24.000Z
defmodule ExAdmin.Paginate do @moduledoc false use Xain import ExAdmin.Theme.Helpers import ExAdmin.Gettext def paginate(_, nil, _, _, _, _, _), do: [] def paginate(link, page_number, page_size, total_pages, record_count, name) do markup do theme_module(Paginate).wrap_pagination1(fn -> if total_pages > 1 do for item <- items(page_number, page_size, total_pages) do theme_module(Paginate).build_item(link, item) end end end) theme_module(Paginate).wrap_pagination2(fn -> record_number = (page_number - 1) * page_size + 1 display_pagination( name, (page_number - 1) * page_size + 1, page_size, record_count, record_number + page_size - 1 ) end) end end defp display_pagination(name, _record_number, 1, record_count, _) do pagination_information(name, record_count) end defp display_pagination(name, record_number, _page_size, record_count, last_number) when last_number < record_count do pagination_information(name, record_number, last_number, record_count) end defp display_pagination(name, record_number, _page_size, record_count, _) do pagination_information(name, record_number, record_count, record_count) end def pagination_information(name, record_number, record_number, record_count) do markup do text(gettext("Displaying") <> Inflex.singularize(" #{name}") <> " ") b("#{record_number}") text(" " <> gettext("of") <> " ") b("#{record_count}") text(" " <> gettext("in total")) end end def pagination_information(name, record_number, last, record_count) do markup do text(gettext("Displaying %{name}", name: name) <> " ") b("#{record_number} - #{last}") text(" " <> gettext("of") <> " ") b("#{record_count}") text(" " <> gettext("in total")) end end def pagination_information(name, total) do markup do text(gettext("Displaying") <> " ") b(gettext("all %{total}", total: total)) text(" #{name}") end end def special_name(:first), do: gettext("« First") def special_name(:prev), do: gettext("‹ Prev") def special_name(:next), do: gettext("Next ›") def special_name(:last), do: gettext("Last »") def window_size, do: 7 def items(page_number, page_size, total_pages) do prefix_links(page_number) |> prefix_gap |> links(page_number, page_size, total_pages) |> postfix_gap |> postfix_links(page_number, total_pages) end def prefix_links(1), do: [] def prefix_links(page_number) do prev = if page_number > 1, do: page_number - 1, else: 1 [first: 1, prev: prev] end def prefix_gap(acc) do acc end def postfix_gap(acc), do: acc def links(acc, page_number, _page_size, total_pages) do half = Kernel.div(window_size(), 2) before = cond do page_number == 1 -> 0 page_number - half < 1 -> 1 true -> page_number - half end aftr = cond do before + half >= total_pages -> total_pages page_number + window_size() >= total_pages -> total_pages true -> page_number + half end before_links = if before > 0 do for x <- before..(page_number - 1), do: {:page, x} else [] end after_links = if page_number < total_pages do for x <- (page_number + 1)..aftr, do: {:page, x} else [] end pregap = if before != 1 and page_number != 1, do: [gap: true], else: [] postgap = if aftr != total_pages and page_number != total_pages, do: [gap: true], else: [] acc ++ pregap ++ before_links ++ [current: page_number] ++ after_links ++ postgap end def postfix_links(acc, page_number, total_pages) do if page_number == total_pages do acc else acc ++ [next: page_number + 1, last: total_pages] end end end
27.19863
94
0.619491
73864e2f2d57341a316500fba4edf58c8108637f
1,991
ex
Elixir
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p1beta1_color_info.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p1beta1_color_info.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p1beta1_color_info.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.Vision.V1.Model.GoogleCloudVisionV1p1beta1ColorInfo do @moduledoc """ Color information consists of RGB channels, score, and the fraction of the image that the color occupies in the image. ## Attributes * `color` (*type:* `GoogleApi.Vision.V1.Model.Color.t`, *default:* `nil`) - RGB components of the color. * `pixelFraction` (*type:* `number()`, *default:* `nil`) - The fraction of pixels the color occupies in the image. Value in range [0, 1]. * `score` (*type:* `number()`, *default:* `nil`) - Image-specific score for this color. Value in range [0, 1]. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :color => GoogleApi.Vision.V1.Model.Color.t(), :pixelFraction => number(), :score => number() } field(:color, as: GoogleApi.Vision.V1.Model.Color) field(:pixelFraction) field(:score) end defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1ColorInfo do def decode(value, options) do GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1ColorInfo.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1ColorInfo do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.566038
141
0.724761
73866e545dd89bb557d962f647677a411838e5ae
1,797
ex
Elixir
clients/books/lib/google_api/books/v1/model/geolayerdata_geo_viewport.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/books/lib/google_api/books/v1/model/geolayerdata_geo_viewport.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/books/lib/google_api/books/v1/model/geolayerdata_geo_viewport.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "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.Books.V1.Model.GeolayerdataGeoViewport do @moduledoc """ The viewport for showing this location. This is a latitude, longitude rectangle. ## Attributes * `hi` (*type:* `GoogleApi.Books.V1.Model.GeolayerdataGeoViewportHi.t`, *default:* `nil`) - * `lo` (*type:* `GoogleApi.Books.V1.Model.GeolayerdataGeoViewportLo.t`, *default:* `nil`) - """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :hi => GoogleApi.Books.V1.Model.GeolayerdataGeoViewportHi.t(), :lo => GoogleApi.Books.V1.Model.GeolayerdataGeoViewportLo.t() } field(:hi, as: GoogleApi.Books.V1.Model.GeolayerdataGeoViewportHi) field(:lo, as: GoogleApi.Books.V1.Model.GeolayerdataGeoViewportLo) end defimpl Poison.Decoder, for: GoogleApi.Books.V1.Model.GeolayerdataGeoViewport do def decode(value, options) do GoogleApi.Books.V1.Model.GeolayerdataGeoViewport.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Books.V1.Model.GeolayerdataGeoViewport do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.235294
96
0.742348
73867d7ddadc882acedd4086f20d33732f0bb7e4
963
exs
Elixir
apps/dockup_ui/test/channels/deployment_channel_test.exs
rudydydy/dockup
0d05d1ef65cc5523800bd852178361521cd3e7d8
[ "MIT" ]
null
null
null
apps/dockup_ui/test/channels/deployment_channel_test.exs
rudydydy/dockup
0d05d1ef65cc5523800bd852178361521cd3e7d8
[ "MIT" ]
null
null
null
apps/dockup_ui/test/channels/deployment_channel_test.exs
rudydydy/dockup
0d05d1ef65cc5523800bd852178361521cd3e7d8
[ "MIT" ]
null
null
null
defmodule DockupUi.DeploymentChannelTest do use DockupUi.ChannelCase, async: true import DockupUi.Factory alias DockupUi.DeploymentChannel test "update_deployment_status broadcasts a status_updated event" do DockupUi.Endpoint.subscribe("deployments:all") deployment = insert(:deployment, status: "started") DeploymentChannel.update_deployment_status(deployment) assert_receive %Phoenix.Socket.Broadcast{ topic: "deployments:all", event: "status_updated", payload: ^deployment } end test "when deployment status is 'queued' update_deployment_status sends out 'deployment_created' event" do DockupUi.Endpoint.subscribe("deployments:all") deployment = insert(:deployment, status: "queued") DeploymentChannel.update_deployment_status(deployment) assert_receive %Phoenix.Socket.Broadcast{ topic: "deployments:all", event: "deployment_created", payload: ^deployment } end end
33.206897
108
0.750779
73868e411478deebdaef56fb79c3457de585ab14
933
exs
Elixir
day20/task1.exs
joskov/advent2016
cdade8f0f47bf67b9dd29f8e25f4e8351cada309
[ "MIT" ]
2
2016-12-26T20:44:04.000Z
2017-02-10T19:59:55.000Z
day20/task1.exs
joskov/advent2016
cdade8f0f47bf67b9dd29f8e25f4e8351cada309
[ "MIT" ]
null
null
null
day20/task1.exs
joskov/advent2016
cdade8f0f47bf67b9dd29f8e25f4e8351cada309
[ "MIT" ]
null
null
null
defmodule Task do def parse_line(string) do [_, a, b] = Regex.run(~r/(\d+)-(\d+)/, string) {String.to_integer(a), String.to_integer(b)} end def run([], _removed, result), do: result def run(_list, [], result), do: result def run(list, _removed, result) do IO.puts("Min is #{result}, list left #{length(list)}") {list, removed, result} = Enum.reduce(list, {[], [], result}, &check_row/2) run(list, removed, result) end def check_row({min, max} = current, {rest, removed, result}) do if (result >= min && result <= max) do {rest, [current | removed], max + 1} else {[current | rest], removed, result} end end def calculate(input) do input |> String.split("\n") |> List.delete_at(-1) |> Enum.map(&parse_line/1) |> run(false, 0) end end {:ok, input} = File.read("input.txt") # IO.puts input result = Task.calculate(input) IO.inspect result
25.216216
79
0.594855
738692e987fe5ea7e0aac06c421ccce1cb6de8af
269
exs
Elixir
test/http_test.exs
gordalina/hush_gcp_secret_manager
38719f3a96fd07aa8a736200bd68fe92c9017625
[ "Apache-2.0" ]
15
2021-02-25T17:09:54.000Z
2021-03-02T19:53:00.000Z
test/http_test.exs
gordalina/hush_gcp_secret_manager
38719f3a96fd07aa8a736200bd68fe92c9017625
[ "Apache-2.0" ]
1
2021-09-11T12:27:23.000Z
2021-09-12T10:59:24.000Z
test/http_test.exs
gordalina/hush_gcp_secret_manager
38719f3a96fd07aa8a736200bd68fe92c9017625
[ "Apache-2.0" ]
null
null
null
defmodule Hush.Provider.GcpSecretManager.HttpTest do use ExUnit.Case doctest Hush.Provider.GcpSecretManager.Http alias Hush.Provider.GcpSecretManager test "for_scope/1" do assert_raise CaseClauseError, fn -> GcpSecretManager.Http.get("", []) end end end
26.9
77
0.776952
7386a9fe3ab0627bad3f0f55764c520b5f470f18
1,742
ex
Elixir
lib/covid19_questionnaire_web/schemas/questionnaire_request.ex
Delegation-numerique-en-sante/covid-19-elixir
c4b49c713642c0e022ab1ea79e9d5fb10964dffd
[ "MIT" ]
3
2020-04-08T19:15:22.000Z
2020-05-24T22:37:54.000Z
lib/covid19_questionnaire_web/schemas/questionnaire_request.ex
Delegation-numerique-en-sante/covid-19-elixir
c4b49c713642c0e022ab1ea79e9d5fb10964dffd
[ "MIT" ]
10
2020-04-05T17:31:49.000Z
2020-06-10T11:09:17.000Z
lib/covid19_questionnaire_web/schemas/questionnaire_request.ex
Delegation-numerique-en-sante/covid19-algorithme-orientation-api
c4b49c713642c0e022ab1ea79e9d5fb10964dffd
[ "MIT" ]
null
null
null
defmodule Covid19QuestionnaireWeb.Schemas.QuestionnaireRequest do @moduledoc """ Schéma de la requête pour lancer le algorithme d'orientation. """ require OpenApiSpex alias Covid19QuestionnaireWeb.Schemas.Questionnaire alias OpenApiSpex.Schema OpenApiSpex.schema(%{ title: "QuestionnaireRequest", description: "Corps de la requête POST pour lancer l'algorithme d'orientation", type: :object, properties: %{ questionnaire: %Schema{anyOf: [Questionnaire]} }, required: [:questionnaire], example: %{ "questionnaire" => %{ "metadata" => %{ "form_version" => "2020-05-10", "algo_version" => "2020-05-10", "orientation" => "SAMU" }, "respondent" => %{ "age_range" => "sup_65", "imc" => 21.9, "postal_code" => "75000" }, "symptoms" => %{ "sore_throat_aches" => true, "temperature_cat" => "35.5-37.7", "agueusia_anosmia" => true, "breathlessness" => true, "cough" => true, "diarrhea" => true, "tiredness" => true, "tiredness_details" => true, "feeding_day" => true }, "risk_factors" => %{ "breathing_disease" => true, "heart_disease" => 1, "kidney_disease" => true, "liver_disease" => true, "diabetes" => true, "immunosuppressant_disease" => 1, "cancer" => true, "pregnant" => 1, "sickle_cell" => true }, "calculations" => %{ "fever_algo" => true, "heart_disease_algo" => true, "immunosuppressant_disease_algo" => true } } } }) end
28.557377
83
0.528129
7386c49a040f62af71057d27d25e84f4e3a3f2dc
21,431
ex
Elixir
lib/nas_luminaire.ex
flixbi/element-parsers
b92ef1cff139130acbac4f40d0d48568a3de6590
[ "MIT" ]
1
2021-11-10T18:06:59.000Z
2021-11-10T18:06:59.000Z
lib/nas_luminaire.ex
SeppPenner/element-parsers
8a2594e0f15ca7177f6782d0441f25e3e55b8416
[ "MIT" ]
null
null
null
lib/nas_luminaire.ex
SeppPenner/element-parsers
8a2594e0f15ca7177f6782d0441f25e3e55b8416
[ "MIT" ]
null
null
null
defmodule Parser do use Platform.Parsing.Behaviour use Bitwise require Logger require Timex #ELEMENT IoT Parser for NAS Luminaire Controller Zhaga UL2030 v0.6.29 # According to documentation provided by NAS: https://www.nasys.no/wp-content/uploads/Luminaire_Controller_Zhaga_UL2030_6.pdf # Payload Description Version v0.6.29 # # Changelog # 2019-04-04 [gw]: Initial version # Used ports # 24, Status, Uplink # 25, Usage, Uplink # 50, Configuration, Uplink/Downlink # 51, Update Mode, Downlink # 52, Multicast, Downlink # 60, Command, Uplink/Downlink # 99, Boot/Debug, Uplink ### Status Message ### def parse(<<unix_timestamp::32-little, status, rssi::signed, profiles::binary>>, %{meta: %{frame_port: 24}} = _meta) do << relay_2::1, fw_error::1, hw_error::1, dig_error::1, thr_error::1, ldr_error::1, dali_connection_error::1, dali_error::1 >> = <<status>> map = %{ type: "status", dali: status_to_atom(dali_error), dali_connection: status_to_atom(dali_connection_error), ldr: status_to_atom(ldr_error), thr: status_to_atom(thr_error), dig: status_to_atom(dig_error), hw: status_to_atom(hw_error), fw: status_to_atom(fw_error), relay_2: relay_status_to_atom(relay_2), timestamp: DateTime.from_unix!(unix_timestamp), timestamp_unix: unix_timestamp, rssi: rssi, } map |> add_profiles(profiles, 0) end ### Usage Message ### def parse(bin, %{meta: %{frame_port: 25}} = _meta) do read_usage_messages(bin) end ### Config message responses (fPort 50) ### # set sunrise/sunset response def parse(<<0x06FFFFFFFFFFFF::56>>, %{meta: %{frame_port: 50}}) do %{ type: "config", info: "sunrise/sunset config disabled" } end def parse(<<0x06, sunrise_offset::signed, sunset_offset::signed, latitude::little-16, longitude::little-16>>, %{meta: %{frame_port: 50}}) do %{ type: "config", sunrise_offset: sunrise_offset, sunset_offset: sunset_offset, latitude: latitude / 100, longitude: longitude / 100 } end # set status report interval response def parse(<<0x07, interval::little-32>>, %{meta: %{frame_port: 50}}) do %{ type: "config", status_report_interval: interval } end # apply profile response def parse(<<0x08, profile_id, profile_seq, addr, days_active, rest::binary>>, %{meta: %{frame_port: 50}}) do map = %{ type: "config", profile_id: profile_id, profile_seq: profile_seq, dali_addr: profile_addr_to_dali_addr(<<addr>>), holidays_active: is_day_active(days_active, 1), mondays_active: is_day_active(days_active, 2), tuesdays_active: is_day_active(days_active, 4), wednesdays_active: is_day_active(days_active, 8), thursdays_active: is_day_active(days_active, 16), fridays_active: is_day_active(days_active, 32), saturdays_active: is_day_active(days_active, 64), sundays_active: is_day_active(days_active, 128), } add_dim_steps(map, rest, 1) end # set time response def parse(<<0x09, timestamp::little-32>>, %{meta: %{frame_port: 50}}) do %{ type: "config", timestamp_unix: timestamp, timestamp: DateTime.from_unix!(timestamp) } end ### Command Message Responses (fPort 60) ### # DALI status (can contain up to 25 devices) def parse(<<0x00, rest::binary>>, %{meta: %{frame_port: 60}}) do parse_dali_status_recursively(rest) end # set dim level def parse(<<0x01, addr, dim_level>>, %{meta: %{frame_port: 60}}) do %{ type: "command", dali_address: profile_addr_to_dali_addr(<<addr>>), dim_level: dim_level } end # Custom DALI request response def parse(<<0x03, rest::binary>>, %{meta: %{frame_port: 60}}) do parse_custom_dali_response_recursively(rest) end ### Boot/Debug message ### # is actually 15 bytes long, instead of 14 according to the docs def parse(<<0x00, serial::little-32, fw::24, timestamp::little-32, hw, opt, _rest::binary>>, %{meta: %{frame_port: 99}} = _meta) do <<major::8, minor::8, patch::8>> = <<fw::24>> %{ type: "debug", status: "boot", serial: Base.encode16(<<serial::32>>), firmware: "#{major}.#{minor}.#{patch}", timestamp: DateTime.from_unix!(timestamp), timestamp_unix: timestamp, hw_setup: hw, opt: opt } end def parse(<<0x01, _rest::binary>>, %{meta: %{frame_port: 99}} = _meta) do %{ type: "debug", status: "shutdown" } end def parse(<<0x10, 2::8, _rest::binary>>, %{meta: %{frame_port: 99}} = _meta) do %{ type: "debug", status: "error", error_code: 2, error: "Multiple unconfigured drivers detected" } end def parse(<<0x10, error, _rest::binary>>, %{meta: %{frame_port: 99}} = _meta) do %{ type: "debug", status: "error", error_code: error, error: "Unknown error" } end def parse(payload, meta) do Logger.warn("Could not parse payload #{inspect payload} with meta #{inspect meta}") [] end ### Common helper defp profile_addr_to_dali_addr(<<0xFE>>), do: "Broadcast" defp profile_addr_to_dali_addr(<<1::1, 0::1, 0::1, dali_group_addr::4, 0::1>>), do: "Group address #{dali_group_addr}" defp profile_addr_to_dali_addr(<<0::1, dali_single_addr::6, 0::1>>), do: "Single device #{dali_single_addr}" defp profile_addr_to_dali_addr(other) do Logger.info("Unknown DALI address #{inspect other}") "" end ### Apply Profile Helper ### defp add_dim_steps(map, <<step_time, dim_level, rest::binary>>, i) do {:ok, midnight} = NaiveDateTime.new(0, 1, 1, 0, 0, 0) step_time = midnight |> Timex.to_datetime() |> Timex.shift(minutes: step_time * 10) |> Timex.format!("{h24}:{m}") map |> Map.put("dim_step_#{i}_time", step_time) |> Map.put("dim_step_#{i}_level", dim_level) |> add_dim_steps(rest, i + 1) end defp add_dim_steps(map, <<>>, _), do: map ### Command Message Response Helper ### defp parse_dali_status_recursively(<<addr, status, rest::binary>>) do result = %{ type: "command", dali_address: profile_addr_to_dali_addr(<<addr>>), dali_status: parse_dali_status(<<status>>) } [result] ++ parse_dali_status_recursively(rest) end defp parse_dali_status_recursively(<<>>), do: [] defp parse_dali_status(<<0x04>>), do: "Ballast is off" defp parse_dali_status(<<0x02>>), do: "Lamp is burned out" defp parse_dali_status(<<other>>), do: "Unknown dali status #{inspect other}" ### Custom DALI Request Response helper ### defp parse_custom_dali_response_recursively(<<addr, query, answer, rest::binary>>) do result = %{ type: "command", dali_address: profile_addr_to_dali_addr(<<addr>>), dali_query: dali_query_to_string(query), dali_response: parse_dali_response(query, answer) } [result] ++ parse_custom_dali_response_recursively(rest) end defp parse_custom_dali_response_recursively(<<>>), do: [] defp dali_query_to_string(161), do: "Max level" defp dali_query_to_string(162), do: "Min level" defp dali_query_to_string(163), do: "Power on level" defp dali_query_to_string(164), do: "Failure level" defp dali_query_to_string(165), do: "Fade time/rate" defp dali_query_to_string(_), do: "Unknown query" defp parse_dali_response(165, answer), do: "<#{answer / 10}s / 45 steps/s" defp parse_dali_response(query, answer) when query <= 164 and query >= 161, do: answer defp parse_dali_response(_, answer), do: answer ### Status Message helper ### defp add_profiles(map, <<id, seq, addr, days_active, current_level, rest::binary>>, i) do map |> Map.put("profile_#{i}_id", id) |> Map.put("profile_#{i}_seq", seq) |> Map.put("profile_#{i}_addr", profile_addr_to_dali_addr(<<addr>>)) |> Map.put("profile_#{i}_current_dim_level", current_level) |> Map.put("profile_#{i}_holidays", is_day_active(days_active, 1)) |> Map.put("profile_#{i}_mondays", is_day_active(days_active, 2)) |> Map.put("profile_#{i}_tuesdays", is_day_active(days_active, 4)) |> Map.put("profile_#{i}_wednesdays", is_day_active(days_active, 8)) |> Map.put("profile_#{i}_thursdays", is_day_active(days_active, 16)) |> Map.put("profile_#{i}_fridays", is_day_active(days_active, 32)) |> Map.put("profile_#{i}_saturdays", is_day_active(days_active, 64)) |> Map.put("profile_#{i}_sundays", is_day_active(days_active, 128)) |> add_profiles(rest, i + 1) end defp add_profiles(map, <<>>, _), do: map defp is_day_active(days_active, day) do only_selected_day = Bitwise.band(days_active, day) cond do only_selected_day == 0 -> "not active" only_selected_day > 0 -> "active" end end defp status_to_atom(0), do: :ok defp status_to_atom(1), do: :alert defp relay_status_to_atom(0), do: :off defp relay_status_to_atom(1), do: :on ### Usage Message helper ### defp read_usage_messages(<<addr, reported_fields, rest::binary>>) do << _rfu::2, system_voltage::1, # uint8, V power_factor_instant::1, # uint8, divide by 100 load_side_energy_instant::1, # uint16, W load_side_energy_total::1, # uint32, Wh active_energy_instant::1, # uint16, W active_energy_total::1 # uint32, Wh >> = <<reported_fields>> {map, new_rest} = { %{ type: "usage", dali_address: profile_addr_to_dali_addr(<<addr>>) }, rest } |> add_active_energy_total(active_energy_total) |> add_active_energy_instant(active_energy_instant) |> add_load_side_energy_total(load_side_energy_total) |> add_load_side_energy_instant(load_side_energy_instant) |> add_power_factor_instant(power_factor_instant) |> add_system_voltage(system_voltage) [map] ++ read_usage_messages(new_rest) end defp read_usage_messages(<<>>), do: [] defp add_active_energy_total({map, <<active_energy_total::little-32, rest::binary>>}, 1) do { Map.put(map, :active_energy_total, active_energy_total), rest } end defp add_active_energy_total(map_with_rest_tuple, 0), do: map_with_rest_tuple defp add_active_energy_instant({map, <<active_energy_instant::little-16, rest::binary>>}, 1) do { Map.put(map, :active_energy_instant, active_energy_instant), rest } end defp add_active_energy_instant(map_with_rest_tuple, 0), do: map_with_rest_tuple defp add_load_side_energy_total({map, <<load_side_energy_total::little-32, rest::binary>>}, 1) do { Map.put(map, :load_side_energy_total, load_side_energy_total), rest } end defp add_load_side_energy_total(map_with_rest_tuple, 0), do: map_with_rest_tuple defp add_load_side_energy_instant({map, <<load_side_energy_instant::little-16, rest::binary>>}, 1) do { Map.put(map, :load_side_energy_instant, load_side_energy_instant), rest } end defp add_load_side_energy_instant(map_with_rest_tuple, 0), do: map_with_rest_tuple defp add_power_factor_instant({map, <<power_factor_instant::8, rest::binary>>}, 1) do { Map.put(map, :power_factor_instant, power_factor_instant / 100), rest } end defp add_power_factor_instant(map_with_rest_tuple, 0), do: map_with_rest_tuple defp add_system_voltage({map, <<system_voltage::8, rest::binary>>}, 1) do { Map.put(map, :system_voltage, system_voltage), rest } end defp add_system_voltage(map_with_rest_tuple, 0), do: map_with_rest_tuple def fields() do [ %{ "field" => "type", "display" => "Messagetype", }, # Status Message %{ "field" => "dali", "display" => "Dali state" }, %{ "field" => "dali_connection", "display" => "Dali connection state" }, %{ "field" => "ldr", "display" => "LDR state" }, %{ "field" => "thr", "display" => "THR state" }, %{ "field" => "dig", "display" => "DIG state" }, %{ "field" => "hw", "display" => "Hardware state" }, %{ "field" => "fw", "display" => "Firmware state" }, %{ "field" => "relay_2", "display" => "Relay 2 state" }, %{ "field" => "timestamp", "display" => "Timestamp" }, %{ "field" => "timestamp_unix", "display" => "Timestamp Unix" }, %{ "field" => "rssi", "display" => "RSSI", "unit" => "dBm" }, # Usage Message %{ "field" => "dali_address", "display" => "Dali address" }, %{ "field" => "active_energy_total", "display" => "Active energy total", "unit" => "Wh" }, %{ "field" => "active_energy_instant", "display" => "Active energy consumption", "unit" => "W" }, %{ "field" => "load_side_energy_total", "display" => "Load side energy total", "unit" => "Wh" }, %{ "field" => "load_side_energy_instant", "display" => "Load side energy consumption", "unit" => "W" }, %{ "field" => "power_factor_instant", "display" => "Power factor instant", }, %{ "field" => "system_voltage", "display" => "System voltage", "unit" => "V" }, ] end def tests() do [ ### Status Message (sample from docs) ### { :parse_hex, "28E29B59018E0416FE1E32022AFEE132", %{meta: %{frame_port: 24}}, %{ "profile_0_id" => 4, "profile_0_seq" => 22, "profile_0_addr" => "Broadcast", "profile_0_holidays" => "not active", "profile_0_mondays" => "active", "profile_0_tuesdays" => "active", "profile_0_wednesdays" => "active", "profile_0_thursdays" => "active", "profile_0_fridays" => "not active", "profile_0_saturdays" => "not active", "profile_0_sundays" => "not active", "profile_0_current_dim_level" => 50, "profile_1_id" => 2, "profile_1_seq" => 42, "profile_1_addr" => "Broadcast", "profile_1_holidays" => "active", "profile_1_mondays" => "not active", "profile_1_tuesdays" => "not active", "profile_1_wednesdays" => "not active", "profile_1_thursdays" => "not active", "profile_1_fridays" => "active", "profile_1_saturdays" => "active", "profile_1_sundays" => "active", "profile_1_current_dim_level" => 50, dali: :alert, dali_connection: :ok, ldr: :ok, thr: :ok, dig: :ok, hw: :ok, fw: :ok, relay_2: :off, rssi: -114, timestamp_unix: 1503388200, timestamp: DateTime.from_unix!(1503388200), type: "status" } }, ### Usage message (sample from docs) ### { :parse_hex, "04030000000000000603151400000000", %{meta: %{frame_port: 25}}, [ %{ active_energy_instant: 0, active_energy_total: 0, dali_address: "Single device 2", type: "usage" }, %{ active_energy_instant: 0, active_energy_total: 5141, dali_address: "Single device 3", type: "usage" } ] }, { # real payload from device :parse_hex, "011F4E04000006004D04000007002A", %{meta: %{frame_port: 25}}, [ %{ active_energy_instant: 6, active_energy_total: 1102, dali_address: "", load_side_energy_instant: 7, load_side_energy_total: 1101, power_factor_instant: 0.42, type: "usage" } ] }, ### config message responses ### {# sunrise/sunset config was disabled :parse_hex, "06FFFFFFFFFFFF", %{meta: %{frame_port: 50}}, %{ type: "config", info: "sunrise/sunset config disabled" } }, { # sunrise/sunset config sample from doc :parse_hex, "06E21E9619B309", %{meta: %{frame_port: 50}}, %{ type: "config", sunrise_offset: -30, sunset_offset: 30, latitude: 65.50, longitude: 24.83 } }, { # set status report interval :parse_hex, "0708070000", %{meta: %{frame_port: 50}}, %{ type: "config", status_report_interval: 1800 } }, { # apply profile with dim sequence (sample from doc, except fridays also active) :parse_hex, "081603FE3E061E24503C1E6650", %{meta: %{frame_port: 50}}, %{ "dim_step_1_time" => "01:00", "dim_step_1_level" => 30, "dim_step_2_time" => "06:00", "dim_step_2_level" => 80, "dim_step_3_time" => "10:00", "dim_step_3_level" => 30, "dim_step_4_time" => "17:00", "dim_step_4_level" => 80, type: "config", profile_id: 22, profile_seq: 3, dali_addr: "Broadcast", holidays_active: "not active", mondays_active: "active", tuesdays_active: "active", wednesdays_active: "active", thursdays_active: "active", fridays_active: "active", saturdays_active: "not active", sundays_active: "not active" } }, { # set device time :parse_hex, "09782BCC5C", %{meta: %{frame_port: 50}}, %{ type: "config", timestamp: DateTime.from_unix!(1556884344), timestamp_unix: 1556884344, } }, ### Command message responses ### { # Get DALI connection status with one device :parse_hex, "000204", %{meta: %{frame_port: 60}}, [ %{ type: "command", dali_address: "Single device 1", dali_status: "Ballast is off" } ] }, { # Get DALI connection status with multiple devices (sample from docs) :parse_hex, "00020406020C02", %{meta: %{frame_port: 60}}, [ %{ type: "command", dali_address: "Single device 1", dali_status: "Ballast is off" }, %{ type: "command", dali_address: "Single device 3", dali_status: "Lamp is burned out" }, %{ type: "command", dali_address: "Single device 6", dali_status: "Lamp is burned out" } ] }, {# set dimming level to 0 :parse_hex, "01FE00", %{meta: %{frame_port: 60}}, %{ type: "command", dali_address: "Broadcast", dim_level: 0 } }, {# set dimming level to 100 :parse_hex, "01FE64", %{meta: %{frame_port: 60}}, %{ type: "command", dali_address: "Broadcast", dim_level: 100 } }, { # custom DALI response (sample from docs) :parse_hex, "0348A1FE48A2A848A3FE48A4FE48A507", %{meta: %{frame_port: 60}}, [ %{ type: "command", dali_address: "Single device 36", dali_query: "Max level", dali_response: 254 }, %{ type: "command", dali_address: "Single device 36", dali_query: "Min level", dali_response: 168 }, %{ type: "command", dali_address: "Single device 36", dali_query: "Power on level", dali_response: 254 }, %{ type: "command", dali_address: "Single device 36", dali_query: "Failure level", dali_response: 254 }, %{ type: "command", dali_address: "Single device 36", dali_query: "Fade time/rate", dali_response: "<0.7s / 45 steps/s" }, ] }, ### Boot/debug message ### { # boot (sample from docs) :parse_hex, "00FF001047000405C31441590500", %{meta: %{frame_port: 99}}, %{ type: "debug", status: "boot", serial: "471000FF", firmware: "0.4.5", timestamp: DateTime.from_unix!(1497437379), timestamp_unix: 1497437379, hw_setup: 5, opt: 0 } }, { # shutdown (sample NOT from docs) :parse_hex, "01", %{meta: %{frame_port: 99}}, %{ type: "debug", status: "shutdown" } }, { # error 02 (sample NOT from docs) :parse_hex, "1002", %{meta: %{frame_port: 99}}, %{ type: "debug", status: "error", error_code: 2, error: "Multiple unconfigured drivers detected" } }, { # error unknown (sample NOT from docs) :parse_hex, "1000", %{meta: %{frame_port: 99}}, %{ type: "debug", status: "error", error_code: 0, error: "Unknown error" } } ] end end
30.659514
142
0.574028
7386c59f384ef829fab13c2b76394ae0402665ad
5,625
ex
Elixir
lib/capuli.ex
merongivian/capuli
aebb93832055fb02cf9e660e2483ad89d0029e7f
[ "MIT" ]
6
2018-06-10T20:41:50.000Z
2019-10-13T01:43:06.000Z
lib/capuli.ex
merongivian/capuli
aebb93832055fb02cf9e660e2483ad89d0029e7f
[ "MIT" ]
1
2018-03-10T01:28:34.000Z
2018-06-10T17:16:07.000Z
lib/capuli.ex
merongivian/capuli
aebb93832055fb02cf9e660e2483ad89d0029e7f
[ "MIT" ]
1
2022-01-01T20:19:18.000Z
2022-01-01T20:19:18.000Z
defmodule Capuli do @moduledoc """ Capuli parses xml files through a DSL defined in a module, this module will be the parser. Use `element` if you want declare one tag and `elements` for multiple tags. Here is a parser for an Atom entry: defmodule AtomEntry do use Capuli element :title element :description element :link, as: :url, value: :href, with: [ type: "text/html" ] elements :images end You can use the `AtomEntry` inside other parsers as well: defmodule Atom do use Capuli element :link elements :entry, as: :entries, module: AtomEntry end ## Element(s) Options: * `:as` - the key used for setting the name of the element * `:value` - retrieves the value from an specific attribute, it takes the value from the tag by default * `:with` - search tags with specific attributes, the tag must have all attributes * `:module` - used for parsing the extracted value Capuli sets a `parse` method that is used for processing the xml: xml = "<rss>.....<rss>" Atom.parse(xml) """ @doc false defmacro __using__(_) do quote do import Capuli, only: [element: 2, element: 1, elements: 2, elements: 1] @before_compile Capuli Module.register_attribute(__MODULE__, :element_definitions, accumulate: true) Module.register_attribute(__MODULE__, :elements_definitions, accumulate: true) end end @doc false defmacro __before_compile__(_env) do quote do @doc false def parse(source) do parsed_element_definitions = Capuli.execute_definitions( source, @element_definitions, :get_element ) parsed_elements_definitions = Capuli.execute_definitions( source, @elements_definitions, :get_elements ) Map.merge( parsed_element_definitions, parsed_elements_definitions ) end end end @doc """ Defines the element that will be extracted ## Options: `:as`, `:value`, `:with`, `module` See the "Element(s) options" section at the module documentation for more info. """ defmacro element(name, opts \\ []) do quote bind_quoted: [name: name, opts: opts] do Module.put_attribute(__MODULE__, :element_definitions, [name, opts]) end end @doc """ Defines the elements that will be extracted ## Options: `:as`, `:value`, `:with`, `module` See the "Element(s) options" section at the module documentation for more info. """ defmacro elements(name, opts \\ []) do quote bind_quoted: [name: name, opts: opts] do Module.put_attribute(__MODULE__, :elements_definitions, [name, opts]) end end @doc false def execute_definitions(source, definitions, extractor) do Enum.reduce definitions, %{}, fn(extractor_attributes, parsed_source) -> extracted_element = apply( __MODULE__, extractor, [source | extractor_attributes] ) key = extracted_element |> Map.keys |> List.first case extracted_element do %{^key => nil} -> parsed_source %{^key => ""} -> parsed_source %{^key => []} -> parsed_source _ -> Map.merge(parsed_source, extracted_element) end end end @doc false def get_element(source, name, opts \\ []) do value = get_element_value(source, name, Keyword.drop(opts, [:as])) %{opts[:as] || name => value} end @doc false def get_elements(source, name, opts \\ []) do get_values = fn(parsed_elements, opts) -> if opts[:module] do Enum.map(parsed_elements, &opts[:module].parse/1) else Enum.map(parsed_elements, & value_extractor(&1, opts)) end end name = Atom.to_string(name) values = source |> Floki.find(create_selector(name, opts[:with])) |> get_values.(opts) %{opts[:as] => values} end defp get_element_value(source, name, opts) do name = Atom.to_string(name) try_exact_find = fn(source, name) -> if is_list(source) and Enum.count(source) > 1 do Enum.find(source, &(elem(&1, 0) == name)) else source end end value = source |> Floki.find(create_selector(name, opts[:with])) # NOTE: floki.find sometimes returns more than one value # for example when theres another node with the same name # but with a namespace |> try_exact_find.(name) |> value_extractor(opts) if opts[:module], do: opts[:module].parse(value), else: value end defp value_extractor(value, opts) do if opts[:value] do value |> Floki.attribute(Atom.to_string opts[:value]) |> List.first() else value_matcher(value) end end defp value_matcher([{_, _, [value]}]), do: value defp value_matcher({_, _, [value]}), do: value defp value_matcher({_, _, value}) when is_list(value), do: value defp value_matcher(value), do: value defp create_selector(name, attributes) do name = name |> String.replace(":", "|") |> String.replace("_", "-") name <> create_attributes_selector(attributes) end defp create_attributes_selector(attributes) defp create_attributes_selector(nil), do: "" defp create_attributes_selector(attributes) do Enum.reduce attributes, "", fn({name, value}, selector) -> selector <> ~s([#{name}="#{value}"]) end end end
26.285047
84
0.614578
7387059538fc9e90d87d142984544a8a7aea75cc
853
ex
Elixir
test/support/conn_case.ex
philcallister/ticker-phoenix
052fddec24de3b3e48a9513a0d3782f3c9227c81
[ "MIT" ]
15
2016-11-02T14:03:00.000Z
2021-03-23T20:34:14.000Z
test/support/conn_case.ex
philcallister/ticker-phoenix
052fddec24de3b3e48a9513a0d3782f3c9227c81
[ "MIT" ]
null
null
null
test/support/conn_case.ex
philcallister/ticker-phoenix
052fddec24de3b3e48a9513a0d3782f3c9227c81
[ "MIT" ]
2
2019-08-09T18:33:09.000Z
2020-07-14T16:28:14.000Z
defmodule TickerPhoenix.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also import other functionality to make it easier to build and query models. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest import TickerPhoenix.Router.Helpers # The default endpoint for testing @endpoint TickerPhoenix.Endpoint end end setup tags do {:ok, conn: Phoenix.ConnTest.build_conn()} end end
24.371429
56
0.726846
7387169661a177e790a8a8e2e0076162756d1f68
1,964
ex
Elixir
clients/webmaster/lib/google_api/webmaster/v3/model/search_analytics_query_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/webmaster/lib/google_api/webmaster/v3/model/search_analytics_query_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/webmaster/lib/google_api/webmaster/v3/model/search_analytics_query_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "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.Webmaster.V3.Model.SearchAnalyticsQueryResponse do @moduledoc """ A list of rows, one per result, grouped by key. Metrics in each row are aggregated for all data grouped by that key either by page or property, as specified by the aggregation type parameter. ## Attributes * `responseAggregationType` (*type:* `String.t`, *default:* `nil`) - How the results were aggregated. * `rows` (*type:* `list(GoogleApi.Webmaster.V3.Model.ApiDataRow.t)`, *default:* `nil`) - A list of rows grouped by the key values in the order given in the query. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :responseAggregationType => String.t(), :rows => list(GoogleApi.Webmaster.V3.Model.ApiDataRow.t()) } field(:responseAggregationType) field(:rows, as: GoogleApi.Webmaster.V3.Model.ApiDataRow, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Webmaster.V3.Model.SearchAnalyticsQueryResponse do def decode(value, options) do GoogleApi.Webmaster.V3.Model.SearchAnalyticsQueryResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Webmaster.V3.Model.SearchAnalyticsQueryResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.28
193
0.745418
73871e574ee076aad36a9b621ccdcd96e7ab5027
1,136
exs
Elixir
apps/admin/config/dev.exs
impressarix/Phoenix-Webstore
31376183b853e594b224fb1051897a00cd20b6ec
[ "Apache-2.0" ]
null
null
null
apps/admin/config/dev.exs
impressarix/Phoenix-Webstore
31376183b853e594b224fb1051897a00cd20b6ec
[ "Apache-2.0" ]
null
null
null
apps/admin/config/dev.exs
impressarix/Phoenix-Webstore
31376183b853e594b224fb1051897a00cd20b6ec
[ "Apache-2.0" ]
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 :emporium_admin, EmporiumAdmin.Endpoint, http: [port: 4001], debug_errors: true, code_reloader: true, cache_static_lookup: false, check_origin: false, watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin"]] # Watch static and templates for browser reloading. config :emporium_admin, EmporiumAdmin.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{web/views/.*(ex)$}, ~r{web/templates/.*(eex)$} ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. # Do not configure such in production as keeping # and calculating stacktraces is usually expensive. config :phoenix, :stacktrace_depth, 20 config :emporium_admin, api_url: "http://localhost:4000"
29.894737
74
0.723592
7387211f63ae78ece3ace499b5ba4b2ab7e2fde8
3,904
ex
Elixir
lib/new_relixir/agent.ex
edipox/new-relixir
00de7b6016b840d14004c32e562604de25c0c9b5
[ "MIT" ]
null
null
null
lib/new_relixir/agent.ex
edipox/new-relixir
00de7b6016b840d14004c32e562604de25c0c9b5
[ "MIT" ]
null
null
null
lib/new_relixir/agent.ex
edipox/new-relixir
00de7b6016b840d14004c32e562604de25c0c9b5
[ "MIT" ]
null
null
null
defmodule NewRelixir.Agent do require Logger @base_url "http://~s/agent_listener/invoke_raw_method?" @doc """ Connects to New Relic and sends the hopefully correctly formatted data and registers it under the given hostname. """ def push(hostname, data, errors) do if NewRelixir.active? do collector = get_redirect_host() run_id = connect(collector, hostname) case push_metric_data(collector, run_id, data) do :ok -> push_error_data(collector, run_id, errors) error -> Logger.error(inspect(error)) end end end ## NewRelixir protocol def get_redirect_host() do url = url(method: :get_redirect_host) case request(url) do {:ok, 200, body} -> struct = Poison.decode!(body) struct["return_value"] {:ok, 503, _} -> raise RuntimeError.message("newrelic_down") {:error, :timeout} -> raise RuntimeError.message("newrelic_down") end end def connect(collector, hostname, attempts_count \\ 1) do url = url(collector, [method: :connect]) data = [%{ :agent_version => "1.5.0.103", :app_name => [app_name()], :host => l2b(hostname), :identifier => app_name(), :pid => l2i(:os.getpid()), :environment => [], :language => Application.get_env(:new_relixir, :language, "python"), :settings => %{} }] case request(url, Poison.encode!(data)) do {:ok, 200, body} -> struct = Poison.decode!(body) return = struct["return_value"] return["agent_run_id"] {:ok, 503, body} -> raise RuntimeError.exception("newrelic - connect - #{inspect(body)}") {:error, :timeout} -> if attempts_count > 0 do connect(collector, hostname, attempts_count-1) else raise RuntimeError.exception("newrelic - connect - timeout") end end end def push_metric_data(collector, run_id, metric_data) do url = url(collector, [method: :metric_data, run_id: run_id]) data = [run_id | metric_data] push_data(url, data) end def push_error_data(collector, run_id, error_data) do url = url(collector, [method: :error_data, run_id: run_id]) data = [run_id, error_data] push_data(url, data) end def push_data(url, data) do result = request(url, Poison.encode!(data)) case result do {:ok, 200, body} -> struct = Poison.decode!(body) case struct["exception"] do nil -> :ok exception -> {:error, exception} end; {:ok, 503, body} -> raise RuntimeError.exception("newrelic - push_data - #{inspect(body)}") {:error, :timeout} -> raise RuntimeError.exception("newrelic - push_data - timeout") end end ## Helpers defp l2b(char_list) do to_string(char_list) end defp l2i(char_list) do :erlang.list_to_integer(char_list) end defp app_name() do Application.get_env(:new_relixir, :application_name) end defp license_key() do Application.get_env(:new_relixir, :license_key) end def request(url, body \\ "[]") do headers = [{'Content-Encoding', 'identity'}] case :hackney.post(url, headers, body, [:with_body]) do {:ok, status, _, body} -> {:ok, status, body} error -> error end end def url(args) do url("collector.newrelic.com", args) end def url(host, args) do base_args = [ protocol_version: 10, license_key: license_key(), marshal_format: :json ] base_url = String.replace(@base_url, "~s", host) segments = List.flatten([base_url, urljoin(args ++ base_args)]) Enum.join(segments) end defp urljoin([]), do: [] defp urljoin([h | t]) do [url_var(h) | (for x <- t, do: ["&", url_var(x)])] end defp url_var({key, value}), do: [to_string(key), "=", to_string(value)] end
26.201342
79
0.607582
738726d1d0107490f76a6ab492adf0a0ffe63e6d
444
ex
Elixir
lib/mipha/accounts/location.ex
ZPVIP/mipha
a7df054f72eec7de88b60d94c501488375bdff6a
[ "MIT" ]
156
2018-06-01T19:52:32.000Z
2022-02-03T10:58:10.000Z
lib/mipha/accounts/location.ex
ZPVIP/mipha
a7df054f72eec7de88b60d94c501488375bdff6a
[ "MIT" ]
139
2018-07-10T01:57:23.000Z
2021-08-02T21:29:24.000Z
lib/mipha/accounts/location.ex
ZPVIP/mipha
a7df054f72eec7de88b60d94c501488375bdff6a
[ "MIT" ]
29
2018-07-17T08:43:45.000Z
2021-12-14T13:45:30.000Z
defmodule Mipha.Accounts.Location do @moduledoc false use Ecto.Schema import Ecto.Changeset alias Mipha.Accounts.{User, Location, Company} @type t :: %Location{} schema "locations" do field :name, :string has_many :users, User has_many :companies, Company timestamps() end @doc false def changeset(location, attrs) do location |> cast(attrs, [:name]) |> validate_required([:name]) end end
16.444444
48
0.668919
73872abb4504f1828e198e6875023bb1f9255c3d
1,861
ex
Elixir
lib/live_sup_web/live/widgets/blameless/blameless_incidents_by_type_live.ex
livesup-dev/livesup
eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446
[ "Apache-2.0", "MIT" ]
null
null
null
lib/live_sup_web/live/widgets/blameless/blameless_incidents_by_type_live.ex
livesup-dev/livesup
eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446
[ "Apache-2.0", "MIT" ]
3
2022-02-23T15:51:48.000Z
2022-03-14T22:52:43.000Z
lib/live_sup_web/live/widgets/blameless/blameless_incidents_by_type_live.ex
livesup-dev/livesup
eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446
[ "Apache-2.0", "MIT" ]
null
null
null
defmodule LiveSupWeb.Live.Widgets.Blameless.IncidentsByTypeLive do use LiveSupWeb.Live.Widgets.WidgetLive @impl true def render_widget(assigns) do ~H""" <.live_component module={SmartRenderComponent} id={@widget_data.id} let={widget_data} widget_data={@widget_data}> <!-- Incidents by Type --> <.live_component module={WidgetHeaderComponent} id={"#{widget_data.id}-header"} widget_data={widget_data} /> <!-- Widget Content --> <div class="p-2 grid justify-items-center min-h-[132px]"> <%= live_component(LiveSupWeb.Output.VegaLiteStaticComponent, id: "blameless-incidents-by-type-chart", spec: build_spec(widget_data)) %> </div> <!-- /Widget Content --> <!-- /Incidents by Type --> <.live_component module={WidgetFooterComponent} id={"#{widget_data.id}-footer"} widget_data={widget_data} /> </.live_component> """ end def build_spec(widget_data) do data = widget_data.data |> Enum.map(fn {key, value} -> %{"category" => key, "value" => value} end) # Initialize the specification, optionally with some top-level properties %{ "$schema" => "https://vega.github.io/schema/vega-lite/v5.json", "description" => "", "data" => %{ "values" => data }, "background" => nil, "mark" => "arc", "encoding" => %{ "theta" => %{"field" => "value", "type" => "quantitative", "stack" => true}, "color" => %{ "field" => "category", "type" => "nominal", "legend" => %{"title" => "Type", "labelColor" => "white", "titleColor" => "white"} } }, "layer" => [ %{ "mark" => %{"type" => "arc", "outerRadius" => 80} }, %{ "mark" => %{"type" => "text", "radius" => 100} } ] } end end
33.232143
144
0.551854
738754bed9ebeea25c83a691f744fb4636fca5f0
68
exs
Elixir
test/test_helper.exs
elixir-berlin/juntos
64dd05888f357cf0c74da11d1eda69bab7f38e95
[ "MIT" ]
1
2019-11-15T15:39:24.000Z
2019-11-15T15:39:24.000Z
test/test_helper.exs
elixir-berlin/juntos
64dd05888f357cf0c74da11d1eda69bab7f38e95
[ "MIT" ]
166
2020-06-30T16:07:48.000Z
2021-11-25T00:02:24.000Z
test/test_helper.exs
elixir-berlin/juntos
64dd05888f357cf0c74da11d1eda69bab7f38e95
[ "MIT" ]
null
null
null
ExUnit.start() Ecto.Adapters.SQL.Sandbox.mode(Juntos.Repo, :manual)
22.666667
52
0.779412
73876f1985ed2b4b51bfb5082c9ce4afcd6036f0
263
ex
Elixir
lib/live_view_todos.ex
MarvinKweyu/LiveViewTodos
89c48d1692be56d50c779587cac4e6a654c68919
[ "MIT" ]
null
null
null
lib/live_view_todos.ex
MarvinKweyu/LiveViewTodos
89c48d1692be56d50c779587cac4e6a654c68919
[ "MIT" ]
null
null
null
lib/live_view_todos.ex
MarvinKweyu/LiveViewTodos
89c48d1692be56d50c779587cac4e6a654c68919
[ "MIT" ]
null
null
null
defmodule LiveViewTodos do @moduledoc """ LiveViewTodos 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
26.3
66
0.764259
7387b0601fec90a842775992b407932378213537
828
exs
Elixir
test/rocketpay_web/views/users_view_test.exs
LuizFerK/Rocketpay
4388f22231c43fb58e777dfb04a342e82b548df7
[ "MIT" ]
null
null
null
test/rocketpay_web/views/users_view_test.exs
LuizFerK/Rocketpay
4388f22231c43fb58e777dfb04a342e82b548df7
[ "MIT" ]
null
null
null
test/rocketpay_web/views/users_view_test.exs
LuizFerK/Rocketpay
4388f22231c43fb58e777dfb04a342e82b548df7
[ "MIT" ]
null
null
null
defmodule RocketpayWeb.UsersViewTest do use RocketpayWeb.ConnCase, async: true import Phoenix.View alias Rocketpay.{Account, User} alias RocketpayWeb.UsersView test "renders create.json" do params = %{ name: "Luiz", password: "123456", nickname: "Luuu", email: "[email protected]", age: 18 } {:ok, %User{id: user_id, account: %Account{id: account_id}} = user} = Rocketpay.create_user(params) response = render(UsersView, "create.json", user: user) expected_response = %{ message: "User created", user: %{ account: %{ balance: Decimal.new("0.00"), id: account_id }, id: user_id, name: "Luiz", nickname: "Luuu" } } assert response == expected_response end end
21.230769
73
0.59058
7387b67b9ceb64572b4d550de00e0f1a117ce367
377
exs
Elixir
priv/repo/migrations/20190905094949_add_project_market_segments_table.exs
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
81
2017-11-20T01:20:22.000Z
2022-03-05T12:04:25.000Z
priv/repo/migrations/20190905094949_add_project_market_segments_table.exs
rmoorman/sanbase2
226784ab43a24219e7332c49156b198d09a6dd85
[ "MIT" ]
359
2017-10-15T14:40:53.000Z
2022-01-25T13:34:20.000Z
priv/repo/migrations/20190905094949_add_project_market_segments_table.exs
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
16
2017-11-19T13:57:40.000Z
2022-02-07T08:13:02.000Z
defmodule Sanbase.Repo.Migrations.AddProjectMarketSegmentsTable do use Ecto.Migration @table "project_market_segments" def change do create table(@table) do add(:project_id, references(:project)) add(:market_segment_id, references(:market_segments)) end create(unique_index(:project_market_segments, [:project_id, :market_segment_id])) end end
29
85
0.758621
7387b756d8dcd1d188a240267febbf4535ce2da5
1,567
ex
Elixir
priv/cabbage/apps/itest/lib/watcher_security_critical_api/connection.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
priv/cabbage/apps/itest/lib/watcher_security_critical_api/connection.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
priv/cabbage/apps/itest/lib/watcher_security_critical_api/connection.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
# Copyright 2019-2020 OmiseGO Pte Ltd # # 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 class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. if Code.ensure_loaded?(WatcherSecurityCriticalAPI.Connection) do # override Tesla connection module if it exists because it's pointing to localhost Code.compiler_options(ignore_module_conflict: true) defmodule WatcherSecurityCriticalAPI.Connection do @moduledoc """ Handle Tesla connections for WatcherSecurityCriticalAPI. """ use Tesla # Add any middleware here (authentication) plug(Tesla.Middleware.BaseUrl, "http://localhost:7434") plug(Tesla.Middleware.Headers, [{"user-agent", "Elixir"}, {"Content-Type", "application/json"}]) plug(Tesla.Middleware.EncodeJson, engine: Poison) @doc """ Configure an authless client connection # Returns Tesla.Env.client """ @spec new() :: Tesla.Env.client() def new() do Tesla.client([]) end end end
33.340426
100
0.731334
7387c190e61beb0e31253376db0972ff15eb7f37
110
exs
Elixir
config/config.exs
glific/passwordless_auth
e5b7a7c1792c8ad4eea129094080e8696fb905ca
[ "Apache-2.0" ]
null
null
null
config/config.exs
glific/passwordless_auth
e5b7a7c1792c8ad4eea129094080e8696fb905ca
[ "Apache-2.0" ]
null
null
null
config/config.exs
glific/passwordless_auth
e5b7a7c1792c8ad4eea129094080e8696fb905ca
[ "Apache-2.0" ]
null
null
null
use Mix.Config # Removed default config option of ExTwilio for SMS adapter import_config "#{Mix.env()}.exs"
18.333333
59
0.754545
7387c455f89c84618e86fd95a7cbdf9462e90955
2,164
ex
Elixir
clients/big_query/lib/google_api/big_query/v2/model/dataset_list.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/big_query/lib/google_api/big_query/v2/model/dataset_list.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/big_query/lib/google_api/big_query/v2/model/dataset_list.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.BigQuery.V2.Model.DatasetList do @moduledoc """ ## Attributes - datasets ([DatasetListDatasets]): An array of the dataset resources in the project. Each resource contains basic information. For full information about a particular dataset resource, use the Datasets: get method. This property is omitted when there are no datasets in the project. Defaults to: `null`. - etag (String.t): A hash value of the results page. You can use this property to determine if the page has changed since the last request. Defaults to: `null`. - kind (String.t): The list type. This property always returns the value \&quot;bigquery#datasetList\&quot;. Defaults to: `null`. - nextPageToken (String.t): A token that can be used to request the next results page. This property is omitted on the final results page. Defaults to: `null`. """ defstruct [ :"datasets", :"etag", :"kind", :"nextPageToken" ] end defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.DatasetList do import GoogleApi.BigQuery.V2.Deserializer def decode(value, options) do value |> deserialize(:"datasets", :list, GoogleApi.BigQuery.V2.Model.DatasetListDatasets, options) end end defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.DatasetList do def encode(value, options) do GoogleApi.BigQuery.V2.Deserializer.serialize_non_nil(value, options) end end
40.074074
306
0.749538
738800c6aa26e47ea7c5bad535ecac952b7b1ab7
2,191
exs
Elixir
rumbl/test/controllers/auth_test.exs
enilsen16/elixir
b4d1d45858a25e4beb39e07de8685f3d93d6a520
[ "MIT" ]
null
null
null
rumbl/test/controllers/auth_test.exs
enilsen16/elixir
b4d1d45858a25e4beb39e07de8685f3d93d6a520
[ "MIT" ]
null
null
null
rumbl/test/controllers/auth_test.exs
enilsen16/elixir
b4d1d45858a25e4beb39e07de8685f3d93d6a520
[ "MIT" ]
null
null
null
defmodule Rumbl.AuthTest do use Rumbl.ConnCase alias Rumbl.Auth setup %{conn: conn} do conn = conn |> bypass_through(Rumbl.Router, :browser) |> get("/") {:ok, %{conn: conn}} end test "authenticate_user halts when no current_user exists", %{conn: conn} do conn = Auth.authenticate_user(conn, []) assert conn.halted end test "authenticate_user continues when the current_user exists", %{conn: conn} do conn = conn |> assign(:current_user, %Rumbl.User{}) |> Auth.authenticate_user([]) refute(conn.halted) end test "login puts the user in the session", %{conn: conn} do login_conn = conn |> Auth.login(%Rumbl.User{id: 123}) |> send_resp(:ok, "") next_conn = get(login_conn, "/") assert get_session(next_conn, :user_id) == 123 end test "logout drops the session", %{conn: conn} do logout_conn = conn |> put_session(:user_id, 123) |> Auth.logout() |> send_resp(:ok, "") next_conn = get(logout_conn, "/") refute get_session(next_conn, :user_id) end test "call places user from session into assigns", %{conn: conn} do user = insert_user() conn = conn |> put_session(:user_id, user.id) |> Auth.call(Repo) assert conn.assigns.current_user.id == user.id end test "call with no session sets current_user assign to nil", %{conn: conn} do conn = Auth.call(conn, Repo) assert conn.assigns.current_user == nil end test "login with a valid username and pass", %{conn: conn} do user = insert_user(username: "me", password: "secret") {:ok, conn} = Auth.login_by_username_and_pass(conn, "me", "secret", repo: Repo) assert conn.assigns.current_user.id == user.id end test "login with a not found user", %{conn: conn} do assert {:error, :not_found, _conn} = Auth.login_by_username_and_pass(conn, "me", "secret", repo: Repo) end test "login with password mismatch", %{conn: conn} do _ = insert_user(username: "me", password: "secret") assert {:error, :unauthorized, _conn} = Auth.login_by_username_and_pass(conn, "me", "wrong", repo: Repo) end end
26.39759
83
0.633501
73880d4a002ec84df4668649b19c7ae54544af49
515
exs
Elixir
test/epicenter_web/uploaded_file_test.exs
geometricservices/epi-viewpoin
ecb5316ea0f3f7299d5ff63e2de588539005ac1c
[ "Apache-2.0" ]
5
2021-02-25T18:43:09.000Z
2021-02-27T06:00:35.000Z
test/epicenter_web/uploaded_file_test.exs
geometricservices/epi-viewpoint
ecb5316ea0f3f7299d5ff63e2de588539005ac1c
[ "Apache-2.0" ]
3
2021-12-13T17:52:47.000Z
2021-12-17T01:35:31.000Z
test/epicenter_web/uploaded_file_test.exs
geometricservices/epi-viewpoint
ecb5316ea0f3f7299d5ff63e2de588539005ac1c
[ "Apache-2.0" ]
1
2022-01-27T23:26:38.000Z
2022-01-27T23:26:38.000Z
defmodule EpicenterWeb.UploadedFileTest do use Epicenter.SimpleCase, async: true alias Epicenter.Tempfile alias EpicenterWeb.UploadedFile describe "from_plug_upload" do test "creates a new ImportedFile with a sanitized filename and the contents of the file" do path = Tempfile.write_csv!("file contents") UploadedFile.from_plug_upload(%{path: path, filename: " somé//crazy\nfilename"}) |> assert_eq(%{file_name: "somécrazy filename", contents: "file contents"}) end end end
32.1875
95
0.737864
738815b433b6715a41bd982766387f2dffce1e70
4,141
ex
Elixir
lib/kazan/request.ex
afatsini/kazan
1df9673dc8740ba7fa389a9c4683e3389e854f27
[ "MIT" ]
null
null
null
lib/kazan/request.ex
afatsini/kazan
1df9673dc8740ba7fa389a9c4683e3389e854f27
[ "MIT" ]
null
null
null
lib/kazan/request.ex
afatsini/kazan
1df9673dc8740ba7fa389a9c4683e3389e854f27
[ "MIT" ]
null
null
null
defmodule Kazan.Request do @moduledoc """ Kazan.Request is a struct that describes an HTTP request. Users should mostly treat this struct as opaque - `Kazan.run` consumes it, and functions in the various `Kazan.Apis` submodules construct it. """ defstruct [ :method, :path, :query_params, :content_type, :body, :response_model ] import Kazan.Codegen.Naming, only: [definition_ref_to_model_module: 1] @type t :: %__MODULE__{ method: String.t(), path: String.t(), query_params: Map.t(), content_type: String.t(), body: String.t(), response_model: atom | nil } @external_resource Kazan.Config.oai_spec() @op_map Kazan.Config.oai_spec() |> File.read!() |> Poison.decode!() |> Kazan.Swagger.swagger_to_op_map() @doc """ Creates a kazan request for a given operation. ### Parameters - `operation` should be the nickname of an operation found in the swagger dict - `params` should be a Map of parameters to send in the request. """ @spec create(String.t(), Map.t()) :: {:ok, t()} | {:error, atom} def create(operation, params) do case validate_request(operation, params) do {:ok, op} -> {:ok, build_request(op, params)} {:error, _} = err -> err end end # Checks that we have all the expected parameters for our request. @spec validate_request(String.t(), Map.t()) :: {:ok, t} | {:error, term} defp validate_request(operation, params) do operation = @op_map[operation] if operation != nil do operation |> Map.get("parameters", []) |> Enum.filter(&Map.get(&1, "required", false)) |> Enum.map(&Map.get(&1, "name")) |> Enum.reject(&Map.has_key?(params, &1)) |> case do [] -> {:ok, operation} missing -> {:error, {:missing_params, missing}} end else {:error, :unknown_op} end end @spec build_request(Map.t(), Map.t()) :: __MODULE__.t() defp build_request(operation, params) do param_groups = Enum.group_by(operation["parameters"], fn param -> param["in"] end) %__MODULE__{ method: operation["method"], path: build_path(operation["path"], param_groups, params), query_params: build_query_params(param_groups, params), content_type: content_type(operation), body: build_body(param_groups, params), response_model: definition_ref_to_model_module( operation["responses"]["200"]["schema"]["$ref"] ) } end @spec build_path(String.t(), Map.t(), Map.t()) :: String.t() defp build_path(path, param_groups, params) do path_params = Map.get(param_groups, "path", []) Enum.reduce(path_params, path, fn param, path -> name = param["name"] String.replace(path, "{#{name}}", params[name]) end) end @spec build_query_params(Map.t(), Map.t()) :: Map.t() defp build_query_params(param_groups, params) do param_groups |> Map.get("query", []) |> Enum.filter(&Map.has_key?(params, &1["name"])) |> Enum.map(fn param -> {param["name"], params[param["name"]]} end) |> Enum.into(%{}) end @spec build_body(Map.t(), Map.t()) :: String.t() | no_return defp build_body(param_groups, params) do case Map.get(param_groups, "body", []) do [body_param] -> model = params[body_param["name"]] {:ok, data} = model.__struct__.encode(model) Poison.encode!(data) [] -> nil _others -> raise "More than one body param in swagger operation spec..." end end @spec content_type(Map.t()) :: String.t() | no_return defp content_type(operation) do cond do operation["method"] == "get" -> nil "application/json" in operation["consumes"] -> "application/json" "application/merge-patch+json" in operation["consumes"] -> "application/merge-patch+json" "*/*" in operation["consumes"] -> "application/json" :otherwise -> raise "Can't find supported content-type: #{inspect(operation)}" end end end
28.170068
80
0.605168
7388637a6af163696807d81fdb57697ce1762bc1
602
exs
Elixir
witchcraft-examples/mix.exs
feihong/elixir-examples
dda6128f729199dad21220925df3bae241911fbd
[ "Apache-2.0" ]
null
null
null
witchcraft-examples/mix.exs
feihong/elixir-examples
dda6128f729199dad21220925df3bae241911fbd
[ "Apache-2.0" ]
null
null
null
witchcraft-examples/mix.exs
feihong/elixir-examples
dda6128f729199dad21220925df3bae241911fbd
[ "Apache-2.0" ]
null
null
null
defmodule Examples.Mixfile do use Mix.Project def project do [ app: :examples, version: "0.1.0", elixir: "~> 1.5", start_permanent: Mix.env == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}, {:witchcraft, "~> 1.0.0"}, ] end end
20.066667
88
0.566445
73889ab96023db635ce327e86cf9243e1ae2ca39
2,897
ex
Elixir
clients/games/lib/google_api/games/v1/model/player_achievement.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/model/player_achievement.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/model/player_achievement.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.Games.V1.Model.PlayerAchievement do @moduledoc """ This is a JSON template for an achievement object. ## Attributes * `achievementState` (*type:* `String.t`, *default:* `nil`) - The state of the achievement. Possible values are: - "HIDDEN" - Achievement is hidden. - "REVEALED" - Achievement is revealed. - "UNLOCKED" - Achievement is unlocked. * `currentSteps` (*type:* `integer()`, *default:* `nil`) - The current steps for an incremental achievement. * `experiencePoints` (*type:* `String.t`, *default:* `nil`) - Experience points earned for the achievement. This field is absent for achievements that have not yet been unlocked and 0 for achievements that have been unlocked by testers but that are unpublished. * `formattedCurrentStepsString` (*type:* `String.t`, *default:* `nil`) - The current steps for an incremental achievement as a string. * `id` (*type:* `String.t`, *default:* `nil`) - The ID of the achievement. * `kind` (*type:* `String.t`, *default:* `games#playerAchievement`) - Uniquely identifies the type of this resource. Value is always the fixed string games#playerAchievement. * `lastUpdatedTimestamp` (*type:* `String.t`, *default:* `nil`) - The timestamp of the last modification to this achievement's state. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :achievementState => String.t(), :currentSteps => integer(), :experiencePoints => String.t(), :formattedCurrentStepsString => String.t(), :id => String.t(), :kind => String.t(), :lastUpdatedTimestamp => String.t() } field(:achievementState) field(:currentSteps) field(:experiencePoints) field(:formattedCurrentStepsString) field(:id) field(:kind) field(:lastUpdatedTimestamp) end defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.PlayerAchievement do def decode(value, options) do GoogleApi.Games.V1.Model.PlayerAchievement.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.PlayerAchievement do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.985507
265
0.704177
73889fa338f318c5d7a39044f72ebe3df1d21793
331
exs
Elixir
apps/biz/config/dev.exs
aforward/wuw
8f41157aeb9fce738a402e757bf78a322a890b7a
[ "MIT" ]
null
null
null
apps/biz/config/dev.exs
aforward/wuw
8f41157aeb9fce738a402e757bf78a322a890b7a
[ "MIT" ]
null
null
null
apps/biz/config/dev.exs
aforward/wuw
8f41157aeb9fce738a402e757bf78a322a890b7a
[ "MIT" ]
null
null
null
use Mix.Config config :biz, Biz.Repo, [ adapter: Ecto.Adapters.Postgres, database: "wuw_#{Mix.env}", username: "postgres", password: "", hostname: "localhost", ] config :mix_test_watch, setup_tasks: [ "ecto.drop --quiet", "ecto.create --quiet", "ecto.migrate", ], ansi_enabled: :ignore, clear: true
17.421053
34
0.637462
7388d0ed56929e7323d7ab4e11f3a132763eae27
12,029
ex
Elixir
clients/compute/lib/google_api/compute/v1/api/disk_types.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/disk_types.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/disk_types.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# 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.Compute.V1.Api.DiskTypes do @moduledoc """ API calls for all endpoints tagged `DiskTypes`. """ alias GoogleApi.Compute.V1.Connection alias GoogleApi.Gax.{Request, Response} @doc """ Retrieves an aggregated list of disk types. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String.t): Project ID for this request. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): 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.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :filter (String.t): A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either &#x3D;, !&#x3D;, &gt;, or &lt;. For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name !&#x3D; example-instance. You can also filter nested fields. For example, you could specify scheduling.automaticRestart &#x3D; false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart &#x3D; true) (cpuPlatform &#x3D; \&quot;Intel Skylake\&quot;). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform &#x3D; \&quot;Intel Skylake\&quot;) OR (cpuPlatform &#x3D; \&quot;Intel Broadwell\&quot;) AND (scheduling.automaticRestart &#x3D; true). - :maxResults (integer()): The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) - :orderBy (String.t): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using orderBy&#x3D;\&quot;creationTimestamp desc\&quot;. This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by name or creationTimestamp desc is supported. - :pageToken (String.t): Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. ## Returns {:ok, %GoogleApi.Compute.V1.Model.DiskTypeAggregatedList{}} on success {:error, info} on failure """ @spec compute_disk_types_aggregated_list(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.DiskTypeAggregatedList.t()} | {:error, Tesla.Env.t()} def compute_disk_types_aggregated_list(connection, project, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :filter => :query, :maxResults => :query, :orderBy => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{project}/aggregated/diskTypes", %{ "project" => URI.encode_www_form(project) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.DiskTypeAggregatedList{}]) end @doc """ Returns the specified disk type. Gets a list of available disk types by making a list() request. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String.t): Project ID for this request. - zone (String.t): The name of the zone for this request. - disk_type (String.t): Name of the disk type to return. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): 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.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. ## Returns {:ok, %GoogleApi.Compute.V1.Model.DiskType{}} on success {:error, info} on failure """ @spec compute_disk_types_get(Tesla.Env.client(), String.t(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.DiskType.t()} | {:error, Tesla.Env.t()} def compute_disk_types_get( connection, project, zone, disk_type, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{project}/zones/{zone}/diskTypes/{diskType}", %{ "project" => URI.encode_www_form(project), "zone" => URI.encode_www_form(zone), "diskType" => URI.encode_www_form(disk_type) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.DiskType{}]) end @doc """ Retrieves a list of disk types available to the specified project. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String.t): Project ID for this request. - zone (String.t): The name of the zone for this request. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): 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.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :filter (String.t): A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either &#x3D;, !&#x3D;, &gt;, or &lt;. For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name !&#x3D; example-instance. You can also filter nested fields. For example, you could specify scheduling.automaticRestart &#x3D; false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart &#x3D; true) (cpuPlatform &#x3D; \&quot;Intel Skylake\&quot;). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform &#x3D; \&quot;Intel Skylake\&quot;) OR (cpuPlatform &#x3D; \&quot;Intel Broadwell\&quot;) AND (scheduling.automaticRestart &#x3D; true). - :maxResults (integer()): The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) - :orderBy (String.t): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using orderBy&#x3D;\&quot;creationTimestamp desc\&quot;. This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by name or creationTimestamp desc is supported. - :pageToken (String.t): Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. ## Returns {:ok, %GoogleApi.Compute.V1.Model.DiskTypeList{}} on success {:error, info} on failure """ @spec compute_disk_types_list(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.DiskTypeList.t()} | {:error, Tesla.Env.t()} def compute_disk_types_list(connection, project, zone, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :filter => :query, :maxResults => :query, :orderBy => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{project}/zones/{zone}/diskTypes", %{ "project" => URI.encode_www_form(project), "zone" => URI.encode_www_form(zone) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.DiskTypeList{}]) end end
61.060914
1,213
0.713443
7388de96520ca49e692e8cffce2daab602672a30
142
ex
Elixir
web/controllers/tp_attribute_import_job_controller.ex
zombalo/cgrates_web_jsonapi
47845be4311839fe180cc9f2c7c6795649da4430
[ "MIT" ]
null
null
null
web/controllers/tp_attribute_import_job_controller.ex
zombalo/cgrates_web_jsonapi
47845be4311839fe180cc9f2c7c6795649da4430
[ "MIT" ]
null
null
null
web/controllers/tp_attribute_import_job_controller.ex
zombalo/cgrates_web_jsonapi
47845be4311839fe180cc9f2c7c6795649da4430
[ "MIT" ]
null
null
null
defmodule CgratesWebJsonapi.TpAttributeImportJobController do use CgratesWebJsonapi.CsvImportJob, module: CgratesWebJsonapi.TpAttribute end
35.5
75
0.894366
73892b169aea9a44f02eea782fe634cab4cea0a1
718
ex
Elixir
web/gettext.ex
colbydehart/MartaWhistle
852d1aaecb1fe5705fdcaab30283870613f6a66f
[ "MIT" ]
null
null
null
web/gettext.ex
colbydehart/MartaWhistle
852d1aaecb1fe5705fdcaab30283870613f6a66f
[ "MIT" ]
null
null
null
web/gettext.ex
colbydehart/MartaWhistle
852d1aaecb1fe5705fdcaab30283870613f6a66f
[ "MIT" ]
null
null
null
defmodule TrainWhistle.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. By using [Gettext](https://hexdocs.pm/gettext), your module gains a set of macros for translations, for example: import TrainWhistle.Gettext # Simple translation gettext "Here is the string to translate" # Plural translation ngettext "Here is the string to translate", "Here are the strings to translate", 3 # Domain-based translation dgettext "errors", "Here is the error message to translate" See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. """ use Gettext, otp_app: :train_whistle end
28.72
72
0.685237
738934df556c631bf8a417a7679cbdc3eb1e52d3
9,032
exs
Elixir
test/sanbase/alerts/metric/metric_trigger_settings_test.exs
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
81
2017-11-20T01:20:22.000Z
2022-03-05T12:04:25.000Z
test/sanbase/alerts/metric/metric_trigger_settings_test.exs
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
359
2017-10-15T14:40:53.000Z
2022-01-25T13:34:20.000Z
test/sanbase/alerts/metric/metric_trigger_settings_test.exs
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
16
2017-11-19T13:57:40.000Z
2022-02-07T08:13:02.000Z
defmodule Sanbase.Alert.MetricTriggerSettingsTest do use Sanbase.DataCase, async: false import Sanbase.Factory import Sanbase.TestHelpers import ExUnit.CaptureLog alias Sanbase.Alert.UserTrigger alias Sanbase.Alert.Evaluator alias Sanbase.Metric alias Sanbase.Alert.Trigger.MetricTriggerSettings @metrics_5m_min_interval Metric.available_metrics( filter: :min_interval_less_or_equal, filter_interval: "5m" ) setup_all_with_mocks([ { Sanbase.Timeline.TimelineEvent, [:passthrough], maybe_create_event_async: fn user_trigger_tuple, _, _ -> user_trigger_tuple end } ]) do [] end describe "metrics with text selector" do setup do # Clean children on exit, otherwise DB calls from async tasks can be attempted clean_task_supervisor_children() Sanbase.Cache.clear_all(:alerts_evaluator_cache) user = insert(:user, user_settings: %{settings: %{alert_notify_telegram: true}}) Sanbase.Accounts.UserSettings.set_telegram_chat_id(user.id, 123_123_123_123) %{user: user} end test "signal with text selector works", context do %{user: user} = context trigger_settings = %{ type: "metric_signal", metric: "social_volume_total", target: %{text: "random text"}, channel: "telegram", operation: %{above: 300} } {:ok, trigger} = UserTrigger.create_user_trigger(user, %{ title: "Generic title", is_public: true, cooldown: "12h", settings: trigger_settings }) # Return a fun with arity 5 that will return different results # for consecutive calls mock_fun = [ fn -> {:ok, 100} end, fn -> {:ok, 5000} end ] |> Sanbase.Mock.wrap_consecutives(arity: 5) Sanbase.Mock.prepare_mock( Sanbase.SocialData.MetricAdapter, :aggregated_timeseries_data, mock_fun ) |> Sanbase.Mock.run_with_mocks(fn -> [triggered] = MetricTriggerSettings.type() |> UserTrigger.get_active_triggers_by_type() |> Evaluator.run() assert triggered.id == trigger.id end) end end describe "metrics with slug selector" do setup do # Clean children on exit, otherwise DB calls from async tasks can be attempted clean_task_supervisor_children() Sanbase.Cache.clear_all(:alerts_evaluator_cache) user = insert(:user) Sanbase.Accounts.UserSettings.set_telegram_chat_id(user.id, 123_123_123_123) project = Sanbase.Factory.insert(:random_project) %{user: user, project: project} end test "signal with a metric works - above operation", context do %{project: project, user: user} = context trigger_settings = %{ type: "metric_signal", metric: "active_addresses_24h", target: %{slug: project.slug}, channel: "telegram", operation: %{above: 300} } {:ok, trigger} = UserTrigger.create_user_trigger(user, %{ title: "Generic title", is_public: true, cooldown: "12h", settings: trigger_settings }) # Return a fun with arity 5 that will return different results # for consecutive calls mock_fun = [ fn -> {:ok, %{project.slug => 100}} end, fn -> {:ok, %{project.slug => 5000}} end ] |> Sanbase.Mock.wrap_consecutives(arity: 5) Sanbase.Mock.prepare_mock( Sanbase.Clickhouse.MetricAdapter, :aggregated_timeseries_data, mock_fun ) |> Sanbase.Mock.run_with_mocks(fn -> [triggered] = MetricTriggerSettings.type() |> UserTrigger.get_active_triggers_by_type() |> Evaluator.run() assert triggered.id == trigger.id payload = triggered.trigger.settings.payload |> Map.values() |> hd first_line = "[##{project.ticker}](https://app.santiment.net/charts?slug=#{project.slug}) | *#{project.name}'s Active Addresses for the last 24 hours is above 300* 💥\n\n" assert payload =~ first_line assert payload =~ "Was: 100\nNow: 5,000.00\n\n" assert payload =~ "\*_Generated by the value of the metric at" end) end test "signal with a metric and extra explanation works ", context do %{project: project, user: user} = context trigger_settings = %{ type: "metric_signal", metric: "active_addresses_24h", target: %{slug: project.slug}, channel: "telegram", operation: %{above: 300}, extra_explanation: "A surge in tranaction volume *may suggest a growing interest and interaction* with the token" } {:ok, trigger} = UserTrigger.create_user_trigger(user, %{ title: "Generic title", is_public: true, cooldown: "12h", settings: trigger_settings }) # Return a fun with arity 5 that will return different results # for consecutive calls mock_fun = [ fn -> {:ok, %{project.slug => 100}} end, fn -> {:ok, %{project.slug => 5000}} end ] |> Sanbase.Mock.wrap_consecutives(arity: 5) Sanbase.Mock.prepare_mock( Sanbase.Clickhouse.MetricAdapter, :aggregated_timeseries_data, mock_fun ) |> Sanbase.Mock.run_with_mocks(fn -> [triggered] = MetricTriggerSettings.type() |> UserTrigger.get_active_triggers_by_type() |> Evaluator.run() assert triggered.id == trigger.id payload = triggered.trigger.settings.payload |> Map.values() |> hd first_line = "[##{project.ticker}](https://app.santiment.net/charts?slug=#{project.slug}) | *#{project.name}'s Active Addresses for the last 24 hours is above 300* 💥\n\n" assert payload =~ first_line assert payload =~ "Was: 100\nNow: 5,000.00\n\n" assert payload =~ "🧐 A surge in tranaction volume *may suggest a growing interest and interaction* with the token\n\n" assert payload =~ "\*_Generated by the value of the metric at" end) end test "signal with metric works - percent change operation", context do %{project: project, user: user} = context trigger_settings = %{ type: "metric_signal", metric: "active_addresses_24h", target: %{slug: project.slug}, channel: "telegram", operation: %{percent_up: 100} } {:ok, trigger} = UserTrigger.create_user_trigger(user, %{ title: "Generic title", is_public: true, cooldown: "12h", settings: trigger_settings }) mock_fun = [ fn -> {:ok, %{project.slug => 100}} end, fn -> {:ok, %{project.slug => 500}} end ] |> Sanbase.Mock.wrap_consecutives(arity: 5) Sanbase.Mock.prepare_mock( Sanbase.Clickhouse.MetricAdapter, :aggregated_timeseries_data, mock_fun ) |> Sanbase.Mock.run_with_mocks(fn -> [triggered] = MetricTriggerSettings.type() |> UserTrigger.get_active_triggers_by_type() |> Evaluator.run() assert triggered.id == trigger.id end) end test "can create triggers with all available metrics with min interval less than 5 min", context do %{project: project, user: user} = context @metrics_5m_min_interval |> Enum.shuffle() |> Enum.take(100) |> Enum.each(fn metric -> trigger_settings = %{ type: "metric_signal", metric: metric, target: %{slug: project.slug}, channel: "telegram", operation: %{above: 300} } {:ok, _} = UserTrigger.create_user_trigger(user, %{ title: "Generic title", is_public: true, cooldown: "12h", settings: trigger_settings }) end) end test "cannot create triggers with random metrics", context do %{project: project, user: user} = context metrics = Enum.map(1..100, fn _ -> rand_str() end) Enum.each(metrics, fn metric -> trigger_settings = %{ type: "metric_signal", metric: metric, target: %{slug: project.slug}, channel: "telegram", operation: %{above: 300} } assert capture_log(fn -> {:error, error_msg} = UserTrigger.create_user_trigger(user, %{ title: "Generic title", is_public: true, cooldown: "12h", settings: trigger_settings }) assert error_msg =~ "not supported or is mistyped" end) end) end end end
29.808581
167
0.583592
738938a78374ec078a716799726a02b607359e90
481
exs
Elixir
config/test.exs
domix/xebex
e1c9e21245a1daf3c818ddd60433fdbc4d7611be
[ "Apache-2.0" ]
1
2015-10-13T02:11:26.000Z
2015-10-13T02:11:26.000Z
config/test.exs
domix/xebex
e1c9e21245a1daf3c818ddd60433fdbc4d7611be
[ "Apache-2.0" ]
null
null
null
config/test.exs
domix/xebex
e1c9e21245a1daf3c818ddd60433fdbc4d7611be
[ "Apache-2.0" ]
null
null
null
use Mix.Config # We don't run a server during test. If one is required, # you can enable the server option below. config :xebex, Xebex.Endpoint, http: [port: 4001], server: false # Print only warnings and errors during test config :logger, level: :warn # Configure your database config :xebex, Xebex.Repo, adapter: Ecto.Adapters.Postgres, username: "postgres", password: "postgres", database: "xebex_test", hostname: "localhost", pool: Ecto.Adapters.SQL.Sandbox
24.05
56
0.727651
73897c07fb4e831f1834851bd1becc0de4eaf730
228
exs
Elixir
test/koans/equalities_koan_test.exs
Imtiyaaz1234/elixir-koans
e1a8a55e3acbb88bb598becf3f40cb52f912e60a
[ "MIT" ]
1,944
2016-04-24T02:46:10.000Z
2022-03-29T00:19:17.000Z
test/koans/equalities_koan_test.exs
Imtiyaaz1234/elixir-koans
e1a8a55e3acbb88bb598becf3f40cb52f912e60a
[ "MIT" ]
157
2016-04-23T18:40:24.000Z
2022-02-10T14:00:45.000Z
test/koans/equalities_koan_test.exs
Imtiyaaz1234/elixir-koans
e1a8a55e3acbb88bb598becf3f40cb52f912e60a
[ "MIT" ]
636
2016-04-23T17:18:00.000Z
2022-03-23T10:04:06.000Z
defmodule EqualitiesTests do use ExUnit.Case import TestHarness test "Equalities" do answers = [ true, false, 1, 2, 1, 4, 2 ] test_all(Equalities, answers) end end
12
33
0.54386