hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
list
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
list
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
list
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
ff5404872ac1446722827e913f83679d6f3b1bda
2,647
ex
Elixir
lib/instagram_clone_web/live/user_live/settings.ex
hminy572/InstagramClonePETAL
577cdad0e17399e47ef9d3f8e789bd07e33012b9
[ "MIT" ]
1
2021-08-18T13:01:26.000Z
2021-08-18T13:01:26.000Z
lib/instagram_clone_web/live/user_live/settings.ex
hminy572/InstagramClonePETAL
577cdad0e17399e47ef9d3f8e789bd07e33012b9
[ "MIT" ]
null
null
null
lib/instagram_clone_web/live/user_live/settings.ex
hminy572/InstagramClonePETAL
577cdad0e17399e47ef9d3f8e789bd07e33012b9
[ "MIT" ]
null
null
null
defmodule InstagramCloneWeb.UserLive.Settings do use InstagramCloneWeb, :live_view alias InstagramClone.Accounts alias InstagramClone.Accounts.User alias InstagramClone.Uploaders.Avatar @extension_whitelist ~w(.jpg .jpeg .png) @impl true def mount(_params, session, socket) do socket = assign_defaults(session, socket) changeset = Accounts.change_user(socket.assigns.current_user) settings_path = Routes.live_path(socket, __MODULE__) pass_settings_path = Routes.live_path(socket, InstagramCloneWeb.UserLive.PassSettings) {:ok, socket |> assign(changeset: changeset) |> assign(page_title: "Edit Profile") |> assign(settings_path: settings_path, pass_settings_path: pass_settings_path) |> allow_upload(:avatar_url, accept: @extension_whitelist, max_file_size: 9_000_000, progress: &handle_progress/3, auto_upload: true)} end @impl true def handle_event("validate", %{"user" => user_params}, socket) do changeset = socket.assigns.current_user |> Accounts.change_user(user_params) |> Map.put(:action, :validate) {:noreply, socket |> assign(changeset: changeset)} end def handle_event("upload_avatar", _params, socket) do {:noreply, socket} end @impl true def handle_event("save", %{"user" => user_params}, socket) do case Accounts.update_user(socket.assigns.current_user, user_params) do {:ok, _user} -> {:noreply, socket |> put_flash(:info, "User updated successfully") |> push_redirect(to: socket.assigns.settings_path)} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign(socket, :changeset, changeset)} end end @impl true def handle_params(_params, uri, socket) do {:noreply, socket |> assign(current_uri_path: URI.parse(uri).path)} end defp handle_progress(:avatar_url, entry, socket) do if entry.done? do avatar_url = Avatar.get_avatar_url(socket, entry) user_params = %{"avatar_url" => avatar_url} case Accounts.update_user(socket.assigns.current_user, user_params) do {:ok, _user} -> Avatar.update(socket, socket.assigns.current_user.avatar_url, entry) current_user = Accounts.get_user!(socket.assigns.current_user.id) {:noreply, socket |> put_flash(:info, "Avatar updated successfully") |> assign(current_user: current_user)} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign(socket, :changeset, changeset)} end else {:noreply, socket} end end end
31.141176
90
0.668682
ff541d1d2e0990f385e97f9e2ea969cc1f1a73c0
972
ex
Elixir
lib/phoenix14_base/application.ex
pgrunwald/phoenix14_base
991313f244af350245f5fd3e8fe6716a1a9e88a4
[ "MIT" ]
1
2019-03-28T05:47:39.000Z
2019-03-28T05:47:39.000Z
lib/phoenix14_base/application.ex
pgrunwald/phoenix14_base
991313f244af350245f5fd3e8fe6716a1a9e88a4
[ "MIT" ]
null
null
null
lib/phoenix14_base/application.ex
pgrunwald/phoenix14_base
991313f244af350245f5fd3e8fe6716a1a9e88a4
[ "MIT" ]
1
2020-05-23T09:20:53.000Z
2020-05-23T09:20:53.000Z
defmodule Phoenix14Base.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do # List all child processes to be supervised children = [ # Start the Ecto repository Phoenix14Base.Repo, # Start the endpoint when the application starts Phoenix14BaseWeb.Endpoint # Starts a worker by calling: Phoenix14Base.Worker.start_link(arg) # {Phoenix14Base.Worker, arg}, ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Phoenix14Base.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 Phoenix14BaseWeb.Endpoint.config_change(changed, removed) :ok end end
30.375
72
0.726337
ff544765f6189ca6c133b166046f87c96cf7642d
538
exs
Elixir
mix.exs
andreihod/fipex
6612fb9b0df5acc7876c66f88ff525d9a03b1d5d
[ "MIT" ]
null
null
null
mix.exs
andreihod/fipex
6612fb9b0df5acc7876c66f88ff525d9a03b1d5d
[ "MIT" ]
null
null
null
mix.exs
andreihod/fipex
6612fb9b0df5acc7876c66f88ff525d9a03b1d5d
[ "MIT" ]
null
null
null
defmodule Fipex.MixProject do use Mix.Project def project do [ app: :fipex, version: "0.1.0", elixir: "~> 1.9", 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 [ {:httpoison, "~> 1.6.1"}, {:exvcr, "~> 0.10", only: :test}, {:poison, "~> 3.1"} ] end end
17.933333
59
0.539033
ff54526c4e550103257b62e75e7eb5aa810e30c8
1,594
ex
Elixir
day06/puzzle.ex
mikehelmick/AdventOfCode2019
9981b85b25eb9f04351ce5657ff07fd067ce1231
[ "Apache-2.0" ]
null
null
null
day06/puzzle.ex
mikehelmick/AdventOfCode2019
9981b85b25eb9f04351ce5657ff07fd067ce1231
[ "Apache-2.0" ]
null
null
null
day06/puzzle.ex
mikehelmick/AdventOfCode2019
9981b85b25eb9f04351ce5657ff07fd067ce1231
[ "Apache-2.0" ]
null
null
null
defmodule Puzzle do def update_entry(nil, val), do: {nil, [val]} def update_entry(l, val), do: {l, l ++ [val]} # builds incoming and outgoing edges representing the orbital graph def build_edges([], o_map, i_map, allobjs), do: {o_map, i_map, MapSet.to_list(allobjs)} def build_edges([line | rest], o_map, i_map, allobjs) do #IO.puts("line #{line}") [inner, outer] = String.split(line, ")") {_, updates_o_map} = Map.get_and_update(o_map, inner, fn x -> update_entry(x, outer) end) updated_i_map = Map.put(i_map, outer, inner) new_all = MapSet.put(allobjs, inner) |> MapSet.put(outer) build_edges(rest, updates_o_map, updated_i_map, new_all) end # Counts edges from a body to COM def crawl("COM", _, acc), do: acc def crawl(obj, map, acc) do #IO.puts("crawl #{obj}") crawl(Map.get(map, obj), map, acc + 1) end # Counts all edges in the system def count_edges([], _, acc), do: acc def count_edges(["COM"|rest], map, acc), do: count_edges(rest, map, acc) # for each object in the system, cound path to COM. def count_edges([obj|rest], map, acc) do IO.puts("counting #{obj}, current #{acc}") count_edges(rest, map, crawl(obj, map, 0) + acc) end end input = IO.read(:stdio, :all) |> String.trim() |> String.split("\n") # just built in and out edges in case out was needed for part 2 {_out_edges, in_edges, allobjs} = Puzzle.build_edges(input, %{}, %{}, MapSet.new()) IO.puts("all #{inspect(allobjs)}") IO.puts("edges #{inspect(in_edges)}") count = Puzzle.count_edges(allobjs, in_edges, 0) IO.puts("answer #{count}")
34.652174
93
0.658093
ff545c60f9c16157e5acba9f857f716ced8dab7e
434
exs
Elixir
elixir/randomFunctions/fact.exs
trxeste/wrk
3e05e50ff621866f0361cc8494ce8f6bb4d97fae
[ "BSD-3-Clause" ]
1
2017-10-16T03:00:50.000Z
2017-10-16T03:00:50.000Z
elixir/randomFunctions/fact.exs
trxeste/wrk
3e05e50ff621866f0361cc8494ce8f6bb4d97fae
[ "BSD-3-Clause" ]
null
null
null
elixir/randomFunctions/fact.exs
trxeste/wrk
3e05e50ff621866f0361cc8494ce8f6bb4d97fae
[ "BSD-3-Clause" ]
null
null
null
defmodule Factorial do # Simple recursive function def fac(0), do: 1 def fac(n) when n > 0, do: n * fac(n - 1) # Tail recursive function def fac_tail(0), do: 1 def fac_tail(n), do: fac_tail(n, 1) def fac_tail(1, acc), do: acc def fac_tail(n, acc) when n > 1, do: fac_tail(n - 1, acc * n) # Using Enumeration features def fac_reduce(0), do: 1 def fac_reduce(n) when n > 0, do: Enum.reduce(1..n, 1, &*/2) end
27.125
63
0.624424
ff5460d3b90875899b0ba646034389e24c2b5684
1,998
ex
Elixir
lib/vex/validators/inclusion.ex
emjrdev/vex
c4a863ed39d4723ccf45231252d81c0f0df45de1
[ "MIT" ]
560
2015-01-12T00:07:27.000Z
2022-02-07T03:21:44.000Z
lib/vex/validators/inclusion.ex
emjrdev/vex
c4a863ed39d4723ccf45231252d81c0f0df45de1
[ "MIT" ]
55
2015-02-16T18:59:57.000Z
2021-12-23T12:34:25.000Z
lib/vex/validators/inclusion.ex
emjrdev/vex
c4a863ed39d4723ccf45231252d81c0f0df45de1
[ "MIT" ]
63
2015-02-12T03:49:50.000Z
2021-12-12T00:11:01.000Z
defmodule Vex.Validators.Inclusion do @moduledoc """ Ensure a value is a member of a list of values. ## Options * `:in`: The list. * `:message`: Optional. A custom error message. May be in EEx format and use the fields described in "Custom Error Messages," below. The list can be provided in place of the keyword list if no other options are needed. ## Examples iex> Vex.Validators.Inclusion.validate(1, [1, 2, 3]) :ok iex> Vex.Validators.Inclusion.validate(1, [in: [1, 2, 3]]) :ok iex> Vex.Validators.Inclusion.validate(4, [1, 2, 3]) {:error, "must be one of [1, 2, 3]"} iex> Vex.Validators.Inclusion.validate("a", ~w(a b c)) :ok iex> Vex.Validators.Inclusion.validate(nil, ~w(a b c)) {:error, ~S(must be one of ["a", "b", "c"])} iex> Vex.Validators.Inclusion.validate(nil, [in: ~w(a b c), allow_nil: true]) :ok iex> Vex.Validators.Inclusion.validate("", [in: ~w(a b c), allow_blank: true]) :ok ## Custom Error Messages Custom error messages (in EEx format), provided as :message, can use the following values: iex> Vex.Validators.Inclusion.__validator__(:message_fields) [value: "The bad value", list: "List"] An example: iex> Vex.Validators.Inclusion.validate("a", in: [1, 2, 3], message: "<%= inspect value %> is not an allowed value") {:error, ~S("a" is not an allowed value)} """ use Vex.Validator @message_fields [value: "The bad value", list: "List"] def validate(value, options) when is_list(options) do if Keyword.keyword?(options) do unless_skipping(value, options) do list = Keyword.get(options, :in) result( Enum.member?(list, value), message(options, "must be one of #{inspect(list)}", value: value, list: list) ) end else validate(value, in: options) end end defp result(true, _), do: :ok defp result(false, message), do: {:error, message} end
31.21875
121
0.621622
ff546b9d3bc159c0c85b759a1dc5efe9ded53c3a
8,283
ex
Elixir
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_intent.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_intent.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_intent.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.Dialogflow.V2.Model.GoogleCloudDialogflowV2Intent do @moduledoc """ Represents an intent. Intents convert a number of user expressions or patterns into an action. An action is an extraction of a user command or sentence semantics. ## Attributes * `action` (*type:* `String.t`, *default:* `nil`) - Optional. The name of the action associated with the intent. Note: The action name must not contain whitespaces. * `defaultResponsePlatforms` (*type:* `list(String.t)`, *default:* `nil`) - Optional. The list of platforms for which the first responses will be copied from the messages in PLATFORM_UNSPECIFIED (i.e. default platform). * `displayName` (*type:* `String.t`, *default:* `nil`) - Required. The name of this intent. * `events` (*type:* `list(String.t)`, *default:* `nil`) - Optional. The collection of event names that trigger the intent. If the collection of input contexts is not empty, all of the contexts must be present in the active user session for an event to trigger this intent. Event names are limited to 150 characters. * `followupIntentInfo` (*type:* `list(GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentFollowupIntentInfo.t)`, *default:* `nil`) - Read-only. Information about all followup intents that have this intent as a direct or indirect parent. We populate this field only in the output. * `inputContextNames` (*type:* `list(String.t)`, *default:* `nil`) - Optional. The list of context names required for this intent to be triggered. Format: `projects/<Project ID>/agent/sessions/-/contexts/<Context ID>`. * `isFallback` (*type:* `boolean()`, *default:* `nil`) - Optional. Indicates whether this is a fallback intent. * `messages` (*type:* `list(GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentMessage.t)`, *default:* `nil`) - Optional. The collection of rich messages corresponding to the `Response` field in the Dialogflow console. * `mlDisabled` (*type:* `boolean()`, *default:* `nil`) - Optional. Indicates whether Machine Learning is disabled for the intent. Note: If `ml_disabled` setting is set to true, then this intent is not taken into account during inference in `ML ONLY` match mode. Also, auto-markup in the UI is turned off. * `name` (*type:* `String.t`, *default:* `nil`) - The unique identifier of this intent. Required for Intents.UpdateIntent and Intents.BatchUpdateIntents methods. Format: `projects/<Project ID>/agent/intents/<Intent ID>`. * `outputContexts` (*type:* `list(GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2Context.t)`, *default:* `nil`) - Optional. The collection of contexts that are activated when the intent is matched. Context messages in this collection should not set the parameters field. Setting the `lifespan_count` to 0 will reset the context when the intent is matched. Format: `projects/<Project ID>/agent/sessions/-/contexts/<Context ID>`. * `parameters` (*type:* `list(GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentParameter.t)`, *default:* `nil`) - Optional. The collection of parameters associated with the intent. * `parentFollowupIntentName` (*type:* `String.t`, *default:* `nil`) - Read-only after creation. The unique identifier of the parent intent in the chain of followup intents. You can set this field when creating an intent, for example with CreateIntent or BatchUpdateIntents, in order to make this intent a followup intent. It identifies the parent followup intent. Format: `projects/<Project ID>/agent/intents/<Intent ID>`. * `priority` (*type:* `integer()`, *default:* `nil`) - Optional. The priority of this intent. Higher numbers represent higher priorities. - If the supplied value is unspecified or 0, the service translates the value to 500,000, which corresponds to the `Normal` priority in the console. - If the supplied value is negative, the intent is ignored in runtime detect intent requests. * `resetContexts` (*type:* `boolean()`, *default:* `nil`) - Optional. Indicates whether to delete all contexts in the current session when this intent is matched. * `rootFollowupIntentName` (*type:* `String.t`, *default:* `nil`) - Read-only. The unique identifier of the root intent in the chain of followup intents. It identifies the correct followup intents chain for this intent. We populate this field only in the output. Format: `projects/<Project ID>/agent/intents/<Intent ID>`. * `trainingPhrases` (*type:* `list(GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentTrainingPhrase.t)`, *default:* `nil`) - Optional. The collection of examples that the agent is trained on. * `webhookState` (*type:* `String.t`, *default:* `nil`) - Optional. Indicates whether webhooks are enabled for the intent. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :action => String.t(), :defaultResponsePlatforms => list(String.t()), :displayName => String.t(), :events => list(String.t()), :followupIntentInfo => list( GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentFollowupIntentInfo.t() ), :inputContextNames => list(String.t()), :isFallback => boolean(), :messages => list(GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentMessage.t()), :mlDisabled => boolean(), :name => String.t(), :outputContexts => list(GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2Context.t()), :parameters => list(GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentParameter.t()), :parentFollowupIntentName => String.t(), :priority => integer(), :resetContexts => boolean(), :rootFollowupIntentName => String.t(), :trainingPhrases => list(GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentTrainingPhrase.t()), :webhookState => String.t() } field(:action) field(:defaultResponsePlatforms, type: :list) field(:displayName) field(:events, type: :list) field(:followupIntentInfo, as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentFollowupIntentInfo, type: :list ) field(:inputContextNames, type: :list) field(:isFallback) field(:messages, as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentMessage, type: :list ) field(:mlDisabled) field(:name) field(:outputContexts, as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2Context, type: :list ) field(:parameters, as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentParameter, type: :list ) field(:parentFollowupIntentName) field(:priority) field(:resetContexts) field(:rootFollowupIntentName) field(:trainingPhrases, as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentTrainingPhrase, type: :list ) field(:webhookState) end defimpl Poison.Decoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2Intent do def decode(value, options) do GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2Intent.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2Intent do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
48.723529
219
0.7053
ff54b668f614e4a29bcdfd3c1431719f28f278bb
527
ex
Elixir
lib/ex_oapi/parser/context/xml.ex
mnussbaumer/ex_oapi
f5eb610283a7f92a69e6266effc0dc4e2c497b61
[ "MIT" ]
null
null
null
lib/ex_oapi/parser/context/xml.ex
mnussbaumer/ex_oapi
f5eb610283a7f92a69e6266effc0dc4e2c497b61
[ "MIT" ]
null
null
null
lib/ex_oapi/parser/context/xml.ex
mnussbaumer/ex_oapi
f5eb610283a7f92a69e6266effc0dc4e2c497b61
[ "MIT" ]
null
null
null
defmodule ExOAPI.Parser.V3.Context.XML do use TypedEctoSchema import Ecto.Changeset @list_of_fields [ :name, :namespace, :prefix, :attribute, :wrapped ] @primary_key false typed_embedded_schema do field(:name, :string) field(:namespace, :string) field(:prefix, :string) field(:attribute, :boolean, default: false) field(:wrapped, :boolean, default: false) end def map_cast(struct \\ %__MODULE__{}, params) do struct |> cast(params, @list_of_fields) end end
18.821429
50
0.664137
ff54c3ab4efbca90a94eae7e188c542ac51c2afc
15,722
ex
Elixir
clients/artifact_registry/lib/google_api/artifact_registry/v1/api/projects.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/artifact_registry/lib/google_api/artifact_registry/v1/api/projects.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/artifact_registry/lib/google_api/artifact_registry/v1/api/projects.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.ArtifactRegistry.V1.Api.Projects do @moduledoc """ API calls for all endpoints tagged `Projects`. """ alias GoogleApi.ArtifactRegistry.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Gets a repository. ## Parameters * `connection` (*type:* `GoogleApi.ArtifactRegistry.V1.Connection.t`) - Connection to server * `projects_id` (*type:* `String.t`) - Part of `name`. Required. The name of the repository to retrieve. * `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`. * `repositories_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `: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`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ArtifactRegistry.V1.Model.Repository{}}` on success * `{:error, info}` on failure """ @spec artifactregistry_projects_locations_repositories_get( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ArtifactRegistry.V1.Model.Repository.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def artifactregistry_projects_locations_repositories_get( connection, projects_id, locations_id, repositories_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url( "/v1/projects/{projectsId}/locations/{locationsId}/repositories/{repositoriesId}", %{ "projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1), "repositoriesId" => URI.encode(repositories_id, &(URI.char_unreserved?(&1) || &1 == ?/)) } ) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.ArtifactRegistry.V1.Model.Repository{}]) end @doc """ Lists repositories. ## Parameters * `connection` (*type:* `GoogleApi.ArtifactRegistry.V1.Connection.t`) - Connection to server * `projects_id` (*type:* `String.t`) - Part of `parent`. Required. The name of the parent resource whose repositories will be listed. * `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `: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`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - The maximum number of repositories to return. * `:pageToken` (*type:* `String.t`) - The next_page_token value returned from a previous list request, if any. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ArtifactRegistry.V1.Model.ListRepositoriesResponse{}}` on success * `{:error, info}` on failure """ @spec artifactregistry_projects_locations_repositories_list( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ArtifactRegistry.V1.Model.ListRepositoriesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def artifactregistry_projects_locations_repositories_list( connection, projects_id, locations_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/projects/{projectsId}/locations/{locationsId}/repositories", %{ "projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.ArtifactRegistry.V1.Model.ListRepositoriesResponse{}] ) end @doc """ Gets a docker image. ## Parameters * `connection` (*type:* `GoogleApi.ArtifactRegistry.V1.Connection.t`) - Connection to server * `projects_id` (*type:* `String.t`) - Part of `name`. Required. The name of the docker images. * `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`. * `repositories_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`. * `docker_images_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `: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`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ArtifactRegistry.V1.Model.DockerImage{}}` on success * `{:error, info}` on failure """ @spec artifactregistry_projects_locations_repositories_docker_images_get( Tesla.Env.client(), String.t(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ArtifactRegistry.V1.Model.DockerImage.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def artifactregistry_projects_locations_repositories_docker_images_get( connection, projects_id, locations_id, repositories_id, docker_images_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url( "/v1/projects/{projectsId}/locations/{locationsId}/repositories/{repositoriesId}/dockerImages/{dockerImagesId}", %{ "projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1), "repositoriesId" => URI.encode(repositories_id, &URI.char_unreserved?/1), "dockerImagesId" => URI.encode(docker_images_id, &(URI.char_unreserved?(&1) || &1 == ?/)) } ) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.ArtifactRegistry.V1.Model.DockerImage{}]) end @doc """ Lists docker images. ## Parameters * `connection` (*type:* `GoogleApi.ArtifactRegistry.V1.Connection.t`) - Connection to server * `projects_id` (*type:* `String.t`) - Part of `parent`. Required. The name of the parent resource whose docker images will be listed. * `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`. * `repositories_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `: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`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - The maximum number of artifacts to return. * `:pageToken` (*type:* `String.t`) - The next_page_token value returned from a previous list request, if any. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ArtifactRegistry.V1.Model.ListDockerImagesResponse{}}` on success * `{:error, info}` on failure """ @spec artifactregistry_projects_locations_repositories_docker_images_list( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ArtifactRegistry.V1.Model.ListDockerImagesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def artifactregistry_projects_locations_repositories_docker_images_list( connection, projects_id, locations_id, repositories_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url( "/v1/projects/{projectsId}/locations/{locationsId}/repositories/{repositoriesId}/dockerImages", %{ "projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1), "repositoriesId" => URI.encode(repositories_id, &URI.char_unreserved?/1) } ) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.ArtifactRegistry.V1.Model.ListDockerImagesResponse{}] ) end end
43.430939
196
0.616397
ff54d1ea5a2deefbb216e124fe414c016fac1d03
4,329
ex
Elixir
lib/slack/group.ex
jclem/slack_ex
e2376cea87c35d14cc31dc545ff8e99106dee28c
[ "MIT" ]
21
2016-06-28T04:03:55.000Z
2020-01-19T01:51:11.000Z
lib/slack/group.ex
jclem/slack_ex
e2376cea87c35d14cc31dc545ff8e99106dee28c
[ "MIT" ]
5
2016-06-28T04:34:14.000Z
2019-12-09T20:09:12.000Z
lib/slack/group.ex
jclem/slack_ex
e2376cea87c35d14cc31dc545ff8e99106dee28c
[ "MIT" ]
6
2016-06-28T04:27:08.000Z
2020-04-22T11:07:03.000Z
defmodule Slack.Group do @moduledoc """ Functions for working with private channels (groups) """ @base "groups" use Slack.Request @doc """ Archive a private channel. https://api.slack.com/methods/groups.archive ## Examples Slack.Group.archive(client, channel: "G1234567890") """ @spec archive(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :archive @doc """ Close a private channel. https://api.slack.com/methods/groups.close ## Examples Slack.Group.close(client, channel: "G1234567890") """ @spec close(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :close @doc """ Create a private channel. https://api.slack.com/methods/groups.create ## Examples Slack.Group.create(client, name: "newchannel") """ @spec create(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :create @doc """ Replace a private channel. https://api.slack.com/methods/groups.createChild ## Examples Slack.Group.createChild(client, channel: "G1234567890") """ @spec createChild(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :createChild @doc """ Get the history of a private channel. https://api.slack.com/methods/groups.history ## Examples Slack.Group.history(client, channel: "G1234567890") """ @spec history(Slack.Client.t, Keyword.t) :: Slack.slack_response defget :history @doc """ Get the info of a private channel. https://api.slack.com/methods/groups.info ## Examples Slack.Group.info(client, channel: "G1234567890") """ @spec info(Slack.Client.t, Keyword.t) :: Slack.slack_response defget :info @doc """ Invite a user to a private channel. https://api.slack.com/methods/groups.invite ## Examples Slack.Group.invite(client, channel: "G1234567890", user: "U1234567890") """ @spec invite(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :invite @doc """ Kick a user from a private channel. https://api.slack.com/methods/groups.kick ## Examples Slack.Group.kick(client, channel: "G1234567890", user: "U1234567890") """ @spec kick(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :kick @doc """ Leave a private channel. https://api.slack.com/methods/groups.leave ## Examples Slack.Group.leave(client, channel: "G1234567890") """ @spec leave(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :leave @doc """ List private channels. https://api.slack.com/methods/groups.list ## Examples Slack.Group.list(client) """ @spec list(Slack.Client.t, Keyword.t) :: Slack.slack_response defget :list @doc """ Move the read cursor in a private channel. https://api.slack.com/methods/groups.mark ## Examples Slack.Group.mark(client, channel: "G1234567890", ts: 1234567890.123456) """ @spec mark(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :mark @doc """ Open a private channel. https://api.slack.com/methods/groups.open ## Examples Slack.Group.open(client, channel: "G1234567890") """ @spec open(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :open @doc """ Rename a private channel. https://api.slack.com/methods/groups.rename ## Examples Slack.Group.rename(client, channel: "G1234567890", name: "newname") """ @spec rename(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :rename @doc """ Set the purpose of a private channel. https://api.slack.com/methods/groups.setPurpose ## Examples Slack.Group.setPurpose(client, channel: "G1234567890", purpose: "purpose") """ @spec setPurpose(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :setPurpose @doc """ Set the topic of a private channel. https://api.slack.com/methods/groups.setTopic ## Examples Slack.Group.setTopic(client, channel: "G1234567890", topic: "topic") """ @spec setTopic(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :setTopic @doc """ Unarchive a private channel. https://api.slack.com/methods/groups.unarchive ## Examples Slack.Group.unarchive(client, channel: "G1234567890") """ @spec unarchive(Slack.Client.t, Keyword.t) :: Slack.slack_response defpost :unarchive end
21.430693
80
0.678448
ff54e56d56e518cbd4ba5431c3e6928d20b837f8
2,774
ex
Elixir
clients/service_user/lib/google_api/service_user/v1/model/system_parameters.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/service_user/lib/google_api/service_user/v1/model/system_parameters.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/service_user/lib/google_api/service_user/v1/model/system_parameters.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.ServiceUser.V1.Model.SystemParameters do @moduledoc """ ### System parameter configuration A system parameter is a special kind of parameter defined by the API system, not by an individual API. It is typically mapped to an HTTP header and/or a URL query parameter. This configuration specifies which methods change the names of the system parameters. ## Attributes * `rules` (*type:* `list(GoogleApi.ServiceUser.V1.Model.SystemParameterRule.t)`, *default:* `nil`) - Define system parameters. The parameters defined here will override the default parameters implemented by the system. If this field is missing from the service config, default system parameters will be used. Default system parameters and names is implementation-dependent. Example: define api key for all methods system_parameters rules: - selector: "*" parameters: - name: api_key url_query_parameter: api_key Example: define 2 api key names for a specific method. system_parameters rules: - selector: "/ListShelves" parameters: - name: api_key http_header: Api-Key1 - name: api_key http_header: Api-Key2 **NOTE:** All service configuration rules follow "last one wins" order. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :rules => list(GoogleApi.ServiceUser.V1.Model.SystemParameterRule.t()) } field(:rules, as: GoogleApi.ServiceUser.V1.Model.SystemParameterRule, type: :list) end defimpl Poison.Decoder, for: GoogleApi.ServiceUser.V1.Model.SystemParameters do def decode(value, options) do GoogleApi.ServiceUser.V1.Model.SystemParameters.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceUser.V1.Model.SystemParameters do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.675
130
0.692862
ff550dce7bfb237abbe189333b608a1089e91a50
5,313
ex
Elixir
core/sup_tree_gear/gear_log_writer.ex
wses-yoshida/antikythera
e108e59d2339edd0b0fad31ad4f41f56df45be55
[ "Apache-2.0" ]
null
null
null
core/sup_tree_gear/gear_log_writer.ex
wses-yoshida/antikythera
e108e59d2339edd0b0fad31ad4f41f56df45be55
[ "Apache-2.0" ]
null
null
null
core/sup_tree_gear/gear_log_writer.ex
wses-yoshida/antikythera
e108e59d2339edd0b0fad31ad4f41f56df45be55
[ "Apache-2.0" ]
null
null
null
# Copyright(c) 2015-2019 ACCESS CO., LTD. All rights reserved. use Croma defmodule AntikytheraCore.GearLog.Writer do @moduledoc """ A `GenServer` that writes log messages from each gear's `Logger` process into a gzipped file. This `GenServer` is spawned per gear; each of which resides in the gear's supervision tree. Although opened log files are regularly rotated, this `GenServer` also supports on-demand log rotation. After each successful log rotation, old log file is uploaded to cloud storage. """ use GenServer alias Antikythera.{Time, ContextId, GearName} alias AntikytheraCore.GearLog.{LogRotation, Level, ContextHelper} alias AntikytheraCore.Config.Gear, as: GearConfig alias AntikytheraCore.Ets.ConfigCache alias AntikytheraCore.Alert.Manager, as: CoreAlertManager require AntikytheraCore.Logger, as: L alias AntikytheraEal.LogStorage @rotate_interval (if Mix.env() == :test, do: 500, else: 2 * 60 * 60 * 1000) defmodule State do use Croma.Struct, recursive_new?: true, fields: [ log_state: LogRotation.State, min_level: Level, uploader: Croma.TypeGen.nilable(Croma.Pid), ] end def start_link([gear_name, logger_name]) do opts = if logger_name, do: [name: logger_name], else: [] %GearConfig{log_level: min_level} = ConfigCache.Gear.read(gear_name) GenServer.start_link(__MODULE__, {gear_name, min_level}, opts) end @impl true def init({gear_name, min_level}) do # Since the log writer process receives a large number of messages, specifying this option improves performance. Process.flag(:message_queue_data, :off_heap) log_file_path = AntikytheraCore.Path.gear_log_file_path(gear_name) log_state = LogRotation.init(@rotate_interval, log_file_path) {:ok, %State{log_state: log_state, min_level: min_level}} end @impl true def handle_cast({_, level, _, _} = gear_log, %State{log_state: log_state, min_level: min_level} = state) do if Level.write_to_log?(min_level, level) do next_log_state = LogRotation.write_log(log_state, gear_log) {:noreply, %State{state | log_state: next_log_state}} else {:noreply, state} end end @impl true def handle_cast({:set_min_level, level}, state) do {:noreply, %State{state | min_level: level}} end def handle_cast({:rotate_and_start_upload, gear_name}, %State{log_state: log_state, uploader: uploader} = state) do next_log_state = LogRotation.rotate(log_state) if uploader do # Currently an uploader is working and recent log files will be uploaded => do nothing {:noreply, %State{state | log_state: next_log_state}} else {pid, _ref} = spawn_monitor(LogStorage, :upload_rotated_logs, [gear_name]) {:noreply, %State{state | log_state: next_log_state, uploader: pid}} end end @impl true def handle_info(:rotate, %State{log_state: log_state} = state) do next_log_state = LogRotation.rotate(log_state) {:noreply, %State{state | log_state: next_log_state}} end def handle_info({:DOWN, _ref, :process, _pid, _reason}, state) do {:noreply, %State{state | uploader: nil}} end @impl true def terminate(_reason, %State{log_state: log_state}) do LogRotation.terminate(log_state) end # # Public API # for level <- [:debug, :info, :error] do defun unquote(level)(logger_name :: v[atom], msg :: v[String.t]) :: :ok do unquote(level)(logger_name, Time.now(), ContextHelper.get!(), msg) end if level == :error do # Restrict `logger_name` to `atom` instead of `GenServer.server` for alert manager name resolution defun unquote(level)(logger_name :: v[atom], t :: v[Time.t], context_id :: v[ContextId.t], msg :: v[String.t]) :: :ok do # The caller process is responsible for sending an error message to the gear's `AlertManager`, # in order to keep `GearLog.Writer` decoupled from the alerting functionality. CoreAlertManager.notify(resolve_alert_manager_name(logger_name), body(msg, context_id), t) GenServer.cast(logger_name, {t, unquote(level), context_id, msg}) end else defun unquote(level)(logger_name :: v[atom], t :: v[Time.t], context_id :: v[ContextId.t], msg :: v[String.t]) :: :ok do GenServer.cast(logger_name, {t, unquote(level), context_id, msg}) end end end defun set_min_level(gear_name :: v[GearName.t], level :: v[Level.t]) :: :ok do case logger_name(gear_name) do nil -> :ok name -> GenServer.cast(name, {:set_min_level, level}) end end defun rotate_and_start_upload_in_all_nodes(gear_name :: v[GearName.t]) :: :abcast do case logger_name(gear_name) do nil -> :ok name -> GenServer.abcast(name, {:rotate_and_start_upload, gear_name}) end end defunp logger_name(gear_name :: v[GearName.t]) :: nil | atom do try do AntikytheraCore.GearModule.logger(gear_name) rescue ArgumentError -> L.info("#{gear_name} isn't installed") nil end end defunp resolve_alert_manager_name(logger_name :: v[atom]) :: atom do [gear_top_module_str, "Logger"] = Module.split(logger_name) Module.safe_concat(gear_top_module_str, "AlertManager") end defp body(message, context_id) do "#{message}\nContext: #{context_id}" end end
36.641379
126
0.697911
ff55178721242741ccf153fe1dafc8797b86d42c
1,042
exs
Elixir
test/ex_changerate/supported_symbols.exs
81dr/ex_changerate
b5df0d1aeac755d2826d000b08e23077ca7a0c62
[ "0BSD" ]
2
2020-06-07T09:29:23.000Z
2020-11-16T01:59:40.000Z
test/ex_changerate/supported_symbols.exs
81dr/ex_changerate
b5df0d1aeac755d2826d000b08e23077ca7a0c62
[ "0BSD" ]
null
null
null
test/ex_changerate/supported_symbols.exs
81dr/ex_changerate
b5df0d1aeac755d2826d000b08e23077ca7a0c62
[ "0BSD" ]
null
null
null
defmodule ExChangerate.SupportedSymbolsTest do @moduledoc false use ExUnit.Case, async: true test "valid request: defaults" do {:ok, state} = ExChangerate.SupportedSymbols.get() {:ok, symbols} = Map.fetch(state, "symbols") nok_code = Map.get(symbols, "NOK") |> Map.get("code") aud_description = Map.get(symbols, "AUD") |> Map.get("description") assert(nok_code, "NOK") assert(aud_description, "Australian Dollar") end test "valid request: with standard json format" do {:ok, state} = ExChangerate.SupportedSymbols.get(format: "json") {:ok, symbols} = Map.fetch(state, "symbols") chf_code = Map.get(symbols, "HUF") |> Map.get("code") uah_description = Map.get(symbols, "UAH") |> Map.get("description") assert(chf_code, "HUF") assert(uah_description, "Ukrainian Hryvnia") end test "invalid request: with unsupported xml format" do {:error, state} = ExChangerate.SupportedSymbols.get(format: "xml") assert(state, "Only JSON format is currently supported.") end end
31.575758
71
0.683301
ff552d6fdf5f49eaabd6897e78f2d6c674898968
1,975
exs
Elixir
mix.exs
zabirauf/ex_microsoftbot
ebfe0ed7f8ba1e9717117918e653d7e818942f90
[ "MIT" ]
35
2016-05-11T02:34:27.000Z
2021-04-29T07:34:11.000Z
mix.exs
zabirauf/ex_microsoftbot
ebfe0ed7f8ba1e9717117918e653d7e818942f90
[ "MIT" ]
27
2016-07-10T18:32:25.000Z
2021-09-29T07:00:22.000Z
mix.exs
zabirauf/ex_microsoftbot
ebfe0ed7f8ba1e9717117918e653d7e818942f90
[ "MIT" ]
23
2016-05-10T18:53:13.000Z
2021-06-25T22:04:21.000Z
defmodule ExMicrosoftBot.Mixfile do use Mix.Project def project do [ app: :ex_microsoftbot, version: "3.0.0", elixir: "~> 1.8", description: description(), build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, package: package(), deps: deps(), docs: [ main: "readme", extras: ["README.md", "CHANGELOG.md"] ] ] end def description do "This library provides Elixir API wrapper for the Microsoft Bot Framework." end defp package do [ licenses: ["MIT License"], maintainers: ["Zohaib Rauf", "Ben Hayden"], links: %{ "GitHub" => "https://github.com/zabirauf/ex_microsoftbot", "Docs" => "https://hexdocs.pm/ex_microsoftbot/" } ] end def application do [ mod: {ExMicrosoftBot, []}, env: [ endpoint: "https://api.botframework.com", openid_valid_keys_url: "https://login.botframework.com/v1/.well-known/openidconfiguration", issuer_claim: "https://api.botframework.com", audience_claim: Application.get_env(:ex_microsoftbot, :app_id), disable_token_validation: false ], registered: [ExMicrosoftBot.TokenManager, ExMicrosoftBot.SigningKeysManager], applications: applications(Mix.env()) ] end defp applications(env) when env in [:dev, :prod] do [:logger, :jose, :tzdata, :timex, :poison] end defp applications(:test) do [:bypass | applications(:dev)] end defp deps do [ {:httpoison, "~> 1.7"}, {:poison, "~> 4.0"}, {:jose, "~> 1.7"}, {:timex, "~> 3.0"}, {:tzdata, "~> 1.0"}, {:inch_ex, "~> 2.0.0", only: :docs}, {:dialyxir, "~> 0.3", only: [:dev]}, {:ex_doc, "~> 0.19", only: [:dev]}, {:bypass, "~> 1.0", only: :test}, # Required by bypass, incompatible with OTP 22 since 2.8.0: {:cowboy, "< 2.8.0", only: :test} ] end end
25.986842
83
0.563544
ff5554a386982f5c2217823112af3ce227e6a1dc
6,081
exs
Elixir
lib/mix/test/mix/cli_test.exs
Papillon6814/elixir
65ee884105a52951a6a46077dec19a83f182f7bf
[ "Apache-2.0" ]
null
null
null
lib/mix/test/mix/cli_test.exs
Papillon6814/elixir
65ee884105a52951a6a46077dec19a83f182f7bf
[ "Apache-2.0" ]
null
null
null
lib/mix/test/mix/cli_test.exs
Papillon6814/elixir
65ee884105a52951a6a46077dec19a83f182f7bf
[ "Apache-2.0" ]
1
2020-11-25T02:22:55.000Z
2020-11-25T02:22:55.000Z
Code.require_file("../test_helper.exs", __DIR__) defmodule Mix.CLITest do use MixTest.Case @moduletag :tmp_dir test "default task" do in_fixture("no_mixfile", fn -> File.write!("mix.exs", """ defmodule P do use Mix.Project def project, do: [app: :p, version: "0.1.0"] end """) mix(~w[]) assert File.regular?("_build/dev/lib/p/ebin/Elixir.A.beam") end) end @tag :unix test "Mix.raise/2 can set exit code", %{tmp_dir: tmp_dir} do File.cd!(tmp_dir, fn -> File.mkdir_p!("lib") File.write!("mix.exs", """ defmodule MyProject do use Mix.Project def project do [app: :my_project, version: "0.0.1", aliases: aliases()] end defp aliases do [ custom: &error(&1, exit_code: 99), ] end defp error(_args, opts), do: Mix.raise("oops", opts) end """) assert {_, 99} = mix_code(~w[custom]) end) end test "compiles and invokes simple task from CLI", %{tmp_dir: tmp_dir} do File.cd!(tmp_dir, fn -> File.mkdir_p!("lib") File.write!("mix.exs", """ defmodule MyProject do use Mix.Project def project do [app: :my_project, version: "0.0.1"] end def hello_world do "Hello from MyProject!" end end """) File.write!("lib/hello.ex", """ defmodule Mix.Tasks.MyHello do use Mix.Task @shortdoc "Says hello" def run(_) do IO.puts(Mix.Project.get!().hello_world()) Mix.shell().info("This won't appear") Mix.raise("oops") end end """) contents = mix(~w[my_hello], [{"MIX_QUIET", "1"}]) assert contents =~ "Hello from MyProject!\n" refute contents =~ "This won't appear" contents = mix(~w[my_hello], [{"MIX_QUIET", "0"}]) assert contents =~ "Hello from MyProject!\n" assert contents =~ "This won't appear" contents = mix(~w[my_hello], [{"MIX_DEBUG", "1"}]) assert contents =~ "** Running mix my_hello (inside MyProject)" assert contents =~ "** (Mix.Error) oops" contents = mix(~w[my_hello], [{"MIX_DEBUG", "0"}]) refute contents =~ "** Running mix my_hello (inside MyProject)" refute contents =~ "** (Mix.Error) oops" end) end test "no task error", %{tmp_dir: tmp_dir} do File.cd!(tmp_dir, fn -> contents = mix(~w[no_task]) assert contents =~ "** (Mix) The task \"no_task\" could not be found" end) end test "tasks with slashes in them raise a NoTaskError right away", %{tmp_dir: tmp_dir} do File.cd!(tmp_dir, fn -> contents = mix(~w[my/task]) assert contents =~ "** (Mix) The task \"my/task\" could not be found" end) end test "--help smoke test", %{tmp_dir: tmp_dir} do File.cd!(tmp_dir, fn -> output = mix(~w[--help]) assert output =~ "Mix is a build tool for Elixir" assert output =~ "mix help TASK" end) end test "--version smoke test", %{tmp_dir: tmp_dir} do File.cd!(tmp_dir, fn -> output = mix(~w[--version]) assert output =~ ~r/Erlang.+\n\nMix [0-9\.a-z]+/ end) end test "env config", %{tmp_dir: tmp_dir} do File.cd!(tmp_dir, fn -> File.write!("custom.exs", """ defmodule P do use Mix.Project def project, do: [app: :p, version: "0.1.0"] end """) System.put_env("MIX_ENV", "prod") System.put_env("MIX_EXS", "custom.exs") output = mix(["run", "-e", "IO.inspect {Mix.env(), System.argv()}", "--", "1", "2", "3"]) assert output =~ ~s({:prod, ["1", "2", "3"]}) end) after System.delete_env("MIX_ENV") System.delete_env("MIX_EXS") end test "env config defaults to the tasks's preferred cli environment", %{tmp_dir: tmp_dir} do File.cd!(tmp_dir, fn -> File.write!("custom.exs", """ defmodule P do use Mix.Project def project, do: [app: :p, version: "0.1.0"] end defmodule Mix.Tasks.TestTask do use Mix.Task @preferred_cli_env :prod def run(args) do IO.inspect {Mix.env(), args} end end """) System.put_env("MIX_EXS", "custom.exs") output = mix(["test_task", "a", "b", "c"]) assert output =~ ~s({:prod, ["a", "b", "c"]}) end) after System.delete_env("MIX_EXS") end test "target config defaults to the user's preferred cli target", %{tmp_dir: tmp_dir} do File.cd!(tmp_dir, fn -> File.write!("custom.exs", """ defmodule P do use Mix.Project def project, do: [app: :p, version: "0.1.0", preferred_cli_target: [test_task: :other]] end defmodule Mix.Tasks.TestTask do use Mix.Task def run(args) do IO.inspect {Mix.target, args} end end """) System.put_env("MIX_EXS", "custom.exs") output = mix(["test_task", "a", "b", "c"]) assert output =~ ~s({:other, ["a", "b", "c"]}) end) after System.delete_env("MIX_EXS") end @tag tmp_dir: "new_with_tests" test "new with tests and cover", %{tmp_dir: tmp_dir} do File.cd!(tmp_dir, fn -> output = mix(~w[new .]) assert output =~ "* creating lib/new_with_tests.ex" output = mix(~w[test test/new_with_tests_test.exs --cover]) assert File.regular?("_build/test/lib/new_with_tests/ebin/Elixir.NewWithTests.beam") assert output =~ "1 doctest, 1 test, 0 failures" assert output =~ "Generating cover results ..." assert File.regular?("cover/Elixir.NewWithTests.html") end) end @tag tmp_dir: "sup_with_tests" test "new --sup with tests", %{tmp_dir: tmp_dir} do File.cd!(tmp_dir, fn -> output = mix(~w[new --sup .]) assert output =~ "* creating lib/sup_with_tests.ex" output = mix(~w[test]) assert File.regular?("_build/test/lib/sup_with_tests/ebin/Elixir.SupWithTests.beam") assert output =~ "1 doctest, 1 test, 0 failures" end) end end
26.788546
95
0.564052
ff55719a7ac0563e75c1d75842ae4f35e252c925
6,343
ex
Elixir
clients/container_analysis/lib/google_api/container_analysis/v1alpha1/model/containeranalysis_google_devtools_cloudbuild_v1_build_options.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/container_analysis/lib/google_api/container_analysis/v1alpha1/model/containeranalysis_google_devtools_cloudbuild_v1_build_options.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/container_analysis/lib/google_api/container_analysis/v1alpha1/model/containeranalysis_google_devtools_cloudbuild_v1_build_options.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.ContainerAnalysis.V1alpha1.Model.ContaineranalysisGoogleDevtoolsCloudbuildV1BuildOptions do @moduledoc """ Optional arguments to enable specific features of builds. ## Attributes * `diskSizeGb` (*type:* `String.t`, *default:* `nil`) - Requested disk size for the VM that runs the build. Note that this is *NOT* "disk free"; some of the space will be used by the operating system and build utilities. Also note that this is the minimum disk size that will be allocated for the build -- the build may run with a larger disk than requested. At present, the maximum disk size is 1000GB; builds that request more than the maximum are rejected with an error. * `dynamicSubstitutions` (*type:* `boolean()`, *default:* `nil`) - Option to specify whether or not to apply bash style string operations to the substitutions. NOTE: this is always enabled for triggered builds and cannot be overridden in the build configuration file. * `env` (*type:* `list(String.t)`, *default:* `nil`) - A list of global environment variable definitions that will exist for all build steps in this build. If a variable is defined in both globally and in a build step, the variable will use the build step value. The elements are of the form "KEY=VALUE" for the environment variable "KEY" being given the value "VALUE". * `logStreamingOption` (*type:* `String.t`, *default:* `nil`) - Option to define build log streaming behavior to Google Cloud Storage. * `logging` (*type:* `String.t`, *default:* `nil`) - Option to specify the logging mode, which determines if and where build logs are stored. * `machineType` (*type:* `String.t`, *default:* `nil`) - Compute Engine machine type on which to run the build. * `pool` (*type:* `GoogleApi.ContainerAnalysis.V1alpha1.Model.ContaineranalysisGoogleDevtoolsCloudbuildV1BuildOptionsPoolOption.t`, *default:* `nil`) - Optional. Specification for execution on a `WorkerPool`. See [running builds in a private pool](https://cloud.google.com/build/docs/private-pools/run-builds-in-private-pool) for more information. * `requestedVerifyOption` (*type:* `String.t`, *default:* `nil`) - Requested verifiability options. * `secretEnv` (*type:* `list(String.t)`, *default:* `nil`) - A list of global environment variables, which are encrypted using a Cloud Key Management Service crypto key. These values must be specified in the build's `Secret`. These variables will be available to all build steps in this build. * `sourceProvenanceHash` (*type:* `list(String.t)`, *default:* `nil`) - Requested hash for SourceProvenance. * `substitutionOption` (*type:* `String.t`, *default:* `nil`) - Option to specify behavior when there is an error in the substitution checks. NOTE: this is always set to ALLOW_LOOSE for triggered builds and cannot be overridden in the build configuration file. * `volumes` (*type:* `list(GoogleApi.ContainerAnalysis.V1alpha1.Model.ContaineranalysisGoogleDevtoolsCloudbuildV1Volume.t)`, *default:* `nil`) - Global list of volumes to mount for ALL build steps Each volume is created as an empty volume prior to starting the build process. Upon completion of the build, volumes and their contents are discarded. Global volume names and paths cannot conflict with the volumes defined a build step. Using a global volume in a build with only one step is not valid as it is indicative of a build request with an incorrect configuration. * `workerPool` (*type:* `String.t`, *default:* `nil`) - This field deprecated; please use `pool.name` instead. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :diskSizeGb => String.t() | nil, :dynamicSubstitutions => boolean() | nil, :env => list(String.t()) | nil, :logStreamingOption => String.t() | nil, :logging => String.t() | nil, :machineType => String.t() | nil, :pool => GoogleApi.ContainerAnalysis.V1alpha1.Model.ContaineranalysisGoogleDevtoolsCloudbuildV1BuildOptionsPoolOption.t() | nil, :requestedVerifyOption => String.t() | nil, :secretEnv => list(String.t()) | nil, :sourceProvenanceHash => list(String.t()) | nil, :substitutionOption => String.t() | nil, :volumes => list( GoogleApi.ContainerAnalysis.V1alpha1.Model.ContaineranalysisGoogleDevtoolsCloudbuildV1Volume.t() ) | nil, :workerPool => String.t() | nil } field(:diskSizeGb) field(:dynamicSubstitutions) field(:env, type: :list) field(:logStreamingOption) field(:logging) field(:machineType) field(:pool, as: GoogleApi.ContainerAnalysis.V1alpha1.Model.ContaineranalysisGoogleDevtoolsCloudbuildV1BuildOptionsPoolOption ) field(:requestedVerifyOption) field(:secretEnv, type: :list) field(:sourceProvenanceHash, type: :list) field(:substitutionOption) field(:volumes, as: GoogleApi.ContainerAnalysis.V1alpha1.Model.ContaineranalysisGoogleDevtoolsCloudbuildV1Volume, type: :list ) field(:workerPool) end defimpl Poison.Decoder, for: GoogleApi.ContainerAnalysis.V1alpha1.Model.ContaineranalysisGoogleDevtoolsCloudbuildV1BuildOptions do def decode(value, options) do GoogleApi.ContainerAnalysis.V1alpha1.Model.ContaineranalysisGoogleDevtoolsCloudbuildV1BuildOptions.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.ContainerAnalysis.V1alpha1.Model.ContaineranalysisGoogleDevtoolsCloudbuildV1BuildOptions do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
59.280374
573
0.727889
ff557bb306675762b3536b2d03168873e2b25e9a
1,760
exs
Elixir
test/ex_plasma/typed_data/transaction_test.exs
omisego/ex_plasma
27c33206297a4d6832a9419c4e61e04b3c2c9f71
[ "Apache-2.0" ]
6
2019-11-15T13:34:24.000Z
2020-03-02T11:38:01.000Z
test/ex_plasma/typed_data/transaction_test.exs
omisego/ex_plasma
27c33206297a4d6832a9419c4e61e04b3c2c9f71
[ "Apache-2.0" ]
34
2019-11-20T03:33:22.000Z
2020-05-27T18:40:10.000Z
test/ex_plasma/typed_data/transaction_test.exs
omisego/ex_plasma
27c33206297a4d6832a9419c4e61e04b3c2c9f71
[ "Apache-2.0" ]
6
2020-06-02T19:00:36.000Z
2021-08-19T11:06:33.000Z
defmodule ExPlasma.TypedData.TransactionTest do @moduledoc false use ExUnit.Case, async: true alias ExPlasma.Transaction describe "encode/1" do test "builds a eip712 transaction object" do encoded = ExPlasma.TypedData.encode(%Transaction{tx_type: 1}) assert encoded == [ <<25, 1>>, [ "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)", "OMG Network", "1", "0xd17e1233a03affb9092d5109179b43d6a8828607", "0xfad5c7f626d80f9256ef01929f3beb96e058b8b4b0e3fe52d84f054c0e2a7a83" ], "Transaction(uint256 txType,Input input0,Input input1,Input input2,Input input3,Output output0,Output output1,Output output2,Output output3,uint256 txData,bytes32 metadata)Input(uint256 blknum,uint256 txindex,uint256 oindex)Output(uint256 outputType,bytes20 outputGuard,address currency,uint256 amount)", <<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1>>, [], [], <<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0>>, <<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0>> ] end end describe "hash/1" do test "hashes a eip 712 encoded object" do encoded_hash = ExPlasma.TypedData.hash(%Transaction{tx_type: 1}) assert encoded_hash == <<196, 145, 245, 73, 70, 135, 10, 204, 85, 216, 199, 89, 153, 191, 31, 94, 60, 22, 20, 81, 54, 74, 38, 48, 248, 239, 148, 10, 173, 134, 85, 114>> end end end
44
319
0.55625
ff5589a9973054bdef270e114991f7e11931d750
625
ex
Elixir
lib/base58.ex
JohnPochta/CryptoBase58Elixir
501d59f3f018639868dc492288690695f85d1d1b
[ "MIT" ]
null
null
null
lib/base58.ex
JohnPochta/CryptoBase58Elixir
501d59f3f018639868dc492288690695f85d1d1b
[ "MIT" ]
null
null
null
lib/base58.ex
JohnPochta/CryptoBase58Elixir
501d59f3f018639868dc492288690695f85d1d1b
[ "MIT" ]
null
null
null
defmodule Base58 do @alphabet ~c(123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz) @doc """ Encodes the given integer. """ def encode(x), do: _encode(x, []) @doc """ Decodes the given string. """ def decode(enc), do: _decode(enc |> to_charlist, 0) defp _encode(0, []), do: [@alphabet |> hd] |> to_string defp _encode(0, acc), do: acc |> to_string defp _encode(x, acc) do _encode(div(x, 58), [Enum.at(@alphabet, rem(x, 58)) | acc]) end defp _decode([], acc), do: acc defp _decode([c | cs], acc) do _decode(cs, (acc * 58) + Enum.find_index(@alphabet, &(&1 == c))) end end
25
74
0.6224
ff558ce81ee0a9ec3e0d0941e88bb35d530ad1de
100
exs
Elixir
apps/evm/test/evm/operation/sha3_test.exs
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
152
2018-10-27T04:52:03.000Z
2022-03-26T10:34:00.000Z
apps/evm/test/evm/operation/sha3_test.exs
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
270
2018-04-14T07:34:57.000Z
2018-10-25T18:10:45.000Z
apps/evm/test/evm/operation/sha3_test.exs
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
25
2018-10-27T12:15:13.000Z
2022-01-25T20:31:14.000Z
defmodule EVM.Operation.Sha3Test do use ExUnit.Case, async: true doctest EVM.Operation.Sha3 end
20
35
0.79
ff55918012fcb28c230f12ccf42e05b6a9d7bbad
704
ex
Elixir
web/gettext.ex
AgtLucas/jean-grey
2aa3de025de67124c0d2bc6621f7795b547011e5
[ "MIT" ]
null
null
null
web/gettext.ex
AgtLucas/jean-grey
2aa3de025de67124c0d2bc6621f7795b547011e5
[ "MIT" ]
null
null
null
web/gettext.ex
AgtLucas/jean-grey
2aa3de025de67124c0d2bc6621f7795b547011e5
[ "MIT" ]
null
null
null
defmodule JeanGrey.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. By using [Gettext](http://hexdocs.pm/gettext), your module gains a set of macros for translations, for example: import JeanGrey.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](http://hexdocs.pm/gettext) for detailed usage. """ use Gettext, otp_app: :jean_grey end
28.16
71
0.678977
ff559230c58d9fec9053d91bb10f097a3cf42a69
650
exs
Elixir
mix.exs
mark-b-kauffman/bblearn_rest_client
63fb0da9b8027e385df927f43ec5e9ea4a517570
[ "BSD-3-Clause" ]
null
null
null
mix.exs
mark-b-kauffman/bblearn_rest_client
63fb0da9b8027e385df927f43ec5e9ea4a517570
[ "BSD-3-Clause" ]
null
null
null
mix.exs
mark-b-kauffman/bblearn_rest_client
63fb0da9b8027e385df927f43ec5e9ea4a517570
[ "BSD-3-Clause" ]
null
null
null
defmodule BblearnRestClient.MixProject do use Mix.Project def project do [ app: :bblearn_rest_client, version: "0.1.0", elixir: "~> 1.6", 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"}, {:httpoison, "~> 1.0"}, {:poison, "~> 3.1"} ] end end
20.967742
88
0.569231
ff55a9353883233e7cbf7e9d5aabddf5c0278e85
1,852
exs
Elixir
server/apps/boardr/mix.exs
AlphaHydrae/boardr
98eed02801f88c065a24bf13051c5cf96270a5f7
[ "MIT" ]
1
2021-04-08T17:26:27.000Z
2021-04-08T17:26:27.000Z
server/apps/boardr/mix.exs
AlphaHydrae/boardr
98eed02801f88c065a24bf13051c5cf96270a5f7
[ "MIT" ]
1
2022-02-13T05:50:46.000Z
2022-02-13T05:50:46.000Z
server/apps/boardr/mix.exs
AlphaHydrae/boardr
98eed02801f88c065a24bf13051c5cf96270a5f7
[ "MIT" ]
null
null
null
defmodule Boardr.MixProject do use Mix.Project def project do [ app: :boardr, version: "0.1.0", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", elixirc_paths: elixirc_paths(Mix.env()), lockfile: "../../mix.lock", elixir: "~> 1.9", start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [ :httpoison, :logger, :runtime_tools, :wx, :observer ], mod: {Boardr.Application, []} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to create, migrate and run the seeds file at once: # # $ mix ecto.setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.create --quiet", "ecto.migrate", "test"] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:ecto_sql, "~> 3.1"}, {:httpoison, "~> 1.6"}, {:inflex, "~> 2.0"}, {:jason, "~> 1.0"}, {:joken, "~> 2.0"}, {:libcluster, "~> 3.1"}, {:postgrex, "~> 0.15.0"}, {:swarm, "~> 3.0"}, # Development {:ex_doc, "~> 0.21.2", only: :dev}, # Documentation generator # Test {:faker, "~> 0.13", only: :test}, # Random data generation {:hammox, "~> 0.2.1", only: :test} # Behavior-based mocks ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] end
26.084507
79
0.544816
ff55ae2d21767a8a9d5db3e133a9c6f2ef4232a8
2,417
ex
Elixir
apps/bot/lib/bot/schedulers/github_issues.ex
elixirschool/extracurricular
eb8b725fa49ca91b1c6b7e610a8522bc81a80de1
[ "MIT" ]
48
2017-08-21T02:08:16.000Z
2022-01-05T14:02:56.000Z
apps/bot/lib/bot/schedulers/github_issues.ex
elixirschool/extracurricular
eb8b725fa49ca91b1c6b7e610a8522bc81a80de1
[ "MIT" ]
68
2017-08-21T02:17:32.000Z
2017-11-09T15:56:27.000Z
apps/bot/lib/bot/schedulers/github_issues.ex
elixirschool/extracurricular
eb8b725fa49ca91b1c6b7e610a8522bc81a80de1
[ "MIT" ]
26
2017-08-21T04:28:22.000Z
2018-12-09T14:20:29.000Z
defmodule Bot.Scheduler.GitHubIssues do @moduledoc """ GitHub Issues scheduler checks for new and closed issues on tracked repos """ use GenServer alias Bot.GitHub alias Data.{Opportunities, Projects, TaskSupervisor} # milliseconds @five_minutes 300_000 @projects_per_check 5 # seconds @two_hours 7200 # milliseconds @thirty_seconds 30000 # milliseconds @twelve_hours @two_hours * 6000 def check_repo(%{id: project_id, url: url}) do url |> repo |> GitHub.issues() |> Enum.map(&Map.put(&1, "project_id", project_id)) |> Enum.each(&insert_or_update/1) end def handle_info(:checks, state) do new_state = state |> Enum.filter(&expired?/1) |> Enum.take(@projects_per_check) |> perform_checks |> update_check_times(state) Process.send_after(self(), :checks, @five_minutes) {:noreply, new_state} end def handle_info(:project_database_sync, state) do new_state = Map.merge(state, init_state()) Process.send_after(self(), :project_database_sync, @twelve_hours) {:noreply, new_state} end def init(_opts) do Process.send_after(self(), :checks, @thirty_seconds) Process.send_after(self(), :project_database_sync, @twelve_hours) {:ok, init_state()} end def start_link(opts \\ []), do: GenServer.start_link(__MODULE__, %{}, opts) defp expired?({_id, %{last_check: last_check}}), do: last_check + @two_hours < now() defp init_state do Projects.all() |> Enum.map(&project_state/1) |> Enum.into(%{}) end defp insert_or_update(%{"html_url" => html_url} = issue) do issue |> Map.put("url", html_url) |> Opportunities.insert_or_update() end defp now, do: DateTime.to_unix(DateTime.utc_now()) defp perform_checks(projects), do: Enum.map(projects, &supervised_check(&1)) defp project_state(%{id: id} = project), do: {id, Map.put(project, :last_check, random_time())} defp random_time, do: now() + Enum.random(1..3600) defp repo("https://github.com/" <> slug), do: slug defp supervised_check({_id, project}) do Task.Supervisor.start_child(TaskSupervisor, __MODULE__, :check_repo, [project]) project end defp update_check_times(recently_checked, state) do recently_checked |> Enum.map(&Map.put(&1, :last_check, now())) |> Enum.reduce(state, fn %{id: id} = project, acc -> Map.put(acc, id, project) end) end end
25.442105
97
0.674803
ff55c908b26f762927c91697ea807e0ad8cc7ffd
330
ex
Elixir
server/lib/realtime_web/channels/auth/channels_authorization.ex
gustavoarmoa/realtime
e8075779ed19bfb8c22541dc1e5e8ea032d5b823
[ "Apache-2.0" ]
4,609
2019-10-25T12:28:35.000Z
2022-03-31T23:05:06.000Z
server/lib/realtime_web/channels/auth/channels_authorization.ex
gustavoarmoa/realtime
e8075779ed19bfb8c22541dc1e5e8ea032d5b823
[ "Apache-2.0" ]
223
2019-09-27T03:21:45.000Z
2022-03-29T23:04:03.000Z
server/lib/realtime_web/channels/auth/channels_authorization.ex
gustavoarmoa/realtime
e8075779ed19bfb8c22541dc1e5e8ea032d5b823
[ "Apache-2.0" ]
187
2019-10-27T07:44:15.000Z
2022-03-29T19:34:52.000Z
defmodule RealtimeWeb.ChannelsAuthorization do alias RealtimeWeb.JwtVerification def authorize(token) when is_binary(token) do token |> clean_token() |> JwtVerification.verify() end def authorize(_token), do: :error defp clean_token(token) do Regex.replace(~r/\s|\n/, URI.decode(token), "") end end
20.625
51
0.706061
ff55ce12af5f977cade809a990d37169c5802ac1
305
ex
Elixir
lib/trento/domain/sap_system/events/sap_system_health_changed.ex
trento-project/web
3260b30c781bffbbb0e5205cd650966c4026b9ac
[ "Apache-2.0" ]
1
2022-03-22T16:59:34.000Z
2022-03-22T16:59:34.000Z
lib/trento/domain/sap_system/events/sap_system_health_changed.ex
trento-project/web
3260b30c781bffbbb0e5205cd650966c4026b9ac
[ "Apache-2.0" ]
24
2022-03-22T16:45:25.000Z
2022-03-31T13:00:02.000Z
lib/trento/domain/sap_system/events/sap_system_health_changed.ex
trento-project/web
3260b30c781bffbbb0e5205cd650966c4026b9ac
[ "Apache-2.0" ]
1
2022-03-30T14:16:16.000Z
2022-03-30T14:16:16.000Z
defmodule Trento.Domain.Events.SapSystemHealthChanged do @moduledoc """ This event is emitted when the SAP System health has changed. """ use Trento.Event defevent do field :sap_system_id, Ecto.UUID field :health, Ecto.Enum, values: [:passing, :warning, :critical, :unknown] end end
23.461538
79
0.721311
ff562e31d62acaf70d3d952e3a688178665d2aab
327
ex
Elixir
lib/resty/associations/belongs_to.ex
paulhenri-l/resty
b6aec738569355bab53fbc732bfd323c63348b85
[ "MIT" ]
3
2018-11-17T11:11:47.000Z
2019-09-13T16:13:43.000Z
lib/resty/associations/belongs_to.ex
paulhenri-l/resty
b6aec738569355bab53fbc732bfd323c63348b85
[ "MIT" ]
38
2018-11-11T01:28:41.000Z
2019-04-01T21:28:02.000Z
lib/resty/associations/belongs_to.ex
paulhenri-l/resty
b6aec738569355bab53fbc732bfd323c63348b85
[ "MIT" ]
1
2019-01-10T12:41:48.000Z
2019-01-10T12:41:48.000Z
defmodule Resty.Associations.BelongsTo do defstruct [:related, :attribute, :foreign_key, {:eager_load, true}] @moduledoc false @doc false def fetch(association, resource) do case Map.get(resource, association.foreign_key) do nil -> nil id -> Resty.Repo.find(association.related, id) end end end
23.357143
69
0.703364
ff56411e40e2ad4ee79f55b530586657b19272c5
1,178
exs
Elixir
mix.exs
sabiwara/enumancer
b0ff768ada92b4bfc68c774257177c114c68a651
[ "MIT" ]
27
2021-07-31T07:36:26.000Z
2022-02-04T18:47:44.000Z
mix.exs
sabiwara/enumancer
b0ff768ada92b4bfc68c774257177c114c68a651
[ "MIT" ]
null
null
null
mix.exs
sabiwara/enumancer
b0ff768ada92b4bfc68c774257177c114c68a651
[ "MIT" ]
1
2021-08-13T03:40:52.000Z
2021-08-13T03:40:52.000Z
defmodule Enumancer.MixProject do use Mix.Project @version "0.0.1" @github_url "https://github.com/sabiwara/enumancer" def project do [ app: :enumancer, version: @version, elixir: "~> 1.12", start_permanent: Mix.env() == :prod, deps: deps(), preferred_cli_env: [ docs: :docs, "hex.publish": :docs, dialyzer: :test ], # hex description: "Elixir macros to effortlessly define highly optimized Enum pipelines", package: package(), name: "Enumancer", docs: docs() ] end def application do [] end defp deps do [ # doc, benchs {:ex_doc, "~> 0.25.0", only: :docs, runtime: false}, {:benchee, "~> 1.0", only: :bench, runtime: false}, # CI {:dialyxir, "~> 1.0", only: :test, runtime: false} ] end defp package do [ maintainers: ["sabiwara"], licenses: ["MIT"], links: %{"GitHub" => @github_url}, files: ~w(lib mix.exs README.md LICENSE.md) ] end defp docs do [ source_ref: "v#{@version}", source_url: @github_url, homepage_url: @github_url ] end end
19.966102
90
0.547538
ff56550d72ee44f3a70b8ca189435054b916d579
1,070
ex
Elixir
lib/koans/11_sigils.ex
trungle1612/elixir-koans
1ef8dda3ec46ff762aa342314373cca444172026
[ "MIT" ]
null
null
null
lib/koans/11_sigils.ex
trungle1612/elixir-koans
1ef8dda3ec46ff762aa342314373cca444172026
[ "MIT" ]
null
null
null
lib/koans/11_sigils.ex
trungle1612/elixir-koans
1ef8dda3ec46ff762aa342314373cca444172026
[ "MIT" ]
null
null
null
defmodule Sigils do use Koans @intro "Sigils" koan "The ~s sigil is a different way of expressing string literals" do assert ~s{This is a string} == "This is a string" end koan "Sigils are useful to avoid escaping quotes in strings" do assert "\"Welcome to the jungle\", they said." == ~s("Welcome to the jungle", they said.) end koan "Sigils can use different delimiters" do matches? = ~s{This works!} == ~s[This works!] assert matches? == true end koan "The lowercase ~s sigil supports string interpolation" do assert ~s[1 + 1 = #{1 + 1}] == "1 + 1 = 2" end koan "The ~S sigil is similar to ~s but doesn't do interpolation" do assert ~S[1 + 1 = #{1+1}] == "1 + 1 = \#\{1+1\}" end koan "The ~w sigil creates word lists" do assert ~w(Hello world) == ["Hello", "world"] end koan "The ~w sigil also allows interpolation" do assert ~w(Hello 1#{1 + 1}3) == ["Hello", "123"] end koan "The ~W sigil behaves to ~w as ~S behaves to ~s" do assert ~W(Hello #{1+1}) == ["Hello", "\#\{1+1\}"] end end
27.435897
93
0.61028
ff5657e38007d28ef5aba9b0253488a96ed6a3f1
2,215
ex
Elixir
lib/mix/lib/mix/tasks/loadpaths.ex
wstrinz/elixir
1048b34d6c816f8e5dbd4fdbaaf9baa41b4f0d95
[ "Apache-2.0" ]
1
2021-04-28T21:35:01.000Z
2021-04-28T21:35:01.000Z
lib/mix/lib/mix/tasks/loadpaths.ex
wstrinz/elixir
1048b34d6c816f8e5dbd4fdbaaf9baa41b4f0d95
[ "Apache-2.0" ]
1
2018-09-10T23:36:45.000Z
2018-09-10T23:36:45.000Z
lib/mix/lib/mix/tasks/loadpaths.ex
wstrinz/elixir
1048b34d6c816f8e5dbd4fdbaaf9baa41b4f0d95
[ "Apache-2.0" ]
8
2018-02-20T18:30:53.000Z
2019-06-18T14:23:31.000Z
defmodule Mix.Tasks.Loadpaths do use Mix.Task @moduledoc """ Loads the application and its dependencies paths. ## Configuration * `:elixir` - matches the current Elixir version against the given requirement ## Command line options * `--no-archives-check` - does not check archive * `--no-deps-check` - does not check dependencies * `--no-elixir-version-check` - does not check Elixir version """ def run(args) do config = Mix.Project.config() unless "--no-elixir-version-check" in args do check_elixir_version(config, args) end unless "--no-archives-check" in args do Mix.Task.run("archive.check", args) end # --no-deps is used only internally. It has no purpose # from Mix.CLI because running a task may load deps. unless "--no-deps" in args do Mix.Task.run("deps.loadpaths", args) end if config[:app] do load_project(config, args) end :ok end defp check_elixir_version(config, _) do if req = config[:elixir] do case Version.parse_requirement(req) do {:ok, req} -> unless Version.match?(System.version(), req) do raise Mix.ElixirVersionError, target: config[:app] || Mix.Project.get(), expected: req, actual: System.version() end :error -> Mix.raise("Invalid Elixir version requirement #{req} in mix.exs file") end end end defp load_project(config, _args) do vsn = {System.version(), :erlang.system_info(:otp_release)} scm = config[:build_scm] # Erase the app build if we have lock mismatch. # We do this to force full recompilation when # any of SCM or Elixir version changes. Applies # to dependencies and the main project alike. case Mix.Dep.ElixirSCM.read() do {:ok, old_vsn, _} when old_vsn != vsn -> rm_rf_app(config) {:ok, _, old_scm} when old_scm != scm -> rm_rf_app(config) _ -> :ok end Enum.each(Mix.Project.load_paths(config), &Code.prepend_path(&1)) end defp rm_rf_app(config) do File.rm_rf(Mix.Project.app_path(config)) File.rm_rf(Mix.Project.consolidation_path(config)) end end
26.686747
80
0.63702
ff5681365e1b11219a44dfb7caec000a72076f5a
1,276
ex
Elixir
lib/countriex.ex
gvl/countriex
4d647f1e3347e9f7c6fe8ac32703aa77aff69bbe
[ "MIT" ]
null
null
null
lib/countriex.ex
gvl/countriex
4d647f1e3347e9f7c6fe8ac32703aa77aff69bbe
[ "MIT" ]
null
null
null
lib/countriex.ex
gvl/countriex
4d647f1e3347e9f7c6fe8ac32703aa77aff69bbe
[ "MIT" ]
null
null
null
defmodule Countriex do @moduledoc """ Provides all sorts useful information for every country in the ISO 3166 standard, and helper methods to filter/retrieve that information by. """ @doc """ Returns all country data """ def all, do: Countriex.Data.countries() @doc """ Returns the first matching country with the given criteria, or `nil` if a country with that data does not exist. ## Examples iex> c = Countriex.get_by(:alpha2, "US") iex> c.name "United States of America" iex> Countriex.get_by(:alpha2, "XX") nil iex> Countriex.get_by(:foo, "XX") nil """ def get_by(field, value), do: all() |> Enum.find(fn country -> matches?(country, field, value) end) @doc """ Returns all countries matching the given criteria, or `[]` if the criteria does not match any countries ## Examples iex> c = Countriex.filter(:region, "Americas") iex> c |> List.first |> Map.get(:name) "Antigua and Barbuda" iex> c |> length 57 iex> Countriex.filter(:region, "foo") [] """ def filter(field, value), do: all() |> Enum.filter(fn country -> matches?(country, field, value) end) defp matches?(country, field, value), do: Map.get(country, field) == value end
26.583333
142
0.634796
ff56878f9186558952f776260635ac8b74c987bd
143
ex
Elixir
lib/beet_diet_web/controllers/page_controller.ex
Vaysman/beer-diet
14bf38e08afc25bd3f0139d8fff75f0df1821793
[ "MIT" ]
null
null
null
lib/beet_diet_web/controllers/page_controller.ex
Vaysman/beer-diet
14bf38e08afc25bd3f0139d8fff75f0df1821793
[ "MIT" ]
null
null
null
lib/beet_diet_web/controllers/page_controller.ex
Vaysman/beer-diet
14bf38e08afc25bd3f0139d8fff75f0df1821793
[ "MIT" ]
null
null
null
defmodule BeetDietWeb.PageController do use BeetDietWeb, :controller def index(conn, _params) do render(conn, "index.html") end end
17.875
39
0.741259
ff56a522c2114738661fd523b6453aa3a8a67fa9
2,391
ex
Elixir
lib/oli_web/live/common/hierarchy/move_modal.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
1
2022-03-17T20:35:47.000Z
2022-03-17T20:35:47.000Z
lib/oli_web/live/common/hierarchy/move_modal.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
9
2021-11-02T16:52:09.000Z
2022-03-25T15:14:01.000Z
lib/oli_web/live/common/hierarchy/move_modal.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
null
null
null
defmodule OliWeb.Common.Hierarchy.MoveModal do use Phoenix.LiveComponent use Phoenix.HTML import OliWeb.Curriculum.Utils alias OliWeb.Common.Hierarchy.HierarchyPicker alias Oli.Delivery.Hierarchy.HierarchyNode def render( %{ id: id, node: %HierarchyNode{uuid: uuid, revision: revision} = node, hierarchy: %HierarchyNode{} = hierarchy, from_container: %HierarchyNode{} = from_container, active: %HierarchyNode{} = active } = assigns ) do ~L""" <div class="modal fade show" style="display: block" id="<%= id %>" tabindex="-1" role="dialog" aria-hidden="true" phx-hook="ModalLaunch"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Move <%= resource_type_label(revision) |> String.capitalize() %></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <%= live_component HierarchyPicker, id: "#{id}_hierarchy_picker", hierarchy: hierarchy, active: active, select_mode: :container, filter_items_fn: fn items -> Enum.filter(items, &(&1.uuid != uuid)) end %> <div class="text-center text-secondary mt-2"> <b><%= revision.title %></b> will be placed here </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal" phx-click="MoveModal.cancel">Cancel</button> <button type="submit" class="btn btn-primary" phx-click="MoveModal.move_item" phx-value-uuid="<%= node.uuid %>" phx-value-from_uuid="<%= from_container.uuid %>" phx-value-to_uuid="<%= active.uuid %>" <%= if can_move?(from_container, active) , do: "", else: "disabled" %>> Move </button> </div> </div> </div> </div> """ end defp can_move?(from_container, active) do active.uuid != nil && active.uuid != from_container.uuid end end
37.359375
141
0.547888
ff56db3c46825b8feee2510120f81d5bc04d9a08
224
ex
Elixir
lib/changelog.ex
wojtekmach/changelog
a3af0e7ef232d232e9fafd1e24976d5c2da63c98
[ "Apache-2.0" ]
1
2018-01-28T21:17:29.000Z
2018-01-28T21:17:29.000Z
lib/changelog.ex
wojtekmach/changelog
a3af0e7ef232d232e9fafd1e24976d5c2da63c98
[ "Apache-2.0" ]
2
2018-01-27T21:15:51.000Z
2019-09-15T19:09:00.000Z
lib/changelog.ex
wojtekmach/changelog
a3af0e7ef232d232e9fafd1e24976d5c2da63c98
[ "Apache-2.0" ]
null
null
null
defmodule Changelog do defmodule Release do defstruct [:version, :date, notes: []] end def fetch(name) do Changelog.Fetcher.fetch(name) end def parse!(text) do Changelog.Parser.parse!(text) end end
16
42
0.678571
ff57130ea3948ad6b0b5b3ae6b64c28f8769d2f4
2,114
exs
Elixir
config/dev.exs
noahjames404/elixir-pheonix-framework
c1587709d67ef7c9bad247d4fe4ec80e23e4041b
[ "MIT" ]
null
null
null
config/dev.exs
noahjames404/elixir-pheonix-framework
c1587709d67ef7c9bad247d4fe4ec80e23e4041b
[ "MIT" ]
null
null
null
config/dev.exs
noahjames404/elixir-pheonix-framework
c1587709d67ef7c9bad247d4fe4ec80e23e4041b
[ "MIT" ]
null
null
null
use Mix.Config # Configure your database config :hello, Hello.Repo, username: "postgres", password: "root", database: "hello_dev", hostname: "localhost", show_sensitive_data_on_connection_error: true, pool_size: 10 # 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 webpack to recompile .js and .css sources. config :hello, HelloWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [ node: [ "node_modules/webpack/bin/webpack.js", "--mode", "development", "--watch-stdin", cd: Path.expand("../assets", __DIR__) ] ] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # Mix task: # # mix phx.gen.cert # # Note that this task requires Erlang/OTP 20 or later. # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: # # https: [ # port: 4001, # cipher_suite: :strong, # keyfile: "priv/cert/selfsigned_key.pem", # certfile: "priv/cert/selfsigned.pem" # ], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :hello, HelloWeb.Endpoint, live_reload: [ patterns: [ ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", ~r"priv/gettext/.*(po)$", ~r"lib/hello_web/(live|views)/.*(ex)$", ~r"lib/hello_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. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime
27.454545
68
0.687323
ff57543d1a0586ceb2164b838dfbbfca25965d89
2,724
ex
Elixir
lib/ex_amqp_helpers.ex
briankereszturi/examqphelpers
1269a47778724067fe29239c9858a8d2a637fdc1
[ "MIT" ]
null
null
null
lib/ex_amqp_helpers.ex
briankereszturi/examqphelpers
1269a47778724067fe29239c9858a8d2a637fdc1
[ "MIT" ]
null
null
null
lib/ex_amqp_helpers.ex
briankereszturi/examqphelpers
1269a47778724067fe29239c9858a8d2a637fdc1
[ "MIT" ]
null
null
null
defmodule ExAmqpHelpers do use GenServer use AMQP require Logger defp conn_string() do rconf = Application.get_env(:api, :rabbitmq) case rconf[:user] do nil -> "amqp://#{rconf[:host]}" _ -> "amqp://#{rconf[:user]}:#{rconf[:password]}@#{rconf[:host]}" end end def start_link, do: GenServer.start_link(__MODULE__, [], []) def init(_), do: connect() # TODO: Reconnect logic. def connect() do case Connection.open(conn_string()) do {:ok, conn} -> Logger.info "Connected to RabbitMQ." Process.monitor(conn.pid) {:ok, chan} = Channel.open(conn) {:ok, %{conn: conn, chan: chan}} {:error, _} -> :timer.sleep(5000) # Wait and reconnect. Logger.info "Attempting to reconnect to RabbitMQ..." connect() end end def handle_info({:DOWN, _, :process, _pid, _reason}, _) do {:ok, state} = connect() {:noreply, state} end # Get Message def get_message_autoack(queue) do with {:ok, message, ack_fn} <- get_message(queue), :ok <- ack_fn.(), do: {:ok, message} end def get_message(queue), do: GenServer.call(:queue_manager, {:get_message, queue}) def handle_call({:get_message, queue}, _from, %{chan: chan}=state) do case Basic.get(chan, queue) do {:ok, message, meta} -> ack_fn = fn -> Basic.ack(chan, meta.delivery_tag) end {:reply, {:ok, message, ack_fn}, state} _ -> {:reply, :empty, state} end end # Get Queue Size def get_queue_size(queue) do count = GenServer.call(:queue_manager, {:get_queue_size, queue}) {:ok, count} end def handle_call({:get_queue_size, queue}, _from, %{chan: chan}=state) do case Queue.declare(chan, queue, durable: true) do {:ok, %{message_count: c}} -> {:reply, c, state} _ -> {:reply, 0, state} end end # Publish Message def publish_message(message, queue), do: GenServer.call(:queue_manager, {:publish_message, queue, message}) def handle_call({:publish_message, queue, message}, _from, %{chan: chan}=state) do exchange = queue <> "exchange" {:ok, _} = Queue.declare(chan, queue, durable: true) :ok = Exchange.fanout(chan, exchange, durable: true) :ok = Queue.bind(chan, queue, exchange) :ok = Basic.publish(chan, exchange, "", message) {:reply, :ok, state} end # Purge queue def purge_queue(queue), do: GenServer.call(:queue_manager, {:purge_queue, queue}) def handle_call({:purge_queue, queue}, _from, %{chan: chan}=state) do case Queue.purge(chan, queue) do {:ok, %{message_count: _}} -> {:reply, :ok, state} _ -> {:reply, :error, state} end end end
27.515152
84
0.606094
ff57741591b6dd170ddf94ab51a42b04f582dca2
3,007
exs
Elixir
elixir/elixir-elm-playground/test/playground_web/controllers/board_controller_test.exs
marcinbiegun/exercises
36ad942e8d40d6471136326a3f6d09285bbd90aa
[ "MIT" ]
1
2018-12-11T14:09:14.000Z
2018-12-11T14:09:14.000Z
elixir/elixir-elm-playground/test/playground_web/controllers/board_controller_test.exs
marcinbiegun/exercises
36ad942e8d40d6471136326a3f6d09285bbd90aa
[ "MIT" ]
null
null
null
elixir/elixir-elm-playground/test/playground_web/controllers/board_controller_test.exs
marcinbiegun/exercises
36ad942e8d40d6471136326a3f6d09285bbd90aa
[ "MIT" ]
null
null
null
defmodule PlaygroundWeb.BoardControllerTest do use PlaygroundWeb.ConnCase alias Playground.Repo alias Playground.Todo alias Playground.Coherence.User, as: User @create_attrs %{name: "some name"} @update_attrs %{name: "some updated name"} @invalid_attrs %{name: nil} def create_user() do user_attrs = %{name: "test", email: "test@example.com", password: "test", password_confirmation: "test"} {:ok, user} = User.changeset(%User{}, user_attrs) |> Repo.insert user end def fixture(:board) do user = create_user() {:ok, board} = Todo.create_board(@create_attrs |> Map.merge(%{user_id: user.id})) board end describe "index" do test "lists all boards", %{conn: conn} do conn = get conn, board_path(conn, :index) assert html_response(conn, 200) =~ "Listing Boards" end end describe "new board" do test "renders form", %{conn: conn} do conn = get conn, board_path(conn, :new) assert html_response(conn, 200) =~ "New Board" end end describe "create board" do test "redirects to show when data is valid", %{conn: conn} do user = create_user() conn = post conn, board_path(conn, :create), board: @create_attrs |> Map.merge(%{user_id: user.id}) assert %{id: id} = redirected_params(conn) assert redirected_to(conn) == board_path(conn, :show, id) conn = get conn, board_path(conn, :show, id) assert html_response(conn, 200) =~ "Show Board" end test "renders errors when data is invalid", %{conn: conn} do conn = post conn, board_path(conn, :create), board: @invalid_attrs assert html_response(conn, 200) =~ "New Board" end end describe "edit board" do setup [:create_board] test "renders form for editing chosen board", %{conn: conn, board: board} do conn = get conn, board_path(conn, :edit, board) assert html_response(conn, 200) =~ "Edit Board" end end describe "update board" do setup [:create_board] test "redirects when data is valid", %{conn: conn, board: board} do conn = put conn, board_path(conn, :update, board), board: @update_attrs assert redirected_to(conn) == board_path(conn, :show, board) conn = get conn, board_path(conn, :show, board) assert html_response(conn, 200) =~ "some updated name" end test "renders errors when data is invalid", %{conn: conn, board: board} do conn = put conn, board_path(conn, :update, board), board: @invalid_attrs assert html_response(conn, 200) =~ "Edit Board" end end describe "delete board" do setup [:create_board] test "deletes chosen board", %{conn: conn, board: board} do conn = delete conn, board_path(conn, :delete, board) assert redirected_to(conn) == board_path(conn, :index) assert_error_sent 404, fn -> get conn, board_path(conn, :show, board) end end end defp create_board(_) do board = fixture(:board) {:ok, board: board} end end
30.373737
108
0.652145
ff57cff2fe406ba810c521e5d888f1521e3f297c
1,354
ex
Elixir
lib/crit_web/views/reservations/reservation_view.ex
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
6
2019-07-16T19:31:23.000Z
2021-06-05T19:01:05.000Z
lib/crit_web/views/reservations/reservation_view.ex
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
null
null
null
lib/crit_web/views/reservations/reservation_view.ex
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
3
2020-02-24T23:38:27.000Z
2020-08-01T23:50:17.000Z
defmodule CritWeb.Reservations.ReservationView do use CritWeb, :view import Pile.TimeHelper alias CritWeb.Reservations.ReservationController alias CritBiz.ViewModels.Reservation.CalendarEntry alias Pile.Extras.IntegerX def date_or_dates_header(first_date, last_date) do header = if Date.compare(first_date, last_date) == :eq do "Reservations on #{date_string(first_date)}" else "Reservations from #{date_string(first_date)} through #{date_string(last_date)}" end ~E""" <h2 class="ui header"><%=header%></h2> """ end def count_header(count) do "#{IntegerX.to_words(count)} #{Inflex.inflect("reservation", count)}" |> Recase.to_title end def popup_body(reservation_id, animal_names, procedure_names) do link = Phoenix.HTML.Link.link( "Click to edit or delete", to: ReservationController.path(:show, reservation_id)) ~E""" <%= Enum.join(animal_names, ", ") %><br/> <%= Enum.join(procedure_names, ", ") %> <p> <%= link %></p> """ |> Phoenix.HTML.safe_to_string end def render("week.json", %{reservations: reservations, institution: institution}) do one = fn reservation -> CalendarEntry.to_map(reservation, institution) end %{data: Enum.map(reservations, one)} end end
28.208333
88
0.650665
ff57ffa8c3aa3d8d3b8a76c646309137286737d2
1,492
exs
Elixir
mix.exs
antonmi/grpc
b13a8d3467351796769488d9e7a116cbb1935737
[ "Apache-2.0" ]
null
null
null
mix.exs
antonmi/grpc
b13a8d3467351796769488d9e7a116cbb1935737
[ "Apache-2.0" ]
null
null
null
mix.exs
antonmi/grpc
b13a8d3467351796769488d9e7a116cbb1935737
[ "Apache-2.0" ]
null
null
null
defmodule GRPC.Mixfile do use Mix.Project @version "0.4.0" def project do [ app: :grpc, version: @version, elixir: "~> 1.5", elixirc_paths: elixirc_paths(Mix.env()), build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, deps: deps(), package: package(), description: "The Elixir implementation of gRPC", docs: [ extras: ["README.md"], main: "readme", source_ref: "v#{@version}", source_url: "https://github.com/elixir-grpc/grpc" ] ] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do [extra_applications: [:logger]] end defp deps do ex_doc_version = if System.version() |> Version.compare("1.7.0") == :lt do "~> 0.18.0" else "~> 0.19" end [ {:protobuf, "~> 0.5"}, {:gun, github: "elixir-grpc/gun", tag: "grpc-1.3.2"}, {:ex_doc, ex_doc_version, only: :dev}, {:inch_ex, "~> 1.0", only: [:dev, :test]}, {:dialyxir, "~> 0.5", only: :dev, runtime: false} ] end defp package do %{ maintainers: ["Bing Han"], licenses: ["Apache 2"], links: %{"GitHub" => "https://github.com/elixir-grpc/grpc"}, files: ~w(mix.exs README.md lib src config LICENSE .formatter.exs) } end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] end
24.459016
72
0.55496
ff5813b01d47b10cc59cc6c8c06b5bd4041f2bca
2,362
ex
Elixir
clients/classroom/lib/google_api/classroom/v1/model/course_alias.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/classroom/lib/google_api/classroom/v1/model/course_alias.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/classroom/lib/google_api/classroom/v1/model/course_alias.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Classroom.V1.Model.CourseAlias do @moduledoc """ Alternative identifier for a course. An alias uniquely identifies a course. It must be unique within one of the following scopes: * domain: A domain-scoped alias is visible to all users within the alias creator's domain and can be created only by a domain admin. A domain-scoped alias is often used when a course has an identifier external to Classroom. * project: A project-scoped alias is visible to any request from an application using the Developer Console project ID that created the alias and can be created by any project. A project-scoped alias is often used when an application has alternative identifiers. A random value can also be used to avoid duplicate courses in the event of transmission failures, as retrying a request will return `ALREADY_EXISTS` if a previous one has succeeded. ## Attributes * `alias` (*type:* `String.t`, *default:* `nil`) - Alias string. The format of the string indicates the desired alias scoping. * `d:` indicates a domain-scoped alias. Example: `d:math_101` * `p:` indicates a project-scoped alias. Example: `p:abc123` This field has a maximum length of 256 characters. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :alias => String.t() | nil } field(:alias) end defimpl Poison.Decoder, for: GoogleApi.Classroom.V1.Model.CourseAlias do def decode(value, options) do GoogleApi.Classroom.V1.Model.CourseAlias.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Classroom.V1.Model.CourseAlias do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
50.255319
800
0.757832
ff584877691723b33faf8afac8e153e5f667bc94
4,304
ex
Elixir
lib/dnsimple/services.ex
remiprev/dnsimple-elixir
7a8eb0cec64797f3e72601b5395d8629836ef904
[ "MIT" ]
null
null
null
lib/dnsimple/services.ex
remiprev/dnsimple-elixir
7a8eb0cec64797f3e72601b5395d8629836ef904
[ "MIT" ]
14
2021-02-19T07:09:55.000Z
2022-02-24T12:33:37.000Z
lib/dnsimple/services.ex
littleairmada/dnsimple-elixir
a1b71a9c84d1a440f86199b8f48754e1c88ca19f
[ "MIT" ]
null
null
null
defmodule Dnsimple.Services do @moduledoc """ Provides functions to interact with the [one-click service endpoints](https://developer.dnsimple.com/v2/services/). See: - https://developer.dnsimple.com/v2/services - https://developer.dnsimple.com/v2/services/domains/ """ alias Dnsimple.Client alias Dnsimple.Listing alias Dnsimple.Response alias Dnsimple.Service @doc """ Returns the list of available one-click services. See: - https://developer.dnsimple.com/v2/services/#list ## Examples: client = %Dnsimple.Client{access_token: "a1b2c3d4"} {:ok, response} = Dnsimple.Templates.list_services(client) {:ok, response} = Dnsimple.Templates.list_services(client, sort: "short_name:desc") """ @spec list_services(Client.t, Keyword.t) :: {:ok|:error, Response.t} def list_services(client, options \\ []) do url = Client.versioned("/services") Listing.get(client, url, options) |> Response.parse(%{"data" => [%Service{settings: [%Service.Setting{}]}], "pagination" => %Response.Pagination{}}) end @doc """ Returns a one-click service. See: - https://developer.dnsimple.com/v2/services/#get ## Examples: client = %Dnsimple.Client{access_token: "a1b2c3d4"} {:ok, response} = Dnsimple.Templates.get_service(client, service_id = 1) {:ok, response} = Dnsimple.Templates.get_service(client, service_id = "wordpress") """ @spec get_service(Client.t, integer | String.t, Keyword.t) :: {:ok|:error, Response.t} def get_service(client, service_id, options \\ []) do url = Client.versioned("/services/#{service_id}") Client.get(client, url, options) |> Response.parse(%{"data" => %Service{settings: [%Service.Setting{}]}}) end @doc """ Lists the one-click services already applied to a domain. See: - https://developer.dnsimple.com/v2/services/domains/#applied ## Examples: client = %Dnsimple.Client{access_token: "a1b2c3d4"} {:ok, response} = Dnsimple.Services.applied_services(client, account_id = 1010, domain_id = "example.com") {:ok, response} = Dnsimple.Services.applied_services(client, account_id = 1010, domain_id = "example.com", page: 2) """ @spec applied_services(Client.t, String.t | integer, String.t | integer, Keyword.t) :: {:ok|:error, Response.t} def applied_services(client, account_id, domain_id, options \\ []) do url = Client.versioned("/#{account_id}/domains/#{domain_id}/services") Listing.get(client, url, options) |> Response.parse(%{"data" => [%Service{settings: [%Service.Setting{}]}], "pagination" => %Response.Pagination{}}) end @doc """ Apply a one-click service to a domain. See: - https://developer.dnsimple.com/v2/services/domains/#apply ## Examples: client = %Dnsimple.Client{access_token: "a1b2c3d4"} {:ok, response} = Dnsimple.Services.apply_service(client, account_id = 1010, domain_id = "example.com", service_id = 12) {:ok, response} = Dnsimple.Services.apply_service(client, account_id = 1010, domain_id = "example.com", service_id = 27, %{ %{settings: %{setting_name: "setting value"}} }) """ @spec apply_service(Client.t, String.t | integer, String.t | integer, String.t | integer, map(), keyword()) :: {:ok|:error, Response.t} def apply_service(client, account_id, domain_id, service_id, settings \\ %{}, options \\ []) do url = Client.versioned("/#{account_id}/domains/#{domain_id}/services/#{service_id}") Client.post(client, url, settings, options) |> Response.parse(nil) end @doc """ Remove a one-click service previously applied to a domain. See: - https://developer.dnsimple.com/v2/services/domains/#unapply ## Examples: client = %Dnsimple.Client{access_token: "a1b2c3d4"} {:ok, response} = Dnsimple.Services.unapply_service(client, account_id = 1010, domain_id = "example.com", service_id = 12) """ @spec unapply_service(Client.t, String.t | integer, String.t | integer, String.t | integer, keyword()) :: {:ok|:error, Response.t} def unapply_service(client, account_id, domain_id, service_id, options \\ []) do url = Client.versioned("/#{account_id}/domains/#{domain_id}/services/#{service_id}") Client.delete(client, url, options) |> Response.parse(nil) end end
33.889764
137
0.676812
ff58888ad6d7e7cadbd4dd13726ca31265bddf1a
1,838
ex
Elixir
test/support/model_case.ex
muziyoshiz/admiral_stats_api
f9a6eaa2d34604ec207168f6192b98788e16bf58
[ "MIT" ]
null
null
null
test/support/model_case.ex
muziyoshiz/admiral_stats_api
f9a6eaa2d34604ec207168f6192b98788e16bf58
[ "MIT" ]
null
null
null
test/support/model_case.ex
muziyoshiz/admiral_stats_api
f9a6eaa2d34604ec207168f6192b98788e16bf58
[ "MIT" ]
null
null
null
defmodule AdmiralStatsApi.ModelCase do @moduledoc """ This module defines the test case to be used by model tests. You may define functions here to be used as helpers in your model tests. See `errors_on/2`'s definition as reference. 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 alias AdmiralStatsApi.Repo import Ecto import Ecto.Changeset import Ecto.Query import AdmiralStatsApi.ModelCase end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(AdmiralStatsApi.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(AdmiralStatsApi.Repo, {:shared, self()}) end :ok end @doc """ Helper for returning list of errors in a struct when given certain data. ## Examples Given a User schema that lists `:name` as a required field and validates `:password` to be safe, it would return: iex> errors_on(%User{}, %{password: "password"}) [password: "is unsafe", name: "is blank"] You could then write your assertion like: assert {:password, "is unsafe"} in errors_on(%User{}, %{password: "password"}) You can also create the changeset manually and retrieve the errors field directly: iex> changeset = User.changeset(%User{}, password: "password") iex> {:password, "is unsafe"} in changeset.errors true """ def errors_on(struct, data) do struct.__struct__.changeset(struct, data) |> Ecto.Changeset.traverse_errors(&AdmiralStatsApi.ErrorHelpers.translate_error/1) |> Enum.flat_map(fn {key, errors} -> for msg <- errors, do: {key, msg} end) end end
27.848485
86
0.693145
ff58b1014f094e7e0394e73a9b361a402ba515d6
4,629
ex
Elixir
apps/language_server/lib/language_server/dialyzer/manifest.ex
rupurt/elixir-ls
67face6dd668e7d5d363e28f6b4305a1a64473c7
[ "Apache-2.0" ]
null
null
null
apps/language_server/lib/language_server/dialyzer/manifest.ex
rupurt/elixir-ls
67face6dd668e7d5d363e28f6b4305a1a64473c7
[ "Apache-2.0" ]
null
null
null
apps/language_server/lib/language_server/dialyzer/manifest.ex
rupurt/elixir-ls
67face6dd668e7d5d363e28f6b4305a1a64473c7
[ "Apache-2.0" ]
null
null
null
defmodule ElixirLS.LanguageServer.Dialyzer.Manifest do alias ElixirLS.LanguageServer.{Dialyzer, JsonRpc} import Record import Dialyzer.Utils require Logger @manifest_vsn :v2 defrecord(:plt, [:info, :types, :contracts, :callbacks, :exported_types]) def build_new_manifest() do parent = self() Task.start_link(fn -> active_plt = load_elixir_plt() transfer_plt(active_plt, parent) Dialyzer.analysis_finished(parent, :noop, active_plt, %{}, %{}, %{}, nil, nil) end) end def write(_, _, _, _, _, nil) do nil end def write(root_path, active_plt, mod_deps, md5, warnings, timestamp) do Task.start_link(fn -> manifest_path = manifest_path(root_path) plt( info: info, types: types, contracts: contracts, callbacks: callbacks, exported_types: exported_types ) = active_plt manifest_data = { @manifest_vsn, mod_deps, md5, warnings, :ets.tab2list(info), :ets.tab2list(types), :ets.tab2list(contracts), :ets.tab2list(callbacks), :ets.tab2list(exported_types) } # Because the manifest file can be several megabytes, we do a write-then-rename # to reduce the likelihood of corrupting the manifest JsonRpc.log_message(:info, "[ElixirLS Dialyzer] Writing manifest...") File.mkdir_p!(Path.dirname(manifest_path)) tmp_manifest_path = manifest_path <> ".new" File.write!(tmp_manifest_path, :erlang.term_to_binary(manifest_data, compressed: 9)) File.rename(tmp_manifest_path, manifest_path) File.touch!(manifest_path, timestamp) JsonRpc.log_message(:info, "[ElixirLS Dialyzer] Done writing manifest.") end) end def read(root_path) do manifest_path = manifest_path(root_path) timestamp = normalize_timestamp(Mix.Utils.last_modified(manifest_path)) { @manifest_vsn, mod_deps, md5, warnings, info_list, types_list, contracts_list, callbacks_list, exported_types_list } = File.read!(manifest_path) |> :erlang.binary_to_term() plt( info: info, types: types, contracts: contracts, callbacks: callbacks, exported_types: exported_types ) = active_plt = :dialyzer_plt.new() for item <- info_list, do: :ets.insert(info, item) for item <- types_list, do: :ets.insert(types, item) for item <- contracts_list, do: :ets.insert(contracts, item) for item <- callbacks_list, do: :ets.insert(callbacks, item) for item <- exported_types_list, do: :ets.insert(exported_types, item) {:ok, active_plt, mod_deps, md5, warnings, timestamp} rescue _ -> :error end def load_elixir_plt() do :dialyzer_plt.from_file(to_charlist(elixir_plt_path())) rescue _ -> build_elixir_plt() catch _ -> build_elixir_plt() end def elixir_plt_path() do Path.join([Mix.Utils.mix_home(), "elixir-ls-#{otp_vsn()}_elixir-#{System.version()}"]) end defp build_elixir_plt() do JsonRpc.show_message(:info, "Building core Elixir PLT. This will take a few minutes.") files = Path.join([Application.app_dir(:elixir), "**/*.beam"]) |> Path.wildcard() |> Enum.map(&pathname_to_module/1) |> expand_references() |> Enum.map(&:code.which/1) |> Enum.filter(&is_list/1) File.mkdir_p!(Path.dirname(elixir_plt_path())) :dialyzer.run( analysis_type: :plt_build, files: files, from: :byte_code, output_plt: to_charlist(elixir_plt_path()) ) JsonRpc.show_message(:info, "Saved Elixir PLT to #{elixir_plt_path()}") :dialyzer_plt.from_file(to_charlist(elixir_plt_path())) end defp otp_vsn() do major = :erlang.system_info(:otp_release) |> List.to_string() vsn_file = Path.join([:code.root_dir(), "releases", major, "OTP_VERSION"]) try do {:ok, contents} = File.read(vsn_file) String.split(contents, "\n", trim: true) else [full] -> full _ -> major catch :error, _ -> major end end defp manifest_path(root_path) do Path.join([ root_path, ".elixir_ls/dialyzer_manifest_#{otp_vsn()}_elixir-#{System.version()}_#{Mix.env()}" ]) end defp transfer_plt(active_plt, pid) do plt( info: info, types: types, contracts: contracts, callbacks: callbacks, exported_types: exported_types ) = active_plt for table <- [info, types, contracts, callbacks, exported_types] do :ets.give_away(table, pid, nil) end end end
26.757225
90
0.642255
ff58b84b519d46794168f3af99eaf443f330c823
2,417
ex
Elixir
clients/logging/lib/google_api/logging/v2/model/log_view.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/logging/lib/google_api/logging/v2/model/log_view.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/logging/lib/google_api/logging/v2/model/log_view.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Logging.V2.Model.LogView do @moduledoc """ Describes a view over log entries in a bucket. ## Attributes * `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The creation timestamp of the view. * `description` (*type:* `String.t`, *default:* `nil`) - Describes this view. * `filter` (*type:* `String.t`, *default:* `nil`) - Filter that restricts which log entries in a bucket are visible in this view.Filters are restricted to be a logical AND of ==/!= of any of the following: originating project/folder/organization/billing account. resource type log idFor example:SOURCE("projects/myproject") AND resource.type = "gce_instance" AND LOG_ID("stdout") * `name` (*type:* `String.t`, *default:* `nil`) - The resource name of the view.For example:projects/my-project/locations/global/buckets/my-bucket/views/my-view * `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The last update timestamp of the view. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :createTime => DateTime.t() | nil, :description => String.t() | nil, :filter => String.t() | nil, :name => String.t() | nil, :updateTime => DateTime.t() | nil } field(:createTime, as: DateTime) field(:description) field(:filter) field(:name) field(:updateTime, as: DateTime) end defimpl Poison.Decoder, for: GoogleApi.Logging.V2.Model.LogView do def decode(value, options) do GoogleApi.Logging.V2.Model.LogView.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Logging.V2.Model.LogView do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.966102
383
0.701696
ff590c80faedc95ba1532599d267aa5689c3e081
222
exs
Elixir
observer/payroll.exs
joshnuss/design-patterns-in-elixir
7f07cae0701ad460b6b275e382fad03324656989
[ "MIT" ]
516
2015-09-25T18:43:37.000Z
2022-03-22T16:33:08.000Z
observer/payroll.exs
joshnuss/design-patterns-in-elixir
7f07cae0701ad460b6b275e382fad03324656989
[ "MIT" ]
2
2017-10-01T22:33:34.000Z
2019-02-21T18:21:54.000Z
observer/payroll.exs
joshnuss/design-patterns-in-elixir
7f07cae0701ad460b6b275e382fad03324656989
[ "MIT" ]
52
2015-11-15T05:58:45.000Z
2022-01-21T20:01:17.000Z
defmodule Payroll do use GenEvent def handle_event({:changed, employee}, state) do IO.puts("Cut a new check for #{employee.name}!") IO.puts("His salary is now #{employee.salary}!") {:ok, state} end end
20.181818
52
0.657658
ff5941205ebee4c6d5272b112220aaef594bbeb3
1,231
exs
Elixir
config/prod.secret.exs
calleluks/ex-remit
893dbc42c9ace6db6ee044f82371075198089fdc
[ "MIT" ]
null
null
null
config/prod.secret.exs
calleluks/ex-remit
893dbc42c9ace6db6ee044f82371075198089fdc
[ "MIT" ]
null
null
null
config/prod.secret.exs
calleluks/ex-remit
893dbc42c9ace6db6ee044f82371075198089fdc
[ "MIT" ]
null
null
null
# In this file, we load production configuration and secrets # from environment variables. You can also hardcode secrets, # although such is generally not recommended and you have to # remember to add this file to your .gitignore. use Mix.Config database_url = System.get_env("DATABASE_URL") || raise """ environment variable DATABASE_URL is missing. For example: ecto://USER:PASS@HOST/DATABASE """ config :remit, Remit.Repo, ssl: true, url: database_url, pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10") secret_key_base = System.get_env("SECRET_KEY_BASE") || raise """ environment variable SECRET_KEY_BASE is missing. You can generate one by calling: mix phx.gen.secret """ config :remit, RemitWeb.Endpoint, http: [ port: String.to_integer(System.get_env("PORT") || "4000"), transport_options: [socket_opts: [:inet6]] ], secret_key_base: secret_key_base # ## Using releases (Elixir v1.9+) # # If you are doing OTP releases, you need to instruct Phoenix # to start each relevant endpoint: # # config :remit, RemitWeb.Endpoint, server: true # # Then you can assemble a release by calling `mix release`. # See `mix help release` for more information.
29.309524
67
0.717303
ff594c3ce486fd07d5c1a8bd6d48913d26dea0ec
581
exs
Elixir
test/bs/movement_test.exs
andersjanmyr/battlesnake-server-2018
091b4d1201d144de232be08fd7fb6df8156c5ee2
[ "MIT" ]
3
2018-07-14T22:55:23.000Z
2019-02-25T06:11:55.000Z
test/bs/movement_test.exs
andersjanmyr/battlesnake-server-2018
091b4d1201d144de232be08fd7fb6df8156c5ee2
[ "MIT" ]
7
2020-02-12T03:22:59.000Z
2022-02-10T20:23:52.000Z
test/bs/movement_test.exs
andersjanmyr/battlesnake-server-2018
091b4d1201d144de232be08fd7fb6df8156c5ee2
[ "MIT" ]
12
2018-03-27T05:27:20.000Z
2019-04-02T08:19:04.000Z
defmodule Bs.MovementTest do alias Bs.Movement use Bs.Case, async: false use Bs.Point import Map import List @moduletag :capture_log test ".next updates snake locations" do actual = build(:world, snakes: [build(:snake, url: "down.mock")]) |> Movement.next() assert [p(0, 1)] = actual.snakes |> first() |> get(:coords) end test ".next provides a default" do actual = build(:world, snakes: [build(:snake, url: "invalid.mock")]) |> Movement.next() assert [p(0, -1)] = actual.snakes |> first() |> get(:coords) end end
20.75
65
0.614458
ff5961e445825b5465400a8cb13436c079ea1eec
9,527
ex
Elixir
lib/clustered_case.ex
hewsut/ex_unit_clustered_case
7762c0a0cce1c78703a1955ce9bc89c0ff9d2f88
[ "Apache-2.0" ]
48
2018-07-20T20:19:23.000Z
2021-11-10T09:22:52.000Z
lib/clustered_case.ex
hewsut/ex_unit_clustered_case
7762c0a0cce1c78703a1955ce9bc89c0ff9d2f88
[ "Apache-2.0" ]
9
2018-07-20T19:02:07.000Z
2019-07-29T05:23:38.000Z
lib/clustered_case.ex
hewsut/ex_unit_clustered_case
7762c0a0cce1c78703a1955ce9bc89c0ff9d2f88
[ "Apache-2.0" ]
7
2018-07-30T02:13:59.000Z
2019-12-11T15:28:47.000Z
defmodule ExUnit.ClusteredCase do @moduledoc """ Helpers for defining clustered test cases. Use this in place of `ExUnit.Case` when defining test modules where you will be defining clustered tests. `#{__MODULE__}` extends `ExUnit.Case` to provide additional helpers for those tests. Since `#{__MODULE__}` is an extension of `ExUnit.Case`, it takes the same options, and imports the same test helpers and callbacks. It adds new helpers, `scenario/3`, `node_setup/1`, and `node_setup/2`, and aliases the `#{__MODULE__.Cluster}` module for convenience. ## Examples defmodule KVStoreTests do # Use the module use ExUnit.ClusteredCase # Define a clustered scenario scenario "given a healthy cluster", [cluster_size: 3] do # Set up each node in the cluster prior to each test node_setup do {:ok, _} = Application.ensure_all_started(:kv_store) end # Define a test to run in this scenario test "always pass" do assert true end end end ## Context All tests receive a context as an argument, just like with `ExUnit.Case`, the primary difference to be aware of is that the context contains a key, `:cluster`, which is the pid of the cluster manager, and is used to invoke functions in the `#{__MODULE__}.Cluster` module during tests. defmodule KVStoreTests do use ExUnit.ClusteredCase scenario "given a healthy cluster", [cluster_size: 3] do # You can use normal setup functions to setup context for the # test, this is run once prior to each test setup do {:ok, foo: :bar} end # Like `setup`, but is run on all nodes prior to each test node_setup do {:ok, _} = Application.ensure_all_started(:kv_store) end test "cluster has three nodes", %{cluster: c} = context do assert length(Cluster.members(c)) == 3 end end end See the `ExUnit.Case` documentation for information on tags, filters, and more. """ @doc false defmacro __using__(opts \\ []) do quote do @__clustered_case_scenario nil use ExUnit.Case, unquote(opts) alias unquote(__MODULE__).Cluster import unquote(__MODULE__), only: [scenario: 3, node_setup: 1, node_setup: 2] setup_all do on_exit(fn -> unquote(__MODULE__).Cluster.Supervisor.cleanup_clusters_for_test_module(__MODULE__) end) end end end @doc """ Creates a new clustered test scenario. Usage of this macro is similar to that of `ExUnit.Case.describe/2`, but has some differences. While `describe/2` simply groups tests under a common description, `scenario/3` both describes the group of tests, and initializes a cluster which will be made available for each test in that scenario. NOTE: It is important to be aware that each scenario is a distinct cluster, and that all tests within a single scenario are running against the same cluster. If tests within a scenario may conflict with one another - perhaps by modifying shared state, or triggering crashes which may bring down shared processes, etc., then you have a couple options: - Disable async testing for the module - Modify your tests to prevent conflict, e.g. writing to different keys in a k/v store, rather than the same key - Split the scenario into many, where the tests can run in isolation. ## Options You can configure a scenario with the following options: - `cluster_size: integer`, will create a cluster of the given size, this option is mutually exclusive with `:nodes`, if the latter is used, this option will be ignored. - `nodes: [[node_opt]]`, a list of node specifications to use when creating the cluster, see `t:#{__MODULE__}.Node.node_opt/0` for specific options available. If used, `:cluster_size` is ignored. - `env: [{String.t, String.t}]`, will set the given key/values in the environment when creating nodes. If you need different values for each node, you will need to use `:nodes` - `erl_flags: [String.t]`, additional arguments to pass to `erl` when creating nodes, like `:env`, if you need different args for each node, you will need to use `:nodes` - `config: Keyword.t`, configuration overrides to apply to all nodes in the cluster - `boot_timeout: integer`, the amount of time to allow for nodes to boot, in milliseconds - `init_timeout: integer`, the amount of time to allow for nodes to be initialized, in milliseconds ## Examples defmodule KVStoreTest do use ExUnit.ClusteredCase @scenario_opts [cluster_size: 3] scenario "given a healthy cluster", @scenario_opts do node_setup do {:ok, _} = Application.ensure_all_started(:kv_store) end test "writes are replicated to all nodes", %{cluster: cluster} do writer = Cluster.random_member(cluster) key = self() value = key assert Cluster.call(writer, KVStore, :put, [key, value]) == :ok results = Cluster.map(cluster, KVStore, :get, [key]) assert Enum.all?(results, fn val -> val == value end) end end end Since all scenarios are also describes, you can run all the tests for a scenario by it's description: mix test --only describe:"given a healthy cluster" or by passing the exact line the scenario starts on: mix test path/to/file:123 Like `describe/2`, you cannot nest `scenario/3`. Use the same technique of named setups recommended in the `describe/2` documentation for composition. """ defmacro scenario(message, options, do: block) do quote do if @__clustered_case_scenario do raise "cannot call scenario/2 inside another scenario. See the documentation " <> "for scenario/2 on named setups and how to handle hierarchies" end message = unquote(message) options = unquote(options) @__clustered_case_scenario message @__clustered_case_scenario_config options try do describe message do setup context do alias unquote(__MODULE__).Cluster.Supervisor, as: CS # Start cluster if not started {:ok, cluster} = CS.init_cluster_for_scenario!( __MODULE__, @__clustered_case_scenario, @__clustered_case_scenario_config ) Map.put(context, :cluster, cluster) end unquote(block) end after @__clustered_case_scenario nil @__clustered_case_scenario_config nil end end end @doc """ Like `ExUnit.Callbacks.setup/1`, but is executed on every node in the cluster. You can pass a block, a unary function as an atom, or a list of such atoms. If you pass a unary function, it receives the test setup context, however unlike `setup/1`, the value returned from this function does not modify the context. Use `setup/1` or `setup/2` for that. NOTE: This callback is invoked _on_ each node in the cluster for the given scenario. ## Examples def start_apps(_context) do {:ok, _} = Application.ensure_all_started(:kv_store) :ok end scenario "given a healthy cluster", [cluster_size: 3] do node_setup :start_apps node_setup do # This form is also acceptable {:ok, _} = Application.ensure_all_started(:kv_store) end end """ defmacro node_setup(do: block) do quote do setup %{cluster: cluster} = context do results = unquote(__MODULE__).Cluster.map(cluster, fn -> unquote(block) end) case results do {:error, _} = err -> exit(err) _ -> :ok end context end end end defmacro node_setup(callback) when is_atom(callback) do quote do setup %{cluster: cluster} = context do results = unquote(__MODULE__).Cluster.map(cluster, __MODULE__, unquote(callback), [context]) case results do {:error, _} = err -> exit(err) _ -> :ok end context end end end defmacro node_setup(callbacks) when is_list(callbacks) do quote bind_quoted: [callbacks: callbacks] do for cb <- callbacks do unless is_atom(cb) do raise ArgumentError, "expected list of callbacks as atoms, but got: #{callbacks}" end node_setup(cb) end end end @doc """ Same as `node_setup/1`, but receives the test setup context as a parameter. ## Examples scenario "given a healthy cluster", [cluster_size: 3] do node_setup _context do # Do something on each node end end """ defmacro node_setup(var, do: block) do quote do setup %{cluster: cluster} = context do result = unquote(__MODULE__).Cluster.each(cluster, fn -> case context do unquote(var) -> unquote(block) end end) case result do {:error, _} = err -> exit(err) end context end end end end
31.133987
101
0.630419
ff598cd0ba0740ceede51fde2e880ba1ea6c69b6
2,785
exs
Elixir
installer/templates/phx_single/config/runtime.exs
nelsonmestevao/phoenix
6a705dec3f46b5c6ac8f55c9df4e406f59619ebe
[ "MIT" ]
null
null
null
installer/templates/phx_single/config/runtime.exs
nelsonmestevao/phoenix
6a705dec3f46b5c6ac8f55c9df4e406f59619ebe
[ "MIT" ]
null
null
null
installer/templates/phx_single/config/runtime.exs
nelsonmestevao/phoenix
6a705dec3f46b5c6ac8f55c9df4e406f59619ebe
[ "MIT" ]
null
null
null
import Config # config/runtime.exs is executed for all environments, including # during releases. It is executed after compilation and before the # system starts, so it is typically used to load production configuration # and secrets from environment variables or elsewhere. Do not define # any compile-time configuration in here, as it won't be applied. # The block below contains prod specific runtime configuration. # ## Using releases # # If you use `mix release`, you need to explicitly enable the server # by passing the PHX_SERVER=true when you start it: # # PHX_SERVER=true bin/<%= @app_name %> start # # Alternatively, you can use `mix phx.gen.release` to generate a `bin/server` # script that automatically sets the env var above. if System.get_env("PHX_SERVER") do config :<%= @app_name %>, <%= @endpoint_module %>, server: true end if config_env() == :prod do # The secret key base is used to sign/encrypt cookies and other secrets. # A default value is used in config/dev.exs and config/test.exs but you # want to use a different value for prod and you most likely don't want # to check this value into version control, so we use an environment # variable instead. secret_key_base = System.get_env("SECRET_KEY_BASE") || raise """ environment variable SECRET_KEY_BASE is missing. You can generate one by calling: mix phx.gen.secret """ host = System.get_env("PHX_HOST") || "example.com" port = String.to_integer(System.get_env("PORT") || "4000") config :<%= @app_name %>, <%= @endpoint_module %>, url: [host: host, port: 443, scheme: "https"], http: [ # Enable IPv6 and bind on all interfaces. # Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access. # See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html # for details about using IPv6 vs IPv4 and loopback vs public addresses. ip: {0, 0, 0, 0, 0, 0, 0, 0}, port: port ], secret_key_base: secret_key_base # ## Configuring the mailer # # In production you need to configure the mailer to use a different adapter. # Also, you may need to configure the Swoosh API client of your choice if you # are not using SMTP. Here is an example of the configuration: # # config :<%= @app_name %>, <%= @app_module %>.Mailer, # adapter: Swoosh.Adapters.Mailgun, # api_key: System.get_env("MAILGUN_API_KEY"), # domain: System.get_env("MAILGUN_DOMAIN") # # For this example you need include a HTTP client required by Swoosh API client. # Swoosh supports Hackney and Finch out of the box: # # config :swoosh, :api_client, Swoosh.ApiClient.Hackney # # See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details.<% end %> end
40.362319
87
0.694075
ff59b167c704f571114b16fbb9ed53de8ef01c94
438
exs
Elixir
priv/repo/seeds.exs
DianaOlympos/remote_test
e222d4e937789871baab3a7b4fd8428b714c1af4
[ "MIT" ]
1
2020-09-18T03:32:45.000Z
2020-09-18T03:32:45.000Z
priv/repo/seeds.exs
DianaOlympos/remote_test
e222d4e937789871baab3a7b4fd8428b714c1af4
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
DianaOlympos/remote_test
e222d4e937789871baab3a7b4fd8428b714c1af4
[ "MIT" ]
null
null
null
# Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # RemotePoints.Repo.insert!(%RemotePoints.SomeSchema{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong. for _n <- 0..99, do: RemotePoints.Repo.insert!(%RemotePoints.Points.User{})
31.285714
75
0.712329
ff59b2eda3dd3b804bcd5c6e7e6245ae84485bb9
3,607
ex
Elixir
lib/sanbase_web/graphql/schema/types/social_data_types.ex
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
81
2017-11-20T01:20:22.000Z
2022-03-05T12:04:25.000Z
lib/sanbase_web/graphql/schema/types/social_data_types.ex
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
359
2017-10-15T14:40:53.000Z
2022-01-25T13:34:20.000Z
lib/sanbase_web/graphql/schema/types/social_data_types.ex
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
16
2017-11-19T13:57:40.000Z
2022-02-07T08:13:02.000Z
defmodule SanbaseWeb.Graphql.SocialDataTypes do use Absinthe.Schema.Notation alias SanbaseWeb.Graphql.Resolvers.SocialDataResolver import SanbaseWeb.Graphql.Cache, only: [cache_resolve: 1] enum :trending_words_sources do value(:telegram) value(:twitter) value(:bitcointalk) value(:reddit) value(:all) end enum :social_dominance_sources do value(:telegram) value(:professional_traders_chat) value(:reddit) value(:discord) value(:all) end enum :social_gainers_losers_status_enum do value(:gainer) value(:loser) value(:newcomer) value(:all) end enum :social_volume_type do value(:reddit_comments_overview) value(:professional_traders_chat_overview) value(:telegram_chats_overview) value(:telegram_discussion_overview) value(:discord_discussion_overview) value(:discord_chats_overview) end enum :topic_search_sources do value(:telegram) value(:professional_traders_chat) value(:reddit) value(:discord) end object :popular_search_term do field(:title, non_null(:string)) field(:options, :json) field(:datetime, non_null(:datetime)) field(:search_term, non_null(:string)) field(:selector_type, non_null(:string)) field(:updated_at, :datetime) field :created_at, non_null(:datetime) do resolve(fn %{inserted_at: inserted_at}, _, _ -> {:ok, inserted_at} end) end end object :topic_search do field(:chart_data, list_of(:chart_data)) end object :messages do field(:text, :string) field(:datetime, non_null(:datetime)) end object :chart_data do field(:mentions_count, :float) field(:datetime, non_null(:datetime)) end object :social_volume do field(:datetime, non_null(:datetime)) field(:mentions_count, :integer) end object :social_dominance do field(:datetime, non_null(:datetime)) field(:dominance, :float) end object :trending_words do field(:datetime, non_null(:datetime)) field(:top_words, list_of(:word_with_context)) end object :trending_word_position do field(:datetime, non_null(:datetime)) field(:position, :integer) end object :word_with_context do field :context, list_of(:word_context) do cache_resolve(&SocialDataResolver.word_context/3) end field(:score, :float) field(:word, :string) end object :word_trend_score do field(:datetime, non_null(:datetime)) field(:score, non_null(:float)) field(:source, :trending_words_sources) end object :word_context do field(:word, non_null(:string)) field(:score, non_null(:float)) end object :words_context do field(:word, non_null(:string)) field(:context, list_of(:word_context)) end object :words_social_volume do field(:word, non_null(:string)) field(:timeseries_data, list_of(:social_volume)) end object :top_social_gainers_losers do field(:datetime, non_null(:datetime)) field(:projects, list_of(:projects_change)) end object :projects_change do field(:slug, non_null(:string)) field :project, :project do cache_resolve(&SocialDataResolver.project_from_slug/3) end field(:change, non_null(:float)) field(:status, :social_gainers_losers_status_enum) end object :social_gainers_losers_status do field(:datetime, non_null(:datetime)) field(:change, non_null(:float)) field(:status, :social_gainers_losers_status_enum) end input_object :word_selector_input_object do field(:word, :string) field(:words, list_of(:string)) end end
23.730263
60
0.705295
ff59bf6f311e62db16d063f78378d09e40e6be1b
3,063
ex
Elixir
clients/spanner/lib/google_api/spanner/v1/model/partition_read_request.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/spanner/lib/google_api/spanner/v1/model/partition_read_request.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/spanner/lib/google_api/spanner/v1/model/partition_read_request.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Spanner.V1.Model.PartitionReadRequest do @moduledoc """ The request for PartitionRead ## Attributes - columns ([String.t]): The columns of table to be returned for each row matching this request. Defaults to: `null`. - index (String.t): If non-empty, the name of an index on table. This index is used instead of the table primary key when interpreting key_set and sorting result rows. See key_set for further information. Defaults to: `null`. - keySet (KeySet): Required. &#x60;key_set&#x60; identifies the rows to be yielded. &#x60;key_set&#x60; names the primary keys of the rows in table to be yielded, unless index is present. If index is present, then key_set instead names index keys in index. It is not an error for the &#x60;key_set&#x60; to name rows that do not exist in the database. Read yields nothing for nonexistent rows. Defaults to: `null`. - partitionOptions (PartitionOptions): Additional options that affect how many partitions are created. Defaults to: `null`. - table (String.t): Required. The name of the table in the database to be read. Defaults to: `null`. - transaction (TransactionSelector): Read only snapshot transactions are supported, read/write and single use transactions are not. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :columns => list(any()), :index => any(), :keySet => GoogleApi.Spanner.V1.Model.KeySet.t(), :partitionOptions => GoogleApi.Spanner.V1.Model.PartitionOptions.t(), :table => any(), :transaction => GoogleApi.Spanner.V1.Model.TransactionSelector.t() } field(:columns, type: :list) field(:index) field(:keySet, as: GoogleApi.Spanner.V1.Model.KeySet) field(:partitionOptions, as: GoogleApi.Spanner.V1.Model.PartitionOptions) field(:table) field(:transaction, as: GoogleApi.Spanner.V1.Model.TransactionSelector) end defimpl Poison.Decoder, for: GoogleApi.Spanner.V1.Model.PartitionReadRequest do def decode(value, options) do GoogleApi.Spanner.V1.Model.PartitionReadRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Spanner.V1.Model.PartitionReadRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
48.619048
417
0.739471
ff59d145a1fadb160494db1c069d6ef3295eedce
1,026
ex
Elixir
lib/roshambo_web/plugs/game_plug.ex
xaviRodri/roshambo
7cfd465cc40a7dc405c2854e9135f516df3809bd
[ "MIT" ]
null
null
null
lib/roshambo_web/plugs/game_plug.ex
xaviRodri/roshambo
7cfd465cc40a7dc405c2854e9135f516df3809bd
[ "MIT" ]
null
null
null
lib/roshambo_web/plugs/game_plug.ex
xaviRodri/roshambo
7cfd465cc40a7dc405c2854e9135f516df3809bd
[ "MIT" ]
null
null
null
defmodule RoshamboWeb.Plugs.GamePlug do use Plug.Builder def call(conn, opts) do conn |> super(opts) |> fetch_cookies(signed: ["roshambo-game"]) |> maybe_assign_game_id end # Both the game_id stored in the cookies and the one in the params must be the same defp maybe_assign_game_id( %{ cookies: %{"roshambo-game" => %{game_id: game_id, player: player}}, params: %{"game_id" => game_id} } = conn ), do: conn |> assign(:game_id, game_id) |> assign(:player, player) defp maybe_assign_game_id(%{params: %{"game_id" => game_id}} = conn) do with true <- Roshambo.game_exists?(game_id), {:ok, _game, player} <- Roshambo.add_random_player(game_id) do conn |> assign(:game_id, game_id) |> assign(:player, player) |> put_resp_cookie("roshambo-game", %{game_id: game_id, player: player}, sign: true) else false -> put_status(conn, 404) {:error, :is_full} -> put_status(conn, 403) end end end
31.090909
90
0.616959
ff59f612c6ca75b8a2df25aabd9b0cf3d7f4ca3a
565
ex
Elixir
examples/swagger_demo/web/views/changeset_view.ex
Whatnot-Inc/bureaucrat
d0634c6017dc68f8a23078cbc8c181a4b2d3e6db
[ "Unlicense" ]
326
2015-08-19T10:05:07.000Z
2022-03-28T08:49:33.000Z
examples/swagger_demo/web/views/changeset_view.ex
Whatnot-Inc/bureaucrat
d0634c6017dc68f8a23078cbc8c181a4b2d3e6db
[ "Unlicense" ]
64
2015-08-19T06:44:19.000Z
2022-03-29T06:23:34.000Z
examples/swagger_demo/web/views/changeset_view.ex
Whatnot-Inc/bureaucrat
d0634c6017dc68f8a23078cbc8c181a4b2d3e6db
[ "Unlicense" ]
66
2016-01-08T20:40:40.000Z
2022-03-03T02:15:15.000Z
defmodule SwaggerDemo.ChangesetView do use SwaggerDemo.Web, :view @doc """ Traverses and translates changeset errors. See `Ecto.Changeset.traverse_errors/2` and `SwaggerDemo.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
28.25
65
0.739823
ff5a601b633fc8e28c76846e46d12742ab670553
235
exs
Elixir
community/betterdev/priv/repo/migrations/20170611062313_create_community_link.exs
earthrid/betterdev.link
b8efe279e82810075ba36673483f7f4d6862bc19
[ "MIT" ]
79
2017-07-03T13:04:08.000Z
2022-02-11T13:59:37.000Z
community/betterdev/priv/repo/migrations/20170611062313_create_community_link.exs
earthrid/betterdev.link
b8efe279e82810075ba36673483f7f4d6862bc19
[ "MIT" ]
16
2017-07-09T03:16:27.000Z
2022-01-14T14:29:57.000Z
community/betterdev/priv/repo/migrations/20170611062313_create_community_link.exs
earthrid/betterdev.link
b8efe279e82810075ba36673483f7f4d6862bc19
[ "MIT" ]
10
2017-07-09T02:58:59.000Z
2021-09-14T08:01:02.000Z
defmodule Betterdev.Repo.Migrations.CreateBetterdev.Community.Link do use Ecto.Migration def change do create table(:community_links) do add :title, :string add :uri, :string timestamps() end end end
16.785714
69
0.689362
ff5a61ee4f8931cd195f7a3860ef2cdb705fe981
861
ex
Elixir
lib/teiserver/telemetry/schemas/client_property.ex
icexuick/teiserver
22f2e255e7e21f977e6b262acf439803626a506c
[ "MIT" ]
6
2021-02-08T10:42:53.000Z
2021-04-25T12:12:03.000Z
lib/teiserver/telemetry/schemas/client_property.ex
icexuick/teiserver
22f2e255e7e21f977e6b262acf439803626a506c
[ "MIT" ]
14
2021-08-01T02:36:14.000Z
2022-01-30T21:15:03.000Z
lib/teiserver/telemetry/schemas/client_property.ex
icexuick/teiserver
22f2e255e7e21f977e6b262acf439803626a506c
[ "MIT" ]
7
2021-05-13T12:55:28.000Z
2022-01-14T06:39:06.000Z
defmodule Teiserver.Telemetry.ClientProperty do use CentralWeb, :schema @primary_key false schema "teiserver_telemetry_client_properties" do belongs_to :user, Central.Account.User, primary_key: true belongs_to :property_type, Teiserver.Telemetry.PropertyType, primary_key: true field :last_updated, :utc_datetime field :value, :string end @doc """ Builds a changeset based on the `struct` and `params`. """ @spec changeset(Map.t(), Map.t()) :: Ecto.Changeset.t() def changeset(struct, params \\ %{}) do struct |> cast(params, [:user_id, :property_type_id, :last_updated, :value]) |> validate_required([:user_id, :property_type_id, :last_updated, :value]) end @spec authorize(atom, Plug.Conn.t(), Map.t()) :: boolean def authorize(_action, conn, _params), do: allow?(conn, "teiserver.admin.telemetry") end
33.115385
86
0.70964
ff5a83943cab3f14970688af78fcd042ff3fd675
241
ex
Elixir
server/web/controllers/page_controller.ex
CircleAcademy/circle-website
b519e1e7c1d90566b7dfdaeda20ddd71abf6c832
[ "MIT" ]
null
null
null
server/web/controllers/page_controller.ex
CircleAcademy/circle-website
b519e1e7c1d90566b7dfdaeda20ddd71abf6c832
[ "MIT" ]
null
null
null
server/web/controllers/page_controller.ex
CircleAcademy/circle-website
b519e1e7c1d90566b7dfdaeda20ddd71abf6c832
[ "MIT" ]
null
null
null
defmodule Website.PageController do use Website.Web, :controller def index(conn, _params) do conn |> put_resp_header("content-type", "text/html; charset=utf-8") |> Plug.Conn.send_file(200, "priv/dist/index.html") end end
21.909091
66
0.697095
ff5aa32a808269c189dd114d249c33fa3622398b
34,951
exs
Elixir
lib/elixir/test/elixir/kernel/errors_test.exs
NJichev/elixir
aef81d1aadfd9522ab4efb6d04103a73584ac9a1
[ "Apache-2.0" ]
2
2018-11-15T06:38:14.000Z
2018-11-17T18:03:14.000Z
lib/elixir/test/elixir/kernel/errors_test.exs
NJichev/elixir
aef81d1aadfd9522ab4efb6d04103a73584ac9a1
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/kernel/errors_test.exs
NJichev/elixir
aef81d1aadfd9522ab4efb6d04103a73584ac9a1
[ "Apache-2.0" ]
null
null
null
Code.require_file("../test_helper.exs", __DIR__) defmodule Kernel.ErrorsTest do use ExUnit.Case, async: true defmacro hello do quote location: :keep do def hello, do: :world end end test "no optional arguments in fn" do assert_eval_raise CompileError, "nofile:1: anonymous functions cannot have optional arguments", 'fn x \\\\ 1 -> x end' assert_eval_raise CompileError, "nofile:1: anonymous functions cannot have optional arguments", 'fn x, y \\\\ 1 -> x + y end' end test "invalid fn" do assert_eval_raise SyntaxError, "nofile:1: expected anonymous functions to be defined with -> inside: 'fn'", 'fn 1 end' assert_eval_raise SyntaxError, ~r"nofile:2: unexpected operator ->. If you want to define multiple clauses, ", 'fn 1\n2 -> 3 end' end test "invalid token" do assert_eval_raise SyntaxError, "nofile:1: unexpected token: \"\u200B\" (column 7, codepoint U+200B)", '[foo: \u200B]\noops' end test "reserved tokens" do assert_eval_raise SyntaxError, "nofile:1: reserved token: __aliases__", '__aliases__' assert_eval_raise SyntaxError, "nofile:1: reserved token: __block__", '__block__' end test "invalid __CALLER__" do assert_eval_raise CompileError, "nofile:1: __CALLER__ is available only inside defmacro and defmacrop", 'defmodule Sample do def hello do __CALLER__ end end' end test "invalid __STACKTRACE__" do assert_eval_raise CompileError, "nofile:1: __STACKTRACE__ is available only inside catch and rescue clauses of try expressions", 'defmodule Sample do def hello do __STACKTRACE__ end end' assert_eval_raise CompileError, "nofile:1: __STACKTRACE__ is available only inside catch and rescue clauses of try expressions", 'defmodule Sample do try do raise "oops" rescue _ -> def hello do __STACKTRACE__ end end end' end test "invalid quoted token" do assert_eval_raise SyntaxError, "nofile:1: syntax error before: \"world\"", '"hello" "world"' assert_eval_raise SyntaxError, "nofile:1: syntax error before: 'Foobar'", '1 Foobar' assert_eval_raise SyntaxError, "nofile:1: syntax error before: foo", 'Foo.:foo' assert_eval_raise SyntaxError, "nofile:1: syntax error before: \"foo\"", 'Foo.:"foo\#{:bar}"' assert_eval_raise SyntaxError, "nofile:1: syntax error before: \"", 'Foo.:"\#{:bar}"' end test "invalid identifier" do message = fn name -> "nofile:1: invalid character \"@\" (codepoint U+0040) in identifier: #{name}" end assert_eval_raise SyntaxError, message.("foo@"), 'foo@' assert_eval_raise SyntaxError, message.("foo@"), 'foo@ ' assert_eval_raise SyntaxError, message.("foo@bar"), 'foo@bar' message = fn name -> "nofile:1: invalid character \"@\" (codepoint U+0040) in alias: #{name}" end assert_eval_raise SyntaxError, message.("Foo@"), 'Foo@' assert_eval_raise SyntaxError, message.("Foo@bar"), 'Foo@bar' message = "nofile:1: invalid character \"!\" (codepoint U+0021) in alias: Foo!" assert_eval_raise SyntaxError, message, 'Foo!' message = "nofile:1: invalid character \"?\" (codepoint U+003F) in alias: Foo?" assert_eval_raise SyntaxError, message, 'Foo?' message = "nofile:1: invalid character \"ó\" (codepoint U+00F3) in alias (only ascii characters are allowed): Foó" assert_eval_raise SyntaxError, message, 'Foó' message = ~r""" Elixir expects unquoted Unicode atoms, variables, and calls to be in NFC form. Got: "foó" \(codepoints 0066 006F 006F 0301\) Expected: "foó" \(codepoints 0066 006F 00F3\) """ assert_eval_raise SyntaxError, message, :unicode.characters_to_nfd_list("foó") end test "kw missing space" do msg = "nofile:1: keyword argument must be followed by space after: foo:" assert_eval_raise SyntaxError, msg, "foo:bar" assert_eval_raise SyntaxError, msg, "foo:+" assert_eval_raise SyntaxError, msg, "foo:+1" end test "invalid map start" do assert_eval_raise SyntaxError, "nofile:1: expected %{ to define a map, got: %[", "{:ok, %[], %{}}" end test "sigil terminator" do assert_eval_raise TokenMissingError, "nofile:3: missing terminator: \" (for sigil ~r\" starting at line 1)", '~r"foo\n\n' assert_eval_raise TokenMissingError, "nofile:3: missing terminator: } (for sigil ~r{ starting at line 1)", '~r{foo\n\n' end test "dot terminator" do assert_eval_raise TokenMissingError, "nofile:1: missing terminator: \" (for function name starting at line 1)", 'foo."bar' end test "string terminator" do assert_eval_raise TokenMissingError, "nofile:1: missing terminator: \" (for string starting at line 1)", '"bar' end test "heredoc start" do assert_eval_raise SyntaxError, "nofile:1: heredoc start must be followed by a new line after \"\"\"", '"""bar\n"""' end test "heredoc terminator" do assert_eval_raise TokenMissingError, "nofile:2: missing terminator: \"\"\" (for heredoc starting at line 1)", '"""\nbar' assert_eval_raise SyntaxError, "nofile:2: invalid location for heredoc terminator, please escape token or move it to its own line: \"\"\"", '"""\nbar"""' end test "unexpected end" do assert_eval_raise SyntaxError, "nofile:1: unexpected token: end", '1 end' assert_eval_raise SyntaxError, ~r" HINT: it looks like the \"end\" on line 2 does not have a matching \"do\" defined before it", ''' defmodule MyApp do def one end def two do end end ''' assert_eval_raise SyntaxError, ~r" HINT: it looks like the \"end\" on line 3 does not have a matching \"do\" defined before it", ''' defmodule MyApp do def one end def two do end end ''' assert_eval_raise SyntaxError, ~r" HINT: it looks like the \"end\" on line 6 does not have a matching \"do\" defined before it", ''' defmodule MyApp do def one do end def two end end ''' end test "missing end" do assert_eval_raise TokenMissingError, "nofile:1: missing terminator: end (for \"do\" starting at line 1)", 'foo do 1' assert_eval_raise TokenMissingError, ~r"HINT: it looks like the \"do\" on line 2 does not have a matching \"end\"", ''' defmodule MyApp do def one do # end def two do end end ''' assert_eval_raise SyntaxError, ~r"HINT: it looks like the \"do\" on line 3 does not have a matching \"end\"", ''' defmodule MyApp do ( def one do # end def two do end ) end ''' end test "syntax error" do assert_eval_raise SyntaxError, "nofile:1: syntax error before: '.'", '+.foo' end test "syntax error before sigil" do msg = fn x -> "nofile:1: syntax error before: sigil ~s starting with content '#{x}'" end assert_eval_raise SyntaxError, msg.("bar baz"), '~s(foo) ~s(bar baz)' assert_eval_raise SyntaxError, msg.(""), '~s(foo) ~s()' assert_eval_raise SyntaxError, msg.("bar "), '~s(foo) ~s(bar \#{:baz})' assert_eval_raise SyntaxError, msg.(""), '~s(foo) ~s(\#{:bar} baz)' end test "op ambiguity" do max = 1 assert max == 1 assert max(1, 2) == 2 end test "syntax error with do" do assert_eval_raise SyntaxError, ~r/nofile:1: unexpected token: do./, 'if true, do\n' assert_eval_raise SyntaxError, ~r/nofile:1: unexpected keyword: do:./, 'if true do:\n' end test "syntax error on parens call" do msg = "nofile:1: unexpected parentheses. If you are making a function call, do not " <> "insert spaces between the function name and the opening parentheses. " <> "Syntax error before: '('" assert_eval_raise SyntaxError, msg, 'foo (hello, world)' end test "syntax error on nested no parens call" do msg = ~r"nofile:1: unexpected comma. Parentheses are required to solve ambiguity" assert_eval_raise SyntaxError, msg, '[foo 1, 2]' assert_eval_raise SyntaxError, msg, '[foo bar 1, 2]' assert_eval_raise SyntaxError, msg, '[do: foo 1, 2]' assert_eval_raise SyntaxError, msg, 'foo(do: bar 1, 2)' assert_eval_raise SyntaxError, msg, '{foo 1, 2}' assert_eval_raise SyntaxError, msg, '{foo bar 1, 2}' assert_eval_raise SyntaxError, msg, 'foo 1, foo 2, 3' assert_eval_raise SyntaxError, msg, 'foo 1, @bar 3, 4' assert_eval_raise SyntaxError, msg, 'foo 1, 2 + bar 3, 4' assert_eval_raise SyntaxError, msg, 'foo(1, foo 2, 3)' assert is_list(List.flatten([1])) assert is_list(Enum.reverse([3, 2, 1], [4, 5, 6])) assert is_list(Enum.reverse([3, 2, 1], [4, 5, 6])) assert false || is_list(Enum.reverse([3, 2, 1], [4, 5, 6])) assert [List.flatten(List.flatten([1]))] == [[1]] interpret = fn x -> Macro.to_string(Code.string_to_quoted!(x)) end assert interpret.("f 1 + g h 2, 3") == "f(1 + g(h(2, 3)))" assert interpret.("assert [] = TestRepo.all from p in Post, where: p.title in ^[]") == "assert([] = TestRepo.all(from(p in Post, where: p.title() in ^[])))" end test "syntax error on atom dot alias" do msg = "nofile:1: atom cannot be followed by an alias. If the '.' was meant to be " <> "part of the atom's name, the atom name must be quoted. Syntax error before: '.'" assert_eval_raise SyntaxError, msg, ':foo.Bar' assert_eval_raise SyntaxError, msg, ':"+".Bar' end test "syntax error with no token" do assert_eval_raise TokenMissingError, "nofile:1: missing terminator: ) (for \"(\" starting at line 1)", 'case 1 (' end test "clause with defaults" do message = ~r"nofile:3: def hello/1 defines defaults multiple times" assert_eval_raise CompileError, message, ~C''' defmodule Kernel.ErrorsTest.ClauseWithDefaults do def hello(_arg \\ 0) def hello(_arg \\ 1) end ''' assert_eval_raise CompileError, message, ~C''' defmodule Kernel.ErrorsTest.ClauseWithDefaults do def hello(_arg \\ 0), do: nil def hello(_arg \\ 1), do: nil end ''' assert_eval_raise CompileError, message, ~C''' defmodule Kernel.ErrorsTest.ClauseWithDefaults do def hello(_arg \\ 0) def hello(_arg \\ 1), do: nil end ''' assert_eval_raise CompileError, message, ~C''' defmodule Kernel.ErrorsTest.ClauseWithDefaults do def hello(_arg \\ 0), do: nil def hello(_arg \\ 1) end ''' assert_eval_raise CompileError, ~r"nofile:4: undefined function foo/0", ~C''' defmodule Kernel.ErrorsTest.ClauseWithDefaults5 do def hello( foo, bar \\ foo() ) def hello(foo, bar), do: foo + bar end ''' end test "different defs with defaults" do assert_eval_raise CompileError, "nofile:3: def hello/3 defaults conflicts with hello/2", ~C''' defmodule Kernel.ErrorsTest.DifferentDefsWithDefaults1 do def hello(a, b \\ nil), do: a + b def hello(a, b \\ nil, c \\ nil), do: a + b + c end ''' assert_eval_raise CompileError, "nofile:3: def hello/2 conflicts with defaults from hello/3", ~C''' defmodule Kernel.ErrorsTest.DifferentDefsWithDefaults2 do def hello(a, b \\ nil, c \\ nil), do: a + b + c def hello(a, b \\ nil), do: a + b end ''' end test "bad form" do assert_eval_raise CompileError, "nofile:3: undefined function bar/0", ''' defmodule Kernel.ErrorsTest.BadForm do def foo do bar() end end ''' assert_eval_raise CompileError, "nofile:8: undefined function baz/0", ''' defmodule Sample do def foo do bar() end defoverridable [foo: 0] def foo do baz() end end ''' end test "literal on map and struct" do assert_eval_raise SyntaxError, "nofile:1: syntax error before: '}'", '%{:a}' assert_eval_raise SyntaxError, "nofile:1: syntax error before: '}'", '%{{:a, :b}}' assert_eval_raise SyntaxError, "nofile:1: syntax error before: '{'", '%{a, b}{a: :b}' assert_eval_raise CompileError, "nofile:1: expected key-value pairs in a map, got: put_in(foo.bar().baz(), nil)", 'foo = 1; %{put_in(foo.bar.baz, nil), foo}' end test "struct fields on defstruct" do assert_eval_raise ArgumentError, "struct field names must be atoms, got: 1", ''' defmodule Kernel.ErrorsTest.StructFieldsOnDefstruct do defstruct [1, 2, 3] end ''' end test "struct access on body" do assert_eval_raise CompileError, "nofile:3: cannot access struct Kernel.ErrorsTest.StructAccessOnBody, " <> "the struct was not yet defined or the struct " <> "is being accessed in the same context that defines it", ''' defmodule Kernel.ErrorsTest.StructAccessOnBody do defstruct %{name: "Brasilia"} %Kernel.ErrorsTest.StructAccessOnBody{} end ''' end test "struct errors" do assert_eval_raise CompileError, "nofile:1: BadStruct.__struct__/1 is undefined, cannot expand struct BadStruct", '%BadStruct{}' assert_eval_raise CompileError, "nofile:1: BadStruct.__struct__/0 is undefined, cannot expand struct BadStruct", '%BadStruct{} = %{}' defmodule BadStruct do def __struct__ do [] end end assert_eval_raise CompileError, "nofile:1: expected Kernel.ErrorsTest.BadStruct.__struct__/0 to return a map, got: []", '%#{BadStruct}{} = %{}' defmodule GoodStruct do defstruct name: "john" end assert_eval_raise KeyError, "key :age not found", '%#{GoodStruct}{age: 27}' assert_eval_raise CompileError, "nofile:1: unknown key :age for struct Kernel.ErrorsTest.GoodStruct", '%#{GoodStruct}{age: 27} = %{}' end test "name for defmodule" do assert_eval_raise CompileError, "nofile:1: invalid module name: 3", 'defmodule 1 + 2, do: 3' end test "@compile inline with undefined function" do assert_eval_raise CompileError, "nofile:1: inlined function foo/1 undefined", 'defmodule Test do @compile {:inline, foo: 1} end' end test "invalid unquote" do assert_eval_raise CompileError, "nofile:1: unquote called outside quote", 'unquote 1' end test "invalid unquote splicing in oneliners" do assert_eval_raise ArgumentError, "unquote_splicing only works inside arguments and block contexts, " <> "wrap it in parens if you want it to work with one-liners", ''' defmodule Kernel.ErrorsTest.InvalidUnquoteSplicingInOneliners do defmacro oneliner2 do quote do: unquote_splicing 1 end def callme do oneliner2 end end ''' end test "undefined non-local function" do assert_eval_raise CompileError, "nofile:1: undefined function call/2", 'call foo, do: :foo' end test "invalid attribute" do msg = ~r"cannot inject attribute @foo into function/macro because cannot escape " assert_raise ArgumentError, msg, fn -> defmodule InvalidAttribute do @foo fn -> nil end def bar, do: @foo end end end test "typespec attributes set via Module.put_attribute/4" do message = "attributes type, typep, opaque, spec, callback, and macrocallback " <> "must be set directly via the @ notation" for kind <- [:type, :typep, :opaque, :spec, :callback, :macrocallback] do assert_eval_raise ArgumentError, message, """ defmodule PutTypespecAttribute do Module.put_attribute(__MODULE__, #{inspect(kind)}, {}) end """ end end test "invalid struct field value" do msg = ~r"invalid value for struct field baz, cannot escape " assert_raise ArgumentError, msg, fn -> defmodule InvalidStructFieldValue do defstruct baz: fn -> nil end end end end test "match attribute in module" do msg = "invalid write attribute syntax, you probably meant to use: @foo expression" assert_raise ArgumentError, msg, fn -> defmodule MatchAttributeInModule do @foo = 42 end end end test "invalid fn args" do assert_eval_raise TokenMissingError, "nofile:1: missing terminator: end (for \"fn\" starting at line 1)", 'fn 1' end test "invalid escape" do assert_eval_raise TokenMissingError, "nofile:1: invalid escape \\ at end of file", '1 \\' end test "function local conflict" do assert_eval_raise CompileError, "nofile:3: imported Kernel.&&/2 conflicts with local function", ''' defmodule Kernel.ErrorsTest.FunctionLocalConflict do def other, do: 1 && 2 def _ && _, do: :error end ''' end test "macro local conflict" do assert_eval_raise CompileError, "nofile:6: call to local macro &&/2 conflicts with imported Kernel.&&/2, " <> "please rename the local macro or remove the conflicting import", ''' defmodule Kernel.ErrorsTest.MacroLocalConflict do def hello, do: 1 || 2 defmacro _ || _, do: :ok defmacro _ && _, do: :error def world, do: 1 && 2 end ''' end test "macro with undefined local" do assert_eval_raise UndefinedFunctionError, "function Kernel.ErrorsTest.MacroWithUndefinedLocal.unknown/1" <> " is undefined (function not available)", ''' defmodule Kernel.ErrorsTest.MacroWithUndefinedLocal do defmacrop bar, do: unknown(1) def baz, do: bar() end ''' end test "private macro" do assert_eval_raise UndefinedFunctionError, "function Kernel.ErrorsTest.PrivateMacro.foo/0 is undefined (function not available)", ''' defmodule Kernel.ErrorsTest.PrivateMacro do defmacrop foo, do: 1 defmacro bar, do: __MODULE__.foo defmacro baz, do: bar() end ''' end test "function definition with alias" do assert_eval_raise CompileError, "nofile:2: function names should start with lowercase characters or underscore, invalid name Bar", ''' defmodule Kernel.ErrorsTest.FunctionDefinitionWithAlias do def Bar do :baz end end ''' end test "function import conflict" do assert_eval_raise CompileError, "nofile:3: function exit/1 imported from both :erlang and Kernel, call is ambiguous", ''' defmodule Kernel.ErrorsTest.FunctionImportConflict do import :erlang, warn: false def foo, do: exit(:test) end ''' end test "duplicated function on import options" do assert_eval_raise CompileError, "nofile:2: invalid :only option for import, flatten/1 is duplicated", ''' defmodule Kernel.ErrorsTest.DuplicatedFunctionOnImportOnly do import List, only: [flatten: 1, keyfind: 4, flatten: 1] end ''' assert_eval_raise CompileError, "nofile:2: invalid :except option for import, flatten/1 is duplicated", ''' defmodule Kernel.ErrorsTest.DuplicatedFunctionOnImportExcept do import List, except: [flatten: 1, keyfind: 4, flatten: 1] end ''' end test "unrequired macro" do assert_eval_raise CompileError, "nofile:2: you must require Kernel.ErrorsTest before invoking " <> "the macro Kernel.ErrorsTest.hello/0", ''' defmodule Kernel.ErrorsTest.UnrequiredMacro do Kernel.ErrorsTest.hello() end ''' end test "def defmacro clause change" do assert_eval_raise CompileError, "nofile:3: defmacro foo/1 already defined as def", ''' defmodule Kernel.ErrorsTest.DefDefmacroClauseChange do def foo(1), do: 1 defmacro foo(x), do: x end ''' end test "def defp clause change from another file" do assert_eval_raise CompileError, ~r"nofile:4: def hello/0 already defined as defp", ''' defmodule Kernel.ErrorsTest.DefDefmacroClauseChange do require Kernel.ErrorsTest defp hello, do: :world Kernel.ErrorsTest.hello() end ''' end test "internal function overridden" do assert_eval_raise CompileError, "nofile:2: cannot define def __info__/1 as it is automatically defined by Elixir", ''' defmodule Kernel.ErrorsTest.InternalFunctionOverridden do def __info__(_), do: [] end ''' end test "no macros" do assert_eval_raise CompileError, "nofile:2: could not load macros from module :lists", ''' defmodule Kernel.ErrorsTest.NoMacros do import :lists, only: :macros end ''' end test "invalid macro" do assert_eval_raise CompileError, ~r"nofile: invalid quoted expression: {:foo, :bar, :baz, :bat}", ''' defmodule Kernel.ErrorsTest.InvalidMacro do defmacrop oops do {:foo, :bar, :baz, :bat} end def test, do: oops() end ''' end test "unloaded module" do assert_eval_raise CompileError, "nofile:1: module Certainly.Doesnt.Exist is not loaded and could not be found", 'import Certainly.Doesnt.Exist' end test "module imported from the context it was defined in" do assert_eval_raise CompileError, ~r"nofile:4: module Kernel.ErrorsTest.ScheduledModule.Hygiene is not loaded but was defined.", ''' defmodule Kernel.ErrorsTest.ScheduledModule do defmodule Hygiene do end import Kernel.ErrorsTest.ScheduledModule.Hygiene end ''' end test "module imported from the same module" do assert_eval_raise CompileError, ~r"nofile:3: you are trying to use the module Kernel.ErrorsTest.ScheduledModule.Hygiene which is currently being defined", ''' defmodule Kernel.ErrorsTest.ScheduledModule do defmodule Hygiene do import Kernel.ErrorsTest.ScheduledModule.Hygiene end end ''' end test "already compiled module" do assert_eval_raise ArgumentError, "could not call eval_quoted with argument Record " <> "because the module is already compiled", 'Module.eval_quoted Record, quote(do: 1), [], file: __ENV__.file' end test "@on_load attribute format" do assert_raise ArgumentError, ~r/should be an atom or a {atom, 0} tuple/, fn -> defmodule BadOnLoadAttribute do Module.put_attribute(__MODULE__, :on_load, "not an atom") end end end test "duplicated @on_load attribute" do assert_raise ArgumentError, "the @on_load attribute can only be set once per module", fn -> defmodule DuplicatedOnLoadAttribute do @on_load :foo @on_load :bar end end end test "@on_load attribute with undefined function" do assert_eval_raise CompileError, "nofile:1: @on_load function foo/0 is undefined", 'defmodule UndefinedOnLoadFunction do @on_load :foo end' end test "wrong kind for @on_load attribute" do assert_eval_raise CompileError, "nofile:1: expected @on_load function foo/0 to be defined as \"def\", " <> "got \"defp\"", ''' defmodule PrivateOnLoadFunction do @on_load :foo defp foo do :ok end # To avoid warning: function foo/0 is unused def bar do foo() end end ''' end test "interpolation error" do assert_eval_raise SyntaxError, "nofile:1: unexpected token: ). The \"do\" at line 1 is missing terminator \"end\"", '"foo\#{case 1 do )}bar"' end test "in definition module" do assert_eval_raise CompileError, "nofile:2: cannot define module Kernel.ErrorsTest.InDefinitionModule " <> "because it is currently being defined in nofile:1", ''' defmodule Kernel.ErrorsTest.InDefinitionModule do defmodule Elixir.Kernel.ErrorsTest.InDefinitionModule, do: true end ''' end test "invalid definition" do assert_eval_raise CompileError, "nofile:1: invalid syntax in def 1.(hello)", 'defmodule Kernel.ErrorsTest.InvalidDefinition, do: (def 1.(hello), do: true)' end test "invalid size in bitstrings" do assert_eval_raise CompileError, "nofile:1: cannot use ^x outside of match clauses", 'x = 8; <<a, b::size(^x)>> = <<?a, ?b>>' end test "end of expression" do # All valid examples Code.eval_quoted(''' 1; 2; 3 (;) (;1) (1;) (1; 2) fn -> 1; 2 end fn -> ; end if true do ; end try do ; catch _, _ -> ; after ; end ''') # All invalid examples assert_eval_raise SyntaxError, "nofile:1: syntax error before: ';'", '1+;\n2' assert_eval_raise SyntaxError, "nofile:1: syntax error before: ';'", 'max(1, ;2)' end test "new line error" do assert_eval_raise SyntaxError, "nofile:3: unexpectedly reached end of line. The current expression is invalid or incomplete", 'if true do\n foo = [],\n baz\nend' end test "characters literal are printed correctly in syntax errors" do assert_eval_raise SyntaxError, "nofile:1: syntax error before: ?a", ':ok ?a' assert_eval_raise SyntaxError, "nofile:1: syntax error before: ?\\s", ':ok ?\\s' assert_eval_raise SyntaxError, "nofile:1: syntax error before: ?す", ':ok ?す' end test "invalid \"fn do expr end\"" do assert_eval_raise SyntaxError, "nofile:1: unexpected token: do. Anonymous functions are written as:\n\n fn pattern -> expression end", 'fn do :ok end' end test "bodyless function with guard" do assert_eval_raise CompileError, "nofile:2: missing :do option in \"def\"", ''' defmodule Kernel.ErrorsTest.BodyessFunctionWithGuard do def foo(n) when is_number(n) end ''' assert_eval_raise CompileError, "nofile:2: missing :do option in \"def\"", ''' defmodule Kernel.ErrorsTest.BodyessFunctionWithGuard do def foo(n) when is_number(n), true end ''' end test "invalid args for function head" do assert_eval_raise CompileError, ~r"nofile:2: only variables and \\\\ are allowed as arguments in function head.", ''' defmodule Kernel.ErrorsTest.InvalidArgsForBodylessClause do def foo(nil) def foo(_), do: :ok end ''' end test "bad multi-call" do assert_eval_raise CompileError, "nofile:1: invalid argument for alias, expected a compile time atom or alias, got: 42", 'alias IO.{ANSI, 42}' assert_eval_raise CompileError, "nofile:1: :as option is not supported by multi-alias call", 'alias Elixir.{Map}, as: Dict' assert_eval_raise UndefinedFunctionError, "function List.\"{}\"/1 is undefined or private", '[List.{Chars}, "one"]' end test "macros error stacktrace" do assert [ {:erlang, :+, [1, :foo], _}, {Kernel.ErrorsTest.MacrosErrorStacktrace, :sample, 1, _} | _ ] = rescue_stacktrace(""" defmodule Kernel.ErrorsTest.MacrosErrorStacktrace do defmacro sample(num), do: num + :foo def other, do: sample(1) end """) end test "macros function clause stacktrace" do assert [{__MODULE__, :sample, 1, _} | _] = rescue_stacktrace(""" defmodule Kernel.ErrorsTest.MacrosFunctionClauseStacktrace do import Kernel.ErrorsTest sample(1) end """) end test "macros interpreted function clause stacktrace" do assert [{Kernel.ErrorsTest.MacrosInterpretedFunctionClauseStacktrace, :sample, 1, _} | _] = rescue_stacktrace(""" defmodule Kernel.ErrorsTest.MacrosInterpretedFunctionClauseStacktrace do defmacro sample(0), do: 0 def other, do: sample(1) end """) end test "macros compiled callback" do assert [{Kernel.ErrorsTest, :__before_compile__, [env], _} | _] = rescue_stacktrace(""" defmodule Kernel.ErrorsTest.MacrosCompiledCallback do Module.put_attribute(__MODULE__, :before_compile, Kernel.ErrorsTest) end """) assert %Macro.Env{module: Kernel.ErrorsTest.MacrosCompiledCallback} = env end test "failed remote call stacktrace includes file/line info" do try do bad_remote_call(1) rescue ArgumentError -> assert [ {:erlang, :apply, [1, :foo, []], []}, {__MODULE__, :bad_remote_call, 1, [file: _, line: _]} | _ ] = __STACKTRACE__ end end test "def fails when rescue, else or catch don't have clauses" do assert_eval_raise CompileError, ~r"expected -> clauses for :rescue in \"def\"", """ defmodule Example do def foo do bar() rescue baz() end end """ end defp bad_remote_call(x), do: x.foo defmacro sample(0), do: 0 defmacro before_compile(_) do quote(do: _) end ## Helpers defp assert_eval_raise(given_exception, given_message, string) do assert_raise given_exception, given_message, fn -> Code.eval_string(string) end end defp rescue_stacktrace(string) do try do Code.eval_string(string) nil rescue _ -> __STACKTRACE__ else _ -> flunk("Expected expression to fail") end end end
34.366765
144
0.540843
ff5aacd6e5091d614f199765a0491d6b7985054b
4,233
ex
Elixir
lib/membrane/caps/matcher.ex
mkaput/membrane-core
f65ae3d847f2c10f3ab20d0c7aa75b0faa274ec7
[ "Apache-2.0" ]
null
null
null
lib/membrane/caps/matcher.ex
mkaput/membrane-core
f65ae3d847f2c10f3ab20d0c7aa75b0faa274ec7
[ "Apache-2.0" ]
null
null
null
lib/membrane/caps/matcher.ex
mkaput/membrane-core
f65ae3d847f2c10f3ab20d0c7aa75b0faa274ec7
[ "Apache-2.0" ]
null
null
null
defmodule Membrane.Caps.Matcher do @moduledoc """ Module that allows to specify valid caps and verify that they match specification. Caps specifications (specs) should be in one of the formats: * simply module name of the desired caps (e.g. `Membrane.Caps.Audio.Raw` or `Raw` with proper alias) * tuple with module name and keyword list of specs for specific caps fields (e.g. `{Raw, format: :s24le}`) * list of the formats described above Field values can be specified in following ways: * By a raw value for the field (e.g. `:s24le`) * Using `range/2` for values comparable with `Kernel.<=/2` and `Kernel.>=/2` (e.g. `Matcher.range(0, 255)`) * With `one_of/1` and a list of valid values (e.g `Matcher.one_of([:u8, :s16le, :s32le])`) Checks on the values from list are performed recursivly i.e. it can contain another `range/2`, for example `Matcher.one_of([0, Matcher.range(2, 4), Matcher.range(10, 20)])` If the specs are defined inside of `Membrane.Element.Base.Mixin.SinkBehaviour.def_known_sink_pads/1` and `Membrane.Element.Base.Mixin.SourceBehaviour.def_known_source_pads/1` module name can be ommitted from `range/2` and `one_of/1` calls. """ import Kernel, except: [match?: 2] require Record alias Bunch @type caps_spec_t :: module() | {module(), keyword()} @type caps_specs_t :: :any | caps_spec_t() | [caps_spec_t()] @opaque range_spec_t :: {__MODULE__.Range, any, any} Record.defrecordp(:range_t, __MODULE__.Range, min: 0, max: :infinity) @opaque list_spec_t :: {__MODULE__.In, list()} Record.defrecordp(:in_t, __MODULE__.In, list: []) @doc """ Returns opaque `t:range_spec_t/0` that specifies range of valid values for caps field """ @spec range(any, any) :: range_spec_t def range(min, max) do range_t(min: min, max: max) end @doc """ Returns opaque `t:list_spec_t/0` that specifies list of valid values for caps field """ @spec one_of(list()) :: list_spec_t def one_of(values) when is_list(values) do in_t(list: values) end @doc """ Function used to make sure caps specs are valid. In particular, valid caps: * Have shape described by `t:caps_specs_t/0` type * If they contain keyword list, the keys are present in requested caps type It returns `:ok` when caps are valid and `{:error, reason}` otherwise """ @spec validate_specs(caps_specs_t() | any()) :: :ok | {:error, reason :: tuple()} def validate_specs(specs_list) when is_list(specs_list) do specs_list |> Bunch.Enum.try_each(&validate_specs/1) end def validate_specs({type, keyword_specs}) do caps = type.__struct__ caps_keys = caps |> Map.from_struct() |> Map.keys() |> MapSet.new() spec_keys = keyword_specs |> Keyword.keys() |> MapSet.new() if MapSet.subset?(spec_keys, caps_keys) do :ok else invalid_keys = spec_keys |> MapSet.difference(caps_keys) |> MapSet.to_list() {:error, {:invalid_keys, type, invalid_keys}} end end def validate_specs(specs) when is_atom(specs), do: :ok def validate_specs(specs), do: {:error, {:invalid_specs, specs}} @doc """ Function determining whether the caps match provided specs. When `:any` is used as specs, caps can by anything (i.e. they can be invalid) """ @spec match?(:any, any()) :: true @spec match?(caps_specs_t(), struct()) :: boolean() def match?(:any, _), do: true def match?(specs, %_{} = caps) when is_list(specs) do specs |> Enum.any?(fn spec -> match?(spec, caps) end) end def match?({type, keyword_specs}, %caps_type{} = caps) do type == caps_type && keyword_specs |> Enum.all?(fn kv -> kv |> match_caps_entry(caps) end) end def match?(type, %caps_type{}) when is_atom(type) do type == caps_type end defp match_caps_entry({spec_key, spec_value}, %{} = caps) do {:ok, caps_value} = caps |> Map.fetch(spec_key) match_value(spec_value, caps_value) end defp match_value(in_t(list: specs), value) when is_list(specs) do specs |> Enum.any?(fn spec -> match_value(spec, value) end) end defp match_value(range_t(min: min, max: max), value) do min <= value && value <= max end defp match_value(spec, value) do spec == value end end
34.696721
111
0.677534
ff5aae5948a6ca8e303a8c357a192c4e56fb563e
2,819
ex
Elixir
clients/service_networking/lib/google_api/service_networking/v1/model/update_dns_record_set_request.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/service_networking/lib/google_api/service_networking/v1/model/update_dns_record_set_request.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/service_networking/lib/google_api/service_networking/v1/model/update_dns_record_set_request.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.ServiceNetworking.V1.Model.UpdateDnsRecordSetRequest do @moduledoc """ Request to update a record set from a private managed DNS zone in the shared producer host project. The name, type, ttl, and data values of the existing record set must all exactly match an existing record set in the specified zone. ## Attributes * `consumerNetwork` (*type:* `String.t`, *default:* `nil`) - Required. The network that the consumer is using to connect with services. Must be in the form of projects/{project}/global/networks/{network} {project} is the project number, as in '12345' {network} is the network name. * `existingDnsRecordSet` (*type:* `GoogleApi.ServiceNetworking.V1.Model.DnsRecordSet.t`, *default:* `nil`) - Required. The existing DNS record set to update. * `newDnsRecordSet` (*type:* `GoogleApi.ServiceNetworking.V1.Model.DnsRecordSet.t`, *default:* `nil`) - Required. The new values that the DNS record set should be updated to hold. * `zone` (*type:* `String.t`, *default:* `nil`) - Required. The name of the private DNS zone in the shared producer host project from which the record set will be removed. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :consumerNetwork => String.t(), :existingDnsRecordSet => GoogleApi.ServiceNetworking.V1.Model.DnsRecordSet.t(), :newDnsRecordSet => GoogleApi.ServiceNetworking.V1.Model.DnsRecordSet.t(), :zone => String.t() } field(:consumerNetwork) field(:existingDnsRecordSet, as: GoogleApi.ServiceNetworking.V1.Model.DnsRecordSet) field(:newDnsRecordSet, as: GoogleApi.ServiceNetworking.V1.Model.DnsRecordSet) field(:zone) end defimpl Poison.Decoder, for: GoogleApi.ServiceNetworking.V1.Model.UpdateDnsRecordSetRequest do def decode(value, options) do GoogleApi.ServiceNetworking.V1.Model.UpdateDnsRecordSetRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceNetworking.V1.Model.UpdateDnsRecordSetRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
44.746032
183
0.740688
ff5ac2870cfb0119b60094d3a4c6b5655b08b058
890
ex
Elixir
sample_server/test/support/conn_case.ex
mjaric/finix
fb0dedfdfdd46927d3df239c7c45d7fe92c441c4
[ "Apache-2.0" ]
31
2019-03-26T15:26:21.000Z
2022-02-16T14:33:13.000Z
sample_server/test/support/conn_case.ex
mjaric/finix
fb0dedfdfdd46927d3df239c7c45d7fe92c441c4
[ "Apache-2.0" ]
3
2019-04-05T19:45:09.000Z
2019-10-25T01:48:57.000Z
sample_server/test/support/conn_case.ex
mjaric/finix
fb0dedfdfdd46927d3df239c7c45d7fe92c441c4
[ "Apache-2.0" ]
5
2019-03-27T14:16:28.000Z
2022-02-18T12:01:46.000Z
defmodule SampleServerWeb.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 common datastructures and query the data layer. 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 SampleServerWeb.Router.Helpers # The default endpoint for testing @endpoint SampleServerWeb.Endpoint end end setup _tags do {:ok, conn: Phoenix.ConnTest.build_conn()} end end
25.428571
58
0.733708
ff5ad9ed2efbdac86420a3d259797fbfd28c8b46
1,938
ex
Elixir
lib/glimesh_web/controllers/oauth2_controllers/authorization_controller.ex
itsUnsmart/glimesh.tv
22c532184bb5046f6c6d8232e8bd66ba534c01c1
[ "MIT" ]
1
2020-08-02T00:12:28.000Z
2020-08-02T00:12:28.000Z
lib/glimesh_web/controllers/oauth2_controllers/authorization_controller.ex
itsUnsmart/glimesh.tv
22c532184bb5046f6c6d8232e8bd66ba534c01c1
[ "MIT" ]
null
null
null
lib/glimesh_web/controllers/oauth2_controllers/authorization_controller.ex
itsUnsmart/glimesh.tv
22c532184bb5046f6c6d8232e8bd66ba534c01c1
[ "MIT" ]
null
null
null
defmodule GlimeshWeb.Oauth2Provider.AuthorizationController do @moduledoc false use GlimeshWeb, :controller alias Glimesh.OauthHandler def new(conn, params) do code = Map.get(params, "code") if code != nil do redirect(conn, to: Routes.authorization_path(conn, :show, code)) else conn.assigns[:current_user] |> OauthHandler.preauthorize(params, otp_app: :glimesh) |> case do {:ok, client, scopes} -> render(conn, "new.html", params: params, client: client |> Glimesh.Repo.preload(:app), scopes: scopes ) {:native_redirect, %{code: code}} -> redirect(conn, to: Routes.authorization_path(conn, :show, code)) {:redirect, redirect_uri} -> redirect(conn, external: redirect_uri) {:error, error, status} -> conn |> put_status(status) |> render("error.html", error: error) end end end def create(conn, %{"action" => "authorize"} = params) do conn.assigns[:current_user] |> OauthHandler.authorize(params, otp_app: :glimesh) |> redirect_or_render(conn) end def create(conn, %{"action" => "deny"} = params) do conn.assigns[:current_user] |> OauthHandler.deny(params, otp_app: :glimesh) |> redirect_or_render(conn) end def show(conn, %{"code" => code}) do render(conn, "show.html", code: code) end defp redirect_or_render({:redirect, redirect_uri}, conn) do redirect(conn, external: redirect_uri) end defp redirect_or_render({:native_redirect, payload}, conn) do json(conn, payload) end defp redirect_or_render({:error, error, status}, conn) do conn |> put_status(status) |> render("error.html", error: error) end defp redirect_or_render({:error, {:error, error, status}}, conn) do conn |> put_status(status) |> render("error.html", error: error) end end
26.547945
74
0.624871
ff5af84f62e9f0d9d758ac6c5c21f32401bb44d8
798
ex
Elixir
lib/exrm/plugins/link_sys_config.ex
qhwa/edeliver
f90999b54a90f2eb6d68e21bf5759872b42eee41
[ "Unlicense", "MIT" ]
1
2021-06-25T10:36:14.000Z
2021-06-25T10:36:14.000Z
lib/exrm/plugins/link_sys_config.ex
qhwa/edeliver
f90999b54a90f2eb6d68e21bf5759872b42eee41
[ "Unlicense", "MIT" ]
null
null
null
lib/exrm/plugins/link_sys_config.ex
qhwa/edeliver
f90999b54a90f2eb6d68e21bf5759872b42eee41
[ "Unlicense", "MIT" ]
null
null
null
defmodule ReleaseManager.Plugin.LinkSysConfig do @moduledoc """ Exrm plugin to link the `sys.config` file on deploy hosts. """ use ReleaseManager.Plugin alias ReleaseManager.Utils def before_release(_), do: nil def after_release(%Config{version: version, name: name}) do case System.get_env "LINK_SYS_CONFIG" do sys_config_link_destination = <<_,_::binary>> -> debug "Linking sys.config file" sysconfig_path = Utils.rel_dest_path(Path.join([name, "releases", version, "sys.config"])) if sysconfig_path |> File.exists?, do: sysconfig_path |> File.rm File.ln_s(sys_config_link_destination, sysconfig_path) _ -> nil end end def after_release(_), do: nil def after_cleanup(_), do: nil def after_package(_), do: nil end
28.5
98
0.691729
ff5b0e481de992df20961d3281252db4c4ba2ca0
673
ex
Elixir
lib/postpone/mock.ex
marcinwysocki/postpone
e57e3fb78ac40273eb6f1a90267deabca2f5f3ba
[ "MIT" ]
null
null
null
lib/postpone/mock.ex
marcinwysocki/postpone
e57e3fb78ac40273eb6f1a90267deabca2f5f3ba
[ "MIT" ]
null
null
null
lib/postpone/mock.ex
marcinwysocki/postpone
e57e3fb78ac40273eb6f1a90267deabca2f5f3ba
[ "MIT" ]
null
null
null
defmodule Postpone.Mock do use Agent alias Postpone.Mock.Server @doc false defmacro __using__(_) do quote do import Mock import Postpone.Mock end end defmacro with_timers_mock(do: block) do quote do with_mock Postpone, send_after: fn msg, to, time -> Server.set(time, fn -> send(to, msg) end) end, apply_after: fn fun, time -> Server.set(time, fun) end do unquote(block) end end end @spec advance_timers_by(number) :: :ok def advance_timers_by(time) do Server.advance_timers_by(time) end @spec run_all_timers :: :ok def run_all_timers do Server.run_all_timers() end end
19.794118
86
0.658247
ff5b43faa4ca1ce8957abbec3b00a93de1028b59
446
exs
Elixir
config/config.exs
root-mt/KeycloakEx
5c409b442472c2525b04002f3e6e75e9d207d2ca
[ "MIT" ]
null
null
null
config/config.exs
root-mt/KeycloakEx
5c409b442472c2525b04002f3e6e75e9d207d2ca
[ "MIT" ]
null
null
null
config/config.exs
root-mt/KeycloakEx
5c409b442472c2525b04002f3e6e75e9d207d2ca
[ "MIT" ]
null
null
null
import Config config :keycloak, :host_uri, "http://localhost:8081" config :keycloak, Keycloak.Clients.Admin, realm: "master", username: "admin", password: "test123!", client_id: "admin-cli", client_secret: "83bf8d8e-e608-477b-b812-48b9ac4aa43a" config :keycloak, Keycloak.Clients.User, realm: "keycloak-ex", client_id: "keycloak-ex", site: "https://localhost:4002", scope: "keycloak_scope" #import_config "#{Mix.env()}.exs"
23.473684
55
0.70852
ff5bb5dc8a714694b9785c171ee311cc7dc65fe4
1,083
exs
Elixir
apps/artemis_web/test/artemis_web/controllers/user_anonymization_controller_test.exs
chrislaskey/atlas_platform
969aea95814f62d3471f93000ee5ad77edb9d1bf
[ "MIT" ]
10
2019-07-05T19:59:20.000Z
2021-05-23T07:36:11.000Z
apps/artemis_web/test/artemis_web/controllers/user_anonymization_controller_test.exs
chrislaskey/atlas_platform
969aea95814f62d3471f93000ee5ad77edb9d1bf
[ "MIT" ]
7
2019-07-12T21:41:01.000Z
2020-08-17T21:29:22.000Z
apps/artemis_web/test/artemis_web/controllers/user_anonymization_controller_test.exs
chrislaskey/atlas_platform
969aea95814f62d3471f93000ee5ad77edb9d1bf
[ "MIT" ]
4
2019-07-05T20:04:08.000Z
2021-05-13T16:28:33.000Z
defmodule ArtemisWeb.UserAnonymizationControllerTest do use ArtemisWeb.ConnCase import Artemis.Factories setup %{conn: conn} do {:ok, conn: sign_in(conn)} end describe "create" do test "anonymizes user and redirects to show when data is valid", %{conn: conn} do record = insert(:user) conn = post(conn, Routes.user_anonymization_path(conn, :create, record)) assert %{id: id} = redirected_params(conn) assert redirected_to(conn) == Routes.user_path(conn, :show, id) conn = get(conn, Routes.user_path(conn, :show, id)) assert html_response(conn, 200) =~ "Anonymized User" end test "renders errors when data is invalid", %{conn: conn} do system_user = Mock.system_user() conn = post(conn, Routes.user_anonymization_path(conn, :create, system_user)) assert %{id: id} = redirected_params(conn) assert redirected_to(conn) == Routes.user_path(conn, :show, id) conn = get(conn, Routes.user_path(conn, :show, id)) refute html_response(conn, 200) =~ "Anonymized User" end end end
30.942857
85
0.677747
ff5c06c015dcc1764ba8693ce2dde5d4c75ddac8
343
exs
Elixir
programming_elixir_1.3_snippets/spawn/link2.exs
benjohns1/elixer-app
6e866ec084c5e75442c0b70f66e35f61b5b74d34
[ "MIT" ]
null
null
null
programming_elixir_1.3_snippets/spawn/link2.exs
benjohns1/elixer-app
6e866ec084c5e75442c0b70f66e35f61b5b74d34
[ "MIT" ]
null
null
null
programming_elixir_1.3_snippets/spawn/link2.exs
benjohns1/elixer-app
6e866ec084c5e75442c0b70f66e35f61b5b74d34
[ "MIT" ]
null
null
null
defmodule Link2 do import :timer, only: [sleep: 1] def sad_function do sleep 500 exit(:boom) end def run do spawn_link(__MODULE__, :sad_function, []) receive do msg -> IO.puts "Message Received: #{inspect msg}" after 1000 -> IO.puts "Nothing happened afaik" end end end Link2.run()
19.055556
56
0.606414
ff5c129dad036fafe1c52bd887a47ad427aa548f
1,127
ex
Elixir
lib/ds_wrapper/key.ex
iii-ishida/ds_wrapper
d7a2fbb1c07b33a762743b1c2051b163586fc5d7
[ "MIT" ]
null
null
null
lib/ds_wrapper/key.ex
iii-ishida/ds_wrapper
d7a2fbb1c07b33a762743b1c2051b163586fc5d7
[ "MIT" ]
null
null
null
lib/ds_wrapper/key.ex
iii-ishida/ds_wrapper
d7a2fbb1c07b33a762743b1c2051b163586fc5d7
[ "MIT" ]
null
null
null
defmodule DsWrapper.Key do @moduledoc """ `GoogleApi.Datastore.V1.Model.Key` wrapper """ alias GoogleApi.Datastore.V1.Model.{Key, PathElement} @doc """ Create a new `GoogleApi.Datastore.V1.Model.Key`. ## Examples iex> DsWrapper.Key.new("SomeKind") %GoogleApi.Datastore.V1.Model.Key{path: [%GoogleApi.Datastore.V1.Model.PathElement{kind: "SomeKind"}]} iex> DsWrapper.Key.new("SomeKind", "some-name") %GoogleApi.Datastore.V1.Model.Key{path: [%GoogleApi.Datastore.V1.Model.PathElement{kind: "SomeKind", name: "some-name"}]} iex> DsWrapper.Key.new("SomeKind", 1234) %GoogleApi.Datastore.V1.Model.Key{path: [%GoogleApi.Datastore.V1.Model.PathElement{kind: "SomeKind", id: "1234"}]} """ @spec new(String.t(), integer | String.t() | nil, %Key{}) :: %Key{} def new(kind, id_or_name \\ nil, parent \\ %Key{path: []}) def new(kind, id, parent) when is_integer(id) do %Key{path: parent.path ++ [%PathElement{kind: kind, id: Integer.to_string(id)}]} end def new(kind, name, parent) do %Key{path: parent.path ++ [%PathElement{kind: kind, name: name}]} end end
34.151515
127
0.663709
ff5c1ceb512e60cc7c9260789bc939207202fd48
1,080
ex
Elixir
divvy_tracker/lib/divvy_tracker_web/channels/user_socket.ex
tpennock/divvy-tracker-app
6896a19fd7380a827573231ff56ead8db04c66bf
[ "MIT" ]
null
null
null
divvy_tracker/lib/divvy_tracker_web/channels/user_socket.ex
tpennock/divvy-tracker-app
6896a19fd7380a827573231ff56ead8db04c66bf
[ "MIT" ]
3
2018-12-11T00:07:41.000Z
2018-12-11T00:09:36.000Z
divvy_tracker/lib/divvy_tracker_web/channels/user_socket.ex
tpennock/divvy-tracker-app
6896a19fd7380a827573231ff56ead8db04c66bf
[ "MIT" ]
null
null
null
defmodule DivvyTrackerWeb.UserSocket do use Phoenix.Socket ## Channels # channel "room:*", DivvyTrackerWeb.RoomChannel # Socket params are passed from the client and can # be used to verify and authenticate a user. After # verification, you can put default assigns into # the socket that will be set for all channels, ie # # {:ok, assign(socket, :user_id, verified_user_id)} # # To deny connection, return `:error`. # # See `Phoenix.Token` documentation for examples in # performing token verification on connect. def connect(_params, socket, _connect_info) do {:ok, socket} end # Socket id's are topics that allow you to identify all sockets for a given user: # # def id(socket), do: "user_socket:#{socket.assigns.user_id}" # # Would allow you to broadcast a "disconnect" event and terminate # all active sockets and channels for a given user: # # DivvyTrackerWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. def id(_socket), do: nil end
31.764706
87
0.700926
ff5c2f53e3bb957fe41d9b3fc4fb8c2e5e1a9a35
207
ex
Elixir
test/support/c_example.ex
jeanparpaillon/ex_cast
fd67d0dcf9ac3794c5fbf1070a7be33925361c2b
[ "Apache-2.0" ]
null
null
null
test/support/c_example.ex
jeanparpaillon/ex_cast
fd67d0dcf9ac3794c5fbf1070a7be33925361c2b
[ "Apache-2.0" ]
null
null
null
test/support/c_example.ex
jeanparpaillon/ex_cast
fd67d0dcf9ac3794c5fbf1070a7be33925361c2b
[ "Apache-2.0" ]
null
null
null
defmodule CExample do use Cast, ast: "test/support/c_example/hello.xml" const :version, cast: &integer/1 const :app, cast: &string/1 enum Numbers, contains: "one" enum Buddies, name: "buddy" end
20.7
51
0.700483
ff5c4d24cd1f87c4ecb3cde362c04d2e71674b10
2,047
exs
Elixir
rel/config/console.exs
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
6
2021-11-17T21:10:49.000Z
2022-02-16T19:45:28.000Z
rel/config/console.exs
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
18
2021-11-25T04:31:06.000Z
2022-03-27T04:54:00.000Z
rel/config/console.exs
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
null
null
null
import Config import System, only: [get_env: 1, get_env: 2] config :ra, data_dir: '/data/ra' config :piazza_core, repos: [Console.Repo] config :botanist, ecto_repo: Console.Repo replicas = get_env("REPLICAS", "1") |> String.to_integer() nodes = Enum.map(0..(replicas - 1), & :"console@console-#{&1}.console-headless.#{get_env("NAMESPACE")}.svc.cluster.local") config :console, replicas: replicas, nodes: nodes config :libcluster, topologies: [ watchman: [ strategy: Cluster.Strategy.Epmd, config: [hosts: nodes] ] ] config :console, Console.Guardian, issuer: get_env("HOST"), secret_key: get_env("JWT_SECRET") [_ | rest] = get_env("HOST") |> String.split(".") config :console, ConsoleWeb.Endpoint, url: [host: get_env("HOST"), port: 80], check_origin: ["//#{get_env("HOST")}", "//console"] provider = case get_env("PROVIDER") do "google" -> :gcp "gcp" -> :gcp "aws" -> :aws "azure" -> :azure "equinix" -> :equinix _ -> :custom end if provider != :gcp do config :goth, disabled: true end config :console, Console.Repo, database: "console", username: "console", password: get_env("POSTGRES_PASSWORD"), hostname: get_env("DBHOST") || "console-postgresql", ssl: String.to_existing_atom(get_env("DBSSL") || "false"), pool_size: 10 git_url = get_env("GIT_URL") config :console, workspace_root: "/root", git_url: get_env("GIT_URL"), branch: get_env("BRANCH_NAME") || "master", repo_root: get_env("REPO_ROOT"), forge_config: "/ect/forge/.forge", git_ssh_key: {:home, ".ssh/id_rsa"}, webhook_secret: get_env("WEBHOOK_SECRET"), git_user_name: get_env("GIT_USER", "forge"), git_user_email: get_env("GIT_EMAIL", "forge@piazzaapp.com"), url: get_env("HOST"), incoming_webhook: get_env("PIAZZA_INCOMING_WEBHOOK"), grafana_dns: get_env("GRAFANA_DNS"), piazza_secret: get_env("PIAZZA_WEBHOOK_SECRET"), cluster_name: get_env("CLUSTER_NAME"), provider: provider if String.starts_with?(git_url, "https") do config :console, git_ssh_key: :pass end
24.963415
122
0.679043
ff5c73ca5cc66e92ab1e8c68c2a4f1d386a4b15d
1,383
exs
Elixir
config/config.exs
bundacia/cassette-plug
ee99912204f5085bf4d77e47eaae3978bf59542c
[ "MIT" ]
1
2019-12-15T00:26:38.000Z
2019-12-15T00:26:38.000Z
config/config.exs
bundacia/cassette-plug
ee99912204f5085bf4d77e47eaae3978bf59542c
[ "MIT" ]
null
null
null
config/config.exs
bundacia/cassette-plug
ee99912204f5085bf4d77e47eaae3978bf59542c
[ "MIT" ]
1
2019-12-15T00:26:39.000Z
2019-12-15T00:26:39.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :cassette_plug, key: :value # # And access this configuration in your application as: # # Application.get_env(:cassette_plug, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs" config :cassette, base_authority: "ACME" config :cassette, service: "example.org" # only for running controller tests config :cassette_plug, :secret_key_base, "uohIyjofAtAbo4q6zBmyb4KiLr6FPQtXNvKMiIVyd8dLFndTDDHxJspo9LIqiNT6re5nqlJr2sIs5xsORkTDyQ=="
36.394737
92
0.768619
ff5c7d341a1288f2e9b92bf0fa03637ac2363dc2
9,362
ex
Elixir
lib/generated/delete_records.ex
kevint-simplifi/kayrock
9c88e99ec913728107ec99f9af94dc1d25e0e0d8
[ "MIT" ]
24
2019-06-26T22:08:13.000Z
2022-01-27T00:10:41.000Z
lib/generated/delete_records.ex
kevint-simplifi/kayrock
9c88e99ec913728107ec99f9af94dc1d25e0e0d8
[ "MIT" ]
10
2020-04-10T07:48:53.000Z
2021-03-26T10:50:25.000Z
lib/generated/delete_records.ex
kevint-simplifi/kayrock
9c88e99ec913728107ec99f9af94dc1d25e0e0d8
[ "MIT" ]
11
2019-10-30T12:53:09.000Z
2022-03-09T23:16:42.000Z
defmodule(Kayrock.DeleteRecords) do @api :delete_records @moduledoc "Kayrock-generated module for the Kafka `#{@api}` API\n" _ = " THIS CODE IS GENERATED BY KAYROCK" ( @vmin 0 @vmax 0 ) defmodule(V0.Request) do @vsn 0 @api :delete_records @schema topics: {:array, [topic: :string, partitions: {:array, [partition: :int32, offset: :int64]}]}, timeout: :int32 @moduledoc "Kayrock-generated request struct for Kafka `#{@api}` v#{@vsn} API\nmessages\n\nThe schema of this API is\n```\n#{ inspect(@schema, pretty: true) }\n```\n" _ = " THIS CODE IS GENERATED BY KAYROCK" defstruct(topics: [], timeout: nil, correlation_id: nil, client_id: nil) import(Elixir.Kayrock.Serialize) @typedoc "Request struct for the Kafka `#{@api}` API v#{@vsn}\n" @type t :: %__MODULE__{ topics: [ %{ topic: nil | binary(), partitions: [%{partition: nil | integer(), offset: nil | integer()}] } ], timeout: nil | integer(), correlation_id: nil | integer(), client_id: nil | binary() } @doc "Returns the Kafka API key for this API" @spec api_key :: integer def(api_key) do Kayrock.KafkaSchemaMetadata.api_key(:delete_records) end @doc "Returns the API version (#{@vsn}) implemented by this module" @spec api_vsn :: integer def(api_vsn) do 0 end @doc "Returns a function that can be used to deserialize the wire response from the\nbroker for this message type\n" @spec response_deserializer :: (binary -> {V0.Response.t(), binary}) def(response_deserializer) do &V0.Response.deserialize/1 end @doc "Returns the schema of this message\n\nSee [above](#).\n" @spec schema :: term def(schema) do [ topics: {:array, [topic: :string, partitions: {:array, [partition: :int32, offset: :int64]}]}, timeout: :int32 ] end @doc "Serialize a message to binary data for transfer to a Kafka broker" @spec serialize(t()) :: iodata def(serialize(%V0.Request{} = struct)) do [ <<api_key()::16, api_vsn()::16, struct.correlation_id::32, byte_size(struct.client_id)::16, struct.client_id::binary>>, [ case(Map.fetch!(struct, :topics)) do nil -> <<-1::32-signed>> [] -> <<0::32-signed>> vals when is_list(vals) -> [ <<length(vals)::32-signed>>, for(v <- vals) do [ serialize(:string, Map.fetch!(v, :topic)), case(Map.fetch!(v, :partitions)) do nil -> <<-1::32-signed>> [] -> <<0::32-signed>> vals when is_list(vals) -> [ <<length(vals)::32-signed>>, for(v <- vals) do [ serialize(:int32, Map.fetch!(v, :partition)), serialize(:int64, Map.fetch!(v, :offset)) ] end ] end ] end ] end, serialize(:int32, Map.fetch!(struct, :timeout)) ] ] end end defimpl(Elixir.Kayrock.Request, for: V0.Request) do def(serialize(%V0.Request{} = struct)) do try do V0.Request.serialize(struct) rescue e -> reraise(Kayrock.InvalidRequestError, {e, struct}, __STACKTRACE__) end end def(api_vsn(%V0.Request{})) do V0.Request.api_vsn() end def(response_deserializer(%V0.Request{})) do V0.Request.response_deserializer() end end ( @doc "Returns a request struct for this API with the given version" @spec get_request_struct(integer) :: request_t ) def(get_request_struct(0)) do %V0.Request{} end defmodule(V0.Response) do @vsn 0 @api :delete_records @schema throttle_time_ms: :int32, topics: {:array, [ topic: :string, partitions: {:array, [partition: :int32, low_watermark: :int64, error_code: :int16]} ]} @moduledoc "Kayrock-generated response struct for Kafka `#{@api}` v#{@vsn} API\nmessages\n\nThe schema of this API is\n```\n#{ inspect(@schema, pretty: true) }\n```\n" _ = " THIS CODE IS GENERATED BY KAYROCK" defstruct(throttle_time_ms: nil, topics: [], correlation_id: nil) @typedoc "Response struct for the Kafka `#{@api}` API v#{@vsn}\n" @type t :: %__MODULE__{ throttle_time_ms: nil | integer(), topics: [ %{ topic: nil | binary(), partitions: [ %{ partition: nil | integer(), low_watermark: nil | integer(), error_code: nil | integer() } ] } ], correlation_id: integer() } import(Elixir.Kayrock.Deserialize) @doc "Returns the Kafka API key for this API" @spec api_key :: integer def(api_key) do Kayrock.KafkaSchemaMetadata.api_key(:delete_records) end @doc "Returns the API version (#{@vsn}) implemented by this module" @spec api_vsn :: integer def(api_vsn) do 0 end @doc "Returns the schema of this message\n\nSee [above](#).\n" @spec schema :: term def(schema) do [ throttle_time_ms: :int32, topics: {:array, [ topic: :string, partitions: {:array, [partition: :int32, low_watermark: :int64, error_code: :int16]} ]} ] end @doc "Deserialize data for this version of this API\n" @spec deserialize(binary) :: {t(), binary} def(deserialize(data)) do <<correlation_id::32-signed, rest::binary>> = data deserialize_field( :root, :throttle_time_ms, %__MODULE__{correlation_id: correlation_id}, rest ) end defp(deserialize_field(:root, :throttle_time_ms, acc, data)) do {val, rest} = deserialize(:int32, data) deserialize_field(:root, :topics, Map.put(acc, :throttle_time_ms, val), rest) end defp(deserialize_field(:topics, :topic, acc, data)) do {val, rest} = deserialize(:string, data) deserialize_field(:topics, :partitions, Map.put(acc, :topic, val), rest) end defp(deserialize_field(:partitions, :partition, acc, data)) do {val, rest} = deserialize(:int32, data) deserialize_field(:partitions, :low_watermark, Map.put(acc, :partition, val), rest) end defp(deserialize_field(:partitions, :low_watermark, acc, data)) do {val, rest} = deserialize(:int64, data) deserialize_field(:partitions, :error_code, Map.put(acc, :low_watermark, val), rest) end defp(deserialize_field(:partitions, :error_code, acc, data)) do {val, rest} = deserialize(:int16, data) deserialize_field(:partitions, nil, Map.put(acc, :error_code, val), rest) end defp(deserialize_field(:topics, :partitions, acc, data)) do <<num_elements::32-signed, rest::binary>> = data {vals, rest} = if(num_elements > 0) do Enum.reduce(1..num_elements, {[], rest}, fn _ix, {acc, d} -> {val, r} = deserialize_field(:partitions, :partition, %{}, d) {[val | acc], r} end) else {[], rest} end deserialize_field(:topics, nil, Map.put(acc, :partitions, Enum.reverse(vals)), rest) end defp(deserialize_field(:root, :topics, acc, data)) do <<num_elements::32-signed, rest::binary>> = data {vals, rest} = if(num_elements > 0) do Enum.reduce(1..num_elements, {[], rest}, fn _ix, {acc, d} -> {val, r} = deserialize_field(:topics, :topic, %{}, d) {[val | acc], r} end) else {[], rest} end deserialize_field(:root, nil, Map.put(acc, :topics, Enum.reverse(vals)), rest) end defp(deserialize_field(_, nil, acc, rest)) do {acc, rest} end end ( @doc "Deserializes raw wire data for this API with the given version" @spec deserialize(integer, binary) :: {response_t, binary} ) def(deserialize(0, data)) do V0.Response.deserialize(data) end ( @typedoc "Union type for all request structs for this API" @type request_t :: Kayrock.DeleteRecords.V0.Request.t() ) ( @typedoc "Union type for all response structs for this API" @type response_t :: Kayrock.DeleteRecords.V0.Response.t() ) ( @doc "Returns the minimum version of this API supported by Kayrock (#{@vmin})" @spec min_vsn :: integer def(min_vsn) do 0 end ) ( @doc "Returns the maximum version of this API supported by Kayrock (#{@vmax})" @spec max_vsn :: integer def(max_vsn) do 0 end ) end
30.2
130
0.540162
ff5c929e8ffb6ce37aabf46aa5c0b327043f6145
1,220
ex
Elixir
web/views/error_helpers.ex
tahmidsadik112/bloom
edf9995535cdb189b47addb7aee7311f590c5a87
[ "MIT" ]
null
null
null
web/views/error_helpers.ex
tahmidsadik112/bloom
edf9995535cdb189b47addb7aee7311f590c5a87
[ "MIT" ]
null
null
null
web/views/error_helpers.ex
tahmidsadik112/bloom
edf9995535cdb189b47addb7aee7311f590c5a87
[ "MIT" ]
null
null
null
defmodule Bloom.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do if error = form.errors[field] do content_tag :span, translate_error(error), class: "help-block" end end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # Because error messages were defined within Ecto, we must # call the Gettext module passing our Gettext backend. We # also use the "errors" domain as translations are placed # in the errors.po file. # Ecto will pass the :count keyword if the error message is # meant to be pluralized. # On your own code and templates, depending on whether you # need the message to be pluralized or not, this could be # written simply as: # # dngettext "errors", "1 file", "%{count} files", count # dgettext "errors", "is invalid" # if count = opts[:count] do Gettext.dngettext(Bloom.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(Bloom.Gettext, "errors", msg, opts) end end end
29.756098
71
0.665574
ff5c9e66828e8320696e7a8d1653d9e358ba3436
400
ex
Elixir
lib/blue_jet_web/controllers/identity/email_verification_token_controller.ex
freshcom/freshcom-api
4f2083277943cf4e4e8fd4c4d443c7309f285ad7
[ "BSD-3-Clause" ]
44
2018-05-09T01:08:57.000Z
2021-01-19T07:25:26.000Z
lib/blue_jet_web/controllers/identity/email_verification_token_controller.ex
freshcom/freshcom-api
4f2083277943cf4e4e8fd4c4d443c7309f285ad7
[ "BSD-3-Clause" ]
36
2018-05-08T23:59:54.000Z
2018-09-28T13:50:30.000Z
lib/blue_jet_web/controllers/identity/email_verification_token_controller.ex
freshcom/freshcom-api
4f2083277943cf4e4e8fd4c4d443c7309f285ad7
[ "BSD-3-Clause" ]
9
2018-05-09T14:09:19.000Z
2021-03-21T21:04:04.000Z
defmodule BlueJetWeb.EmailVerificationTokenController do use BlueJetWeb, :controller alias BlueJet.Identity action_fallback BlueJetWeb.FallbackController plug :scrub_params, "data" when action in [:create, :update] def create(conn, %{"data" => %{"type" => "EmailVerificationToken"}}), do: default(conn, :create, &Identity.create_email_verification_token/1, status: :no_content) end
30.769231
96
0.76
ff5caed9581a1e2fa0d63ee8bc1fae2500b2a5a1
223
ex
Elixir
orderapi/lib/orderapi_web/controllers/order_controller.ex
iandeherdt/phoenixshop
cd6e223c676505b75c1340b96908468a5c09fd7c
[ "Apache-2.0" ]
1
2018-03-06T10:32:22.000Z
2018-03-06T10:32:22.000Z
orderapi/lib/orderapi_web/controllers/order_controller.ex
iandeherdt/phoenixshop
cd6e223c676505b75c1340b96908468a5c09fd7c
[ "Apache-2.0" ]
null
null
null
orderapi/lib/orderapi_web/controllers/order_controller.ex
iandeherdt/phoenixshop
cd6e223c676505b75c1340b96908468a5c09fd7c
[ "Apache-2.0" ]
null
null
null
defmodule OrderapiWeb.OrderController do use OrderapiWeb, :controller alias OrderapiWeb.Order def index(conn, _params) do orders = Orderapi.Repo.all(Order) render conn, "index.json", orders: orders end end
22.3
45
0.744395
ff5cc1bf732e391005860e6eec9ceb1cba313c11
555
exs
Elixir
priv/repo/migrations/20210621225953_create_studios.exs
tacohole/banchan
04c9f2fd5464e697d9b69e4bc524ace5f6487487
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
priv/repo/migrations/20210621225953_create_studios.exs
tacohole/banchan
04c9f2fd5464e697d9b69e4bc524ace5f6487487
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
priv/repo/migrations/20210621225953_create_studios.exs
tacohole/banchan
04c9f2fd5464e697d9b69e4bc524ace5f6487487
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
defmodule Banchan.Repo.Migrations.CreateStudios do use Ecto.Migration def change do create table(:studios) do add :name, :string, null: false add :summary, :text add :handle, :citext, null: false add :description, :text add :header_img, :string add :card_img, :string add :default_terms, :text timestamps() end create table(:users_studios, primary_key: false) do add :user_id, references(:users), null: false add :studio_id, references(:studios), null: false end end end
25.227273
55
0.652252
ff5ccb04afbd38c44e297c6db072613f45944a97
1,138
ex
Elixir
lib/roger_ui/partitions.ex
fabianherrera/roger_ui_revamp
7541148d6c24a5d3209e4eedccfb6a43f2b38fdf
[ "MIT" ]
1
2020-01-20T19:42:20.000Z
2020-01-20T19:42:20.000Z
lib/roger_ui/partitions.ex
fabianherrera/roger_ui_revamp
7541148d6c24a5d3209e4eedccfb6a43f2b38fdf
[ "MIT" ]
2
2018-02-19T20:07:29.000Z
2018-03-06T17:18:18.000Z
lib/roger_ui/partitions.ex
fabianherrera/roger_ui_revamp
7541148d6c24a5d3209e4eedccfb6a43f2b38fdf
[ "MIT" ]
2
2018-03-02T00:00:08.000Z
2018-03-02T13:35:49.000Z
defmodule RogerUI.Partitions do @moduledoc """ Generate Partition list from Roger.Info.partitions() """ @doc """ Takes a Keyword list that contains the nodes, status and partitions with queues, like this: [ "server@127.0.0.1": %{ running: %{ "roger_test_partition_1" => %{ default: %{consumer_count: 1, max_workers: 10, message_count: 740, paused: false}, fast: %{consumer_count: 1, max_workers: 10, message_count: 740, paused: false}, other: %{consumer_count: 1, max_workers: 2, message_count: 0, paused: false} } },... ] and transforms it into a partition list """ def normalize(partitions) do partitions |> Enum.flat_map(&capture_node_name(&1)) end defp capture_node_name({node_name, partitions}) do partitions |> Enum.flat_map(&normalize_partition(node_name, &1)) end defp normalize_partition(node_name, {status, partitions}) do Enum.map(partitions, fn {partition_name, _} -> %{ "node_name" => node_name, "status" => status, "partition_name" => partition_name } end) end end
27.756098
93
0.636204
ff5ce691727ff3d88c5510f1fa9626cfc32cfd03
381
exs
Elixir
bench/insert_and_inorder_bench.exs
jdfrens/bst_benchmarking
f49efe899cd6649f6efdc4a0c9f488d0aa0f7dbd
[ "MIT" ]
1
2017-04-02T10:29:33.000Z
2017-04-02T10:29:33.000Z
bench/insert_and_inorder_bench.exs
jdfrens/bst_benchmarking
f49efe899cd6649f6efdc4a0c9f488d0aa0f7dbd
[ "MIT" ]
null
null
null
bench/insert_and_inorder_bench.exs
jdfrens/bst_benchmarking
f49efe899cd6649f6efdc4a0c9f488d0aa0f7dbd
[ "MIT" ]
null
null
null
defmodule InsertAndInorder do use Benchfella @list Enum.to_list(1..1_000) |> Enum.shuffle bench "tuple" do @list |> Enum.reduce(TupleBST.new, fn x, acc -> TupleBST.put(acc, x, x) end) |> TupleBST.inorder end bench "map" do @list |> Enum.reduce(MapBST.new, fn x, acc -> MapBST.put(acc, x, x) end) |> MapBST.inorder end end
17.318182
46
0.595801
ff5ce786a70b094134558ed1e200add9cf9c5d34
785
ex
Elixir
lib/ash_json_api/controllers/post_to_relationship.ex
peillis/ash_json_api
f63ccacebc049eba8d37b8b58181fb46a4a0ea8c
[ "MIT" ]
null
null
null
lib/ash_json_api/controllers/post_to_relationship.ex
peillis/ash_json_api
f63ccacebc049eba8d37b8b58181fb46a4a0ea8c
[ "MIT" ]
null
null
null
lib/ash_json_api/controllers/post_to_relationship.ex
peillis/ash_json_api
f63ccacebc049eba8d37b8b58181fb46a4a0ea8c
[ "MIT" ]
null
null
null
defmodule AshJsonApi.Controllers.PostToRelationship do @moduledoc false alias AshJsonApi.Controllers.{Helpers, Response} alias AshJsonApi.Request def init(options) do # initialize options options end def call(conn, options) do action = options[:action] api = options[:api] route = options[:route] relationship = Ash.Resource.Info.relationship(options[:resource], route.relationship) resource = relationship.destination conn |> Request.from(resource, action, api, route) |> Helpers.fetch_record_from_path(options[:resource]) |> Helpers.add_to_relationship(relationship.name) |> Helpers.render_or_render_errors(conn, fn request -> Response.render_many_relationship(conn, request, 200, relationship) end) end end
29.074074
89
0.73121
ff5cf3d48c9dcccecd5162628a69a4c550b7a2a3
965
exs
Elixir
mix.exs
moranda/ex-pipe-helpers
e3025e001118ef17f6abb8a063826d7a597e2479
[ "Apache-2.0", "MIT" ]
null
null
null
mix.exs
moranda/ex-pipe-helpers
e3025e001118ef17f6abb8a063826d7a597e2479
[ "Apache-2.0", "MIT" ]
null
null
null
mix.exs
moranda/ex-pipe-helpers
e3025e001118ef17f6abb8a063826d7a597e2479
[ "Apache-2.0", "MIT" ]
null
null
null
defmodule PipeHelpers.MixProject do use Mix.Project @source_url "https://github.com/kuon/ex-pipe-helpers" @version "1.0.2" def project do [ name: "PipeHelpers", app: :pipe_helpers, version: @version, elixir: "~> 1.10", start_permanent: Mix.env() == :prod, deps: deps(), docs: docs(), description: description(), package: package(), ] end def application do [ extra_applications: [:logger] ] end defp description() do "A small set of helpers to help structure pipelines" end defp deps do [ # EX Docs generation {:ex_doc, "~> 0.24", only: :dev, runtime: false} ] end defp docs do [ main: "readme", source_url: @source_url, output: "docs/", extras: [ "README.md" ] ] end defp package() do [ licenses: ["Apache-2.0", "MIT"], links: %{"Git" => @source_url} ] end end
17.232143
56
0.545078
ff5cff912b6ba90da8636795b3a6f3b0e6537d86
2,035
ex
Elixir
lib/exredis/config.ex
zorbash/exredis
00d0de97bc12b3f9712198b7a08efb5c0eb9436a
[ "MIT" ]
null
null
null
lib/exredis/config.ex
zorbash/exredis
00d0de97bc12b3f9712198b7a08efb5c0eb9436a
[ "MIT" ]
null
null
null
lib/exredis/config.ex
zorbash/exredis
00d0de97bc12b3f9712198b7a08efb5c0eb9436a
[ "MIT" ]
null
null
null
defmodule Exredis.Config do defmodule Config do defstruct host: nil, port: nil, password: nil, db: nil, reconnect: nil, max_queue: nil, behaviour: nil end @default_config %{ host: "127.0.0.1", port: 6379, password: "", db: 0, reconnect: :no_reconnect, max_queue: :infinity, behaviour: :drop } def settings, do: [:host, :port, :password, :db, :reconnect, :max_queue, :behaviour] def fetch_env do uri_config = Application.get_env(:exredis, :url) |> parse |> Map.from_struct |> filter_nils application_config = settings() |> Enum.reduce(%{}, fn (key, config) -> config |> load_config_key(key) end) |> filter_nils config = @default_config |> Map.merge(uri_config) |> Map.merge(application_config) |> parse_port struct(Config, config) end defp parse_port(m) do n = case is_integer(m.port) do true -> m.port _ -> {i, _} = Integer.parse(m.port) i end %{m | :port=>n} end def parse(nil), do: %Config{} def parse(connection_string) do value = case connection_string do {:system, name} -> System.get_env(name) _ -> connection_string end uri = URI.parse(value) %Config{ host: uri.host, port: uri.port, password: uri.userinfo |> parse_password, db: uri.path |> parse_db } end defp parse_db(nil), do: 0 defp parse_db("/"), do: 0 defp parse_db(path) do path |> String.split("/") |> Enum.at(1) |> String.to_integer end defp parse_password(nil), do: "" defp parse_password(auth) do auth |> String.split(":") |> Enum.at(1) end defp load_config_key(config, key) do r = Application.get_env(:exredis, key) value = case r do {:system, name} -> System.get_env(name) _ -> r end Map.put(config, key, value) end defp filter_nils(map) do map |> Enum.filter(fn {_, v} -> v != nil end) |> Enum.into(%{}) end end
23.390805
106
0.580344
ff5d0fd1eb6f44e2b68e1607dce7140be1bcd1ba
916
ex
Elixir
lib/liquid_voting/application.ex
jinjagit/api
c1a176d8c318e05810bc1635706c56395819191e
[ "MIT" ]
null
null
null
lib/liquid_voting/application.ex
jinjagit/api
c1a176d8c318e05810bc1635706c56395819191e
[ "MIT" ]
10
2020-09-28T06:37:48.000Z
2021-12-22T15:04:38.000Z
lib/liquid_voting/application.ex
jinjagit/api
c1a176d8c318e05810bc1635706c56395819191e
[ "MIT" ]
null
null
null
defmodule LiquidVoting.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do import Supervisor.Spec # List all child processes to be supervised children = [ LiquidVoting.Repo, {Phoenix.PubSub, name: LiquidVoting.PubSub}, LiquidVotingWeb.Endpoint, supervisor(Absinthe.Subscription, [LiquidVotingWeb.Endpoint]) ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: LiquidVoting.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 LiquidVotingWeb.Endpoint.config_change(changed, removed) :ok end end
28.625
67
0.732533
ff5d1e5679482a60cefef19b2c5335bc849221e1
9,155
exs
Elixir
test/bitpal/invoices/invoice_acceptance_test.exs
bitpal/bitpal
0e10eeaacf7a65b23945cfb95e4dbda8bffd4590
[ "BSD-3-Clause-Clear" ]
5
2021-05-04T21:28:00.000Z
2021-12-01T11:19:48.000Z
test/bitpal/invoices/invoice_acceptance_test.exs
bitpal/bitpal
0e10eeaacf7a65b23945cfb95e4dbda8bffd4590
[ "BSD-3-Clause-Clear" ]
71
2021-04-21T05:48:49.000Z
2022-03-23T06:30:37.000Z
test/bitpal/invoices/invoice_acceptance_test.exs
bitpal/bitpal
0e10eeaacf7a65b23945cfb95e4dbda8bffd4590
[ "BSD-3-Clause-Clear" ]
1
2021-04-25T10:35:41.000Z
2021-04-25T10:35:41.000Z
defmodule BitPal.InvoiceAcceptanceTest do use BitPal.IntegrationCase, async: true test "accept after no double spend in timeout", %{currency_id: currency_id} do {:ok, inv, stub, _invoice_handler} = HandlerSubscriberCollector.create_invoice( required_confirmations: 0, double_spend_timeout: 1, currency_id: currency_id ) BackendMock.tx_seen(inv) HandlerSubscriberCollector.await_msg(stub, {:invoice, :paid}) id = inv.id assert [ {{:invoice, :finalized}, %{id: ^id, status: :open, address_id: _}}, {{:invoice, :processing}, %{id: ^id, reason: :verifying}}, {{:invoice, :paid}, %{id: ^id}} ] = HandlerSubscriberCollector.received(stub) end test "accept when block is found while waiting for double spend timout", %{ currency_id: currency_id } do {:ok, inv, stub, _invoice_handler} = HandlerSubscriberCollector.create_invoice( required_confirmations: 0, double_spend_timeout: 1_000, currency_id: currency_id ) BackendMock.tx_seen(inv) BackendMock.confirmed_in_new_block(inv) HandlerSubscriberCollector.await_msg(stub, {:invoice, :paid}) assert [ {{:invoice, :finalized}, _}, {{:invoice, :processing}, %{reason: :verifying}}, {{:invoice, :paid}, _} ] = HandlerSubscriberCollector.received(stub) end test "accept after a confirmation", %{currency_id: currency_id} do {:ok, inv, stub, _invoice_handler} = HandlerSubscriberCollector.create_invoice( required_confirmations: 1, currency_id: currency_id ) BackendMock.tx_seen(inv) BackendMock.confirmed_in_new_block(inv) HandlerSubscriberCollector.await_msg(stub, {:invoice, :paid}) assert [ {{:invoice, :finalized}, _}, {{:invoice, :processing}, %{reason: {:confirming, 1}}}, {{:invoice, :paid}, _} ] = HandlerSubscriberCollector.received(stub) end test "confirmed without being seen", %{currency_id: currency_id} do {:ok, inv, stub, _invoice_handler} = HandlerSubscriberCollector.create_invoice( required_confirmations: 1, currency_id: currency_id ) BackendMock.confirmed_in_new_block(inv) HandlerSubscriberCollector.await_msg(stub, {:invoice, :paid}) assert [ {{:invoice, :finalized}, _}, {{:invoice, :processing}, %{reason: {:confirming, 0}}}, {{:invoice, :paid}, _} ] = HandlerSubscriberCollector.received(stub) end test "accepts after multiple confirmations", %{currency_id: currency_id} do {:ok, inv, stub, _invoice_handler} = HandlerSubscriberCollector.create_invoice( required_confirmations: 3, currency_id: currency_id ) BackendMock.tx_seen(inv) BackendMock.confirmed_in_new_block(inv) BackendMock.issue_blocks(currency_id, 5) HandlerSubscriberCollector.await_msg(stub, {:invoice, :paid}) assert [ {{:invoice, :finalized}, _}, {{:invoice, :processing}, %{reason: {:confirming, 3}}}, {{:invoice, :processing}, %{reason: {:confirming, 2}}}, {{:invoice, :processing}, %{reason: {:confirming, 1}}}, {{:invoice, :paid}, _} ] = HandlerSubscriberCollector.received(stub) end test "multiple invoices", %{currency_id: currency_id} do {:ok, inv0, stub0, _} = HandlerSubscriberCollector.create_invoice( double_spend_timeout: 1, amount: 0.1, required_confirmations: 0, currency_id: currency_id ) {:ok, inv1, stub1, _} = HandlerSubscriberCollector.create_invoice( double_spend_timeout: 1, amount: 1.0, required_confirmations: 1, currency_id: currency_id ) {:ok, inv2, stub2, _} = HandlerSubscriberCollector.create_invoice( double_spend_timeout: 1, amount: 2.0, required_confirmations: 2, currency_id: currency_id ) inv0_id = inv0.id inv1_id = inv1.id inv2_id = inv2.id BackendMock.tx_seen(inv0) BackendMock.tx_seen(inv1) HandlerSubscriberCollector.await_msg(stub0, {:invoice, :paid}) HandlerSubscriberCollector.await_msg(stub1, {:invoice, :processing}) assert [ {{:invoice, :finalized}, %{id: ^inv0_id}}, {{:invoice, :processing}, %{id: ^inv0_id, reason: :verifying}}, {{:invoice, :paid}, %{id: ^inv0_id}} ] = HandlerSubscriberCollector.received(stub0) assert [ {{:invoice, :finalized}, %{id: ^inv1_id}}, {{:invoice, :processing}, %{id: ^inv1_id, reason: {:confirming, 1}}} ] = HandlerSubscriberCollector.received(stub1) assert [ {{:invoice, :finalized}, %{id: ^inv2_id}} ] = HandlerSubscriberCollector.received(stub2) BackendMock.confirmed_in_new_block(inv2) HandlerSubscriberCollector.await_msg(stub2, {:invoice, :processing}) assert [ {{:invoice, :finalized}, %{id: ^inv1_id}}, {{:invoice, :processing}, %{id: ^inv1_id, reason: {:confirming, 1}}} ] = HandlerSubscriberCollector.received(stub1) assert [ {{:invoice, :finalized}, %{id: ^inv2_id}}, {{:invoice, :processing}, %{id: ^inv2_id, reason: {:confirming, 1}}} ] = HandlerSubscriberCollector.received(stub2) BackendMock.issue_blocks(currency_id, 2) HandlerSubscriberCollector.await_msg(stub2, {:invoice, :paid}) assert [ {{:invoice, :finalized}, %{id: ^inv1_id}}, {{:invoice, :processing}, %{id: ^inv1_id, reason: {:confirming, 1}}} ] = HandlerSubscriberCollector.received(stub1) assert [ {{:invoice, :finalized}, %{id: ^inv2_id}}, {{:invoice, :processing}, %{id: ^inv2_id, reason: {:confirming, 1}}}, {{:invoice, :paid}, %{id: ^inv2_id}} ] = HandlerSubscriberCollector.received(stub2) end test "Invoices of the same amount", %{currency_id: currency_id} do inv = [amount: 1.0, required_confirmations: 1, currency_id: currency_id] {:ok, inv0, _, handler0} = HandlerSubscriberCollector.create_invoice(inv) {:ok, inv1, _, handler1} = HandlerSubscriberCollector.create_invoice(inv) assert inv0.amount == inv1.amount assert inv0.address_id != inv1.address_id assert handler0 != handler1 end test "Detect early 0-conf doublespend", %{currency_id: currency_id} do {:ok, inv, stub, _} = HandlerSubscriberCollector.create_invoice( required_confirmations: 0, currency_id: currency_id ) BackendMock.tx_seen(inv) BackendMock.doublespend(inv) HandlerSubscriberCollector.await_msg(stub, {:invoice, :uncollectible}) assert [ {{:invoice, :finalized}, _}, {{:invoice, :processing}, %{reason: :verifying}}, {{:invoice, :uncollectible}, %{reason: :double_spent}} ] = HandlerSubscriberCollector.received(stub) end test "Underpaid invoice", %{currency_id: currency_id} do {:ok, inv, stub, _handler} = HandlerSubscriberCollector.create_invoice( amount: 1.0, required_confirmations: 0, double_spend_timeout: 1, currency_id: currency_id ) BackendMock.tx_seen(%{inv | amount: Money.parse!(0.3, currency_id)}) HandlerSubscriberCollector.await_msg(stub, {:invoice, :underpaid}) due = Money.parse!(0.7, currency_id) assert [ {{:invoice, :finalized}, _}, {{:invoice, :underpaid}, %{amount_due: ^due}} ] = HandlerSubscriberCollector.received(stub) BackendMock.tx_seen(%{inv | amount: Money.parse!(0.7, currency_id)}) HandlerSubscriberCollector.await_msg(stub, {:invoice, :paid}) assert [ {{:invoice, :finalized}, _}, {{:invoice, :underpaid}, %{amount_due: ^due}}, {{:invoice, :processing}, %{reason: :verifying}}, {{:invoice, :paid}, _} ] = HandlerSubscriberCollector.received(stub) end test "Overpaid invoice", %{currency_id: currency_id} do {:ok, inv, stub, _handler} = HandlerSubscriberCollector.create_invoice( amount: 1.0, required_confirmations: 0, double_spend_timeout: 1, currency_id: currency_id ) BackendMock.tx_seen(%{inv | amount: Money.parse!(0.3, currency_id)}) HandlerSubscriberCollector.await_msg(stub, {:invoice, :underpaid}) BackendMock.tx_seen(%{inv | amount: Money.parse!(1.3, currency_id)}) HandlerSubscriberCollector.await_msg(stub, {:invoice, :paid}) due = Money.parse!(0.7, currency_id) overpaid = Money.parse!(0.6, currency_id) assert [ {{:invoice, :finalized}, _}, {{:invoice, :underpaid}, %{amount_due: ^due}}, {{:invoice, :overpaid}, %{overpaid_amount: ^overpaid}}, {{:invoice, :processing}, %{reason: :verifying}}, {{:invoice, :paid}, _} ] = HandlerSubscriberCollector.received(stub) end end
33.907407
82
0.619006
ff5d221739c715451505ec05aebab254738855aa
512
exs
Elixir
test/lcov_ex/formatter_test.exs
paulswartz/lcov_ex
110a0a86ede581067661dd366662d2c40ae91a2a
[ "MIT" ]
1
2020-07-21T17:58:44.000Z
2020-07-21T17:58:44.000Z
test/lcov_ex/formatter_test.exs
GuidoRumi/lcov_ex
3b22cf739a56eb16064d2ba3fe9a4309ae6b87ce
[ "MIT" ]
null
null
null
test/lcov_ex/formatter_test.exs
GuidoRumi/lcov_ex
3b22cf739a56eb16064d2ba3fe9a4309ae6b87ce
[ "MIT" ]
null
null
null
defmodule LcovEx.FormatterTest do use ExUnit.Case describe "ExampleProject" do test "run mix test --cover with LcovEx" do assert LcovEx.Formatter.format_lcov(FakeModule, "path/to/file.ex", [{"foo/0",1},{"bar/2",0}], 2, 1, [{"3",1},{"5",0}], 2, 1) == """ TN:Elixir.FakeModule SF:path/to/file.ex FNDA:1,foo/0 FNDA:0,bar/2 FNF:2 FNH:1 DA:3,1 DA:5,0 LF:2 LH:1 end_of_record """ end end end
21.333333
133
0.515625
ff5d249a17fa8c35b5d06dd59120cf98581da5c7
2,628
ex
Elixir
lib/scribe/migration.ex
rramsden/scribe
4ef506714140da032a76d62b39109cf7a79c9d91
[ "MIT" ]
1
2016-01-24T11:43:59.000Z
2016-01-24T11:43:59.000Z
lib/scribe/migration.ex
rramsden/scribe
4ef506714140da032a76d62b39109cf7a79c9d91
[ "MIT" ]
null
null
null
lib/scribe/migration.ex
rramsden/scribe
4ef506714140da032a76d62b39109cf7a79c9d91
[ "MIT" ]
null
null
null
defmodule Scribe.Migration do import Scribe.Utils @doc """ Run migrations """ def up(project_dir, config) do conn = config.adapter.start_link(config) create_version_table(config.adapter, conn) schema_vsn = read_schema_version(config.adapter, conn) migrations = Enum.filter read_migrations(project_dir), fn(m) -> m[:version] > schema_vsn end execute(:up, migrations, config.adapter, conn) config.adapter.close(conn) end @doc """ Rollback a migration """ def down(project_dir, config) do conn = config.adapter.start_link(config) create_version_table(config.adapter, conn) schema_vsn = read_schema_version(config.adapter, conn) migrations = Enum.filter read_migrations(project_dir), fn(m) -> m[:version] < schema_vsn end sorted_list = Enum.sort migrations, fn(a, b) -> a[:version] > b[:version] end last_migration = case Enum.first(sorted_list) do nil -> [] migration -> [migration] end execute(:down, last_migration, config.adapter, conn) config.adapter.close(conn) end defp execute(_, [], _, _), do: :ok defp execute(direction, [migration|rest], adapter, conn) do [file: path] = Regex.captures(%r/\/\d+_(?<file>.*)\.exs$/g, migration[:path]) Code.require_file migration[:path] module = Mix.Utils.camelize(path) time "Migrating: #{module}" do {migration_sql, _} = Code.eval_string "#{module}.#{direction}" case adapter.execute(migration_sql, conn) do {:error, reason} -> exit(reason) _ -> :ok end case direction do :up -> adapter.execute("INSERT INTO schema_versions VALUES ('#{migration[:version]}')", conn) :down -> adapter.execute("DELETE FROM schema_versions WHERE version = #{migration[:version]}", conn) end end execute(direction, rest, adapter, conn) end defp read_migrations(project_dir) do migration_files = Path.wildcard(Path.join(project_dir, "db/migrations/*")) Enum.map migration_files, fn(path) -> [version: migration_vsn] = Regex.captures(%r/\/(?<version>\d+)_.*\.exs$/g, path) {vsn, _} = String.to_integer(migration_vsn) [path: path, version: vsn] end end defp read_schema_version(adapter, conn) do case adapter.select("SELECT MAX(version) FROM schema_versions", conn) do {:ok, version} when is_integer(version) -> {:ok, version} _ -> 0 end end defp create_version_table(adapter, conn) do create_query = """ CREATE TABLE schema_versions ( version integer NOT NULL ); """ adapter.execute(create_query, conn) end end
32.04878
108
0.660198
ff5d2af7beb80c39e1b5efd160c635502b727043
1,706
exs
Elixir
test/airbrakex/exception_parser_test.exs
rum-and-code/airbrakex
36db3a0f887c7d74492daabf1f33eab98fe9b46f
[ "MIT" ]
null
null
null
test/airbrakex/exception_parser_test.exs
rum-and-code/airbrakex
36db3a0f887c7d74492daabf1f33eab98fe9b46f
[ "MIT" ]
1
2021-05-17T15:36:58.000Z
2021-05-17T15:36:58.000Z
test/airbrakex/exception_parser_test.exs
rum-and-code/airbrakex
36db3a0f887c7d74492daabf1f33eab98fe9b46f
[ "MIT" ]
null
null
null
defmodule Airbrakex.ExceptionParserTest do use ExUnit.Case test "parses exception" do {exception, stacktrace} = try do IO.inspect("test", [], "") rescue e -> {e, __STACKTRACE__} end parsed_exception = Airbrakex.ExceptionParser.parse(exception, stacktrace) backtrace = parsed_exception[:backtrace] message = parsed_exception[:message] type = parsed_exception[:type] assert type == FunctionClauseError assert message == "no function clause matching in IO.inspect/3" backtrace_files = Enum.map(backtrace, fn entry -> entry[:file] end) assert Enum.member?(backtrace_files, "(Elixir.IO) lib/io.ex") assert Enum.member?( backtrace_files, "(Elixir.Airbrakex.ExceptionParserTest) test/airbrakex/exception_parser_test.exs" ) assert Enum.member?(backtrace_files, "(timer) timer.erl") assert Enum.member?(backtrace_files, "(Elixir.ExUnit.Runner) lib/ex_unit/runner.ex") backtrace_functions = Enum.map(backtrace, fn entry -> entry[:function] end) assert Enum.member?(backtrace_functions, "inspect(\"test\", [], \"\")") assert Enum.member?(backtrace_functions, "test parses exception/1") assert Enum.member?(backtrace_functions, "exec_test/1") assert Enum.member?(backtrace_functions, "tc/1") compare = &Version.compare(System.version(), &1) spawn_test = if :lt == compare.("1.6.0") do "-spawn_test/3-fun-1-/3" else if :lt == compare.("1.8.0") do "-spawn_test/3-fun-1-/4" else "-spawn_test_monitor/4-fun-1-/4" end end assert Enum.member?(backtrace_functions, spawn_test) end end
30.464286
94
0.652989
ff5d8785862432560ec5647d3daf194efa8701d0
3,107
ex
Elixir
lib/planga/chat/conversation_user.ex
ResiliaDev/Planga
b21d290dd7c2c7fa30571d0a5124d63bd09c0c9e
[ "MIT" ]
37
2018-07-13T14:08:16.000Z
2021-04-09T15:00:22.000Z
lib/planga/chat/conversation_user.ex
ResiliaDev/Planga
b21d290dd7c2c7fa30571d0a5124d63bd09c0c9e
[ "MIT" ]
9
2018-07-16T15:24:39.000Z
2021-09-01T14:21:20.000Z
lib/planga/chat/conversation_user.ex
ResiliaDev/Planga
b21d290dd7c2c7fa30571d0a5124d63bd09c0c9e
[ "MIT" ]
3
2018-10-05T20:19:25.000Z
2019-12-05T00:30:01.000Z
defmodule Planga.Chat.ConversationUser do @moduledoc """ This schema is the relation between a user and a given conversation. """ use Ecto.Schema # import Ecto.Changeset schema "conversations_users" do # field(:conversation_id, :integer) belongs_to(:conversation, Planga.Chat.Conversation) # field(:user_id, :integer) belongs_to(:user, Planga.Chat.User) field(:role, :string, default: "") field(:banned_until, :utc_datetime) timestamps() end def new(attrs) do %__MODULE__{id: Snowflakex.new!()} |> Ecto.Changeset.cast(Map.new(attrs), [:conversation_id, :user_id, :role, :banned_until]) |> Ecto.Changeset.validate_required([:conversation_id, :user_id]) |> apply_changes end defp apply_changes(changeset) do if changeset.valid? do {:ok, Ecto.Changeset.apply_changes(changeset)} else {:error, changeset.errors} end end # @doc false # def changeset(conversation_user, attrs) do # conversation_user # |> Ecto.Changeset.cast(attrs, [:conversation_id, :user_id]) # |> Ecto.Changeset.validate_required([:conversation_id, :user_id]) # end def ban( conversation_user = %__MODULE__{}, duration_minutes, ban_start_time = %DateTime{} \\ DateTime.utc_now() ) when is_integer(duration_minutes) and duration_minutes > 0 do require Logger ban_end = Timex.add(ban_start_time, Timex.Duration.from_minutes(duration_minutes)) case bannable?(conversation_user) do false -> Logger.warn("Someone attempted to ban unbannable user #{inspect(conversation_user)}") conversation_user true -> %__MODULE__{conversation_user | banned_until: ban_end} end end def bannable?(conversation_user = %__MODULE__{}) do conversation_user.role == nil || conversation_user.role == "" # true end def banned?(conversation_user, current_datetime \\ DateTime.utc_now()) def banned?(_conversation_user = %__MODULE__{banned_until: nil}, _current_datetime), do: false def banned?( _conversation_user = %__MODULE__{banned_until: banned_until = %DateTime{}}, current_datetime ) do DateTime.compare(current_datetime, banned_until) == :lt end def unban(conversation_user = %__MODULE__{}) do %__MODULE__{conversation_user | banned_until: nil} end def set_role(conversation_user = %__MODULE__{}, role) when role in ["", "moderator"] do conversation_user |> Ecto.Changeset.change(role: role) |> apply_changes end def set_role(_conversation_user = %__MODULE__{}, _role), do: {:error, :invalid_role} def is_moderator?(conversation_user = %__MODULE__{}) do conversation_user.role == "moderator" end defmodule Presentation do def conversation_user_dict(conversation_user) do %{ "user_id" => conversation_user.user_id, "role" => conversation_user.role, "banned_until" => case conversation_user.banned_until do nil -> nil datetime -> DateTime.to_unix(datetime) end } end end end
28.768519
96
0.679434
ff5d96325a5cec65429df4c066e51b06044364fd
1,226
ex
Elixir
web/views/error_helpers.ex
bschmeck/ex_gnarl
25d6961795f10a2d49efd1a29167a771ef9772f1
[ "MIT" ]
null
null
null
web/views/error_helpers.ex
bschmeck/ex_gnarl
25d6961795f10a2d49efd1a29167a771ef9772f1
[ "MIT" ]
1
2017-04-21T17:02:56.000Z
2017-04-21T17:02:56.000Z
web/views/error_helpers.ex
bschmeck/ex_gnarl
25d6961795f10a2d49efd1a29167a771ef9772f1
[ "MIT" ]
null
null
null
defmodule ExGnarl.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do if error = form.errors[field] do content_tag :span, translate_error(error), class: "help-block" end end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # Because error messages were defined within Ecto, we must # call the Gettext module passing our Gettext backend. We # also use the "errors" domain as translations are placed # in the errors.po file. # Ecto will pass the :count keyword if the error message is # meant to be pluralized. # On your own code and templates, depending on whether you # need the message to be pluralized or not, this could be # written simply as: # # dngettext "errors", "1 file", "%{count} files", count # dgettext "errors", "is invalid" # if count = opts[:count] do Gettext.dngettext(ExGnarl.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(ExGnarl.Gettext, "errors", msg, opts) end end end
29.902439
73
0.66721
ff5d9ca7c8a6d3b0d26a0ead42d14e2661d206b1
682
ex
Elixir
lib/plausible/site/shared_link.ex
wvffle/analytics
2c0fd55bc67f74af1fe1e2641678d44e9fee61d5
[ "MIT" ]
2
2020-05-16T13:48:44.000Z
2020-05-22T09:52:36.000Z
lib/plausible/site/shared_link.ex
wvffle/analytics
2c0fd55bc67f74af1fe1e2641678d44e9fee61d5
[ "MIT" ]
2
2020-07-09T21:44:35.000Z
2020-07-14T07:06:10.000Z
lib/plausible/site/shared_link.ex
wvffle/analytics
2c0fd55bc67f74af1fe1e2641678d44e9fee61d5
[ "MIT" ]
null
null
null
defmodule Plausible.Site.SharedLink do use Ecto.Schema import Ecto.Changeset schema "shared_links" do belongs_to :site, Plausible.Site field :slug, :string field :password_hash, :string field :password, :string, virtual: true timestamps() end def changeset(link, attrs \\ %{}) do link |> cast(attrs, [:slug, :password]) |> validate_required([:slug]) |> unique_constraint(:slug) |> hash_password() end defp hash_password(link) do case link.changes[:password] do nil -> link password -> hash = Plausible.Auth.Password.hash(password) change(link, password_hash: hash) end end end
20.666667
53
0.640762
ff5df22d4c2e644fec44c422ae378940e4a57b21
161
exs
Elixir
priv/repo/migrations/20180214005744_create_task.exs
inodaf/elixir
e6390cadae4f6bc53a4bf93733372971a20438c5
[ "Unlicense" ]
null
null
null
priv/repo/migrations/20180214005744_create_task.exs
inodaf/elixir
e6390cadae4f6bc53a4bf93733372971a20438c5
[ "Unlicense" ]
null
null
null
priv/repo/migrations/20180214005744_create_task.exs
inodaf/elixir
e6390cadae4f6bc53a4bf93733372971a20438c5
[ "Unlicense" ]
null
null
null
defmodule Taskr.Repo.Migrations.CreateTask do use Ecto.Migration def change do create table(:task) do add :description, :string end end end
16.1
45
0.701863
ff5e50e8a1e70fce2e3a8f39daf3890c39659595
344
exs
Elixir
priv/repo/seeds.exs
deadmp/wiki
29d98ed0517e26d2e3f1c75f70852bc7512d87fc
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
deadmp/wiki
29d98ed0517e26d2e3f1c75f70852bc7512d87fc
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
deadmp/wiki
29d98ed0517e26d2e3f1c75f70852bc7512d87fc
[ "MIT" ]
null
null
null
# Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # Wiki.Repo.insert!(%Wiki.SomeModel{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong.
28.666667
61
0.700581
ff5e569130041463f316669d8d83a0a744fa2e6b
151
ex
Elixir
lib/web/views/document_view.ex
BaltimoreCity/IdeaPortal
dc1c775dfaec2aac974b821cd3700d76770c1e76
[ "MIT" ]
5
2019-08-29T20:22:25.000Z
2020-04-01T17:40:48.000Z
lib/web/views/document_view.ex
BaltimoreCity/IdeaPortal
dc1c775dfaec2aac974b821cd3700d76770c1e76
[ "MIT" ]
34
2019-03-06T17:53:29.000Z
2021-09-01T01:25:23.000Z
lib/web/views/document_view.ex
BaltimoreCity/IdeaPortal
dc1c775dfaec2aac974b821cd3700d76770c1e76
[ "MIT" ]
2
2020-01-10T22:12:36.000Z
2021-01-22T04:37:45.000Z
defmodule Web.DocumentView do use Web, :view def render("show.json", %{document: document}) do Map.take(document, [:id, :filename]) end end
18.875
51
0.675497
ff5e7cdb8a5994d4d81aef8951633abc09047a7f
1,046
ex
Elixir
lib/web/webhook_parser_plug.ex
saifelse/bors-ng
031ecd3474b7c7dc72462a708e120c28cf13b3ad
[ "Apache-2.0" ]
null
null
null
lib/web/webhook_parser_plug.ex
saifelse/bors-ng
031ecd3474b7c7dc72462a708e120c28cf13b3ad
[ "Apache-2.0" ]
71
2021-07-06T15:27:45.000Z
2021-07-07T14:20:40.000Z
lib/web/webhook_parser_plug.ex
saifelse/bors-ng
031ecd3474b7c7dc72462a708e120c28cf13b3ad
[ "Apache-2.0" ]
null
null
null
defmodule BorsNG.WebhookParserPlug do @moduledoc """ Parse the GitHub webhook payload (as JSON) and verify the HMAC-SHA1 signature. """ import Plug.Conn def init(options) do options end def call(conn, options) do if conn.path_info == ["webhook", "github"] do key = Keyword.get(options, :secret) run(conn, options, key) else conn end end def run(conn, _options, nil) do conn end def run(conn, _options, key) do {:ok, body, _} = read_body(conn) signature = case get_req_header(conn, "x-hub-signature") do ["sha1=" <> signature | []] -> {:ok, signature} = Base.decode16(signature, case: :lower) signature x -> x end hmac = :crypto.mac(:hmac, :sha, key, body) case hmac do ^signature -> %Plug.Conn{conn | body_params: Poison.decode!(body)} _ -> conn |> put_resp_content_type("text/plain") |> send_resp(401, "Invalid signature") |> halt end end end
20.115385
80
0.57457
ff5eb0e8b13f1bf461540c4e3e9b296eda67b860
3,176
ex
Elixir
lib/commanded/registration/horde_registry.ex
uberbrodt/commanded_horde_registry
2ecb1dfe90b6eba49bd9b2f012d425cf3e9ff1c7
[ "MIT" ]
5
2019-05-10T16:34:44.000Z
2019-12-07T15:51:47.000Z
lib/commanded/registration/horde_registry.ex
uberbrodt/commanded_horde_registry
2ecb1dfe90b6eba49bd9b2f012d425cf3e9ff1c7
[ "MIT" ]
4
2019-07-04T09:22:19.000Z
2020-01-31T04:59:51.000Z
lib/commanded/registration/horde_registry.ex
uberbrodt/commanded_horde_registry
2ecb1dfe90b6eba49bd9b2f012d425cf3e9ff1c7
[ "MIT" ]
4
2019-09-04T10:00:07.000Z
2020-08-13T17:26:26.000Z
defmodule Commanded.Registration.HordeRegistry do import Commanded.Registration.HordeRegistry.Util alias Commanded.Registration.HordeRegistry.NodeListener require Logger @moduledoc """ Process registration and distribution via [Horde](https://github.com/derekkraan/horde) In order to use this, you will need to update the following config values: ``` config :commanded, registry: Commanded.Registration.HordeRegistry ``` """ @behaviour Commanded.Registration.Adapter @impl Commanded.Registration.Adapter def child_spec(application, _config) do name = Module.concat([application, HordeRegistry]) node_listener_name = Module.concat([application, HordeRegistryNodeListener]) members = get_cluster_members(name) {:ok, [ Horde.Registry.child_spec(name: name, keys: :unique, members: members), {NodeListener, [name: node_listener_name, hordes: [name]]} ], %{registry_name: name}} end @impl Commanded.Registration.Adapter def supervisor_child_spec(_adapter_meta, module, _args) do defaults = [ strategy: :one_for_one, distribution_strategy: Horde.UniformDistribution, name: module, members: get_cluster_members(module) ] overrides = Application.get_env(:commanded_horde_registry, :supervisor_opts, []) opts = Keyword.merge(defaults, overrides) Horde.DynamicSupervisor.child_spec(opts) end @impl Commanded.Registration.Adapter def start_child(adapter_meta, name, supervisor, {module, args}) do via_name = via_tuple(adapter_meta, name) updated_args = Keyword.put(args, :name, via_name) fun = fn -> # spec = Supervisor.child_spec({module, updated_args}, id: {module, name}) DynamicSupervisor.start_child(supervisor, {module, updated_args}) end start(adapter_meta, name, fun) end @impl Commanded.Registration.Adapter def start_link(adapter_meta, name, supervisor, args) do via_name = via_tuple(adapter_meta, name) fun = fn -> GenServer.start_link(supervisor, args, name: via_name) end start(adapter_meta, name, fun) end @impl Commanded.Registration.Adapter def whereis_name(adapter_meta, name) do registry_name = registry_name(adapter_meta) case Horde.Registry.whereis_name({registry_name, name}) do pid when is_pid(pid) -> pid :undefined -> :undefined other -> Logger.warn("unexpected response from Horde.Registry.whereis_name/1: #{inspect(other)}") :undefined end end @impl Commanded.Registration.Adapter def via_tuple(adapter_meta, name) do registry_name = registry_name(adapter_meta) {:via, Horde.Registry, {registry_name, name}} end defp start(adapter_meta, name, func) do case func.() do {:error, {:already_started, nil}} -> case whereis_name(adapter_meta, name) do pid when is_pid(pid) -> {:ok, pid} _other -> {:error, :registered_but_dead} end {:error, {:already_started, pid}} when is_pid(pid) -> {:ok, pid} reply -> reply end end defp registry_name(adapter_meta), do: Map.get(adapter_meta, :registry_name) end
29.137615
96
0.698992
ff5f09c6850d6822bea4e9bf0a3ecc3568ba3752
925
ex
Elixir
lib/tensorflow/core/protobuf/tensorflow_server.pb.ex
pylon/extensor
57eba1660952d94416152531e159abd6b1faaee9
[ "Apache-2.0" ]
58
2018-06-12T00:01:51.000Z
2022-01-30T17:29:42.000Z
lib/tensorflow/core/protobuf/tensorflow_server.pb.ex
pylon/extensor
57eba1660952d94416152531e159abd6b1faaee9
[ "Apache-2.0" ]
9
2018-06-13T19:33:39.000Z
2020-02-17T17:24:15.000Z
lib/tensorflow/core/protobuf/tensorflow_server.pb.ex
pylon/extensor
57eba1660952d94416152531e159abd6b1faaee9
[ "Apache-2.0" ]
3
2018-06-13T19:45:36.000Z
2021-05-16T17:40:08.000Z
defmodule Tensorflow.ServerDef do @moduledoc false use Protobuf, syntax: :proto3 @type t :: %__MODULE__{ cluster: Tensorflow.ClusterDef.t() | nil, job_name: String.t(), task_index: integer, default_session_config: Tensorflow.ConfigProto.t() | nil, protocol: String.t(), port: integer, cluster_device_filters: Tensorflow.ClusterDeviceFilters.t() | nil } defstruct [ :cluster, :job_name, :task_index, :default_session_config, :protocol, :port, :cluster_device_filters ] field(:cluster, 1, type: Tensorflow.ClusterDef) field(:job_name, 2, type: :string) field(:task_index, 3, type: :int32) field(:default_session_config, 4, type: Tensorflow.ConfigProto) field(:protocol, 5, type: :string) field(:port, 6, type: :int32) field(:cluster_device_filters, 7, type: Tensorflow.ClusterDeviceFilters) end
28.90625
75
0.660541
ff5f0e1f93d3b5cd6b62bb4e2025aa4acff04fa4
2,598
exs
Elixir
elixir/all-your-base/test/all_your_base_test.exs
herminiotorres/exercism
82173fcf1f09c27da0134f746a799840aa5eac05
[ "MIT" ]
null
null
null
elixir/all-your-base/test/all_your_base_test.exs
herminiotorres/exercism
82173fcf1f09c27da0134f746a799840aa5eac05
[ "MIT" ]
null
null
null
elixir/all-your-base/test/all_your_base_test.exs
herminiotorres/exercism
82173fcf1f09c27da0134f746a799840aa5eac05
[ "MIT" ]
1
2021-03-15T11:02:40.000Z
2021-03-15T11:02:40.000Z
defmodule AllYourBaseTest do use ExUnit.Case test "convert single bit one to decimal" do assert AllYourBase.convert([1], 2, 10) == [1] end # @tag :pending test "convert binary to single decimal" do assert AllYourBase.convert([1, 0, 1], 2, 10) == [5] end # @tag :pending test "convert single decimal to binary" do assert AllYourBase.convert([5], 10, 2) == [1, 0, 1] end # @tag :pending test "convert binary to multiple decimal" do assert AllYourBase.convert([1, 0, 1, 0, 1, 0], 2, 10) == [4, 2] end # @tag :pending test "convert decimal to binary" do assert AllYourBase.convert([4, 2], 10, 2) == [1, 0, 1, 0, 1, 0] end # @tag :pending test "convert trinary to hexadecimal" do assert AllYourBase.convert([1, 1, 2, 0], 3, 16) == [2, 10] end # @tag :pending test "convert hexadecimal to trinary" do assert AllYourBase.convert([2, 10], 16, 3) == [1, 1, 2, 0] end # @tag :pending test "convert 15-bit integer" do assert AllYourBase.convert([3, 46, 60], 97, 73) == [6, 10, 45] end # @tag :pending test "convert empty list" do assert AllYourBase.convert([], 2, 10) == nil end # @tag :pending test "convert single zero" do assert AllYourBase.convert([0], 10, 2) == [0] end # @tag :pending test "convert multiple zeros" do assert AllYourBase.convert([0, 0, 0], 10, 2) == [0] end # @tag :pending test "convert leading zeros" do assert AllYourBase.convert([0, 6, 0], 7, 10) == [4, 2] end # @tag :pending test "convert first base is one" do assert AllYourBase.convert([0], 1, 10) == nil end # @tag :pending test "convert first base is zero" do assert AllYourBase.convert([], 0, 10) == nil end # @tag :pending test "convert first base is negative" do assert AllYourBase.convert([1], -2, 10) == nil end # @tag :pending test "convert negative digit" do assert AllYourBase.convert([1, -1, 1, 0, 1, 0], 2, 10) == nil end # @tag :pending test "convert invalid positive digit" do assert AllYourBase.convert([1, 2, 1, 0, 1, 0], 2, 10) == nil end # @tag :pending test "convert second base is one" do assert AllYourBase.convert([1, 0, 1, 0, 1, 0], 2, 1) == nil end # @tag :pending test "convert second base is zero" do assert AllYourBase.convert([7], 10, 0) == nil end # @tag :pending test "convert second base is negative" do assert AllYourBase.convert([1], 2, -7) == nil end # @tag :pending test "convert both bases are negative" do assert AllYourBase.convert([1], -2, -7) == nil end end
24.055556
67
0.618168
ff5f3298f4de560c37c618829671b49d3ae064eb
2,009
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/activities.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/activities.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/activities.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DFAReporting.V33.Model.Activities do @moduledoc """ Represents an activity group. ## Attributes * `filters` (*type:* `list(GoogleApi.DFAReporting.V33.Model.DimensionValue.t)`, *default:* `nil`) - List of activity filters. The dimension values need to be all either of type "dfa:activity" or "dfa:activityGroup". * `kind` (*type:* `String.t`, *default:* `nil`) - The kind of resource this is, in this case dfareporting#activities. * `metricNames` (*type:* `list(String.t)`, *default:* `nil`) - List of names of floodlight activity metrics. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :filters => list(GoogleApi.DFAReporting.V33.Model.DimensionValue.t()) | nil, :kind => String.t() | nil, :metricNames => list(String.t()) | nil } field(:filters, as: GoogleApi.DFAReporting.V33.Model.DimensionValue, type: :list) field(:kind) field(:metricNames, type: :list) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.Activities do def decode(value, options) do GoogleApi.DFAReporting.V33.Model.Activities.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.Activities do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.90566
219
0.720757
ff5f36d8772fdc4d05e566c26778c5a7410168d7
2,799
ex
Elixir
apps/omg_conformance/test/support/conformance/merkle_proofs.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
apps/omg_conformance/test/support/conformance/merkle_proofs.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
apps/omg_conformance/test/support/conformance/merkle_proofs.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. defmodule Support.Conformance.MerkleProofs do @moduledoc """ Utility functions used when testing Elixir vs Solidity implementation conformance """ import ExUnit.Assertions, only: [assert: 1] alias OMG.Eth.Encoding @doc """ Checks if the provided proof data returns true (valid proof) in the contract """ def solidity_proof_valid(leaf, index, root_hash, proof, contract) do signature = "checkMembership(bytes,uint256,bytes32,bytes)" args = [leaf, index, root_hash, proof] return_types = [:bool] try do {:ok, result} = call_contract(contract, signature, args, return_types) result # Some incorrect proofs throw, and end up returning something that the ABI decoder borks on, hence rescue rescue e in CaseClauseError -> # this term holds the failure reason, but attempted to be decoded as a bool. It is a huge int %{term: failed_decoding_reason} = e # now we bring it back to binary form binary_reason = :binary.encode_unsigned(failed_decoding_reason) # it should contain 4 bytes of the function selector and then zeros assert_contract_reverted(binary_reason) false end end # see similar function in `Support.Conformance.SignaturesHashes` defp assert_contract_reverted(chopped_reason_binary_result) do # only geth is supported for the merkle proof conformance tests for now :geth = Application.fetch_env!(:omg_eth, :eth_node) # revert from `call_contract` it returns something resembling a reason # binary (beginning with 4-byte function selector). We need to assume that this is in fact a revert assert <<0::size(28)-unit(8)>> = binary_part(chopped_reason_binary_result, 4, 28) end defp call_contract(contract, signature, args, return_types) do data = ABI.encode(signature, args) {:ok, return} = Ethereumex.HttpClient.eth_call(%{to: Encoding.to_hex(contract), data: Encoding.to_hex(data)}) decode_answer(return, return_types) end defp decode_answer(enc_return, return_types) do single_return = enc_return |> Encoding.from_hex() |> ABI.TypeDecoder.decode(return_types) |> hd() {:ok, single_return} end end
37.32
113
0.72383
ff5f4066357b7cc5e76b6927d9f37aa046f22aa2
794
ex
Elixir
domotic_firmware/lib/domotic_firmware/temperature/probe/ds18b20.ex
gcauchon/domotic-pi
af61102fb946670b3e5ec93def6a5c053d894e79
[ "MIT" ]
1
2020-06-11T17:53:20.000Z
2020-06-11T17:53:20.000Z
domotic_firmware/lib/domotic_firmware/temperature/probe/ds18b20.ex
gcauchon/domotic-pi
af61102fb946670b3e5ec93def6a5c053d894e79
[ "MIT" ]
9
2020-12-15T21:19:59.000Z
2021-11-23T13:23:11.000Z
domotic_firmware/lib/domotic_firmware/temperature/probe/ds18b20.ex
gcauchon/domotic-pi
af61102fb946670b3e5ec93def6a5c053d894e79
[ "MIT" ]
1
2021-03-10T15:31:01.000Z
2021-03-10T15:31:01.000Z
defmodule DomoticFirmware.Temperature.Probe.DS18B20 do @behaviour Domotic.Temperature.Probe.Behaviour @base_dir "/sys/bus/w1/devices" def read do with sensor_id <- get_sensor_id(), data <- read_sensor_data(sensor_id), {temp, _} when is_integer(temp) <- parse_temperature(data) do {:ok, temp / 1000} else _ -> {:error, "Invalid sensor configuration"} end end defp get_sensor_id() do File.ls!(@base_dir) |> Enum.filter(&String.starts_with?(&1, "28-")) |> List.first() end defp read_sensor_data(sensor_id), do: File.read!("#{@base_dir}/#{sensor_id}/w1_slave") defp parse_temperature(data) do Regex.run(~r/t=(-?[[:digit:]]+)/, data, capture: :all_but_first) |> List.first() |> Integer.parse() end end
25.612903
88
0.638539
ff5f8b3043033e181e04fbb5fb32e6be7d44974d
2,381
ex
Elixir
clients/storage_transfer/lib/google_api/storage_transfer/v1/model/status.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/storage_transfer/lib/google_api/storage_transfer/v1/model/status.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/storage_transfer/lib/google_api/storage_transfer/v1/model/status.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.StorageTransfer.V1.Model.Status do @moduledoc """ The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). ## Attributes * `code` (*type:* `integer()`, *default:* `nil`) - The status code, which should be an enum value of google.rpc.Code. * `details` (*type:* `list(map())`, *default:* `nil`) - A list of messages that carry the error details. There is a common set of message types for APIs to use. * `message` (*type:* `String.t`, *default:* `nil`) - A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :code => integer(), :details => list(map()), :message => String.t() } field(:code) field(:details, type: :list) field(:message) end defimpl Poison.Decoder, for: GoogleApi.StorageTransfer.V1.Model.Status do def decode(value, options) do GoogleApi.StorageTransfer.V1.Model.Status.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.StorageTransfer.V1.Model.Status do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.403226
134
0.715246