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
08eb3a78136570ee72cceb17fc0b0791cb721519
4,038
exs
Elixir
test/game/session/create_account_test.exs
NatTuck/ex_venture
7a74d33025a580f1e3e93d3755f22258eb3e9127
[ "MIT" ]
null
null
null
test/game/session/create_account_test.exs
NatTuck/ex_venture
7a74d33025a580f1e3e93d3755f22258eb3e9127
[ "MIT" ]
null
null
null
test/game/session/create_account_test.exs
NatTuck/ex_venture
7a74d33025a580f1e3e93d3755f22258eb3e9127
[ "MIT" ]
null
null
null
defmodule Game.Session.CreateAccountTest do use ExUnit.Case use Data.ModelCase use Networking.SocketCase alias Game.Session.CreateAccount setup do human = create_race() fighter = create_class() %{race: human, class: fighter} end test "start creating an account by entering a name", %{socket: socket} do state = CreateAccount.process("user", %{socket: socket}) assert state.create.name == "user" assert @socket.get_prompts() == [{socket, "Race: "}] end test "displays an error if name has a space", %{socket: socket} do %{socket: socket} = CreateAccount.process("user name", %{socket: socket}) assert @socket.get_prompts() == [{socket, "Name: "}] end test "pick a race", %{socket: socket, race: human} do state = CreateAccount.process("human", %{socket: socket, create: %{name: "user"}}) assert state.create.race == human assert @socket.get_prompts() == [{socket, "Class: "}] end test "picking a race again if a mistype", %{socket: socket} do state = CreateAccount.process("humn", %{socket: socket, create: %{name: "user"}}) refute Map.has_key?(state.create, :race) assert @socket.get_prompts() == [{socket, "Race: "}] end test "pick a class", %{socket: socket, race: human, class: fighter} do state = CreateAccount.process("fighter", %{socket: socket, create: %{name: "user", race: human}}) assert state.create.class == fighter assert @socket.get_prompts() == [{socket, "Email (optional, enter for blank): "}] end test "picking a class again if a mistype", %{socket: socket, race: human} do state = CreateAccount.process("figter", %{socket: socket, create: %{name: "user", race: human}}) refute Map.has_key?(state.create, :class) assert @socket.get_prompts() == [{socket, "Class: "}] end test "ask for an optional email", %{socket: socket, race: human, class: fighter} do create_config(:starting_save, base_save() |> Poison.encode!) state = CreateAccount.process("user@example.com", %{socket: socket, create: %{name: "user", race: human, class: fighter}}) assert state.create.email == "user@example.com" assert @socket.get_prompts() == [{socket, "Password: "}] end test "ask for an optional email - give none", %{socket: socket, race: human, class: fighter} do create_config(:starting_save, base_save() |> Poison.encode!) state = CreateAccount.process("", %{socket: socket, create: %{name: "user", race: human, class: fighter}}) assert state.create.email == "" assert @socket.get_prompts() == [{socket, "Password: "}] end test "request email again if it doesn't have an @ sign", %{socket: socket, race: human, class: fighter} do create_config(:starting_save, base_save() |> Poison.encode!) state = CreateAccount.process("userexample.com", %{socket: socket, create: %{name: "user", race: human, class: fighter}}) refute Map.has_key?(state.create, :email) assert @socket.get_prompts() == [{socket, "Email (optional, enter for blank): "}] end test "create the account after password is entered", %{socket: socket, race: human, class: fighter} do create_config(:starting_save, base_save() |> Poison.encode!) create_config(:after_sign_in_message, "Hi") state = CreateAccount.process("password", %{socket: socket, create: %{name: "user", email: "", race: human, class: fighter}}) refute Map.has_key?(state, :create) [{^socket, "Welcome, user!\n\nHi\n"}, {^socket, "{command send='Sign In'}[Press enter to continue]{/command}"}] = @socket.get_echos() end test "failure creating the account after entering the password", %{socket: socket, race: human, class: fighter} do create_config(:starting_save, %{} |> Poison.encode!) state = CreateAccount.process("", %{socket: socket, create: %{name: "user", email: "", race: human, class: fighter}}) refute Map.has_key?(state, :create) assert [{^socket, "There was a problem creating your account.\nPlease start over." <> _}] = @socket.get_echos() end end
40.38
137
0.665676
08eb3bf603dc9818e5ade4a44f0264a0d5a14952
420
ex
Elixir
lib/blockfrost/response/cardano/assets/asset_addresses_response.ex
blockfrost/blockfrost-elixir
b1f8ea7ae47cd3a7037e1c9ed0d3691fc775bdec
[ "Apache-2.0" ]
13
2021-08-31T03:54:37.000Z
2022-01-30T17:39:40.000Z
lib/blockfrost/response/cardano/assets/asset_addresses_response.ex
blockfrost/blockfrost-elixir
b1f8ea7ae47cd3a7037e1c9ed0d3691fc775bdec
[ "Apache-2.0" ]
6
2021-08-30T04:45:52.000Z
2021-09-23T09:15:08.000Z
lib/blockfrost/response/cardano/assets/asset_addresses_response.ex
blockfrost/blockfrost-elixir
b1f8ea7ae47cd3a7037e1c9ed0d3691fc775bdec
[ "Apache-2.0" ]
null
null
null
defmodule Blockfrost.Response.AssetAddressesResponse do use Blockfrost.Response.BaseSchema defmodule AssetAddress do use Blockfrost.Response.BaseSchema embedded_schema do field(:address, :string) field(:quantity, :string) end end @type t :: [%AssetAddress{address: String.t(), quantity: String.t()}] @doc false def cast(body) do Enum.map(body, &AssetAddress.cast/1) end end
21
71
0.707143
08eb5170db9acd8138ae752b42b146ad2eb6d50d
9,119
ex
Elixir
apps/astarte_pairing/lib/astarte_pairing/queries.ex
matt-mazzucato/astarte
34d84941a5019efc42321052f7f34b7d907a38f2
[ "Apache-2.0" ]
3
2018-02-02T14:06:57.000Z
2019-01-11T00:50:40.000Z
apps/astarte_pairing/lib/astarte_pairing/queries.ex
matt-mazzucato/astarte
34d84941a5019efc42321052f7f34b7d907a38f2
[ "Apache-2.0" ]
6
2019-11-15T15:58:56.000Z
2019-12-05T16:49:04.000Z
apps/astarte_pairing/lib/astarte_pairing/queries.ex
matt-mazzucato/astarte
34d84941a5019efc42321052f7f34b7d907a38f2
[ "Apache-2.0" ]
1
2018-07-09T16:08:07.000Z
2018-07-09T16:08:07.000Z
# # This file is part of Astarte. # # Copyright 2017-2018 Ispirata Srl # # 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 Astarte.Pairing.Queries do @moduledoc """ This module is responsible for the interaction with the database. """ alias CQEx.Query alias CQEx.Result require Logger @protocol_revision 1 def get_agent_public_key_pems(client) do get_jwt_public_key_pem = """ SELECT blobAsVarchar(value) FROM kv_store WHERE group='auth' AND key='jwt_public_key_pem'; """ # TODO: add additional keys query = Query.new() |> Query.statement(get_jwt_public_key_pem) with {:ok, res} <- Query.call(client, query), ["system.blobasvarchar(value)": pem] <- Result.head(res) do {:ok, [pem]} else :empty_dataset -> {:error, :public_key_not_found} error -> Logger.warn("DB error: #{inspect(error)}") {:error, :database_error} end end def register_device(client, device_id, extended_id, credentials_secret, opts \\ []) do statement = """ SELECT first_credentials_request, first_registration FROM devices WHERE device_id=:device_id """ device_exists_query = Query.new() |> Query.statement(statement) |> Query.put(:device_id, device_id) |> Query.consistency(:quorum) with {:ok, res} <- Query.call(client, device_exists_query) do case Result.head(res) do :empty_dataset -> registration_timestamp = DateTime.utc_now() |> DateTime.to_unix(:millisecond) Logger.info("register request for new device: #{inspect(extended_id)}") do_register_device(client, device_id, credentials_secret, registration_timestamp, opts) [first_credentials_request: nil, first_registration: registration_timestamp] -> Logger.info("register request for existing unconfirmed device: #{inspect(extended_id)}") do_register_device(client, device_id, credentials_secret, registration_timestamp, opts) [first_credentials_request: _timestamp, first_registration: _registration_timestamp] -> Logger.warn("register request for existing confirmed device: #{inspect(extended_id)}") {:error, :already_registered} end else error -> Logger.warn("DB error: #{inspect(error)}") {:error, :database_error} end end def unregister_device(client, device_id) do with :ok <- check_already_registered_device(client, device_id), :ok <- do_unregister_device(client, device_id) do :ok else %{acc: _acc, msg: msg} -> Logger.warn("DB error: #{inspect(msg)}") {:error, :database_error} {:error, reason} -> Logger.warn("Unregister error: #{inspect(reason)}") {:error, reason} end end defp check_already_registered_device(client, device_id) do statement = """ SELECT device_id FROM devices WHERE device_id=:device_id """ query = Query.new() |> Query.statement(statement) |> Query.put(:device_id, device_id) |> Query.consistency(:quorum) with {:ok, res} <- Query.call(client, query) do case Result.head(res) do [device_id: _device_id] -> :ok :empty_dataset -> {:error, :device_not_registered} end end end defp do_unregister_device(client, device_id) do statement = """ INSERT INTO devices (device_id, first_credentials_request, credentials_secret) VALUES (:device_id, :first_credentials_request, :credentials_secret) """ query = Query.new() |> Query.statement(statement) |> Query.put(:device_id, device_id) |> Query.put(:first_credentials_request, nil) |> Query.put(:credentials_secret, nil) |> Query.consistency(:quorum) with {:ok, _res} <- Query.call(client, query) do :ok end end def select_device_for_credentials_request(client, device_id) do statement = """ SELECT first_credentials_request, cert_aki, cert_serial, inhibit_credentials_request, credentials_secret FROM devices WHERE device_id=:device_id """ do_select_device(client, device_id, statement) end def select_device_for_info(client, device_id) do statement = """ SELECT credentials_secret, inhibit_credentials_request, first_credentials_request FROM devices WHERE device_id=:device_id """ do_select_device(client, device_id, statement) end def select_device_for_verify_credentials(client, device_id) do statement = """ SELECT credentials_secret FROM devices WHERE device_id=:device_id """ do_select_device(client, device_id, statement) end def update_device_after_credentials_request(client, device_id, cert_data, device_ip, nil) do first_credentials_request_timestamp = DateTime.utc_now() |> DateTime.to_unix(:millisecond) update_device_after_credentials_request( client, device_id, cert_data, device_ip, first_credentials_request_timestamp ) end def update_device_after_credentials_request( client, device_id, %{serial: serial, aki: aki} = _cert_data, device_ip, first_credentials_request_timestamp ) do statement = """ UPDATE devices SET cert_aki=:cert_aki, cert_serial=:cert_serial, last_credentials_request_ip=:last_credentials_request_ip, first_credentials_request=:first_credentials_request WHERE device_id=:device_id """ query = Query.new() |> Query.statement(statement) |> Query.put(:device_id, device_id) |> Query.put(:cert_aki, aki) |> Query.put(:cert_serial, serial) |> Query.put(:last_credentials_request_ip, device_ip) |> Query.put(:first_credentials_request, first_credentials_request_timestamp) |> Query.put(:protocol_revision, @protocol_revision) |> Query.consistency(:quorum) case Query.call(client, query) do {:ok, _res} -> :ok error -> Logger.warn("DB error: #{inspect(error)}") {:error, :database_error} end end defp do_select_device(client, device_id, select_statement) do device_query = Query.new() |> Query.statement(select_statement) |> Query.put(:device_id, device_id) |> Query.consistency(:quorum) with {:ok, res} <- Query.call(client, device_query), device_row when is_list(device_row) <- Result.head(res) do {:ok, device_row} else :empty_dataset -> {:error, :device_not_found} error -> Logger.warn("DB error: #{inspect(error)}") {:error, :database_error} end end defp do_register_device(client, device_id, credentials_secret, registration_timestamp, opts) do statement = """ INSERT INTO devices (device_id, first_registration, credentials_secret, inhibit_credentials_request, protocol_revision, total_received_bytes, total_received_msgs, introspection, introspection_minor) VALUES (:device_id, :first_registration, :credentials_secret, :inhibit_credentials_request, :protocol_revision, :total_received_bytes, :total_received_msgs, :introspection, :introspection_minor) """ {introspection, introspection_minor} = opts |> Keyword.get(:initial_introspection, []) |> build_initial_introspection_maps() query = Query.new() |> Query.statement(statement) |> Query.put(:device_id, device_id) |> Query.put(:first_registration, registration_timestamp) |> Query.put(:credentials_secret, credentials_secret) |> Query.put(:inhibit_credentials_request, false) |> Query.put(:protocol_revision, 0) |> Query.put(:total_received_bytes, 0) |> Query.put(:total_received_msgs, 0) |> Query.put(:introspection, introspection) |> Query.put(:introspection_minor, introspection_minor) |> Query.consistency(:quorum) case Query.call(client, query) do {:ok, _res} -> :ok error -> Logger.warn("DB error: #{inspect(error)}") {:error, :database_error} end end defp build_initial_introspection_maps(initial_introspection) do Enum.reduce(initial_introspection, {[], []}, fn introspection_entry, {majors, minors} -> %{ interface_name: interface_name, major_version: major_version, minor_version: minor_version } = introspection_entry {[{interface_name, major_version} | majors], [{interface_name, minor_version} | minors]} end) end end
29.898361
111
0.672771
08eb522ad9c50b48886ad82b9c9cbe0c96035415
1,519
ex
Elixir
clients/iap/lib/google_api/iap/v1/model/test_iam_permissions_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/iap/lib/google_api/iap/v1/model/test_iam_permissions_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/iap/lib/google_api/iap/v1/model/test_iam_permissions_response.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.IAP.V1.Model.TestIamPermissionsResponse do @moduledoc """ Response message for `TestIamPermissions` method. ## Attributes * `permissions` (*type:* `list(String.t)`, *default:* `nil`) - A subset of `TestPermissionsRequest.permissions` that the caller is allowed. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :permissions => list(String.t()) | nil } field(:permissions, type: :list) end defimpl Poison.Decoder, for: GoogleApi.IAP.V1.Model.TestIamPermissionsResponse do def decode(value, options) do GoogleApi.IAP.V1.Model.TestIamPermissionsResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.IAP.V1.Model.TestIamPermissionsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.319149
143
0.743252
08eb5ba09effff744e2f2e91e7de77dc6e9ff404
417
exs
Elixir
test/slurpee_web/views/error_view_test.exs
fremantle-industries/slurpee
e4c36130f96d266ca7ec115577b366f4531c6f29
[ "MIT" ]
15
2021-03-24T07:46:34.000Z
2022-02-16T19:09:58.000Z
test/slurpee_web/views/error_view_test.exs
fremantle-industries/slurpee
e4c36130f96d266ca7ec115577b366f4531c6f29
[ "MIT" ]
30
2021-03-22T23:31:56.000Z
2022-03-01T00:17:50.000Z
test/slurpee_web/views/error_view_test.exs
fremantle-industries/slurpee
e4c36130f96d266ca7ec115577b366f4531c6f29
[ "MIT" ]
1
2021-09-18T23:00:57.000Z
2021-09-18T23:00:57.000Z
defmodule SlurpeeWeb.ErrorViewTest do use SlurpeeWeb.ConnCase, async: true # Bring render/3 and render_to_string/3 for testing custom views import Phoenix.View test "renders 404.html" do assert render_to_string(SlurpeeWeb.ErrorView, "404.html", []) == "Not Found" end test "renders 500.html" do assert render_to_string(SlurpeeWeb.ErrorView, "500.html", []) == "Internal Server Error" end end
27.8
92
0.733813
08eb776d8dd39decfb764d1e758b45de445932dd
2,198
exs
Elixir
test/exdns/storage_test.exs
jeanparpaillon/exdns
53b7fc780399eda96d42052e11e03d5eb0dcd789
[ "MIT" ]
16
2016-05-26T10:11:57.000Z
2021-01-08T15:09:19.000Z
test/exdns/storage_test.exs
jeanparpaillon/exdns
53b7fc780399eda96d42052e11e03d5eb0dcd789
[ "MIT" ]
9
2016-08-11T00:48:27.000Z
2020-09-16T22:10:07.000Z
test/exdns/storage_test.exs
jeanparpaillon/exdns
53b7fc780399eda96d42052e11e03d5eb0dcd789
[ "MIT" ]
11
2016-08-10T08:13:36.000Z
2021-04-03T10:20:11.000Z
defmodule Exdns.StorageTest do use ExUnit.Case, async: false test "create" do assert Exdns.Storage.create(:test) == :ok end test "insert" do Exdns.Storage.create(:test) assert Exdns.Storage.insert(:test, {:key, :value}) assert :ets.lookup(:test, :key) == [key: :value] end test "delete table" do Exdns.Storage.create(:test) assert Exdns.Storage.delete_table(:test) == :ok end test "delete key from table" do Exdns.Storage.create(:test) assert Exdns.Storage.delete(:test, :key) == :ok Exdns.Storage.insert(:test, {:key, :value}) assert Exdns.Storage.select(:test, :key) == [key: :value] assert Exdns.Storage.delete(:test, :key) == :ok assert Exdns.Storage.select(:test, :key) == [] end test "backup table not implemented" do assert Exdns.Storage.backup_table(:test) == {:error, :not_implemented} end test "backup tables not implemented" do assert Exdns.Storage.backup_tables() == {:error, :not_implemented} end test "select key from table" do Exdns.Storage.create(:test) assert Exdns.Storage.select(:test, :key) == [] Exdns.Storage.insert(:test, {:key, :value}) assert Exdns.Storage.select(:test, :key) == [key: :value] end test "select match spec from table" do Exdns.Storage.create(:test) assert Exdns.Storage.select(:test, [{{:"$1", :"$2"}, [], [{{:"$1", :"$2"}}]}], :infinite) == [] Exdns.Storage.insert(:test, {:key, :value}) assert Exdns.Storage.select(:test, :key) == [key: :value] end test "foldl on table" do Exdns.Storage.create(:test) Exdns.Storage.insert(:test, {:key1, 1}) Exdns.Storage.insert(:test, {:key2, 1}) assert Exdns.Storage.foldl(fn({_key, val}, acc) -> val + acc end, 0, :test) == 2 end test "empty table" do Exdns.Storage.create(:test) Exdns.Storage.insert(:test, {:key, :value}) assert Exdns.Storage.select(:test, :key) == [key: :value] Exdns.Storage.empty_table(:test) assert Exdns.Storage.select(:test, :key) == [] end test "list table" do Exdns.Storage.create(:test) Exdns.Storage.insert(:test, {:key, :value}) assert Exdns.Storage.list_table(:test) == [key: :value] end end
30.109589
99
0.639672
08eb7c456efd7dbcf42bb4279bc14d789be55993
1,023
ex
Elixir
data/web/test/support/channel_case.ex
lydiadwyer/trains_elixir
16da18d4582307f4967b6cce7320e9aa08a849c3
[ "Apache-2.0" ]
null
null
null
data/web/test/support/channel_case.ex
lydiadwyer/trains_elixir
16da18d4582307f4967b6cce7320e9aa08a849c3
[ "Apache-2.0" ]
null
null
null
data/web/test/support/channel_case.ex
lydiadwyer/trains_elixir
16da18d4582307f4967b6cce7320e9aa08a849c3
[ "Apache-2.0" ]
null
null
null
defmodule TrainsElixir.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` and also import other functionality to make it easier to build and query models. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with channels use Phoenix.ChannelTest alias TrainsElixir.Repo import Ecto import Ecto.Changeset import Ecto.Query # The default endpoint for testing @endpoint TrainsElixir.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(TrainsElixir.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(TrainsElixir.Repo, {:shared, self()}) end :ok end end
23.25
74
0.707722
08eb9240a89eb5b707ce02755fca62123b53550f
3,078
exs
Elixir
mix.exs
hippware/wocky_queue
45e7121245525763fb4ca90cb22d476a55eaa952
[ "MIT" ]
12
2019-08-30T19:10:54.000Z
2022-03-19T13:53:19.000Z
mix.exs
hippware/wocky_queue
45e7121245525763fb4ca90cb22d476a55eaa952
[ "MIT" ]
19
2019-03-06T17:28:11.000Z
2020-02-18T17:00:28.000Z
mix.exs
hippware/wocky_queue
45e7121245525763fb4ca90cb22d476a55eaa952
[ "MIT" ]
2
2019-12-17T12:51:20.000Z
2021-10-14T18:21:02.000Z
defmodule DawdleDB.MixProject do use Mix.Project @version "0.7.3" def project do [ app: :dawdle_db, version: @version, elixir: "~> 1.7", start_permanent: Mix.env() == :prod, elixirc_paths: elixirc_paths(Mix.env()), deps: deps(), aliases: aliases(), package: package(), description: description(), docs: docs(), test_coverage: [tool: ExCoveralls], preferred_cli_env: [ coveralls: :test, "coveralls.detail": :test, "coveralls.html": :test ], dialyzer: [ flags: [ :error_handling, :race_conditions, :underspecs, :unknown, :unmatched_returns ], plt_add_apps: [:ex_unit], ignore_warnings: "dialyzer_ignore.exs", list_unused_filters: true ] ] end def application do [ extra_applications: [:logger], env: [ log_cleanup_errors: true, channel: {:system, "DAWDLEDB_CHANNEL", "dawdle_db_watcher_notify"}, batch_timeout: {:system, :integer, "DAWDLEDB_BATCH_TIMEOUT", 50}, batch_max_size: {:system, :integer, "DAWDLEDB_BATCH_MAX_SIZE", 10}, db: [ database: {:system, "DAWDLEDB_DB_DATABASE", ""}, username: {:system, "DAWDLEDB_DB_USERNAME", "postgres"}, password: {:system, "DAWDLEDB_DB_PASSWORD", "password"}, hostname: {:system, "DAWDLEDB_DB_HOSTNAME", "localhost"}, port: {:system, :integer, "DAWDLEDB_DB_PORT", 5432}, pool_size: {:system, :integer, "DAWDLEDB_DB_POOL_SIZE", 10} ] ] ] end # This makes sure your factory and any other modules in test/support are # compiled when in the test environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] defp deps do [ {:confex, "~> 3.4"}, {:credo, "~> 1.0", only: [:dev, :test], runtime: false}, {:dawdle, "~> 0.7"}, {:dialyxir, "~> 1.0.0-rc.4", only: [:dev], runtime: false}, {:ecto, "~> 3.0"}, {:ecto_sql, "~> 3.0"}, {:ex_aws, "~> 2.0"}, {:ex_check, ">= 0.0.0", only: [:dev, :test], runtime: false}, {:ex_doc, ">= 0.0.0", only: [:dev, :test]}, {:ex_machina, "~> 2.3", only: :test}, {:excoveralls, "~> 0.10", only: :test}, {:faker, "~> 0.12", only: :test}, {:poison, "~> 3.0 or ~> 4.0"}, {:swarm, "~> 3.4"}, {:postgrex, "~> 0.15.3"}, {:telemetry, "~> 0.4.0"}, {:timex, "~> 3.5"} ] end defp aliases do [ ci: ["ecto.migrate", "check --except dialyzer"] ] end defp description do """ DawdleDB uses Dawdle and SQS to capture change notifications from PostgreSQL. """ end defp package do [ maintainers: ["Bernard Duggan", "Phil Toland"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/hippware/dawdle_db"} ] end defp docs do [ source_ref: "v#{@version}", main: "readme", extras: ["README.md"] ] end end
26.765217
75
0.539311
08ebcb890c3b239c316932a5e4b702392c484768
838
exs
Elixir
test/lob/us_verification_test.exs
itsachen/lob-elixir
b1bacd56fd3a1752cdbda4614354b3120cbc0841
[ "MIT" ]
11
2018-02-07T17:59:17.000Z
2021-11-21T14:11:15.000Z
test/lob/us_verification_test.exs
itsachen/lob-elixir
b1bacd56fd3a1752cdbda4614354b3120cbc0841
[ "MIT" ]
34
2018-02-13T19:59:27.000Z
2022-03-02T19:50:41.000Z
test/lob/us_verification_test.exs
itsachen/lob-elixir
b1bacd56fd3a1752cdbda4614354b3120cbc0841
[ "MIT" ]
8
2019-01-30T00:39:36.000Z
2022-03-01T15:32:17.000Z
defmodule Lob.USVerificationTest do use ExUnit.Case alias Lob.USVerification setup do %{ sample_address: %{ recipient: "LOB.COM", primary_line: "185 BERRY ST STE 6600", city: "SAN FRANCISCO", state: "CA", zip_code: "94107" } } end describe "verify/2" do test "verifies a US address", %{sample_address: sample_address} do {:ok, verified_address, _headers} = USVerification.verify(sample_address) assert verified_address.recipient == "TEST KEYS DO NOT VERIFY ADDRESSES" assert verified_address.primary_line == "SET `primary_line` TO 'deliverable' and `zip_code` to '11111' TO SIMULATE AN ADDRESS" assert verified_address.secondary_line == "SEE https://www.lob.com/docs#us-verification-test-environment FOR MORE INFO" end end end
27.032258
132
0.673031
08ebddc181c2ac2297aad6c071aad638bf002f74
2,018
exs
Elixir
mix.exs
Dhall777/systemstats
380426af8fc898521201311b11881cc8d2db3388
[ "BSD-3-Clause" ]
null
null
null
mix.exs
Dhall777/systemstats
380426af8fc898521201311b11881cc8d2db3388
[ "BSD-3-Clause" ]
null
null
null
mix.exs
Dhall777/systemstats
380426af8fc898521201311b11881cc8d2db3388
[ "BSD-3-Clause" ]
null
null
null
defmodule Systemstats.MixProject do use Mix.Project def project do [ app: :systemstats, version: "0.1.0", elixir: "~> 1.7", elixirc_paths: elixirc_paths(Mix.env()), compilers: [:phoenix, :gettext] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps() ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {Systemstats.Application, []}, extra_applications: [:logger, :runtime_tools, :os_mon] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [ {:decimal, "~> 2.0"}, {:contex, git: "https://github.com/mindok/contex"}, {:phoenix, "~> 1.5.7"}, {:phoenix_ecto, "~> 4.1"}, {:ecto_sql, "~> 3.4"}, {:postgrex, ">= 0.0.0"}, {:phoenix_live_view, "~> 0.15.0"}, {:floki, ">= 0.27.0", only: :test}, {:phoenix_html, "~> 2.11"}, {:phoenix_live_reload, "~> 1.2", only: :dev}, {:phoenix_live_dashboard, "~> 0.4"}, {:telemetry_metrics, "~> 0.4"}, {:telemetry_poller, "~> 0.4"}, {:gettext, "~> 0.11"}, {:jason, "~> 1.0"}, {:plug_cowboy, "~> 2.0"} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to install project dependencies and perform other setup tasks, run: # # $ mix setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ setup: ["deps.get", "ecto.setup", "cmd npm install --prefix assets"], "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"] ] end end
28.828571
84
0.574827
08ebe004f20f0c0aa1d6990199535a045918a993
3,843
ex
Elixir
lib/dynamo/router/utils.ex
aforward-oss/dynamo
c8d47dab7de3ce730d4ec314d23e171051d5eff7
[ "Apache-2.0" ]
1
2017-09-09T21:00:14.000Z
2017-09-09T21:00:14.000Z
lib/dynamo/router/utils.ex
aforward-oss/dynamo
c8d47dab7de3ce730d4ec314d23e171051d5eff7
[ "Apache-2.0" ]
null
null
null
lib/dynamo/router/utils.ex
aforward-oss/dynamo
c8d47dab7de3ce730d4ec314d23e171051d5eff7
[ "Apache-2.0" ]
null
null
null
defexception Dynamo.Router.InvalidSpecError, message: "invalid route specification" defmodule Dynamo.Router.Utils do @moduledoc false @doc """ Convert a given verb to its connection representation. """ def normalize_verb(verb) do String.upcase(to_string(verb)) end @doc """ Generates a representation that will only match routes according to the given `spec`. ## Examples generate_match("/foo/:id") => ["foo", { :id, [], nil }] """ def generate_match(spec) when is_binary(spec) do generate_match list_split(spec), [], [] end def generate_match(match) do { [], match } end @doc """ Generates a fowarding representation that will match any route starting with the given `spec`. ## Examples generate_forward("/foo/:id") => ["foo", { :id, [], nil } | _glob] """ def generate_forward({ :_, _, _ }) do generate_forward "" end def generate_forward(list) when is_list(list) do [h|t] = Enum.reverse(list) glob = { :glob, [], nil } { [], Enum.reverse [ { :|, [], [h, glob] } | t ] } end def generate_forward(spec) when is_binary(spec) do generate_match list_split(spec) ++ ['*glob'], [], [] end @doc """ Splits the given path into several segments. It ignores both leading and trailing slashes in the path. ## Examples split("/foo/bar") #=> ['foo', 'bar'] """ def split(bin) do lc segment inlist String.split(bin, "/"), segment != "", do: segment end ## Helpers # Loops each segment checking for matches. defp generate_match([h|t], vars, acc) do handle_segment_match segment_match(h, []), t, vars, acc end defp generate_match([], vars, acc) do { vars |> Enum.uniq |> Enum.reverse, Enum.reverse(acc) } end # Handle each segment match. They can either be a # :literal ('foo'), an identifier (':bar') or a glob ('*path') def handle_segment_match({ :literal, literal }, t, vars, acc) do generate_match t, vars, [literal|acc] end def handle_segment_match({ :identifier, identifier, expr }, t, vars, acc) do generate_match t, [identifier|vars], [expr|acc] end def handle_segment_match({ :glob, identifier, expr }, t, vars, acc) do if t != [] do raise(Dynamo.Router.InvalidSpecError, message: "cannot have a *glob followed by other segments") end case acc do [hs|ts] -> acc = [{ :|, [], [hs, expr] } | ts] generate_match([], [identifier|vars], acc) _ -> { vars, expr } = generate_match([], [identifier|vars], [expr]) { vars, hd(expr) } end end # In a given segment, checks if there is a match. defp segment_match([?:|argument], []) do identifier = list_to_atom(argument) { :identifier, identifier, { identifier, [], nil } } end defp segment_match([?*|argument], []) do identifier = list_to_atom(argument) { :glob, identifier, { identifier, [], nil } } end defp segment_match([?:|argument], buffer) do identifier = list_to_atom(argument) var = { identifier, [], nil } expr = quote do unquote(binary_from_buffer(buffer)) <> unquote(var) end { :identifier, identifier, expr } end defp segment_match([?*|argument], buffer) do identifier = list_to_atom(argument) var = { identifier, [], nil } expr = quote [hygiene: [vars: false]] do [unquote(binary_from_buffer(buffer)) <> _ | _] = unquote(var) end { :glob, identifier, expr } end defp segment_match([h|t], buffer) do segment_match t, [h|buffer] end defp segment_match([], buffer) do { :literal, binary_from_buffer(buffer) } end defp list_split(bin) do lc segment inlist String.split(bin, "/"), segment != "", do: String.to_char_list!(segment) end defp binary_from_buffer(buffer) do iolist_to_binary(Enum.reverse(buffer)) end end
25.62
102
0.630497
08ebebd9cbde663f79935ba66e7420d24655f481
886
ex
Elixir
clients/cloud_shell/lib/google_api/cloud_shell/v1/metadata.ex
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
clients/cloud_shell/lib/google_api/cloud_shell/v1/metadata.ex
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
clients/cloud_shell/lib/google_api/cloud_shell/v1/metadata.ex
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2020 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.CloudShell.V1 do @moduledoc """ API client metadata for GoogleApi.CloudShell.V1. """ @discovery_revision "20200803" def discovery_revision(), do: @discovery_revision end
32.814815
74
0.759594
08ebec08707761ec05258410999881b9d71be9a1
65
ex
Elixir
lib/gamedex/repo.ex
Lugghawk/GameDex
680d67a925e16ee5ba357d529542d4be4d4c1b99
[ "MIT" ]
null
null
null
lib/gamedex/repo.ex
Lugghawk/GameDex
680d67a925e16ee5ba357d529542d4be4d4c1b99
[ "MIT" ]
null
null
null
lib/gamedex/repo.ex
Lugghawk/GameDex
680d67a925e16ee5ba357d529542d4be4d4c1b99
[ "MIT" ]
null
null
null
defmodule Gamedex.Repo do use Ecto.Repo, otp_app: :gamedex end
16.25
34
0.769231
08ec22ca67a1477e8c82257bcec30981c666c004
1,999
exs
Elixir
mix.exs
robertkeizer/broadway
bdec3f617116671662b81cc65db6f795848a7dee
[ "Apache-2.0" ]
null
null
null
mix.exs
robertkeizer/broadway
bdec3f617116671662b81cc65db6f795848a7dee
[ "Apache-2.0" ]
null
null
null
mix.exs
robertkeizer/broadway
bdec3f617116671662b81cc65db6f795848a7dee
[ "Apache-2.0" ]
null
null
null
defmodule Broadway.MixProject do use Mix.Project @version "1.0.0" @description "Build concurrent and multi-stage data ingestion and data processing pipelines" def project do [ app: :broadway, version: @version, elixir: "~> 1.7", name: "Broadway", description: @description, deps: deps(), docs: docs(), package: package(), test_coverage: [tool: ExCoveralls] ] end def application do [ extra_applications: [:logger] ] end defp deps do [ {:gen_stage, "~> 1.0"}, {:nimble_options, "~> 0.3.0"}, {:telemetry, "~> 0.4.3 or ~> 1.0"}, {:ex_doc, ">= 0.19.0", only: :docs}, {:excoveralls, "~> 0.13.3", only: :test} ] end defp docs do [ main: "introduction", source_ref: "v#{@version}", source_url: "https://github.com/dashbitco/broadway", extra_section: "Guides", extras: [ "guides/examples/introduction.md", "guides/examples/amazon-sqs.md", "guides/examples/apache-kafka.md", "guides/examples/google-cloud-pubsub.md", "guides/examples/rabbitmq.md", "guides/examples/custom-producers.md", "guides/internals/architecture.md" ], groups_for_extras: [ Examples: Path.wildcard("guides/examples/*.md"), Internals: Path.wildcard("guides/internals/*.md") ], groups_for_modules: [ # Ungrouped Modules: # # Broadway # Broadway.Message # Broadway.BatchInfo Acknowledgement: [ Broadway.Acknowledger, Broadway.CallerAcknowledger, Broadway.NoopAcknowledger ], Producers: [ Broadway.Producer, Broadway.DummyProducer ] ] ] end defp package do %{ licenses: ["Apache-2.0"], maintainers: ["Marlus Saraiva", "José Valim"], links: %{"GitHub" => "https://github.com/dashbitco/broadway"} } end end
23.797619
94
0.563782
08ec25f56d3f414423a9d4a2c72c59057e620d17
1,008
ex
Elixir
lib/guitars/endpoint.ex
jeredm/guitars
7e0e1d58220c5220b3b8abae2a2edca928f2db36
[ "Apache-2.0" ]
null
null
null
lib/guitars/endpoint.ex
jeredm/guitars
7e0e1d58220c5220b3b8abae2a2edca928f2db36
[ "Apache-2.0" ]
null
null
null
lib/guitars/endpoint.ex
jeredm/guitars
7e0e1d58220c5220b3b8abae2a2edca928f2db36
[ "Apache-2.0" ]
null
null
null
defmodule Guitars.Endpoint do use Phoenix.Endpoint, otp_app: :guitars socket "/socket", Guitars.UserSocket # Serve at "/" the static files from "priv/static" directory. # # You should set gzip to true if you are running phoenix.digest # when deploying your static files in production. plug Plug.Static, at: "/", from: :guitars, gzip: false, only: ~w(css fonts images js favicon.ico robots.txt) # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. if code_reloading? do socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket plug Phoenix.LiveReloader plug Phoenix.CodeReloader end plug Plug.RequestId plug Plug.Logger plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Poison plug Plug.MethodOverride plug Plug.Head plug Plug.Session, store: :cookie, key: "_guitars_key", signing_salt: "cA1ucDJn" plug Guitars.Router end
25.2
69
0.709325
08ec6b459c9dc5c8ce2596efeb96de718ed8125f
4,329
exs
Elixir
test/guss_test.exs
gullitmiranda/guss
feaf14a251ee2673ddff4b1a76fdf626705ffb46
[ "MIT" ]
3
2018-11-29T01:04:51.000Z
2020-01-29T17:55:37.000Z
test/guss_test.exs
gullitmiranda/guss
feaf14a251ee2673ddff4b1a76fdf626705ffb46
[ "MIT" ]
3
2018-12-14T00:33:44.000Z
2020-02-24T03:53:28.000Z
test/guss_test.exs
gullitmiranda/guss
feaf14a251ee2673ddff4b1a76fdf626705ffb46
[ "MIT" ]
3
2019-08-24T21:01:07.000Z
2020-02-20T18:43:23.000Z
defmodule GussTest do use ExUnit.Case, async: true alias Guss.Resource alias Guss describe "expires_in/1" do test "returns a timestamp for a future second" do expires = Guss.expires_in(3600) assert_valid_expires(expires, 3600) expires = Guss.expires_in({30, :seconds}) assert_valid_expires(expires, 30) end test "returns a timestamp for a future hour" do expires = Guss.expires_in({1, :hour}) assert_valid_expires(expires, 3600) end test "returns a timestamp for a future day" do expires = Guss.expires_in({3, :day}) assert_valid_expires(expires, 3600 * 24 * 3) end end test "get/3 returns a GET resource" do assert %Resource{http_verb: :get} = Guss.get("bucket", "objectname") end test "post/3 returns a GET resource" do assert %Resource{http_verb: :post} = Guss.post("bucket", "objectname") end test "put/3 returns a GET resource" do assert %Resource{http_verb: :put} = Guss.put("bucket", "objectname") end test "delete/3 returns a GET resource" do assert %Resource{http_verb: :delete} = Guss.delete("bucket", "objectname") end describe "new/3" do test "builds a URL to :get" do assert %Resource{http_verb: :get, bucket: "foo", objectname: "bar.txt"} = Guss.new("foo", "bar.txt") end test "sets :http_verb from opts" do Enum.each([:get, :put, :post, :delete], fn verb -> assert %Resource{http_verb: ^verb} = Guss.new("foo", "bar.txt", http_verb: verb) end) end test "sets :account from opts" do assert %Resource{account: "user@example.com"} = Guss.new("foo", "bar.txt", account: "user@example.com") end test "sets base_url from opts" do assert %Resource{base_url: "https://api.localhost"} = Guss.new("foo", "bar.txt", base_url: "https://api.localhost") end test "sets content_type from opts" do assert %Resource{content_type: "video/mp4"} = Guss.new("foo", "bar.mp4", content_type: "video/mp4") end test "sets content_md5 from opts" do hash = :md5 |> :crypto.hash("some content") |> Base.encode16(case: :lower) assert %Resource{content_md5: ^hash} = Guss.new("foo", "bar.mp4", content_md5: hash) end test "sets expires from opts" do expires = Guss.expires_in({1, :day}) assert %Resource{expires: ^expires} = Guss.new("foo", "bar.txt", expires: expires) end end describe "sign/1" do setup _ do {:ok, account} = Goth.Config.get("client_email") {:ok, private_key} = Goth.Config.get("private_key") {:ok, account: account, private_key: private_key} end test "with default params, url expires in 1 hour" do url = %Resource{bucket: "foo", objectname: "bar.txt"} expected_url = %{url | expires: Guss.expires_in({1, :hour})} {:ok, string} = Guss.sign(url) assert {:ok, ^string} = Guss.sign(expected_url) end test "with valid params, returns {:ok, url}", %{account: account, private_key: private_key} do url = %Resource{ bucket: "foo", objectname: "bar.txt", expires: Guss.expires_in({2, :hours}) } {:ok, string} = Guss.sign(url) assert String.match?(string, ~r/^https:\/\/storage.googleapis.com\/foo\/bar.txt\?Expires=/) parsed_url = URI.parse(string) query = parsed_url |> Map.fetch!(:query) |> URI.decode_query() assert is_map(query) assert Map.get(query, "GoogleAccessId", false) assert Map.get(query, "GoogleAccessId") == account assert Map.get(query, "Expires", false) query |> Map.get("Expires") |> String.to_integer() |> assert_valid_expires(3600 * 2) s2s = Guss.StorageV2Signer.string_to_sign(url) {:ok, expected_signature} = Guss.Signature.generate(s2s, private_key) assert Map.get(query, "Signature", false) assert Map.get(query, "Signature", false) == expected_signature end end defp assert_valid_expires(expires, seconds, delta \\ 1) do now = DateTime.utc_now() |> DateTime.to_unix() expected = now + seconds assert_in_delta( expires, expected, delta, "expires delta expected to be less than #{delta} second(s), but it is not" ) end end
28.86
98
0.626473
08ecb1366d4a644116fd5abe7f37bfb414dadd26
995
ex
Elixir
lib/queuetopia/performer.ex
tailcalldev/pg_queuetopia
ea18c6a7633a78cc82473b9b60da205454009af4
[ "MIT" ]
null
null
null
lib/queuetopia/performer.ex
tailcalldev/pg_queuetopia
ea18c6a7633a78cc82473b9b60da205454009af4
[ "MIT" ]
null
null
null
lib/queuetopia/performer.ex
tailcalldev/pg_queuetopia
ea18c6a7633a78cc82473b9b60da205454009af4
[ "MIT" ]
null
null
null
defmodule PgQueuetopia.Performer do @moduledoc """ The behaviour for a PgQueuetopia performer. """ alias PgQueuetopia.Queue.Job @doc """ Callback invoked by the PgQueuetopia to perfom a job. It may return :ok, an :ok tuple or a tuple error, with a string as error. Note that any failure in the processing will cause the job to be retried. """ @callback perform(Job.t()) :: :ok | {:ok, any()} | {:error, binary} @callback backoff(job :: Job.t()) :: pos_integer() defmacro __using__(_) do quote do @behaviour PgQueuetopia.Performer alias PgQueuetopia.Queue.Job alias AntlUtilsElixir.Math @impl PgQueuetopia.Performer def backoff(%Job{} = job) do exponential_backoff(job.attempts, job.max_backoff) end defp exponential_backoff(iteration, max_backoff) do backoff = ((Math.pow(2, iteration) |> round) + 1) * 1_000 min(backoff, max_backoff) end defoverridable backoff: 1 end end end
27.638889
75
0.666332
08ecb57cf932873979509c78beded27bd1e7ca61
42
exs
Elixir
config/dev1.exs
shopping-adventure/gen_serverring
ec75aa647bee80228dc9464b6e143b0633433827
[ "MIT" ]
1
2016-09-23T13:08:09.000Z
2016-09-23T13:08:09.000Z
config/dev1.exs
shopping-adventure/gen_serverring
ec75aa647bee80228dc9464b6e143b0633433827
[ "MIT" ]
null
null
null
config/dev1.exs
shopping-adventure/gen_serverring
ec75aa647bee80228dc9464b6e143b0633433827
[ "MIT" ]
null
null
null
[gen_serverring: [data_dir: "data/dev1"]]
21
41
0.714286
08ecba2daa01011cbbfd923be5a979ffcd7ba46c
2,422
exs
Elixir
programming/elixir/simple_pay/test/controllers/session_controller_test.exs
NomikOS/learning
268f94605214f6861ef476ca7573e68c068ccbe5
[ "Unlicense" ]
null
null
null
programming/elixir/simple_pay/test/controllers/session_controller_test.exs
NomikOS/learning
268f94605214f6861ef476ca7573e68c068ccbe5
[ "Unlicense" ]
null
null
null
programming/elixir/simple_pay/test/controllers/session_controller_test.exs
NomikOS/learning
268f94605214f6861ef476ca7573e68c068ccbe5
[ "Unlicense" ]
null
null
null
defmodule SimplePay.SessionControllerTest do use SimplePay.ConnCase alias SimplePay.Session @valid_attrs %{} @invalid_attrs %{} test "lists all entries on index", %{conn: conn} do conn = get conn, session_path(conn, :index) assert html_response(conn, 200) =~ "Listing sessions" end test "renders form for new resources", %{conn: conn} do conn = get conn, session_path(conn, :new) assert html_response(conn, 200) =~ "New session" end test "creates resource and redirects when data is valid", %{conn: conn} do conn = post conn, session_path(conn, :create), session: @valid_attrs assert redirected_to(conn) == session_path(conn, :index) assert Repo.get_by(Session, @valid_attrs) end test "does not create resource and renders errors when data is invalid", %{conn: conn} do conn = post conn, session_path(conn, :create), session: @invalid_attrs assert html_response(conn, 200) =~ "New session" end test "shows chosen resource", %{conn: conn} do session = Repo.insert! %Session{} conn = get conn, session_path(conn, :show, session) assert html_response(conn, 200) =~ "Show session" end test "renders page not found when id is nonexistent", %{conn: conn} do assert_error_sent 404, fn -> get conn, session_path(conn, :show, -1) end end test "renders form for editing chosen resource", %{conn: conn} do session = Repo.insert! %Session{} conn = get conn, session_path(conn, :edit, session) assert html_response(conn, 200) =~ "Edit session" end test "updates chosen resource and redirects when data is valid", %{conn: conn} do session = Repo.insert! %Session{} conn = put conn, session_path(conn, :update, session), session: @valid_attrs assert redirected_to(conn) == session_path(conn, :show, session) assert Repo.get_by(Session, @valid_attrs) end test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do session = Repo.insert! %Session{} conn = put conn, session_path(conn, :update, session), session: @invalid_attrs assert html_response(conn, 200) =~ "Edit session" end test "deletes chosen resource", %{conn: conn} do session = Repo.insert! %Session{} conn = delete conn, session_path(conn, :delete, session) assert redirected_to(conn) == session_path(conn, :index) refute Repo.get(Session, session.id) end end
36.149254
98
0.694055
08ecee13ae213e8d26938e130f9fe30c83d6170a
611
ex
Elixir
elixir/palindrome-products/lib/palindromes.ex
jiegillet/exercism
bf901cd477aede9d06f322dae0763c968688806d
[ "MIT" ]
null
null
null
elixir/palindrome-products/lib/palindromes.ex
jiegillet/exercism
bf901cd477aede9d06f322dae0763c968688806d
[ "MIT" ]
null
null
null
elixir/palindrome-products/lib/palindromes.ex
jiegillet/exercism
bf901cd477aede9d06f322dae0763c968688806d
[ "MIT" ]
null
null
null
defmodule Palindromes do @doc """ Generates all palindrome products from an optionally given min factor (or 1) to a given max factor. """ @spec generate(non_neg_integer, non_neg_integer) :: map def generate(max_factor, min_factor \\ 1) do for i <- min_factor..max_factor, j <- min_factor..max_factor, i <= j, is_palindrome?(i * j) do {i * j, [i, j]} end |> Enum.reduce(%{}, fn {product, factor}, map -> Map.update(map, product, [factor], fn old -> [factor | old] end) end) end def is_palindrome?(n) do s = Integer.to_string(n) s == String.reverse(s) end end
30.55
101
0.636661
08ed00613d96ee31bdd5a481c019a91456041b73
61
exs
Elixir
day_02/test/day02_test.exs
simon-wolf/advent-of-code-2019
571d30f156a2beeeb49a52a2f0223fff5051e7b3
[ "MIT" ]
1
2021-04-21T16:16:59.000Z
2021-04-21T16:16:59.000Z
day_02/test/day02_test.exs
simon-wolf/advent-of-code-2019
571d30f156a2beeeb49a52a2f0223fff5051e7b3
[ "MIT" ]
null
null
null
day_02/test/day02_test.exs
simon-wolf/advent-of-code-2019
571d30f156a2beeeb49a52a2f0223fff5051e7b3
[ "MIT" ]
null
null
null
defmodule Day02Test do use ExUnit.Case doctest Day02 end
12.2
22
0.786885
08ed0318c5ea2b11b45f618e93a9f278f99f5a59
3,696
ex
Elixir
clients/cloud_shell/lib/google_api/cloud_shell/v1/model/environment.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/cloud_shell/lib/google_api/cloud_shell/v1/model/environment.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/cloud_shell/lib/google_api/cloud_shell/v1/model/environment.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.CloudShell.V1.Model.Environment do @moduledoc """ A Cloud Shell environment, which is defined as the combination of a Docker image specifying what is installed on the environment and a home directory containing the user&#39;s data that will remain across sessions. Each user has a single environment with the ID \&quot;default\&quot;. ## Attributes - dockerImage (String.t): Required. Full path to the Docker image used to run this environment, e.g. \&quot;gcr.io/dev-con/cloud-devshell:latest\&quot;. Defaults to: `null`. - id (String.t): Output only. The environment&#39;s identifier, which is always \&quot;default\&quot;. Defaults to: `null`. - name (String.t): Output only. Full name of this resource, in the format &#x60;users/{owner_email}/environments/{environment_id}&#x60;. &#x60;{owner_email}&#x60; is the email address of the user to whom this environment belongs, and &#x60;{environment_id}&#x60; is the identifier of this environment. For example, &#x60;users/someone@example.com/environments/default&#x60;. Defaults to: `null`. - publicKeys ([PublicKey]): Output only. Public keys associated with the environment. Clients can connect to this environment via SSH only if they possess a private key corresponding to at least one of these public keys. Keys can be added to or removed from the environment using the CreatePublicKey and DeletePublicKey methods. Defaults to: `null`. - sshHost (String.t): Output only. Host to which clients can connect to initiate SSH sessions with the environment. Defaults to: `null`. - sshPort (integer()): Output only. Port to which clients can connect to initiate SSH sessions with the environment. Defaults to: `null`. - sshUsername (String.t): Output only. Username that clients should use when initiating SSH sessions with the environment. Defaults to: `null`. - state (String.t): Output only. Current execution state of this environment. Defaults to: `null`. - Enum - one of [STATE_UNSPECIFIED, DISABLED, STARTING, RUNNING] """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :dockerImage => any(), :id => any(), :name => any(), :publicKeys => list(GoogleApi.CloudShell.V1.Model.PublicKey.t()), :sshHost => any(), :sshPort => any(), :sshUsername => any(), :state => any() } field(:dockerImage) field(:id) field(:name) field(:publicKeys, as: GoogleApi.CloudShell.V1.Model.PublicKey, type: :list) field(:sshHost) field(:sshPort) field(:sshUsername) field(:state) end defimpl Poison.Decoder, for: GoogleApi.CloudShell.V1.Model.Environment do def decode(value, options) do GoogleApi.CloudShell.V1.Model.Environment.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudShell.V1.Model.Environment do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
52.8
397
0.729708
08ed06d2021a11fdd178b78e46d92765220bdfd4
1,811
exs
Elixir
mix.exs
IanLuites/utc_datetime
0abe1d016e2bc7823860e9f402645e16a885aa5d
[ "MIT" ]
1
2020-01-12T03:40:17.000Z
2020-01-12T03:40:17.000Z
mix.exs
IanLuites/utc_datetime
0abe1d016e2bc7823860e9f402645e16a885aa5d
[ "MIT" ]
null
null
null
mix.exs
IanLuites/utc_datetime
0abe1d016e2bc7823860e9f402645e16a885aa5d
[ "MIT" ]
null
null
null
defmodule UTCDateTime.MixProject do use Mix.Project @version "1.0.0" def project do [ app: :utc_datetime, description: "A datetime implementation constraint to UTC.", version: @version, elixir: "~> 1.9", start_permanent: Mix.env() == :prod, deps: deps(), package: package(), # Testing test_coverage: [tool: ExCoveralls], preferred_cli_env: [ coveralls: :test, "coveralls.detail": :test, "coveralls.post": :test, "coveralls.html": :test ], dialyzer: [ignore_warnings: ".dialyzer", plt_add_deps: true], # Docs name: "UTC DateTime", source_url: "https://github.com/IanLuites/utc_datetime", homepage_url: "https://github.com/IanLuites/utc_datetime", docs: [ main: "readme", extras: ["README.md"], source_ref: "v#{@version}", source_url: "https://github.com/IanLuites/utc_datetime" ] ] end def package do [ name: :utc_datetime, maintainers: ["Ian Luites"], licenses: ["MIT"], files: [ # Elixir "lib/utc_datetime", "lib/utc_datetime.ex", ".formatter.exs", "mix.exs", "README*", "LICENSE*" ], links: %{ "GitHub" => "https://github.com/IanLuites/utc_datetime" } ] end def application do [extra_applications: [:logger]] end defp deps do [ {:analyze, "~> 0.1.10", only: [:dev, :test], runtime: false, optional: true}, {:benchee, "~> 1.0", only: :dev, optional: true}, {:dialyxir, "~> 1.0.0-rc.7 ", only: :dev, runtime: false, optional: true}, # Optional Integrations {:ecto, ">= 3.0.0", optional: true}, {:jason, ">= 1.0.0", optional: true} ] end end
24.146667
83
0.546107
08ed280090b7d9038860267be188d9436d0d5f37
51,016
ex
Elixir
lib/ash/actions/managed_relationships.ex
ash-project/ash
63c240ebbdda6efc2ba8b24547f143cb8bd8c57e
[ "MIT" ]
528
2019-12-08T01:51:54.000Z
2022-03-30T10:09:45.000Z
lib/ash/actions/managed_relationships.ex
ash-project/ash
63c240ebbdda6efc2ba8b24547f143cb8bd8c57e
[ "MIT" ]
278
2019-12-04T15:25:06.000Z
2022-03-31T03:40:51.000Z
lib/ash/actions/managed_relationships.ex
ash-project/ash
63c240ebbdda6efc2ba8b24547f143cb8bd8c57e
[ "MIT" ]
53
2020-08-17T22:08:09.000Z
2022-03-24T01:58:59.000Z
defmodule Ash.Actions.ManagedRelationships do @moduledoc false alias Ash.Error.Changes.InvalidRelationship alias Ash.Error.Query.NotFound require Ash.Query def load(_api, created, %{relationships: rels}, _) when rels == %{}, do: {:ok, created} def load(_api, created, %{relationships: nil}, _), do: {:ok, created} def load(api, created, changeset, engine_opts) do Enum.reduce_while(changeset.relationships, {:ok, created}, fn {key, value}, {:ok, acc} -> relationship = Ash.Resource.Info.relationship(changeset.resource, key) case Enum.filter(value, fn {_, opts} -> opts = Ash.Changeset.ManagedRelationshipHelpers.sanitize_opts(relationship, opts) Ash.Changeset.ManagedRelationshipHelpers.must_load?(opts) end) do [] -> {:cont, {:ok, acc}} relationships -> authorize? = engine_opts[:authorize?] && Enum.any?(relationships, fn {_, opts} -> opts[:authorize?] end) actor = engine_opts[:actor] case api.load(acc, key, authorize?: authorize?, actor: actor) do {:ok, loaded} -> {:cont, {:ok, loaded}} {:error, error} -> {:halt, {:error, error}} end end end) end def setup_managed_belongs_to_relationships(changeset, actor, engine_opts) do changeset.relationships |> Enum.map(fn {relationship, val} -> {Ash.Resource.Info.relationship(changeset.resource, relationship), val} end) |> Enum.filter(fn {relationship, _val} -> relationship.type == :belongs_to end) |> Enum.flat_map(fn {relationship, inputs} -> inputs |> Enum.reject(fn {_, opts} -> opts[:ignore?] || opts[:handled?] end) |> Enum.with_index() |> Enum.map(fn {{input, opts}, index} -> {{relationship, {input, opts}}, index} end) end) |> Enum.map(fn {{relationship, {[input], opts}}, index} -> {{relationship, {input, opts}}, index} {{relationship, {other, opts}}, index} -> {{relationship, {other, opts}}, index} end) |> Enum.sort_by(fn {{_rel, {_input, opts}}, _index} -> opts[:meta][:order] end) |> Enum.reduce_while({changeset, %{notifications: []}}, fn {{relationship, {input, opts}}, index}, {changeset, instructions} -> pkeys = pkeys(relationship) changeset = if changeset.action.type == :update do case changeset.api.load(changeset.data, relationship.name, authorize?: opts[:authorize?]) do {:ok, result} -> {:ok, %{changeset | data: result}} {:error, error} -> {:error, error} end else {:ok, changeset} end case changeset do {:ok, changeset} -> opts = Ash.Changeset.ManagedRelationshipHelpers.sanitize_opts(relationship, opts) opts = Keyword.put(opts, :authorize?, engine_opts[:authorize?] && opts[:authorize?]) changeset = if input in [nil, []] && opts[:on_missing] != :ignore do Ash.Changeset.force_change_attribute(changeset, relationship.source_field, nil) |> Ash.Changeset.after_action(fn _changeset, result -> {:ok, Map.put(result, relationship.name, nil)} end) else changeset end current_value = case Map.get(changeset.data, relationship.name) do %Ash.NotLoaded{} -> nil other -> other end input = if is_list(input) do Enum.at(input, 0) else input end match = if input do find_match( List.wrap(current_value), input, pkeys, relationship, opts[:on_no_match] == :match ) else nil end case match do nil -> case opts[:on_lookup] do _ when is_nil(input) -> create_belongs_to_record( changeset, instructions, relationship, input, actor, index, opts ) :ignore -> create_belongs_to_record( changeset, instructions, relationship, input, actor, index, opts ) {_key, _create_or_update, read} -> if is_struct(input) do changeset = changeset |> Ash.Changeset.set_context(%{ private: %{ belongs_to_manage_found: %{relationship.name => %{index => input}} } }) |> Ash.Changeset.force_change_attribute( relationship.source_field, Map.get(input, relationship.destination_field) ) {:cont, {changeset, instructions}} else case Ash.Filter.get_filter(relationship.destination, input) do {:ok, keys} -> relationship.destination |> Ash.Query.for_read(read, input, actor: actor) |> Ash.Query.filter(^keys) |> Ash.Query.do_filter(relationship.filter) |> Ash.Query.sort(relationship.sort) |> Ash.Query.set_context(relationship.context) |> Ash.Query.limit(1) |> Ash.Query.set_tenant(changeset.tenant) |> changeset.api.read_one( authorize?: opts[:authorize?], actor: actor ) |> case do {:ok, nil} -> create_belongs_to_record( changeset, instructions, relationship, input, actor, index, opts ) {:ok, found} -> changeset = changeset |> Ash.Changeset.set_context(%{ private: %{ belongs_to_manage_found: %{ relationship.name => %{index => found} } } }) |> Ash.Changeset.force_change_attribute( relationship.source_field, Map.get(found, relationship.destination_field) ) {:cont, {changeset, instructions}} {:error, error} -> {:halt, {Ash.Changeset.add_error(changeset, error, [ opts[:meta][:id] || relationship.name ]), instructions}} end _ -> create_belongs_to_record( changeset, instructions, relationship, input, actor, index, opts ) end end end _value -> if opts[:on_match] == :destroy do changeset = Ash.Changeset.force_change_attribute( changeset, relationship.source_field, nil ) {:cont, {changeset, instructions}} else {:cont, {changeset, instructions}} end end {:error, error} -> {:halt, {:error, error}} end end) |> validate_required_belongs_to() |> case do {:error, error} -> {:error, error} {changeset, instructions} -> changeset = Map.update!(changeset, :relationships, fn relationships -> Map.new(relationships, fn {rel, inputs} -> {rel, Enum.map(inputs, fn {input, config} -> {input, Keyword.put(config, :handled?, true)} end)} end) end) {changeset, instructions} end end defp validate_required_belongs_to({changeset, instructions}) do changeset.resource |> Ash.Resource.Info.relationships() |> Enum.filter(&(&1.type == :belongs_to)) |> Enum.filter(& &1.required?) |> Enum.reject(fn relationship -> changeset.context[:private][:error][relationship.name] end) |> Enum.reduce({changeset, instructions}, fn required_relationship, {changeset, instructions} -> changeset = case Ash.Changeset.get_attribute(changeset, required_relationship.source_field) do nil -> Ash.Changeset.add_error( changeset, Ash.Error.Changes.Required.exception( field: required_relationship.name, type: :relationship ) ) _ -> changeset end {changeset, instructions} end) end defp create_belongs_to_record( changeset, instructions, relationship, input, actor, index, opts ) do if input in [nil, []] do {:cont, {changeset, instructions}} else case opts[:on_no_match] do ignore when ignore in [:ignore, :match] -> {:cont, {changeset, instructions}} :error -> if opts[:on_lookup] != :ignore do changeset = changeset |> Ash.Changeset.add_error( NotFound.exception( primary_key: input, resource: relationship.destination ), [opts[:meta][:id] || relationship.name] ) |> Ash.Changeset.put_context(:private, %{ error: %{relationship.name => true} }) {:halt, {changeset, instructions}} else changeset = changeset |> Ash.Changeset.add_error( InvalidRelationship.exception( relationship: relationship.name, message: "Changes would create a new related record" ) ) |> Ash.Changeset.put_context(:private, %{ error: %{relationship.name => true} }) {:halt, {changeset, instructions}} end {:create, action_name} -> do_create_belongs_to_record( relationship, action_name, input, changeset, actor, opts, instructions, index ) end end end defp do_create_belongs_to_record( relationship, action_name, input, changeset, actor, opts, instructions, index ) do relationship.destination |> Ash.Changeset.new() |> Ash.Changeset.for_create(action_name, input, require?: false, actor: actor, relationships: opts[:relationships] || [] ) |> Ash.Changeset.set_context(relationship.context) |> Ash.Changeset.set_tenant(changeset.tenant) |> changeset.api.create( actor: actor, authorize?: opts[:authorize?], return_notifications?: true ) |> case do {:ok, created, notifications} -> changeset = changeset |> Ash.Changeset.set_context(%{ private: %{ belongs_to_manage_created: %{relationship.name => %{index => created}} } }) |> Ash.Changeset.force_change_attribute( relationship.source_field, Map.get(created, relationship.destination_field) ) {:cont, {changeset, %{instructions | notifications: instructions.notifications ++ notifications}}} {:error, error} -> {:halt, {Ash.Changeset.add_error(changeset, error, [opts[:meta][:id] || relationship.name]), instructions}} end end def manage_relationships(record, changeset, actor, engine_opts) do changeset.relationships |> Enum.map(fn {relationship, val} -> {Ash.Resource.Info.relationship(changeset.resource, relationship), val} end) |> Enum.flat_map(fn {key, batches} -> batches |> Enum.reject(fn {_, opts} -> opts[:ignore?] end) |> Enum.with_index() |> Enum.map(fn {{batch, opts}, index} -> opts = Keyword.put(opts, :authorize?, engine_opts[:authorize?] && opts[:authorize?]) {key, batch, opts, index} end) end) |> Enum.sort_by(fn {_key, _batch, opts, _index} -> opts[:meta][:order] end) |> Enum.reduce_while({:ok, record, []}, fn {relationship, inputs, opts, index}, {:ok, record, all_notifications} -> inputs = if relationship.cardinality == :many do List.wrap(inputs) else inputs end case manage_relationship(record, relationship, inputs, changeset, actor, index, opts) do {:ok, record, notifications} -> record = if relationship.type == :many_to_many do Map.put( record, relationship.join_relationship, Map.get(record.__struct__.__struct__, relationship.join_relationship) ) else record end {:cont, {:ok, record, notifications ++ all_notifications}} {:error, error} -> {:halt, {:error, error}} end end) end def pkeys(relationship) do identities = relationship.destination |> Ash.Resource.Info.identities() |> Enum.map(& &1.keys) [Ash.Resource.Info.primary_key(relationship.destination) | identities] end defp manage_relationship( record, %{cardinality: :many} = relationship, inputs, changeset, actor, index, opts ) do inputs = List.wrap(inputs) opts = Ash.Changeset.ManagedRelationshipHelpers.sanitize_opts(relationship, opts) pkeys = pkeys(relationship) original_value = case Map.get(record, relationship.name) do %Ash.NotLoaded{} -> [] value -> value end inputs |> Enum.with_index() |> Enum.reduce_while( {:ok, [], [], []}, fn {input, input_index}, {:ok, current_value, all_notifications, all_used} -> case handle_input( record, current_value, original_value, relationship, input, pkeys, changeset, actor, index, opts ) do {:ok, new_value, notifications, used} -> {:cont, {:ok, new_value, all_notifications ++ notifications, all_used ++ used}} {:error, %Ash.Error.Changes.InvalidRelationship{} = error} -> {:halt, {:error, error}} {:error, error} -> case Keyword.fetch(opts[:meta] || [], :inputs_was_list?) do {:ok, false} -> {:halt, {:error, Ash.Changeset.set_path(error, [opts[:meta][:id] || relationship.name])}} _ -> {:halt, {:error, Ash.Changeset.set_path(error, [ opts[:meta][:id] || relationship.name, input_index ])}} end end end ) |> case do {:ok, new_value, all_notifications, all_used} -> case delete_unused( record, original_value, relationship, new_value, all_used, changeset, actor, opts ) do {:ok, new_value, notifications} -> {:ok, Map.put(record, relationship.name, new_value), all_notifications ++ notifications} {:error, %Ash.Error.Changes.InvalidRelationship{} = error} -> {:error, error} {:error, error} -> {:error, Ash.Changeset.set_path(error, [opts[:meta][:id] || relationship.name])} end {:error, error} -> {:error, error} end end defp manage_relationship( record, %{cardinality: :one} = relationship, inputs, changeset, actor, index, opts ) do opts = Ash.Changeset.ManagedRelationshipHelpers.sanitize_opts(relationship, opts) identities = relationship.destination |> Ash.Resource.Info.identities() |> Enum.map(& &1.keys) pkeys = [Ash.Resource.Info.primary_key(relationship.destination) | identities] original_value = if relationship.type == :belongs_to do Map.get(changeset.data, relationship.name) else Map.get(record, relationship.name) end original_value = case original_value do %Ash.NotLoaded{} -> [] value -> value end inputs = List.wrap(inputs) inputs |> Enum.reduce_while( {:ok, original_value, [], []}, fn input, {:ok, current_value, all_notifications, all_used} -> case handle_input( record, current_value, original_value, relationship, input, pkeys, changeset, actor, index, opts ) do {:ok, new_value, notifications, used} -> {:cont, {:ok, new_value, all_notifications ++ notifications, all_used ++ used}} {:error, %Ash.Error.Changes.InvalidRelationship{} = error} -> {:error, error} {:error, error} -> {:halt, {:error, Ash.Changeset.set_path(error, [opts[:meta][:id] || relationship.name])}} end end ) |> case do {:ok, new_value, all_notifications, all_used} -> case delete_unused( record, original_value, relationship, new_value, all_used, changeset, actor, opts ) do {:ok, new_value, notifications} -> {:ok, Map.put(record, relationship.name, Enum.at(List.wrap(new_value), 0)), all_notifications ++ notifications} {:error, %Ash.Error.Changes.InvalidRelationship{} = error} -> {:error, error} {:error, error} -> {:error, Ash.Changeset.set_path(error, [opts[:meta][:id] || relationship.name])} end {:error, %Ash.Error.Changes.InvalidRelationship{} = error} -> {:error, error} {:error, error} -> {:error, Ash.Changeset.set_path(error, [opts[:meta][:id] || relationship.name])} end end defp handle_input( record, current_value, original_value, relationship, input, pkeys, changeset, actor, index, opts ) do match = find_match( List.wrap(original_value), input, pkeys, relationship, opts[:on_no_match] == :match ) if is_nil(match) || opts[:on_match] == :no_match do case handle_create( record, current_value, relationship, input, changeset, actor, index, opts ) do {:ok, current_value, notifications, used} -> {:ok, current_value, notifications, used} {:error, error} -> {:error, error} end else handle_update(record, current_value, relationship, match, input, changeset, actor, opts) end end defp handle_create(record, current_value, relationship, input, changeset, actor, index, opts) do api = changeset.api case opts[:on_lookup] do :ignore -> do_handle_create( record, current_value, relationship, input, changeset, actor, index, opts ) other -> case Map.fetch( changeset.context[:private][:belongs_to_manage_found][relationship.name] || %{}, index ) do :error -> {key, create_or_update, read, join_keys} = case other do {key, create_or_update, read} -> {key, create_or_update, read, []} {key, create_or_update, read, keys} -> {key, create_or_update, read, keys} end case Ash.Filter.get_filter(relationship.destination, input) do {:ok, keys} -> if is_struct(input) do {:ok, input} else relationship.destination |> Ash.Query.for_read(read, input, actor: actor) |> Ash.Query.filter(^keys) |> Ash.Query.do_filter(relationship.filter) |> Ash.Query.sort(relationship.sort) |> Ash.Query.set_context(relationship.context) |> Ash.Query.set_tenant(changeset.tenant) |> Ash.Query.limit(1) |> changeset.api.read_one( authorize?: opts[:authorize?], actor: actor ) end |> case do {:ok, found} when not is_nil(found) -> do_handle_found( relationship, join_keys, input, api, opts, found, current_value, create_or_update, actor, key, record, changeset ) {:ok, _} -> do_handle_create( record, current_value, relationship, input, changeset, actor, index, opts ) {:error, error} -> {:error, error} end {:error, _error} -> do_handle_create( record, current_value, relationship, input, changeset, actor, index, opts ) end {:ok, found} -> {:ok, [found | current_value], [], [found]} end end end defp do_handle_found( relationship, join_keys, input, api, opts, found, current_value, create_or_update, actor, key, record, changeset ) do case relationship.type do :many_to_many -> input = if is_map(input) do input else Enum.into(input, %{}) end {join_input, input} = split_join_keys(input, join_keys) join_relationship = Ash.Resource.Info.relationship( relationship.source, relationship.join_relationship ) relationship.through |> Ash.Changeset.new() |> Ash.Changeset.for_create(create_or_update, join_input, actor: actor) |> Ash.Changeset.force_change_attribute( relationship.source_field_on_join_table, Map.get(record, relationship.source_field) ) |> Ash.Changeset.force_change_attribute( relationship.destination_field_on_join_table, Map.get(found, relationship.destination_field) ) |> Ash.Changeset.set_context(join_relationship.context) |> Ash.Changeset.set_tenant(changeset.tenant) |> api.create( return_notifications?: true, authorize?: opts[:authorize?], actor: actor ) |> case do {:ok, _created, notifications} -> case key do :relate -> {:ok, [found | current_value], notifications, [found]} :relate_and_update -> case handle_update( record, current_value, relationship, found, input, changeset, actor, opts ) do {:ok, new_value, update_notifications, used} -> {:ok, new_value, update_notifications ++ notifications, used} {:error, error} -> {:error, error} end end {:error, error} -> {:error, error} end type when type in [:has_many, :has_one] -> {found, input} = if is_struct(input) do {input, %{}} else {found, input} end found |> Ash.Changeset.new() |> set_source_context({relationship, changeset}) |> Ash.Changeset.for_update(create_or_update, input, relationships: opts[:relationships] || [], actor: actor ) |> Ash.Changeset.force_change_attribute( relationship.destination_field, Map.get(record, relationship.source_field) ) |> Ash.Changeset.set_context(relationship.context) |> Ash.Changeset.set_tenant(changeset.tenant) |> api.update( return_notifications?: true, authorize?: opts[:authorize?], actor: actor ) |> case do {:ok, updated, notifications} -> {:ok, [updated | current_value], notifications, [updated]} {:error, error} -> {:error, error} end :belongs_to -> {:ok, [found | current_value], [], [found]} end end defp do_handle_create(record, current_value, relationship, input, changeset, actor, index, opts) do case opts[:on_no_match] do :error -> if opts[:on_lookup] != :ignore do {:error, NotFound.exception( primary_key: input, resource: relationship.destination )} else {:error, InvalidRelationship.exception( relationship: relationship.name, message: "Changes would create a new related record" )} end {:create, action_name} -> case changeset.context[:private][:belongs_to_manage_created][relationship.name][index] do nil -> created = if is_struct(input) do {:ok, input, []} else relationship.destination |> Ash.Changeset.new() |> set_source_context({relationship, changeset}) |> Ash.Changeset.for_create(action_name, input, require?: false, actor: actor, relationships: opts[:relationships] ) |> Ash.Changeset.force_change_attribute( relationship.destination_field, Map.get(record, relationship.source_field) ) |> Ash.Changeset.set_context(relationship.context) |> Ash.Changeset.set_tenant(changeset.tenant) |> changeset.api.create( return_notifications?: true, authorize?: opts[:authorize?], actor: actor ) end case created do {:ok, created, notifications} -> {:ok, [created | current_value], notifications, [created]} {:error, error} -> {:error, error} end created -> {:ok, [created | current_value], [], [created]} end {:create, action_name, join_action_name, params} -> join_keys = params ++ Enum.map(params, &to_string/1) input = if is_map(input) do input else Enum.into(input, %{}) end {join_params, regular_params} = split_join_keys(input, join_keys) created = if is_struct(input) do {:ok, input, [], [input]} else relationship.destination |> Ash.Changeset.new() |> set_source_context({relationship, changeset}) |> Ash.Changeset.for_create(action_name, regular_params, require?: false, relationships: opts[:relationships], actor: actor ) |> Ash.Changeset.set_context(relationship.context) |> Ash.Changeset.set_tenant(changeset.tenant) |> changeset.api.create( return_notifications?: true, authorize?: opts[:authorize?], actor: actor ) end case created do {:ok, created, regular_notifications} -> join_relationship = Ash.Resource.Info.relationship(relationship.source, relationship.join_relationship) relationship.through |> Ash.Changeset.new() |> Ash.Changeset.for_create(join_action_name, join_params, require?: false, actor: actor ) |> Ash.Changeset.force_change_attribute( relationship.source_field_on_join_table, Map.get(record, relationship.source_field) ) |> Ash.Changeset.force_change_attribute( relationship.destination_field_on_join_table, Map.get(created, relationship.destination_field) ) |> Ash.Changeset.set_context(join_relationship.context) |> Ash.Changeset.set_tenant(changeset.tenant) |> changeset.api.create( return_notifications?: true, authorize?: opts[:authorize?], actor: actor ) |> case do {:ok, _join_row, notifications} -> {:ok, [created | current_value], regular_notifications ++ notifications, [created]} {:error, error} -> {:error, error} end {:error, error} -> {:error, error} end ignore when ignore in [:ignore, :match] -> {:ok, current_value, [], [input]} end end # credo:disable-for-next-line Credo.Check.Refactor.Nesting defp handle_update( source_record, current_value, relationship, match, input, changeset, actor, opts ) do api = changeset.api case opts[:on_match] do # :create case is handled when determining updates/creates :error -> {:error, InvalidRelationship.exception( relationship: relationship.name, message: "Changes would update a record" )} :ignore -> {:ok, [match | current_value], [], [match]} :missing -> {:ok, current_value, [], []} {:destroy, action_name} -> case destroy_data( source_record, match, api, actor, opts, action_name, changeset.tenant, relationship, changeset ) do {:ok, notifications} -> {:ok, current_value, notifications, []} {:error, error} -> {:error, error} end {:unrelate, action_name} -> case unrelate_data( source_record, match, api, actor, opts, action_name, changeset.tenant, relationship, changeset ) do {:ok, notifications} -> {:ok, current_value, notifications, []} {:error, error} -> {:error, error} end {:update, action_name} -> {match, input} = if is_struct(input) do {input, %{}} else {match, input} end match |> Ash.Changeset.new() |> set_source_context({relationship, changeset}) |> Ash.Changeset.for_update(action_name, input, actor: actor, relationships: opts[:relationships] || [] ) |> Ash.Changeset.set_context(relationship.context) |> Ash.Changeset.set_tenant(changeset.tenant) |> api.update(actor: actor, authorize?: opts[:authorize?], return_notifications?: true) |> case do {:ok, updated, update_notifications} -> {:ok, [updated | current_value], update_notifications, [match]} {:error, error} -> {:error, error} end {:update, action_name, join_action_name, params} -> join_keys = params ++ Enum.map(params, &to_string/1) {join_params, regular_params} = split_join_keys(input, join_keys) {match, regular_params} = if is_struct(regular_params) do {regular_params, %{}} else {match, regular_params} end source_value = Map.get(source_record, relationship.source_field) match |> Ash.Changeset.new() |> set_source_context({relationship, changeset}) |> Ash.Changeset.for_update(action_name, regular_params, actor: actor, relationships: opts[:relationships] ) |> Ash.Changeset.set_context(relationship.context) |> Ash.Changeset.set_tenant(changeset.tenant) |> api.update(actor: actor, authorize?: opts[:authorize?], return_notifications?: true) |> case do {:ok, updated, update_notifications} -> destination_value = Map.get(updated, relationship.destination_field) join_relationship = Ash.Resource.Info.relationship(relationship.source, relationship.join_relationship) relationship.through |> Ash.Query.filter(ref(^relationship.source_field_on_join_table) == ^source_value) |> Ash.Query.filter( ref(^relationship.destination_field_on_join_table) == ^destination_value ) |> Ash.Query.set_context(join_relationship.context) |> Ash.Query.limit(1) |> Ash.Query.set_tenant(changeset.tenant) |> changeset.api.read_one( authorize?: opts[:authorize?], actor: actor ) |> case do {:ok, result} -> if join_params == %{} do {:ok, [updated | current_value], update_notifications, [match]} else join_relationship = Ash.Resource.Info.relationship( relationship.source, relationship.join_relationship ) result |> Ash.Changeset.new() |> Ash.Changeset.for_update(join_action_name, join_params, actor: actor) |> Ash.Changeset.set_context(join_relationship.context) |> Ash.Changeset.set_tenant(changeset.tenant) |> api.update( return_notifications?: true, authorize?: opts[:authorize?], actor: actor ) # credo:disable-for-next-line Credo.Check.Refactor.Nesting |> case do {:ok, _updated_join, join_update_notifications} -> {:ok, [updated | current_value], update_notifications ++ join_update_notifications, [updated]} {:error, error} -> {:error, error} end end {:error, error} -> {:error, error} end {:error, error} -> {:error, error} end end end defp find_match(current_value, input, pkeys, relationship \\ nil, force_has_one? \\ false) defp find_match(%Ash.NotLoaded{}, _input, _pkeys, _relationship, _force_has_one?) do nil end defp find_match([match], _input, _pkeys, %{cardinality: :one}, true) do match end defp find_match(current_value, input, pkeys, relationship, _force_has_one?) do Enum.find(current_value, fn current_value -> Enum.any?(pkeys, fn pkey -> matches?(current_value, input, pkey, relationship) end) end) end defp matches?(current_value, input, pkey, relationship) do if relationship && relationship.type in [:has_one, :has_many] && relationship.destination_field in pkey do Enum.all?(pkey, fn field -> if field == relationship.destination_field do if is_struct(input) do do_matches?(current_value, input, field) else # We know that it will be the same as all other records in this relationship # (because thats how has_one and has_many relationships work), so we # can assume its the same as the current value true end else do_matches?(current_value, input, field) end end) else Enum.all?(pkey, fn field -> do_matches?(current_value, input, field) end) end end defp do_matches?(current_value, input, field) do with {:ok, current_val} when not is_nil(current_val) <- Map.fetch(current_value, field), {:ok, input_val} when not is_nil(input_val) <- fetch_field(input, field) do current_val == input_val else _ -> false end end defp split_join_keys(%_{__metadata__: metadata} = input, _join_keys) do {metadata[:join_keys] || %{}, input} end defp split_join_keys(input, :all) do {input, %{}} end defp split_join_keys(input, join_keys) do Map.split(input, join_keys ++ Enum.map(join_keys, &to_string/1)) end defp fetch_field(input, field) do case Map.fetch(input, field) do {:ok, value} -> {:ok, value} :error -> Map.fetch(input, to_string(field)) end end defp set_source_context(changeset, {relationship, original_changeset}) do case changeset.data.__metadata__[:manage_relationship_source] || original_changeset.context[:manage_relationship_source] do nil -> Ash.Changeset.set_context(changeset, %{ manage_relationship_source: [ {relationship.source, relationship.name, original_changeset} ] }) value -> Ash.Changeset.set_context(changeset, %{ manage_relationship_source: value ++ [{relationship.source, relationship.name, original_changeset}] }) end |> Ash.Changeset.after_action(fn changeset, record -> {:ok, Ash.Resource.Info.put_metadata( record, :manage_relationship_source, changeset.context[:manage_relationship_source] )} end) end defp delete_unused( source_record, original_value, relationship, current_value, all_used, changeset, actor, opts ) do api = changeset.api pkey = Ash.Resource.Info.primary_key(relationship.destination) original_value |> List.wrap() |> Enum.reject(&find_match(all_used, &1, [pkey])) |> Enum.reduce_while( {:ok, current_value, []}, fn record, {:ok, current_value, all_notifications} -> case opts[:on_missing] do :ignore -> {:cont, {:ok, [record | current_value], []}} {:destroy, action_name, join_action_name} -> source_value = Map.get(source_record, relationship.source_field) destination_value = Map.get(record, relationship.destination_field) join_relationship = Ash.Resource.Info.relationship(relationship.source, relationship.join_relationship) relationship.through |> Ash.Query.filter(ref(^relationship.source_field_on_join_table) == ^source_value) |> Ash.Query.filter( ref(^relationship.destination_field_on_join_table) == ^destination_value ) |> Ash.Query.limit(1) |> Ash.Query.set_tenant(changeset.tenant) |> Ash.Query.set_context(join_relationship.context) |> Ash.Query.do_filter(relationship.filter) |> Ash.Query.sort(relationship.sort) |> api.read_one( authorize?: opts[:authorize?], actor: actor ) |> case do {:ok, result} -> join_relationship = Ash.Resource.Info.relationship( relationship.source, relationship.join_relationship ) result |> Ash.Changeset.for_destroy( join_action_name, %{}, actor: actor ) |> Ash.Changeset.set_context(join_relationship.context) |> Ash.Changeset.set_tenant(changeset.tenant) |> api.destroy( return_notifications?: true, authorize?: opts[:authorize?], actor: actor ) |> case do {:ok, join_notifications} -> notifications = join_notifications ++ all_notifications record |> Ash.Changeset.new() |> set_source_context({relationship, changeset}) |> Ash.Changeset.for_destroy(action_name, %{}, actor: actor) |> Ash.Changeset.set_context(relationship.context) |> Ash.Changeset.set_tenant(changeset.tenant) |> api.destroy( return_notifications?: true, authorize?: opts[:authorize?], actor: actor ) # credo:disable-for-next-line Credo.Check.Refactor.Nesting |> case do {:ok, destroy_destination_notifications} -> {:cont, {:ok, current_value, notifications ++ all_notifications ++ destroy_destination_notifications}} {:error, error} -> {:halt, {:error, error}} end {:error, error} -> {:halt, {:error, error}} end {:error, error} -> {:halt, {:error, error}} end {:destroy, action_name} -> record |> Ash.Changeset.new() |> set_source_context({relationship, changeset}) |> Ash.Changeset.for_destroy(action_name, %{}, actor: actor) |> Ash.Changeset.set_context(relationship.context) |> Ash.Changeset.set_tenant(changeset.tenant) |> api.destroy( authorize?: opts[:authorize?], actor: actor, return_notifications?: true ) |> case do {:ok, notifications} -> {:cont, {:ok, current_value, notifications ++ all_notifications}} {:error, error} -> {:halt, {:error, error}} end :error -> {:halt, {:error, InvalidRelationship.exception( relationship: relationship.name, message: "Changes would destroy a record" )}} {:unrelate, action_name} -> case unrelate_data( source_record, record, api, actor, opts, action_name, changeset.tenant, relationship, changeset ) do {:ok, notifications} -> {:cont, {:ok, current_value, notifications}} {:error, error} -> {:halt, {:error, error}} end end end ) end defp unrelate_data( source_record, record, api, actor, opts, action_name, tenant, %{type: :many_to_many} = relationship, changeset ) do action_name = action_name || Ash.Resource.Info.primary_action(relationship.through, :destroy).name source_value = Map.get(source_record, relationship.source_field) destination_value = Map.get(record, relationship.destination_field) relationship.through |> Ash.Query.filter(ref(^relationship.source_field_on_join_table) == ^source_value) |> Ash.Query.filter(ref(^relationship.destination_field_on_join_table) == ^destination_value) |> Ash.Query.limit(1) |> Ash.Query.set_tenant(tenant) |> api.read_one(authorize?: opts[:authorize?], actor: actor) |> case do {:ok, result} -> result |> Ash.Changeset.new() |> set_source_context({relationship, changeset}) |> Ash.Changeset.for_destroy(action_name, %{}, actor: actor) |> Ash.Changeset.set_context(relationship.context) |> Ash.Changeset.set_tenant(tenant) |> api.destroy( return_notifications?: true, authorize?: opts[:authorize?], actor: actor ) |> case do {:ok, notifications} -> {:ok, notifications} {:error, error} -> {:error, error} end {:error, error} -> {:error, error} end end defp unrelate_data( _source_record, record, api, actor, opts, action_name, tenant, %{type: type} = relationship, changeset ) when type in [:has_many, :has_one] do action_name = action_name || Ash.Resource.Info.primary_action(relationship.destination, :update).name record |> Ash.Changeset.new() |> set_source_context({relationship, changeset}) |> Ash.Changeset.for_update(action_name, %{}, relationships: opts[:relationships] || [], actor: actor ) |> Ash.Changeset.force_change_attribute(relationship.destination_field, nil) |> Ash.Changeset.set_context(relationship.context) |> Ash.Changeset.set_tenant(tenant) |> api.update(return_notifications?: true, actor: actor, authorize?: opts[:authorize?]) |> case do {:ok, _unrelated, notifications} -> {:ok, notifications} {:error, error} -> {:error, error} end end defp unrelate_data( _source_record, _record, _api, _actor, _opts, _action_name, _tenant, %{type: :belongs_to}, _changeset ) do {:ok, []} end defp destroy_data( source_record, record, api, actor, opts, action_name, tenant, %{type: :many_to_many} = relationship, changeset ) do action_name = action_name || Ash.Resource.Info.primary_action(relationship.through, :destroy).name source_value = Map.get(source_record, relationship.source_field) destination_value = Map.get(record, relationship.destination_field) relationship.through |> Ash.Query.filter(ref(^relationship.source_field_on_join_table) == ^source_value) |> Ash.Query.filter(ref(^relationship.destination_field_on_join_table) == ^destination_value) |> Ash.Query.limit(1) |> Ash.Query.set_tenant(tenant) |> api.read_one(authorize?: opts[:authorize?], actor: actor) |> case do {:ok, result} -> result |> Ash.Changeset.new() |> set_source_context({relationship, changeset}) |> Ash.Changeset.for_destroy(action_name, %{}, actor: actor) |> Ash.Changeset.set_context(relationship.context) |> Ash.Changeset.set_tenant(tenant) |> api.destroy( return_notifications?: true, authorize?: opts[:authorize?], actor: actor ) |> case do {:ok, notifications} -> {:ok, notifications} {:error, error} -> {:error, error} end {:error, error} -> {:error, error} end end defp destroy_data( _source_record, record, api, actor, opts, action_name, tenant, relationship, changeset ) do action_name = action_name || Ash.Resource.Info.primary_action(relationship.destination, :update).name record |> Ash.Changeset.new() |> set_source_context({relationship, changeset}) |> Ash.Changeset.for_destroy(action_name, %{}, relationships: opts[:relationships] || [], actor: actor ) |> Ash.Changeset.set_context(relationship.context) |> Ash.Changeset.set_tenant(tenant) |> api.destroy(return_notifications?: true, actor: actor, authorize?: opts[:authorize?]) end end
31.107317
102
0.499647
08ed2b2bebb80ab0c2e53e4db971320ed372d286
1,218
ex
Elixir
lib/docker/chunked_json.ex
kodumbeats/docker-elixir
b4f8b929691ce2bf9f11743def49009de460431b
[ "Apache-2.0" ]
21
2015-05-10T22:04:55.000Z
2021-12-30T15:04:36.000Z
lib/docker/chunked_json.ex
kodumbeats/docker-elixir
b4f8b929691ce2bf9f11743def49009de460431b
[ "Apache-2.0" ]
3
2015-05-14T17:42:33.000Z
2017-08-08T09:52:12.000Z
lib/docker/chunked_json.ex
kodumbeats/docker-elixir
b4f8b929691ce2bf9f11743def49009de460431b
[ "Apache-2.0" ]
10
2015-06-25T14:25:33.000Z
2018-01-05T15:35:44.000Z
defmodule Docker.ChunkedJson do @behaviour Tesla.Middleware @impl Tesla.Middleware def call(env, next, opts) do opts = opts || [] with {:ok, env} <- Tesla.Middleware.JSON.encode(env, opts), {:ok, env} <- Tesla.run(env, next) do decode(env, opts) end end def decode(env, opts) do with true <- decodable?(env, opts), {:ok, body} <- decode_body(env, opts) do {:ok, %{env | body: body}} else false -> {:ok, env} error -> error end end defp decodable?(env, opts), do: decodable_body?(env) && decodable_content_type?(env, opts) defp decodable_body?(env) do (is_binary(env.body) && env.body != "") || (is_list(env.body) && env.body != []) end defp decodable_content_type?(env, _opts) do case Tesla.get_header(env, "content-type") do "application/json" -> true _ -> false end end defp decode_body(env, _opts) do case Tesla.get_header(env, "transfer-encoding") do "chunked" -> # possible not real JSON, ignore errors case Jason.decode(env.body) do {:ok, body} -> {:ok, body} _ -> {:ok, env.body} end _ -> Jason.decode(env.body) end end end
24.857143
92
0.584565
08ed2e1f8c36f98a4b3d22501d5efaaf2b525125
64
exs
Elixir
test/mipha/follows/queries_test.exs
ZPVIP/mipha
a7df054f72eec7de88b60d94c501488375bdff6a
[ "MIT" ]
156
2018-06-01T19:52:32.000Z
2022-02-03T10:58:10.000Z
test/mipha/follows/queries_test.exs
ZPVIP/mipha
a7df054f72eec7de88b60d94c501488375bdff6a
[ "MIT" ]
139
2018-07-10T01:57:23.000Z
2021-08-02T21:29:24.000Z
test/mipha/follows/queries_test.exs
ZPVIP/mipha
a7df054f72eec7de88b60d94c501488375bdff6a
[ "MIT" ]
29
2018-07-17T08:43:45.000Z
2021-12-14T13:45:30.000Z
defmodule Mipha.Follows.QueriesTest do use Mipha.DataCase end
16
38
0.828125
08ed5497c0d7b029f28fc775ee6d13b38c186d7c
2,459
ex
Elixir
clients/firebase_hosting/lib/google_api/firebase_hosting/v1beta1/model/clone_version_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/firebase_hosting/lib/google_api/firebase_hosting/v1beta1/model/clone_version_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/firebase_hosting/lib/google_api/firebase_hosting/v1beta1/model/clone_version_request.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.FirebaseHosting.V1beta1.Model.CloneVersionRequest do @moduledoc """ The request sent to CloneVersion. ## Attributes * `exclude` (*type:* `GoogleApi.FirebaseHosting.V1beta1.Model.PathFilter.t`, *default:* `nil`) - If provided, only paths that do not match any of the regexes in this list will be included in the new version. * `finalize` (*type:* `boolean()`, *default:* `nil`) - If true, immediately finalize the version after cloning is complete. * `include` (*type:* `GoogleApi.FirebaseHosting.V1beta1.Model.PathFilter.t`, *default:* `nil`) - If provided, only paths that match one or more regexes in this list will be included in the new version. * `sourceVersion` (*type:* `String.t`, *default:* `nil`) - Required. The name of the version to be cloned, in the format: `sites/{site}/versions/{version}` """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :exclude => GoogleApi.FirebaseHosting.V1beta1.Model.PathFilter.t(), :finalize => boolean(), :include => GoogleApi.FirebaseHosting.V1beta1.Model.PathFilter.t(), :sourceVersion => String.t() } field(:exclude, as: GoogleApi.FirebaseHosting.V1beta1.Model.PathFilter) field(:finalize) field(:include, as: GoogleApi.FirebaseHosting.V1beta1.Model.PathFilter) field(:sourceVersion) end defimpl Poison.Decoder, for: GoogleApi.FirebaseHosting.V1beta1.Model.CloneVersionRequest do def decode(value, options) do GoogleApi.FirebaseHosting.V1beta1.Model.CloneVersionRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.FirebaseHosting.V1beta1.Model.CloneVersionRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.677966
169
0.731192
08ed74b21e4fab2b57123584411882313fdb7b90
1,103
ex
Elixir
lib/twinklyhaha_web/channels/user_socket.ex
TraceyOnim/TwinklyHaHa
4dc66c6701bc351847f6ec1677da8cd752c27a86
[ "MIT" ]
2
2020-10-04T12:41:53.000Z
2020-11-11T11:24:54.000Z
lib/twinklyhaha_web/channels/user_socket.ex
TraceyOnim/TwinklyHaHa
4dc66c6701bc351847f6ec1677da8cd752c27a86
[ "MIT" ]
22
2021-12-02T09:16:30.000Z
2022-03-21T06:33:29.000Z
lib/twinklyhaha_web/channels/user_socket.ex
TraceyOnim/TwinklyHaHa
4dc66c6701bc351847f6ec1677da8cd752c27a86
[ "MIT" ]
2
2020-11-09T08:27:19.000Z
2020-11-10T04:25:21.000Z
defmodule TwinklyhahaWeb.UserSocket do use Phoenix.Socket ## Channels # channel "room:*", TwinklyhahaWeb.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. @impl true 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: # # TwinklyhahaWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. @impl true def id(_socket), do: nil end
30.638889
86
0.698096
08ed85312d4de638e5fa050826b4ddb29adba58d
67
exs
Elixir
test/test_helper.exs
franknfjr/blog_lca
0711ad6ba6ee878045905ec58a549527ffa5e0a4
[ "MIT" ]
null
null
null
test/test_helper.exs
franknfjr/blog_lca
0711ad6ba6ee878045905ec58a549527ffa5e0a4
[ "MIT" ]
null
null
null
test/test_helper.exs
franknfjr/blog_lca
0711ad6ba6ee878045905ec58a549527ffa5e0a4
[ "MIT" ]
null
null
null
ExUnit.start Ecto.Adapters.SQL.Sandbox.mode(Login.Repo, :manual)
13.4
51
0.776119
08edc18f61916b7a394f343ff4c4b9b2a808d2d7
532
exs
Elixir
backend/test/getaways_web/schema/query/place_test.exs
Prumme/Projet_phx_ex_gql
6324af91f94f96ee1f8403d5397ab930347e3e4f
[ "Unlicense" ]
null
null
null
backend/test/getaways_web/schema/query/place_test.exs
Prumme/Projet_phx_ex_gql
6324af91f94f96ee1f8403d5397ab930347e3e4f
[ "Unlicense" ]
6
2020-01-31T19:44:15.000Z
2021-09-02T04:26:49.000Z
backend/test/getaways_web/schema/query/place_test.exs
Prumme/Projet_phx_ex_gql
6324af91f94f96ee1f8403d5397ab930347e3e4f
[ "Unlicense" ]
null
null
null
defmodule GetawaysWeb.Schema.Query.PlaceTest do use GetawaysWeb.ConnCase, async: true @query """ query ($slug: String!) { place(slug: $slug) { name } } """ @variables %{"slug" => "place-1"} test "place query returns the place with a given slug" do places_fixture() conn = build_conn() conn = get conn, "/api", query: @query, variables: @variables assert %{ "data" => %{ "place" => %{"name" => "Place 1"} } } == json_response(conn, 200) end end
19.703704
65
0.554511
08edd3bf4f328708d7235254348cbcc95334e615
93
ex
Elixir
lib/ex_matrix_api.ex
Voronchuk/ex_matrix_api
fab0f162c84a7e72f3df257260487a977e4134d5
[ "MIT" ]
2
2020-09-02T23:10:09.000Z
2021-03-29T09:19:15.000Z
lib/ex_matrix_api.ex
Voronchuk/ex_matrix_api
fab0f162c84a7e72f3df257260487a977e4134d5
[ "MIT" ]
null
null
null
lib/ex_matrix_api.ex
Voronchuk/ex_matrix_api
fab0f162c84a7e72f3df257260487a977e4134d5
[ "MIT" ]
null
null
null
defmodule ExMatrixApi do @moduledoc """ Context module for ExMatrixApi library """ end
15.5
40
0.731183
08edf8abb2a47bdea6218ef8246ea5782f6cc0ba
5,695
ex
Elixir
lib/credo/check/code_helper.ex
harlantwood/credo
4569c9c8cfcf74a2074d6911541da0265e52ae99
[ "MIT" ]
null
null
null
lib/credo/check/code_helper.ex
harlantwood/credo
4569c9c8cfcf74a2074d6911541da0265e52ae99
[ "MIT" ]
null
null
null
lib/credo/check/code_helper.ex
harlantwood/credo
4569c9c8cfcf74a2074d6911541da0265e52ae99
[ "MIT" ]
null
null
null
defmodule Credo.Check.CodeHelper do @moduledoc """ This module contains functions that are used by several checks when dealing with the AST. """ alias Credo.Code.Block alias Credo.Code.Parameters alias Credo.Code.Module alias Credo.Code.Scope alias Credo.Code.Charlists alias Credo.Code.Sigils alias Credo.Code.Strings alias Credo.Service.SourceFileScopes alias Credo.SourceFile defdelegate do_block?(ast), to: Block, as: :do_block? defdelegate do_block_for!(ast), to: Block, as: :do_block_for! defdelegate do_block_for(ast), to: Block, as: :do_block_for defdelegate else_block?(ast), to: Block, as: :else_block? defdelegate else_block_for!(ast), to: Block, as: :else_block_for! defdelegate else_block_for(ast), to: Block, as: :else_block_for defdelegate all_blocks_for!(ast), to: Block, as: :all_blocks_for! defdelegate calls_in_do_block(ast), to: Block, as: :calls_in_do_block defdelegate function_count(ast), to: Module, as: :def_count defdelegate def_name(ast), to: Module defdelegate parameter_names(ast), to: Parameters, as: :names defdelegate parameter_count(ast), to: Parameters, as: :count @doc """ Matches a given `name` against a given `list` of "patterns" (Regex or String) and returns `true` if *any* of the patterns matches. For Strings, it returns `true` if the String is part of the given value. iex> matches?("Credo.Check.ModuleDoc", ["Check", "CLI"]) true iex> matches?("Credo.CLI.Command", ["Check", "CLI"]) true iex> matches?("Credo.Execution", ["Check", "CLI"]) false For Regexes, it returns `true` if the Regex matches. iex> matches?("Credo.Check.ModuleDoc", [~/Check/, ~/CLI/]) true """ def matches?(name, list) when is_list(list) do Enum.any?(list, &matches?(name, &1)) end def matches?(name, string) when is_binary(string) do String.contains?(name, string) end def matches?(name, regex) do String.match?(name, regex) end @doc """ Returns the scope for the given line as a tuple consisting of the call to define the scope (`:defmodule`, `:def`, `:defp` or `:defmacro`) and the name of the scope. Examples: {:defmodule, "Foo.Bar"} {:def, "Foo.Bar.baz"} """ def scope_for(source_file, line: line_no) do source_file |> scope_list |> Enum.at(line_no - 1) end @doc """ Returns all scopes for the given source_file per line of source code as tuple consisting of the call to define the scope (`:defmodule`, `:def`, `:defp` or `:defmacro`) and the name of the scope. Examples: [ {:defmodule, "Foo.Bar"}, {:def, "Foo.Bar.baz"}, {:def, "Foo.Bar.baz"}, {:def, "Foo.Bar.baz"}, {:def, "Foo.Bar.baz"}, {:defmodule, "Foo.Bar"} ] """ def scope_list(%SourceFile{filename: filename} = source_file) do case SourceFileScopes.get(filename) do {:ok, value} -> value :notfound -> ast = SourceFile.ast(source_file) lines = SourceFile.lines(source_file) result = Enum.map(lines, fn {line_no, _} -> Scope.name(ast, line: line_no) end) SourceFileScopes.put(filename, result) result end end @doc """ Returns true if the given `child` AST node is part of the larger `parent` AST node. """ def contains_child?(parent, child) do Credo.Code.prewalk(parent, &find_child(&1, &2, child), false) end defp find_child(parent, acc, child), do: {parent, acc || parent == child} @doc """ Takes a SourceFile and returns its source code stripped of all Strings, Sigils and code comments. """ def clean_charlists_strings_sigils_and_comments(%SourceFile{} = source_file) do source_file |> SourceFile.source() |> clean_charlists_strings_sigils_and_comments end def clean_charlists_strings_sigils_and_comments(source) do source |> Sigils.replace_with_spaces("") |> Strings.replace_with_spaces() |> Charlists.replace_with_spaces() |> String.replace(~r/(\A|[^\?])#.+/, "\\1") end @doc """ Takes a SourceFile and returns its source code stripped of all Strings and Sigils. """ def clean_charlists_strings_and_sigils(%SourceFile{} = source_file) do source_file |> SourceFile.source() |> clean_charlists_strings_and_sigils end def clean_charlists_strings_and_sigils(source) do source |> Sigils.replace_with_spaces() |> Strings.replace_with_spaces() |> Charlists.replace_with_spaces() end @doc """ Returns an AST without its metadata. """ def remove_metadata(ast) when is_tuple(ast) do clean_node(ast) end def remove_metadata(ast) do ast |> List.wrap() |> Enum.map(&clean_node/1) end defp clean_node({atom, _meta, list}) when is_list(list) do {atom, [], Enum.map(list, &clean_node/1)} end defp clean_node(do: tuple) when is_tuple(tuple) do [do: clean_node(tuple)] end defp clean_node(do: tuple, else: tuple2) when is_tuple(tuple) do [do: clean_node(tuple), else: clean_node(tuple2)] end defp clean_node({:do, tuple}) when is_tuple(tuple) do {:do, clean_node(tuple)} end defp clean_node({:else, tuple}) when is_tuple(tuple) do {:else, clean_node(tuple)} end defp clean_node({atom, _meta, arguments}) do {atom, [], arguments} end defp clean_node(v) when is_list(v), do: Enum.map(v, &clean_node/1) defp clean_node(tuple) when is_tuple(tuple) do tuple |> Tuple.to_list() |> Enum.map(&clean_node/1) |> List.to_tuple() end defp clean_node(v) when is_atom(v) or is_binary(v) or is_float(v) or is_integer(v), do: v end
26.863208
81
0.661984
08ee1c8e7287899bbefc1f5c34e0bc866c733110
1,960
exs
Elixir
tools/astarte_e2e/mix.exs
Annopaolo/astarte
f8190e8bf044759a9b84bdeb5786a55b6f793a4f
[ "Apache-2.0" ]
191
2018-03-30T13:23:08.000Z
2022-03-02T12:05:32.000Z
tools/astarte_e2e/mix.exs
Annopaolo/astarte
f8190e8bf044759a9b84bdeb5786a55b6f793a4f
[ "Apache-2.0" ]
402
2018-03-30T13:37:00.000Z
2022-03-31T16:47:10.000Z
tools/astarte_e2e/mix.exs
Annopaolo/astarte
f8190e8bf044759a9b84bdeb5786a55b6f793a4f
[ "Apache-2.0" ]
24
2018-03-30T13:29:48.000Z
2022-02-28T11:10:26.000Z
# # This file is part of Astarte. # # Copyright 2020-2021 Ispirata Srl # # 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 AstarteE2E.MixProject do use Mix.Project def project do [ app: :astarte_e2e, version: "0.1.0", elixir: "~> 1.11", start_permanent: Mix.env() == :prod, dialyzer_cache_directory: dialyzer_cache_directory(Mix.env()), deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ mod: {AstarteE2E.Application, []}, extra_applications: [:logger] ] end defp dialyzer_cache_directory(:ci) do "dialyzer_cache" end defp dialyzer_cache_directory(_) do nil end # Run "mix help deps" to learn about dependencies. defp deps do [ {:astarte_device, github: "astarte-platform/astarte-device-sdk-elixir"}, {:phoenix_gen_socket_client, "~> 4.0"}, {:websocket_client, "~> 1.2"}, {:jason, "~> 1.0"}, {:plug_cowboy, "~> 2.0"}, {:skogsra, "~> 2.3"}, {:telemetry, "~> 0.4"}, {:telemetry_metrics_prometheus_core, "~> 0.4"}, {:telemetry_metrics, "~> 0.4"}, {:telemetry_poller, "~> 0.4"}, {:logfmt, "~> 3.3"}, {:pretty_log, "~> 0.1"}, {:observer_cli, "~> 1.5"}, {:bamboo, "~> 1.6"}, {:bamboo_config_adapter, "~> 1.0"}, {:hukai, "~> 0.3"}, {:dialyzex, github: "Comcast/dialyzex", only: [:dev, :ci]} ] end end
27.222222
78
0.622959
08ee2c594032684c47dd336b7d1c938ddbbdad64
1,941
ex
Elixir
lib/raml/common.ex
zachdaniel/ramoulade
11fa7745b595c199d708eb15c46526bc7a249b37
[ "MIT" ]
1
2018-02-21T23:45:02.000Z
2018-02-21T23:45:02.000Z
lib/raml/common.ex
zachdaniel/ramoulade
11fa7745b595c199d708eb15c46526bc7a249b37
[ "MIT" ]
null
null
null
lib/raml/common.ex
zachdaniel/ramoulade
11fa7745b595c199d708eb15c46526bc7a249b37
[ "MIT" ]
null
null
null
defmodule Ramoulade.Raml.Common do def get_required_scalar!(document, yaml, key) do value = get_scalar!(document, yaml, key) if value do value else Ramoulade.error!(document, "Missing value required for key: #{key}, at #{inspect(yaml)}") end end def get_string!(document, yaml, key) do case get_scalar!(document, yaml, key) do nil -> nil value when is_bitstring(value) -> value other -> Ramoulade.error!(document, "String value required for key: #{key}. Got #{inspect other}") end end @spec get_scalar!(struct, map, String.t) :: String.t | no_return def get_scalar!(document, yaml, key) do if is_map(yaml[key]) do if Map.has_key?(yaml[key], "value") do if is_nil_or_null(yaml[key]["value"]) do nil else yaml[key]["value"] end else Ramoulade.error!(document, "Scalar value required for key: #{key}. This can be provided as a map with a value key, or a single scalar value. Got #{inspect yaml[key]}") end else yaml[key] end end def get_list!(document, yaml, key, opts \\ []) do value = yaml[key] if is_nil_or_null(value) do nil else if is_list(value) do value else if opts[:wrap_scalar?] do if is_nil_or_null(value) do nil else [value] end else Ramoulade.error!(document, "List value required for key: #{key}, at #{inspect(yaml)}") end end end end def get_map!(document, yaml, key) do value = yaml[key] if is_nil_or_null(value) do %{} else if is_map(value) do value else Ramoulade.error!(document, "Map value required for key: #{key}, at #{inspect(yaml)}") end end end def is_nil_or_null(nil), do: true def is_nil_or_null(:null), do: true def is_nil_or_null(_), do: false end
26.22973
175
0.593509
08ee30414c5d4d174e886653e7c25c0cf3e857c6
2,060
ex
Elixir
clients/jobs/lib/google_api/jobs/v3/model/money.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/jobs/lib/google_api/jobs/v3/model/money.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/jobs/lib/google_api/jobs/v3/model/money.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Jobs.V3.Model.Money do @moduledoc """ Represents an amount of money with its currency type. ## Attributes * `currencyCode` (*type:* `String.t`, *default:* `nil`) - The 3-letter currency code defined in ISO 4217. * `nanos` (*type:* `integer()`, *default:* `nil`) - Number of nano (10^-9) units of the amount. The value must be between -999,999,999 and +999,999,999 inclusive. If `units` is positive, `nanos` must be positive or zero. If `units` is zero, `nanos` can be positive, zero, or negative. If `units` is negative, `nanos` must be negative or zero. For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. * `units` (*type:* `String.t`, *default:* `nil`) - The whole units of the amount. For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :currencyCode => String.t(), :nanos => integer(), :units => String.t() } field(:currencyCode) field(:nanos) field(:units) end defimpl Poison.Decoder, for: GoogleApi.Jobs.V3.Model.Money do def decode(value, options) do GoogleApi.Jobs.V3.Model.Money.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Jobs.V3.Model.Money do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.867925
420
0.7
08ee4937d02e9d45ee1657006c404c0110a2a3a6
228
ex
Elixir
lib/loki/accounts/error_handler.ex
artjimlop/loki
4ac5f7b4313564971f8dd4213a2022698600786a
[ "Apache-2.0" ]
null
null
null
lib/loki/accounts/error_handler.ex
artjimlop/loki
4ac5f7b4313564971f8dd4213a2022698600786a
[ "Apache-2.0" ]
null
null
null
lib/loki/accounts/error_handler.ex
artjimlop/loki
4ac5f7b4313564971f8dd4213a2022698600786a
[ "Apache-2.0" ]
null
null
null
defmodule Loki.Accounts.ErrorHandler do import Plug.Conn def auth_error(conn, {type, _reason}, _opts) do body = to_string(type) conn |> put_resp_content_type("text/plain") |> send_resp(401, body) end end
19
49
0.688596
08ee592219b925b8510d8ed934be07a19dcb2b6f
4,672
ex
Elixir
clients/managed_identities/lib/google_api/managed_identities/v1/model/domain.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/managed_identities/lib/google_api/managed_identities/v1/model/domain.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/managed_identities/lib/google_api/managed_identities/v1/model/domain.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "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.ManagedIdentities.V1.Model.Domain do @moduledoc """ Represents a managed Microsoft Active Directory domain. If the domain is being changed, it will be placed into the UPDATING state, which indicates that the resource is being reconciled. At this point, Get will reflect an intermediate state. ## Attributes * `admin` (*type:* `String.t`, *default:* `nil`) - Optional. The name of delegated administrator account used to perform Active Directory operations. If not specified, `setupadmin` will be used. * `authorizedNetworks` (*type:* `list(String.t)`, *default:* `nil`) - Optional. The full names of the Google Compute Engine [networks](/compute/docs/networks-and-firewalls#networks) the domain instance is connected to. Networks can be added using UpdateDomain. The domain is only available on networks listed in `authorized_networks`. If CIDR subnets overlap between networks, domain creation will fail. * `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The time the instance was created. * `fqdn` (*type:* `String.t`, *default:* `nil`) - Output only. The fully-qualified domain name of the exposed domain used by clients to connect to the service. Similar to what would be chosen for an Active Directory set up on an internal network. * `labels` (*type:* `map()`, *default:* `nil`) - Optional. Resource labels that can contain user-provided metadata. * `locations` (*type:* `list(String.t)`, *default:* `nil`) - Required. Locations where domain needs to be provisioned. regions e.g. us-west1 or us-east4 Service supports up to 4 locations at once. Each location will use a /26 block. * `name` (*type:* `String.t`, *default:* `nil`) - Required. The unique name of the domain using the form: `projects/{project_id}/locations/global/domains/{domain_name}`. * `reservedIpRange` (*type:* `String.t`, *default:* `nil`) - Required. The CIDR range of internal addresses that are reserved for this domain. Reserved networks must be /24 or larger. Ranges must be unique and non-overlapping with existing subnets in [Domain].[authorized_networks]. * `state` (*type:* `String.t`, *default:* `nil`) - Output only. The current state of this domain. * `statusMessage` (*type:* `String.t`, *default:* `nil`) - Output only. Additional information about the current status of this domain, if available. * `trusts` (*type:* `list(GoogleApi.ManagedIdentities.V1.Model.Trust.t)`, *default:* `nil`) - Output only. The current trusts associated with the domain. * `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The last update time. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :admin => String.t() | nil, :authorizedNetworks => list(String.t()) | nil, :createTime => DateTime.t() | nil, :fqdn => String.t() | nil, :labels => map() | nil, :locations => list(String.t()) | nil, :name => String.t() | nil, :reservedIpRange => String.t() | nil, :state => String.t() | nil, :statusMessage => String.t() | nil, :trusts => list(GoogleApi.ManagedIdentities.V1.Model.Trust.t()) | nil, :updateTime => DateTime.t() | nil } field(:admin) field(:authorizedNetworks, type: :list) field(:createTime, as: DateTime) field(:fqdn) field(:labels, type: :map) field(:locations, type: :list) field(:name) field(:reservedIpRange) field(:state) field(:statusMessage) field(:trusts, as: GoogleApi.ManagedIdentities.V1.Model.Trust, type: :list) field(:updateTime, as: DateTime) end defimpl Poison.Decoder, for: GoogleApi.ManagedIdentities.V1.Model.Domain do def decode(value, options) do GoogleApi.ManagedIdentities.V1.Model.Domain.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ManagedIdentities.V1.Model.Domain do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
58.4
407
0.702055
08ee7bddf460963b726269f7af463b6fc8b117f3
2,002
ex
Elixir
lib/ecto_schema_store/factory.ex
cenurv/ecto_store
3e414cb56b5c788f6adf35bad597f34fa95f2f29
[ "Apache-2.0" ]
8
2016-10-27T15:53:18.000Z
2022-01-03T23:47:45.000Z
lib/ecto_schema_store/factory.ex
cenurv/ecto_store
3e414cb56b5c788f6adf35bad597f34fa95f2f29
[ "Apache-2.0" ]
5
2017-04-25T15:28:29.000Z
2017-10-05T16:08:57.000Z
lib/ecto_schema_store/factory.ex
cenurv/ecto_store
3e414cb56b5c788f6adf35bad597f34fa95f2f29
[ "Apache-2.0" ]
3
2017-08-28T18:51:24.000Z
2020-01-16T22:30:33.000Z
defmodule EctoSchemaStore.Factory do @moduledoc false defmacro build do quote do def generate(keys \\ []) do generate keys, %{} end def generate(keys, fields ) when is_atom keys do generate [keys], fields end def generate(keys, fields) when is_list keys do # Default always applies first. keys = [:default | keys] params_list = Enum.map keys, fn(key) -> try do generate_prepare_fields apply(__MODULE__, :generate_params, [key]) rescue _ -> if key != :default do Logger.warn "Factory '#{key}' not found in '#{__MODULE__}'." end %{} end end params = Enum.reduce params_list, %{}, fn(params, acc) -> Map.merge acc, params end fields = generate_prepare_fields fields params = Map.merge params, fields insert_fields params end def generate_default(fields \\ %{}) do generate [], fields end def generate_default!(fields \\ %{}) do generate! [], fields end def generate!(keys \\ []) do generate! keys, %{} end def generate!(keys, fields) do case generate(keys, fields) do {:ok, response} -> response {:error, message} -> throw message end end defp generate_prepare_fields(fields) when is_list fields do generate_prepare_fields Enum.into(fields, %{}) end defp generate_prepare_fields(fields) when is_map fields do alias_filters(fields) end end end defmacro factory(function, do: block) do name = elem(function, 0) quote do def generate_params(unquote(name)) do unquote(block) end end end defmacro factory(do: block) do quote do factory default do unquote block end end end end
23.27907
80
0.55045
08ee83af1fb67531b896ca6568a569a8811a40b3
3,553
ex
Elixir
lib/cryppo/encryption_strategy.ex
Meeco/cryppo_ex
fd9b6f4f84c6668797b1e31f6e59bb5f42630a2a
[ "Apache-2.0" ]
null
null
null
lib/cryppo/encryption_strategy.ex
Meeco/cryppo_ex
fd9b6f4f84c6668797b1e31f6e59bb5f42630a2a
[ "Apache-2.0" ]
null
null
null
lib/cryppo/encryption_strategy.ex
Meeco/cryppo_ex
fd9b6f4f84c6668797b1e31f6e59bb5f42630a2a
[ "Apache-2.0" ]
1
2021-06-01T07:46:14.000Z
2021-06-01T07:46:14.000Z
defmodule Cryppo.EncryptionStrategy do @moduledoc false # EncryptionStrategy behavior and macros to inject functions common to all EncryptionStrategy modules alias Cryppo.{EncryptedData, EncryptionArtefacts, EncryptionKey} @callback strategy_name :: binary @callback key_length :: integer() @callback generate_key :: EncryptionKey.t() @callback build_encryption_key(any) :: {:ok, EncryptionKey.t()} | {:error, :invalid_encryption_key} @callback encrypt(binary, EncryptionKey.t()) :: {:ok, binary, EncryptionArtefacts.t()} | :encryption_error | {:encryption_error, any} @callback decrypt(EncryptedData.t(), EncryptionKey.t()) :: {:ok, binary} | :decryption_error | {:decryption_error, {any, any}} @callback key_derivation_possible :: boolean() defmacro __using__( strategy_name: strategy_name, key_length: key_length, key_derivation_possible: key_derivation_possible ) when is_binary(strategy_name) do [ quote do alias Cryppo.{EncryptedData, EncryptionArtefacts, EncryptionKey, EncryptionStrategy} @behaviour EncryptionStrategy end, inject_strategy_name(strategy_name), inject_key_length(key_length), inject_key_derivation_possible(key_derivation_possible), inject_run_encryption(), inject_run_decryption() ] end defp inject_strategy_name(strategy_name) do quote do @impl EncryptionStrategy def strategy_name, do: unquote(strategy_name) end end defp inject_key_length(key_length) do quote do @spec key_length :: integer() @impl EncryptionStrategy def key_length, do: unquote(key_length) end end defp inject_key_derivation_possible(true) do quote do @impl EncryptionStrategy def key_derivation_possible, do: true end end defp inject_key_derivation_possible(false) do quote do @impl EncryptionStrategy def key_derivation_possible, do: false end end defp inject_run_encryption do quote do @doc false def run_encryption(data, %EncryptionKey{encryption_strategy_module: __MODULE__} = key) do case encrypt(data, key) do {:ok, encrypted, artefacts} -> EncryptedData.new(__MODULE__, encrypted, artefacts) any -> any end end def run_encryption(_data, %EncryptionKey{key: key, encryption_strategy_module: mod}) do {:incompatible_key, submitted_key_strategy: mod, encryption_strategy: __MODULE__} end def run_encryption(data, raw_key) do with {:ok, key} <- build_encryption_key(raw_key) do run_encryption(data, key) end end end end defp inject_run_decryption do quote do @doc false def run_decryption( %EncryptedData{encryption_strategy_module: __MODULE__} = encrypted_data, %EncryptionKey{encryption_strategy_module: __MODULE__} = encryption_key ) do decrypt(encrypted_data, encryption_key) end def run_decryption(%EncryptedData{encryption_strategy_module: __MODULE__}, %EncryptionKey{ encryption_strategy_module: mod }) do {:incompatible_key, submitted_key_strategy: mod, encryption_strategy: __MODULE__} end def run_decryption(data, raw_key) do with {:ok, key} <- build_encryption_key(raw_key) do run_decryption(data, key) end end end end end
29.363636
103
0.676611
08ee846d5421b899c5444b4a7c4762583000209a
5,085
ex
Elixir
lib/stripe/connect/oauth.ex
mmmries/stripity_stripe
7bfaa2316f24a86fbbfc3cf140b1caff05f5ef9d
[ "BSD-3-Clause" ]
null
null
null
lib/stripe/connect/oauth.ex
mmmries/stripity_stripe
7bfaa2316f24a86fbbfc3cf140b1caff05f5ef9d
[ "BSD-3-Clause" ]
null
null
null
lib/stripe/connect/oauth.ex
mmmries/stripity_stripe
7bfaa2316f24a86fbbfc3cf140b1caff05f5ef9d
[ "BSD-3-Clause" ]
null
null
null
defmodule Stripe.Connect.OAuth do @moduledoc """ Work with Stripe Connect. You can: - generate the URL for starting the OAuth workflow - authorize a new connected account with a token - deauthorize an existing connected account Stripe API reference: https://stripe.com/docs/connect/reference """ alias Stripe.Converter @callback token(code :: String.t()) :: {:ok, map} @callback authorize_url(map) :: String.t() @callback deauthorize_url(url :: String.t()) :: {:ok, map} @authorize_url_valid_keys [ :always_prompt, :client_id, :redirect_uri, :response_type, :scope, :state, :stripe_landing, :stripe_user ] defmodule AuthorizeResponse do defstruct [ :access_token, :livemode, :refresh_token, :scope, :stripe_user_id, :stripe_publishable_key, :token_type ] end defmodule TokenResponse do defstruct [ :access_token, :livemode, :refresh_token, :scope, :stripe_user_id, :stripe_publishable_key, :token_type ] end defmodule DeauthorizeResponse do defstruct [ :stripe_user_id ] end @doc """ Execute the OAuth callback to Stripe using the code supplied in the request parameter of the oauth redirect at the end of the onboarding workflow. ## Example ``` iex(1)> {:ok, resp} = Stripe.Connect.OAuth.token(code) ...(1)> IO.inspect resp %Stripe.Connect.OAuth.TokenResponse{ access_token: "ACCESS_TOKEN", livemode: false, refresh_token: "REFRESH_TOKEN", scope: "read_write", stripe_publishable_key: "PUBLISHABLE_KEY", stripe_user_id: "USER_ID", token_type: "bearer" } ``` """ @spec token(String.t()) :: {:ok, map} | {:error, Stripe.api_error_struct()} def token(code) do endpoint = "token" body = %{ client_secret: get_client_secret(), code: code, grant_type: "authorization_code" } case Stripe.API.oauth_request(:post, endpoint, body) do {:ok, result} -> {:ok, Converter.convert_result(result)} {:error, error} -> {:error, error} end end @doc """ De-authorizes the connected account. Requires the customer to re-establish the link using the onboarding workflow. ## Example ``` iex(1)> {:ok, result} = Stripe.Connect.OAuth.deauthorize(stripe_user_id) ``` """ @spec deauthorize(String.t()) :: {:ok, map} | {:error, Stripe.api_error_struct()} def deauthorize(stripe_user_id) do endpoint = "deauthorize" body = %{ client_id: get_client_id(), stripe_user_id: stripe_user_id } case Stripe.API.oauth_request(:post, endpoint, body) do {:ok, result} -> {:ok, Converter.convert_result(result)} {:error, error} -> {:error, error} end end @doc ~S""" Generate the URL to start a Stripe workflow. ## Paremeter Map Keys The parameter map keys are derived from the [valid request parameter](https://stripe.com/docs/connect/reference) for the Stripe Connect authorize endpoint. A parameter only needs to be provided if you wish to override the default. - `:always_prompt` - `:client_id` - `:redirect_uri` - `:response_type` - `:scope` - `:state` - `:stripe_landing` - `:stripe_user` For ease of use, any parameters you provide will be merged into the following default map with sensible defaults. This also allows you to call the function with no parameters and it will fall back to this map: ``` %{ client_id: client_id, # :connect_client_id from configuration response_type: "code", scope: "read_write" } ``` ## Example ``` connect_opts = %{ state: "2686e7a93156ff5af76a83262ac653", stripe_user: %{ "email" => "local@business.example.net", "url" => "http://local.example.net", "country" => "US", "phone_number" => "5555555678", "business_name" => "Jeanine & Jerome's Jellies", "businessy_type" => "llc", "first_name" => "Jeanine", "last_name" => "Smith", "dob_day" => 29, "dob_month" => 1, "dob_year" => 1983, "street_address" => "123 Main St.", "product_category" => "food_and_restuarants" } } url = Stripe.Connect.OAuth.authorize_url(connect_opts) ``` """ @spec authorize_url(map) :: String.t() def authorize_url(options \\ %{}) do base_url = "https://connect.stripe.com/oauth/authorize?" param_string = get_default_authorize_map() |> Map.merge(options) |> Map.take(@authorize_url_valid_keys) |> Stripe.URI.encode_query() base_url <> param_string end @spec get_client_id() :: String.t() defp get_client_id() do Application.get_env(:stripity_stripe, :connect_client_id) end @spec get_client_secret() :: String.t() defp get_client_secret() do Application.get_env(:stripity_stripe, :api_key) end @spec get_default_authorize_map() :: map defp get_default_authorize_map() do %{ client_id: get_client_id(), response_type: "code", scope: "read_write" } end end
24.447115
148
0.645231
08ee911c13c5ad5fd8f4a03e94026d712ab22a0a
2,321
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/campaign_creative_associations_list_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/campaign_creative_associations_list_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/campaign_creative_associations_list_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.DFAReporting.V33.Model.CampaignCreativeAssociationsListResponse do @moduledoc """ Campaign Creative Association List Response ## Attributes * `campaignCreativeAssociations` (*type:* `list(GoogleApi.DFAReporting.V33.Model.CampaignCreativeAssociation.t)`, *default:* `nil`) - Campaign creative association collection * `kind` (*type:* `String.t`, *default:* `dfareporting#campaignCreativeAssociationsListResponse`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#campaignCreativeAssociationsListResponse". * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Pagination token to be used for the next list operation. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :campaignCreativeAssociations => list(GoogleApi.DFAReporting.V33.Model.CampaignCreativeAssociation.t()), :kind => String.t(), :nextPageToken => String.t() } field( :campaignCreativeAssociations, as: GoogleApi.DFAReporting.V33.Model.CampaignCreativeAssociation, type: :list ) field(:kind) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.CampaignCreativeAssociationsListResponse do def decode(value, options) do GoogleApi.DFAReporting.V33.Model.CampaignCreativeAssociationsListResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.CampaignCreativeAssociationsListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.265625
226
0.747523
08eeb84de21447f7ce885a5bcaf04073bfa342a0
712
ex
Elixir
lib/chat_api_web/gettext.ex
raditya3/papercups
4657b258ee381ac0b7517e57e4d6261ce94b5871
[ "MIT" ]
4,942
2020-07-20T22:35:28.000Z
2022-03-31T15:38:51.000Z
lib/chat_api_web/gettext.ex
raditya3/papercups
4657b258ee381ac0b7517e57e4d6261ce94b5871
[ "MIT" ]
552
2020-07-22T01:39:04.000Z
2022-02-01T00:26:35.000Z
lib/chat_api_web/gettext.ex
raditya3/papercups
4657b258ee381ac0b7517e57e4d6261ce94b5871
[ "MIT" ]
396
2020-07-22T19:27:48.000Z
2022-03-31T05:25:24.000Z
defmodule ChatApiWeb.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. By using [Gettext](https://hexdocs.pm/gettext), your module gains a set of macros for translations, for example: import ChatApiWeb.Gettext # Simple translation gettext("Here is the string to translate") # Plural translation ngettext("Here is the string to translate", "Here are the strings to translate", 3) # Domain-based translation dgettext("errors", "Here is the error message to translate") See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. """ use Gettext, otp_app: :chat_api end
28.48
72
0.678371
08eed732a89289bbddb3b086557ef3301a7d3bae
580
ex
Elixir
lib/adaptable_costs_evaluator_web/views/input_view.ex
patrotom/adaptable-costs-evaluator
c97e65af1e021d7c6acf6564f4671c60321346e3
[ "MIT" ]
null
null
null
lib/adaptable_costs_evaluator_web/views/input_view.ex
patrotom/adaptable-costs-evaluator
c97e65af1e021d7c6acf6564f4671c60321346e3
[ "MIT" ]
4
2021-12-07T12:26:50.000Z
2021-12-30T14:17:25.000Z
lib/adaptable_costs_evaluator_web/views/input_view.ex
patrotom/adaptable-costs-evaluator
c97e65af1e021d7c6acf6564f4671c60321346e3
[ "MIT" ]
null
null
null
defmodule AdaptableCostsEvaluatorWeb.InputView do use AdaptableCostsEvaluatorWeb, :view alias AdaptableCostsEvaluatorWeb.InputView def render("index.json", %{inputs: inputs}) do %{data: render_many(inputs, InputView, "input.json")} end def render("show.json", %{input: input}) do %{data: render_one(input, InputView, "input.json")} end def render("input.json", %{input: input}) do %{ id: input.id, name: input.name, label: input.label, last_value: input.last_value, field_schema_id: input.field_schema_id } end end
25.217391
57
0.681034
08eee28b7d46764b10719d8c0467ca2c085f3517
1,382
ex
Elixir
lib/elixir/lib/access.ex
Nicd/elixir
e62ef92a4be1b562033d35b2d822cc9d6c661077
[ "Apache-2.0" ]
1
2017-09-09T20:59:04.000Z
2017-09-09T20:59:04.000Z
lib/elixir/lib/access.ex
Nicd/elixir
e62ef92a4be1b562033d35b2d822cc9d6c661077
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/access.ex
Nicd/elixir
e62ef92a4be1b562033d35b2d822cc9d6c661077
[ "Apache-2.0" ]
null
null
null
import Kernel, except: [access: 2] defprotocol Access do @moduledoc """ The Access protocol is the underlying protocol invoked when the brackets syntax is used. For instance, `foo[bar]` is translated to `access foo, bar` which, by default, invokes the `Access.access` protocol. This protocol is limited and is implemented only for the following built-in types: keywords, records and functions. """ @only [List, Record, Atom] @doc """ Receives the element being accessed and the access item. """ def access(container, key) end defimpl Access, for: List do @doc """ Access the given key in a tuple list. ## Examples iex> keywords = [a: 1, b: 2] ...> keywords[:a] 1 iex> star_ratings = [{1.0, "★"}, {1.5, "★☆"}, {2.0, "★★"}] ...> star_ratings[1.5] "★☆" """ def access([], _key), do: nil def access(list, key) do case :lists.keyfind(key, 1, list) do { ^key, value } -> value false -> nil end end end defimpl Access, for: Atom do @doc """ The access protocol can only be accessed by atoms at compilation time. If we reach this, we should raise an exception. """ def access(nil, _) do nil end def access(atom, _) do raise "The access protocol can only be invoked for atoms at " <> "compilation time, tried to invoke it for #{inspect atom}" end end
22.290323
68
0.629522
08eeebb0caf90cf7619fb33273a65c2985887b2e
1,952
ex
Elixir
clients/cloud_identity/lib/google_api/cloud_identity/v1/connection.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/cloud_identity/lib/google_api/cloud_identity/v1/connection.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/cloud_identity/lib/google_api/cloud_identity/v1/connection.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "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.CloudIdentity.V1.Connection do @moduledoc """ Handle Tesla connections for GoogleApi.CloudIdentity.V1. """ @type t :: Tesla.Env.client() use GoogleApi.Gax.Connection, scopes: [ # Private Service: https://www.googleapis.com/auth/cloud-identity.devices "https://www.googleapis.com/auth/cloud-identity.devices", # See your device details "https://www.googleapis.com/auth/cloud-identity.devices.lookup", # Private Service: https://www.googleapis.com/auth/cloud-identity.devices.readonly "https://www.googleapis.com/auth/cloud-identity.devices.readonly", # See, change, create, and delete any of the Cloud Identity Groups that you can access, including the members of each group "https://www.googleapis.com/auth/cloud-identity.groups", # See any Cloud Identity Groups that you can access, including group members and their emails "https://www.googleapis.com/auth/cloud-identity.groups.readonly", # See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account. "https://www.googleapis.com/auth/cloud-platform" ], otp_app: :google_api_cloud_identity, base_url: "https://cloudidentity.googleapis.com/" end
40.666667
129
0.735143
08eef2ff62260d1308204a21c57d7f2e7ca4465f
110,272
ex
Elixir
clients/logging/lib/google_api/logging/v2/api/organizations.ex
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "Apache-2.0" ]
null
null
null
clients/logging/lib/google_api/logging/v2/api/organizations.ex
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/logging/lib/google_api/logging/v2/api/organizations.ex
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "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.Api.Organizations do @moduledoc """ API calls for all endpoints tagged `Organizations`. """ alias GoogleApi.Logging.V2.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Gets the Logs Router CMEK settings for the given resource.Note: CMEK for the Logs Router can currently only be configured for GCP organizations. Once configured, it applies to all projects and folders in the GCP organization.See Enabling CMEK for Logs Router (https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Required. The resource for which to retrieve CMEK settings. "projects/[PROJECT_ID]/cmekSettings" "organizations/[ORGANIZATION_ID]/cmekSettings" "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" "folders/[FOLDER_ID]/cmekSettings" Example: "organizations/12345/cmekSettings".Note: CMEK for the Logs Router can currently only be configured for GCP organizations. Once configured, it applies to all projects and folders in the GCP organization. * `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.Logging.V2.Model.CmekSettings{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_get_cmek_settings( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.CmekSettings.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_get_cmek_settings( connection, organizations_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("/v2/organizations/{organizationsId}/cmekSettings", %{ "organizationsId" => URI.encode(organizations_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.Logging.V2.Model.CmekSettings{}]) end @doc """ Updates the Logs Router CMEK settings for the given resource.Note: CMEK for the Logs Router can currently only be configured for GCP organizations. Once configured, it applies to all projects and folders in the GCP organization.UpdateCmekSettings will fail if 1) kms_key_name is invalid, or 2) the associated service account does not have the required roles/cloudkms.cryptoKeyEncrypterDecrypter role assigned for the key, or 3) access to the key is disabled.See Enabling CMEK for Logs Router (https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Required. The resource name for the CMEK settings to update. "projects/[PROJECT_ID]/cmekSettings" "organizations/[ORGANIZATION_ID]/cmekSettings" "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" "folders/[FOLDER_ID]/cmekSettings" Example: "organizations/12345/cmekSettings".Note: CMEK for the Logs Router can currently only be configured for GCP organizations. Once configured, it applies to all projects and folders in the GCP organization. * `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"). * `:updateMask` (*type:* `String.t`) - Optional. Field mask identifying which fields from cmek_settings should be updated. A field will be overwritten if and only if it is in the update mask. Output only fields cannot be updated.See FieldMask for more information.Example: "updateMask=kmsKeyName" * `:body` (*type:* `GoogleApi.Logging.V2.Model.CmekSettings.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.CmekSettings{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_update_cmek_settings( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.CmekSettings.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_update_cmek_settings( connection, organizations_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, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v2/organizations/{organizationsId}/cmekSettings", %{ "organizationsId" => URI.encode(organizations_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.Logging.V2.Model.CmekSettings{}]) end @doc """ Creates a new exclusion in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `parent`. Required. The parent resource in which to create the exclusion: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: "projects/my-logging-project", "organizations/123456789". * `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"). * `:body` (*type:* `GoogleApi.Logging.V2.Model.LogExclusion.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.LogExclusion{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_exclusions_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.LogExclusion.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_exclusions_create( connection, organizations_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, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v2/organizations/{organizationsId}/exclusions", %{ "organizationsId" => URI.encode(organizations_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.Logging.V2.Model.LogExclusion{}]) end @doc """ Deletes an exclusion. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of an existing exclusion to delete: "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" Example: "projects/my-project-id/exclusions/my-exclusion-id". * `exclusions_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `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.Logging.V2.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_exclusions_delete( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_exclusions_delete( connection, organizations_id, exclusions_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(:delete) |> Request.url("/v2/organizations/{organizationsId}/exclusions/{exclusionsId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "exclusionsId" => URI.encode(exclusions_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.Logging.V2.Model.Empty{}]) end @doc """ Gets the description of an exclusion. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of an existing exclusion: "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" Example: "projects/my-project-id/exclusions/my-exclusion-id". * `exclusions_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `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.Logging.V2.Model.LogExclusion{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_exclusions_get( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.LogExclusion.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_exclusions_get( connection, organizations_id, exclusions_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("/v2/organizations/{organizationsId}/exclusions/{exclusionsId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "exclusionsId" => URI.encode(exclusions_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.Logging.V2.Model.LogExclusion{}]) end @doc """ Lists all the exclusions in a parent resource. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `parent`. Required. The parent resource whose exclusions are to be listed. "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" * `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()`) - Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of nextPageToken in the response indicates that more results might be available. * `:pageToken` (*type:* `String.t`) - Optional. If present, then retrieve the next batch of results from the preceding call to this method. pageToken must be the value of nextPageToken from the previous response. The values of other method parameters should be identical to those in the previous call. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.ListExclusionsResponse{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_exclusions_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.ListExclusionsResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_exclusions_list( connection, organizations_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("/v2/organizations/{organizationsId}/exclusions", %{ "organizationsId" => URI.encode(organizations_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.Logging.V2.Model.ListExclusionsResponse{}]) end @doc """ Changes one or more properties of an existing exclusion. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of the exclusion to update: "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" Example: "projects/my-project-id/exclusions/my-exclusion-id". * `exclusions_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `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"). * `:updateMask` (*type:* `String.t`) - Required. A non-empty list of fields to change in the existing exclusion. New values for the fields are taken from the corresponding fields in the LogExclusion included in this request. Fields not mentioned in update_mask are not changed and are ignored in the request.For example, to change the filter and description of an exclusion, specify an update_mask of "filter,description". * `:body` (*type:* `GoogleApi.Logging.V2.Model.LogExclusion.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.LogExclusion{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_exclusions_patch( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.LogExclusion.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_exclusions_patch( connection, organizations_id, exclusions_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, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v2/organizations/{organizationsId}/exclusions/{exclusionsId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "exclusionsId" => URI.encode(exclusions_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.Logging.V2.Model.LogExclusion{}]) end @doc """ Gets information about a location. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Resource name for the location. * `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `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.Logging.V2.Model.Location{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_get( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.Location.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_get( connection, organizations_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 } request = Request.new() |> Request.method(:get) |> Request.url("/v2/organizations/{organizationsId}/locations/{locationsId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_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.Logging.V2.Model.Location{}]) end @doc """ Lists information about the supported locations for this service. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. The resource that owns the locations collection, if applicable. * `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"). * `:filter` (*type:* `String.t`) - The standard list filter. * `:pageSize` (*type:* `integer()`) - The standard list page size. * `:pageToken` (*type:* `String.t`) - The standard list page token. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.ListLocationsResponse{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Logging.V2.Model.ListLocationsResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_list( connection, organizations_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, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v2/organizations/{organizationsId}/locations", %{ "organizationsId" => URI.encode(organizations_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.Logging.V2.Model.ListLocationsResponse{}]) end @doc """ Creates a bucket that can be used to store log entries. Once a bucket has been created, the region cannot be changed. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `parent`. Required. The resource in which to create the bucket: "projects/[PROJECT_ID]/locations/[LOCATION_ID]" Example: "projects/my-logging-project/locations/global" * `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `organizationsId`. * `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"). * `:bucketId` (*type:* `String.t`) - Required. A client-assigned identifier such as "my-bucket". Identifiers are limited to 100 characters and can include only letters, digits, underscores, hyphens, and periods. * `:body` (*type:* `GoogleApi.Logging.V2.Model.LogBucket.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.LogBucket{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_buckets_create( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.LogBucket.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_buckets_create( connection, organizations_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, :bucketId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v2/organizations/{organizationsId}/locations/{locationsId}/buckets", %{ "organizationsId" => URI.encode(organizations_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.Logging.V2.Model.LogBucket{}]) end @doc """ Deletes a bucket. Moves the bucket to the DELETE_REQUESTED state. After 7 days, the bucket will be purged and all logs in the bucket will be permanently deleted. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Required. The full resource name of the bucket to delete. "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" Example: "projects/my-project-id/locations/my-location/buckets/my-bucket-id". * `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `buckets_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `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.Logging.V2.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_buckets_delete( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_buckets_delete( connection, organizations_id, locations_id, buckets_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(:delete) |> Request.url( "/v2/organizations/{organizationsId}/locations/{locationsId}/buckets/{bucketsId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1), "bucketsId" => URI.encode(buckets_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.Logging.V2.Model.Empty{}]) end @doc """ Gets a bucket. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of the bucket: "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" Example: "projects/my-project-id/locations/my-location/buckets/my-bucket-id". * `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `buckets_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `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.Logging.V2.Model.LogBucket{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_buckets_get( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.LogBucket.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_buckets_get( connection, organizations_id, locations_id, buckets_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( "/v2/organizations/{organizationsId}/locations/{locationsId}/buckets/{bucketsId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1), "bucketsId" => URI.encode(buckets_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.Logging.V2.Model.LogBucket{}]) end @doc """ Lists buckets. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `parent`. Required. The parent resource whose buckets are to be listed: "projects/[PROJECT_ID]/locations/[LOCATION_ID]" "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" "folders/[FOLDER_ID]/locations/[LOCATION_ID]" Note: The locations portion of the resource must be specified, but supplying the character - in place of LOCATION_ID will return all buckets. * `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `organizationsId`. * `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()`) - Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of nextPageToken in the response indicates that more results might be available. * `:pageToken` (*type:* `String.t`) - Optional. If present, then retrieve the next batch of results from the preceding call to this method. pageToken must be the value of nextPageToken from the previous response. The values of other method parameters should be identical to those in the previous call. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.ListBucketsResponse{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_buckets_list( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.ListBucketsResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_buckets_list( connection, organizations_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("/v2/organizations/{organizationsId}/locations/{locationsId}/buckets", %{ "organizationsId" => URI.encode(organizations_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.Logging.V2.Model.ListBucketsResponse{}]) end @doc """ Updates a bucket. This method replaces the following fields in the existing bucket with values from the new bucket: retention_periodIf the retention period is decreased and the bucket is locked, FAILED_PRECONDITION will be returned.If the bucket has a LifecycleState of DELETE_REQUESTED, FAILED_PRECONDITION will be returned.A buckets region may not be modified after it is created. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Required. The full resource name of the bucket to update. "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" Example: "projects/my-project-id/locations/my-location/buckets/my-bucket-id". Also requires permission "resourcemanager.projects.updateLiens" to set the locked property * `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `buckets_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `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"). * `:updateMask` (*type:* `String.t`) - Required. Field mask that specifies the fields in bucket that need an update. A bucket field will be overwritten if, and only if, it is in the update mask. name and output only fields cannot be updated.For a detailed FieldMask definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMaskExample: updateMask=retention_days. * `:body` (*type:* `GoogleApi.Logging.V2.Model.LogBucket.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.LogBucket{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_buckets_patch( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.LogBucket.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_buckets_patch( connection, organizations_id, locations_id, buckets_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, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url( "/v2/organizations/{organizationsId}/locations/{locationsId}/buckets/{bucketsId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1), "bucketsId" => URI.encode(buckets_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.Logging.V2.Model.LogBucket{}]) end @doc """ Undeletes a bucket. A bucket that has been deleted may be undeleted within the grace period of 7 days. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Required. The full resource name of the bucket to undelete. "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" Example: "projects/my-project-id/locations/my-location/buckets/my-bucket-id". * `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `buckets_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `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"). * `:body` (*type:* `GoogleApi.Logging.V2.Model.UndeleteBucketRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_buckets_undelete( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_buckets_undelete( connection, organizations_id, locations_id, buckets_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, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url( "/v2/organizations/{organizationsId}/locations/{locationsId}/buckets/{bucketsId}:undelete", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1), "bucketsId" => URI.encode(buckets_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.Logging.V2.Model.Empty{}]) end @doc """ Creates a view over logs in a bucket. A bucket may contain a maximum of 50 views. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `parent`. Required. The bucket in which to create the view "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" Example: "projects/my-logging-project/locations/my-location/buckets/my-bucket" * `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `organizationsId`. * `buckets_id` (*type:* `String.t`) - Part of `parent`. See documentation of `organizationsId`. * `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"). * `:viewId` (*type:* `String.t`) - Required. The id to use for this view. * `:body` (*type:* `GoogleApi.Logging.V2.Model.LogView.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.LogView{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_buckets_views_create( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.LogView.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_buckets_views_create( connection, organizations_id, locations_id, buckets_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, :viewId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url( "/v2/organizations/{organizationsId}/locations/{locationsId}/buckets/{bucketsId}/views", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1), "bucketsId" => URI.encode(buckets_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.Logging.V2.Model.LogView{}]) end @doc """ Deletes a view from a bucket. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Required. The full resource name of the view to delete: "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" Example: "projects/my-project-id/locations/my-location/buckets/my-bucket-id/views/my-view-id". * `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `buckets_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `views_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `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.Logging.V2.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_buckets_views_delete( Tesla.Env.client(), String.t(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_buckets_views_delete( connection, organizations_id, locations_id, buckets_id, views_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(:delete) |> Request.url( "/v2/organizations/{organizationsId}/locations/{locationsId}/buckets/{bucketsId}/views/{viewsId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1), "bucketsId" => URI.encode(buckets_id, &URI.char_unreserved?/1), "viewsId" => URI.encode(views_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.Logging.V2.Model.Empty{}]) end @doc """ Gets a view. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of the policy: "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" Example: "projects/my-project-id/locations/my-location/buckets/my-bucket-id/views/my-view-id". * `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `buckets_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `views_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `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.Logging.V2.Model.LogView{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_buckets_views_get( Tesla.Env.client(), String.t(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.LogView.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_buckets_views_get( connection, organizations_id, locations_id, buckets_id, views_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( "/v2/organizations/{organizationsId}/locations/{locationsId}/buckets/{bucketsId}/views/{viewsId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1), "bucketsId" => URI.encode(buckets_id, &URI.char_unreserved?/1), "viewsId" => URI.encode(views_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.Logging.V2.Model.LogView{}]) end @doc """ Lists views on a bucket. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `parent`. Required. The bucket whose views are to be listed: "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" * `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `organizationsId`. * `buckets_id` (*type:* `String.t`) - Part of `parent`. See documentation of `organizationsId`. * `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()`) - Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of nextPageToken in the response indicates that more results might be available. * `:pageToken` (*type:* `String.t`) - Optional. If present, then retrieve the next batch of results from the preceding call to this method. pageToken must be the value of nextPageToken from the previous response. The values of other method parameters should be identical to those in the previous call. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.ListViewsResponse{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_buckets_views_list( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.ListViewsResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_buckets_views_list( connection, organizations_id, locations_id, buckets_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( "/v2/organizations/{organizationsId}/locations/{locationsId}/buckets/{bucketsId}/views", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1), "bucketsId" => URI.encode(buckets_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.Logging.V2.Model.ListViewsResponse{}]) end @doc """ Updates a view. This method replaces the following fields in the existing view with values from the new view: filter. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `name`. Required. The full resource name of the view to update "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" Example: "projects/my-project-id/locations/my-location/buckets/my-bucket-id/views/my-view-id". * `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `buckets_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `views_id` (*type:* `String.t`) - Part of `name`. See documentation of `organizationsId`. * `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"). * `:updateMask` (*type:* `String.t`) - Optional. Field mask that specifies the fields in view that need an update. A field will be overwritten if, and only if, it is in the update mask. name and output only fields cannot be updated.For a detailed FieldMask definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMaskExample: updateMask=filter. * `:body` (*type:* `GoogleApi.Logging.V2.Model.LogView.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.LogView{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_locations_buckets_views_patch( Tesla.Env.client(), String.t(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.LogView.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_locations_buckets_views_patch( connection, organizations_id, locations_id, buckets_id, views_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, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url( "/v2/organizations/{organizationsId}/locations/{locationsId}/buckets/{bucketsId}/views/{viewsId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1), "bucketsId" => URI.encode(buckets_id, &URI.char_unreserved?/1), "viewsId" => URI.encode(views_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.Logging.V2.Model.LogView{}]) end @doc """ Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be deleted. Entries received after the delete operation with a timestamp before the operation will be deleted. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `logName`. Required. The resource name of the log to delete: "projects/[PROJECT_ID]/logs/[LOG_ID]" "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" "folders/[FOLDER_ID]/logs/[LOG_ID]" [LOG_ID] must be URL-encoded. For example, "projects/my-project-id/logs/syslog", "organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity". For more information about log names, see LogEntry. * `logs_id` (*type:* `String.t`) - Part of `logName`. See documentation of `organizationsId`. * `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.Logging.V2.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_logs_delete( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_logs_delete( connection, organizations_id, logs_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(:delete) |> Request.url("/v2/organizations/{organizationsId}/logs/{logsId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "logsId" => URI.encode(logs_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.Logging.V2.Model.Empty{}]) end @doc """ Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have entries are listed. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `parent`. Required. The resource name that owns the logs: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" * `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()`) - Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of nextPageToken in the response indicates that more results might be available. * `:pageToken` (*type:* `String.t`) - Optional. If present, then retrieve the next batch of results from the preceding call to this method. pageToken must be the value of nextPageToken from the previous response. The values of other method parameters should be identical to those in the previous call. * `:resourceNames` (*type:* `list(String.t)`) - Optional. The resource name that owns the logs: projects/PROJECT_ID/locations/LOCATION_ID/buckets/BUCKET_ID/views/VIEW_ID organization/ORGANIZATION_ID/locations/LOCATION_ID/buckets/BUCKET_ID/views/VIEW_ID billingAccounts/BILLING_ACCOUNT_ID/locations/LOCATION_ID/buckets/BUCKET_ID/views/VIEW_ID folders/FOLDER_ID/locations/LOCATION_ID/buckets/BUCKET_ID/views/VIEW_IDTo support legacy queries, it could also be: "projects/PROJECT_ID" "organizations/ORGANIZATION_ID" "billingAccounts/BILLING_ACCOUNT_ID" "folders/FOLDER_ID" * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.ListLogsResponse{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_logs_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Logging.V2.Model.ListLogsResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_logs_list( connection, organizations_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, :resourceNames => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v2/organizations/{organizationsId}/logs", %{ "organizationsId" => URI.encode(organizations_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.Logging.V2.Model.ListLogsResponse{}]) end @doc """ Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's writer_identity is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `parent`. Required. The resource in which to create the sink: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" Examples: "projects/my-logging-project", "organizations/123456789". * `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"). * `:uniqueWriterIdentity` (*type:* `boolean()`) - Optional. Determines the kind of IAM identity returned as writer_identity in the new sink. If this value is omitted or set to false, and if the sink's parent is a project, then the value returned as writer_identity is the same group or service account used by Logging before the addition of writer identities to this API. The sink's destination must be in the same project as the sink itself.If this field is set to true, or if the sink is owned by a non-project resource such as an organization, then the value of writer_identity will be a unique service account used only for exports from the new sink. For more information, see writer_identity in LogSink. * `:body` (*type:* `GoogleApi.Logging.V2.Model.LogSink.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.LogSink{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_sinks_create(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Logging.V2.Model.LogSink.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_sinks_create( connection, organizations_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, :uniqueWriterIdentity => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v2/organizations/{organizationsId}/sinks", %{ "organizationsId" => URI.encode(organizations_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.Logging.V2.Model.LogSink{}]) end @doc """ Deletes a sink. If the sink has a unique writer_identity, then that service account is also deleted. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `sinkName`. Required. The full resource name of the sink to delete, including the parent resource and the sink identifier: "projects/[PROJECT_ID]/sinks/[SINK_ID]" "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: "projects/my-project-id/sinks/my-sink-id". * `sinks_id` (*type:* `String.t`) - Part of `sinkName`. See documentation of `organizationsId`. * `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.Logging.V2.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_sinks_delete( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_sinks_delete( connection, organizations_id, sinks_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(:delete) |> Request.url("/v2/organizations/{organizationsId}/sinks/{sinksId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "sinksId" => URI.encode(sinks_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.Logging.V2.Model.Empty{}]) end @doc """ Gets a sink. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `sinkName`. Required. The resource name of the sink: "projects/[PROJECT_ID]/sinks/[SINK_ID]" "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: "projects/my-project-id/sinks/my-sink-id". * `sinks_id` (*type:* `String.t`) - Part of `sinkName`. See documentation of `organizationsId`. * `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.Logging.V2.Model.LogSink{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_sinks_get( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.LogSink.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_sinks_get( connection, organizations_id, sinks_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("/v2/organizations/{organizationsId}/sinks/{sinksId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "sinksId" => URI.encode(sinks_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.Logging.V2.Model.LogSink{}]) end @doc """ Lists sinks. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `parent`. Required. The parent resource whose sinks are to be listed: "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]" * `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()`) - Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of nextPageToken in the response indicates that more results might be available. * `:pageToken` (*type:* `String.t`) - Optional. If present, then retrieve the next batch of results from the preceding call to this method. pageToken must be the value of nextPageToken from the previous response. The values of other method parameters should be identical to those in the previous call. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.ListSinksResponse{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_sinks_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Logging.V2.Model.ListSinksResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_sinks_list( connection, organizations_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("/v2/organizations/{organizationsId}/sinks", %{ "organizationsId" => URI.encode(organizations_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.Logging.V2.Model.ListSinksResponse{}]) end @doc """ Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: destination, and filter.The updated sink might also have a new writer_identity; see the unique_writer_identity field. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `sinkName`. Required. The full resource name of the sink to update, including the parent resource and the sink identifier: "projects/[PROJECT_ID]/sinks/[SINK_ID]" "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: "projects/my-project-id/sinks/my-sink-id". * `sinks_id` (*type:* `String.t`) - Part of `sinkName`. See documentation of `organizationsId`. * `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"). * `:uniqueWriterIdentity` (*type:* `boolean()`) - Optional. See sinks.create for a description of this field. When updating a sink, the effect of this field on the value of writer_identity in the updated sink depends on both the old and new values of this field: If the old and new values of this field are both false or both true, then there is no change to the sink's writer_identity. If the old value is false and the new value is true, then writer_identity is changed to a unique service account. It is an error if the old value is true and the new value is set to false or defaulted to false. * `:updateMask` (*type:* `String.t`) - Optional. Field mask that specifies the fields in sink that need an update. A sink field will be overwritten if, and only if, it is in the update mask. name and output only fields cannot be updated.An empty updateMask is temporarily treated as using the following mask for backwards compatibility purposes: destination,filter,includeChildren At some point in the future, behavior will be removed and specifying an empty updateMask will be an error.For a detailed FieldMask definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMaskExample: updateMask=filter. * `:body` (*type:* `GoogleApi.Logging.V2.Model.LogSink.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.LogSink{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_sinks_patch( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.LogSink.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_sinks_patch( connection, organizations_id, sinks_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, :uniqueWriterIdentity => :query, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v2/organizations/{organizationsId}/sinks/{sinksId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "sinksId" => URI.encode(sinks_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.Logging.V2.Model.LogSink{}]) end @doc """ Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: destination, and filter.The updated sink might also have a new writer_identity; see the unique_writer_identity field. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `organizations_id` (*type:* `String.t`) - Part of `sinkName`. Required. The full resource name of the sink to update, including the parent resource and the sink identifier: "projects/[PROJECT_ID]/sinks/[SINK_ID]" "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" "folders/[FOLDER_ID]/sinks/[SINK_ID]" Example: "projects/my-project-id/sinks/my-sink-id". * `sinks_id` (*type:* `String.t`) - Part of `sinkName`. See documentation of `organizationsId`. * `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"). * `:uniqueWriterIdentity` (*type:* `boolean()`) - Optional. See sinks.create for a description of this field. When updating a sink, the effect of this field on the value of writer_identity in the updated sink depends on both the old and new values of this field: If the old and new values of this field are both false or both true, then there is no change to the sink's writer_identity. If the old value is false and the new value is true, then writer_identity is changed to a unique service account. It is an error if the old value is true and the new value is set to false or defaulted to false. * `:updateMask` (*type:* `String.t`) - Optional. Field mask that specifies the fields in sink that need an update. A sink field will be overwritten if, and only if, it is in the update mask. name and output only fields cannot be updated.An empty updateMask is temporarily treated as using the following mask for backwards compatibility purposes: destination,filter,includeChildren At some point in the future, behavior will be removed and specifying an empty updateMask will be an error.For a detailed FieldMask definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMaskExample: updateMask=filter. * `:body` (*type:* `GoogleApi.Logging.V2.Model.LogSink.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.LogSink{}}` on success * `{:error, info}` on failure """ @spec logging_organizations_sinks_update( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.LogSink.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def logging_organizations_sinks_update( connection, organizations_id, sinks_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, :uniqueWriterIdentity => :query, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/v2/organizations/{organizationsId}/sinks/{sinksId}", %{ "organizationsId" => URI.encode(organizations_id, &URI.char_unreserved?/1), "sinksId" => URI.encode(sinks_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.Logging.V2.Model.LogSink{}]) end end
51.843912
716
0.635665
08ef11cdbefa52f9f628be0aa4923e25fb3f5cc9
1,711
ex
Elixir
clients/books/lib/google_api/books/v1/model/dictlayerdata_dict_words_senses_synonyms.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/books/lib/google_api/books/v1/model/dictlayerdata_dict_words_senses_synonyms.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/books/lib/google_api/books/v1/model/dictlayerdata_dict_words_senses_synonyms.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.Books.V1.Model.DictlayerdataDictWordsSensesSynonyms do @moduledoc """ ## Attributes * `source` (*type:* `GoogleApi.Books.V1.Model.DictlayerdataDictWordsSensesSynonymsSource.t`, *default:* `nil`) - * `text` (*type:* `String.t`, *default:* `nil`) - """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :source => GoogleApi.Books.V1.Model.DictlayerdataDictWordsSensesSynonymsSource.t(), :text => String.t() } field(:source, as: GoogleApi.Books.V1.Model.DictlayerdataDictWordsSensesSynonymsSource) field(:text) end defimpl Poison.Decoder, for: GoogleApi.Books.V1.Model.DictlayerdataDictWordsSensesSynonyms do def decode(value, options) do GoogleApi.Books.V1.Model.DictlayerdataDictWordsSensesSynonyms.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Books.V1.Model.DictlayerdataDictWordsSensesSynonyms do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.22
117
0.746932
08ef191f298cee1ba134e4e5c4738df97e363859
971
ex
Elixir
lib/ayesql/runner/ecto.ex
iautom8things/ayesql
c6f6a21fde52f44bcfb59a5b51e170df33a5117d
[ "MIT" ]
100
2018-09-18T12:41:56.000Z
2022-03-08T18:52:56.000Z
lib/ayesql/runner/ecto.ex
iautom8things/ayesql
c6f6a21fde52f44bcfb59a5b51e170df33a5117d
[ "MIT" ]
15
2019-03-24T18:59:22.000Z
2022-03-31T19:32:58.000Z
lib/ayesql/runner/ecto.ex
iautom8things/ayesql
c6f6a21fde52f44bcfb59a5b51e170df33a5117d
[ "MIT" ]
13
2018-09-22T20:05:43.000Z
2021-11-03T20:22:51.000Z
if Code.ensure_loaded?(Ecto.Adapters.SQL) do defmodule AyeSQL.Runner.Ecto do @moduledoc """ This module defines `Ecto` default adapter. Can be used as follows: ```elixir defmodule MyQueries do use AyeSQL, repo: MyRepo defqueries("query/my_queries.sql") end ``` """ use AyeSQL.Runner alias AyeSQL.Query alias AyeSQL.Runner alias Ecto.Adapters.SQL @impl true def run(%Query{statement: stmt, arguments: args}, options) do repo = get_repo(options) with {:ok, result} <- SQL.query(repo, stmt, args) do Runner.handle_result(result) end end ######### # Helpers # Gets repo module. @spec get_repo(keyword()) :: module() | no_return() defp get_repo(options) do repo = options[:repo] if Code.ensure_loaded?(repo) do repo else raise ArgumentError, "Invalid value for #{inspect(repo: repo)}" end end end end
20.659574
71
0.608651
08ef5152ebf18d220ec6c2e2d11fcd5358a0af36
1,743
ex
Elixir
clients/dataflow/lib/google_api/dataflow/v1b3/model/worker_health_report_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/worker_health_report_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/worker_health_report_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Dataflow.V1b3.Model.WorkerHealthReportResponse do @moduledoc """ WorkerHealthReportResponse contains information returned to the worker in response to a health ping. ## Attributes - reportInterval (String.t): A positive value indicates the worker should change its reporting interval to the specified value. The default value of zero means no change in report rate is requested by the server. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :reportInterval => any() } field(:reportInterval) end defimpl Poison.Decoder, for: GoogleApi.Dataflow.V1b3.Model.WorkerHealthReportResponse do def decode(value, options) do GoogleApi.Dataflow.V1b3.Model.WorkerHealthReportResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dataflow.V1b3.Model.WorkerHealthReportResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.3125
236
0.765347
08ef6a46d328a73b1ce579a0a3eb3b050b0303f1
93
ex
Elixir
lib/game_of_life/t_ref.ex
potto007/elixir-game_of_life
28402f57f63e16c2c4c0d52b1130f52a2373e1bd
[ "MIT" ]
null
null
null
lib/game_of_life/t_ref.ex
potto007/elixir-game_of_life
28402f57f63e16c2c4c0d52b1130f52a2373e1bd
[ "MIT" ]
null
null
null
lib/game_of_life/t_ref.ex
potto007/elixir-game_of_life
28402f57f63e16c2c4c0d52b1130f52a2373e1bd
[ "MIT" ]
null
null
null
defmodule GameOfLife.TRef do # defstruct [:name, :ref] @type t :: {atom, reference} end
15.5
30
0.666667
08efa61a971c070c561060b99304a27b031d3338
1,071
ex
Elixir
lib/bedsgarage.ex
bed42/bedsgarage
608e9509b931078f62ff93e7e34f2451b0d10f49
[ "Apache-2.0" ]
null
null
null
lib/bedsgarage.ex
bed42/bedsgarage
608e9509b931078f62ff93e7e34f2451b0d10f49
[ "Apache-2.0" ]
null
null
null
lib/bedsgarage.ex
bed42/bedsgarage
608e9509b931078f62ff93e7e34f2451b0d10f49
[ "Apache-2.0" ]
null
null
null
defmodule Bedsgarage do use Application # See http://elixir-lang.org/docs/stable/elixir/Application.html # for more information on OTP Applications def start(_type, _args) do import Supervisor.Spec # Define workers and child supervisors to be supervised children = [ # Start the endpoint when the application starts supervisor(Bedsgarage.Endpoint, []), supervisor(Bedsgarage.PiGarage, []), #Bedsgarage.PiGarage.start_link(), # Start your own worker by calling: Bedsgarage.Worker.start_link(arg1, arg2, arg3) # worker(Bedsgarage.Worker, [arg1, arg2, arg3]), ] # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Bedsgarage.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 Bedsgarage.Endpoint.config_change(changed, removed) :ok end end
31.5
88
0.718954
08efb1e3cb7efec00fc52be427e0ff34fb87a1c5
1,937
ex
Elixir
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/acl_entry.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/acl_entry.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/acl_entry.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.SQLAdmin.V1beta4.Model.AclEntry do @moduledoc """ An entry for an Access Control list. ## Attributes - expirationTime (DateTime.t): The time when this access control entry expires in RFC 3339 format, for example 2012-11-15T16:19:00.094Z. Defaults to: `null`. - kind (String.t): This is always sql#aclEntry. Defaults to: `null`. - name (String.t): An optional label to identify this entry. Defaults to: `null`. - value (String.t): The whitelisted value for the access control list. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :expirationTime => DateTime.t(), :kind => any(), :name => any(), :value => any() } field(:expirationTime, as: DateTime) field(:kind) field(:name) field(:value) end defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1beta4.Model.AclEntry do def decode(value, options) do GoogleApi.SQLAdmin.V1beta4.Model.AclEntry.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1beta4.Model.AclEntry do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.982456
159
0.718637
08efbe68ed39949892d80907519b2885e0ae87d0
2,164
ex
Elixir
clients/apigee/lib/google_api/apigee/v1/model/google_iam_v1_set_iam_policy_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/apigee/lib/google_api/apigee/v1/model/google_iam_v1_set_iam_policy_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/apigee/lib/google_api/apigee/v1/model/google_iam_v1_set_iam_policy_request.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.Apigee.V1.Model.GoogleIamV1SetIamPolicyRequest do @moduledoc """ Request message for `SetIamPolicy` method. ## Attributes * `policy` (*type:* `GoogleApi.Apigee.V1.Model.GoogleIamV1Policy.t`, *default:* `nil`) - REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. * `updateMask` (*type:* `String.t`, *default:* `nil`) - OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be modified. If no mask is provided, the following default mask is used: paths: "bindings, etag" This field is only used by Cloud IAM. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :policy => GoogleApi.Apigee.V1.Model.GoogleIamV1Policy.t(), :updateMask => String.t() } field(:policy, as: GoogleApi.Apigee.V1.Model.GoogleIamV1Policy) field(:updateMask) end defimpl Poison.Decoder, for: GoogleApi.Apigee.V1.Model.GoogleIamV1SetIamPolicyRequest do def decode(value, options) do GoogleApi.Apigee.V1.Model.GoogleIamV1SetIamPolicyRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Apigee.V1.Model.GoogleIamV1SetIamPolicyRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.964912
167
0.73244
08efcd09e7895829583af8b8d696638208c5c4c3
6,396
exs
Elixir
test/hierbautberlin/file_storage_test.exs
HierBautBerlin/website
91410e7c61c1efad438fe84bf550f87b0056c440
[ "MIT" ]
13
2021-03-06T12:16:34.000Z
2022-03-31T09:46:35.000Z
test/hierbautberlin/file_storage_test.exs
HierBautBerlin/website
91410e7c61c1efad438fe84bf550f87b0056c440
[ "MIT" ]
148
2021-03-05T12:44:55.000Z
2022-03-11T12:09:06.000Z
test/hierbautberlin/file_storage_test.exs
HierBautBerlin/website
91410e7c61c1efad438fe84bf550f87b0056c440
[ "MIT" ]
2
2021-06-02T14:31:21.000Z
2022-02-14T08:36:51.000Z
defmodule Hierbautberlin.FileStorageTest do use Hierbautberlin.DataCase alias Hierbautberlin.FileStorage alias Hierbautberlin.FileStorage.FileItem describe "files" do @valid_attrs %{name: "some name", type: "some type", title: "My File"} @update_attrs %{name: "some updated name", type: "some updated type"} @invalid_attrs %{name: nil, type: nil} def file_fixture(attrs \\ %{}) do {:ok, file} = attrs |> Enum.into(@valid_attrs) |> FileStorage.create_file() file end test "list_files/0 returns all files" do file = file_fixture() assert FileStorage.list_files() == [file] end test "get_file!/1 returns the file with given id" do file = file_fixture() assert FileStorage.get_file!(file.id) == file end test "create_file/1 with valid data creates a file" do assert {:ok, %FileItem{} = file} = FileStorage.create_file(@valid_attrs) assert file.name == "some name" assert file.type == "some type" end test "create_file/1 run again will overwrite the data" do assert {:ok, %FileItem{}} = FileStorage.create_file(@valid_attrs) assert {:ok, %FileItem{} = file} = FileStorage.create_file(%{name: "some name", title: "New Title"}) assert file.name == "some name" assert file.type == "some type" assert file.title == "New Title" end test "create_file/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = FileStorage.create_file(@invalid_attrs) end test "update_file/2 with valid data updates the file" do file = file_fixture() assert {:ok, %FileItem{} = file} = FileStorage.update_file(file, @update_attrs) assert file.name == "some updated name" assert file.type == "some updated type" end test "update_file/2 with invalid data returns error changeset" do file = file_fixture() assert {:error, %Ecto.Changeset{}} = FileStorage.update_file(file, @invalid_attrs) assert file == FileStorage.get_file!(file.id) end test "delete_file/1 deletes the file" do file = file_fixture() assert {:ok, %FileItem{}} = FileStorage.delete_file(file) assert_raise Ecto.NoResultsError, fn -> FileStorage.get_file!(file.id) end end test "change_file/1 returns a file changeset" do file = file_fixture() assert %Ecto.Changeset{} = FileStorage.change_file(file) end end describe "path_for_file" do test "returns a nice filename for a FileItem" do assert FileStorage.path_for_file(%FileItem{ name: "amtsblatt/abl_2021_28_2389_2480_online.pdf" }) == "./file_storage/C985239A3E93DBAA4CD5/1A6E0C5B979F8BE5E0CE/99633E8697D62BE66481/5337/abl_2021_28_2389_2480_online.pdf" end test "returns a nice filename in the storage" do assert FileStorage.path_for_file("amtsblatt/abl_2021_28_2389_2480_online.pdf") == "./file_storage/C985239A3E93DBAA4CD5/1A6E0C5B979F8BE5E0CE/99633E8697D62BE66481/5337/abl_2021_28_2389_2480_online.pdf" end end describe "url_for_file" do test "returns a nice url for a FileItem" do assert FileStorage.url_for_file(%FileItem{ name: "amtsblatt/abl_2021_28_2389_2480_online.pdf" }) == "/filestorage/C985239A3E93DBAA4CD5/1A6E0C5B979F8BE5E0CE/99633E8697D62BE66481/5337/abl_2021_28_2389_2480_online.pdf" end test "returns a nice url in the storage" do assert FileStorage.url_for_file("amtsblatt/abl_2021_28_2389_2480_online.pdf") == "/filestorage/C985239A3E93DBAA4CD5/1A6E0C5B979F8BE5E0CE/99633E8697D62BE66481/5337/abl_2021_28_2389_2480_online.pdf" end end describe "get_file_by_name!/1" do test "returns the file with given name" do FileStorage.create_file(%{name: "this_file.pdf", type: "some/type", title: "My Title"}) file_item = FileStorage.get_file_by_name!("this_file.pdf") assert file_item.name == "this_file.pdf" assert file_item.type == "some/type" end test "throws error if file does not exist" do assert_raise Ecto.NoResultsError, fn -> FileStorage.get_file_by_name!("wrong.pdf") end end end describe "store_file/4" do test "stores a file and creates a db entry" do File.touch("this_file_exists.pdf") FileStorage.store_file( "this_file_exists.pdf", "this_file_exists.pdf", "application/pdf", "My File" ) assert FileStorage.exists?("this_file_exists.pdf") assert File.exists?( "./file_storage/A154C2456073E64CBE2C/C5F68BBA3DB6F113B2E6/77EEBF27B6FBB35E8FC7/018B/this_file_exists.pdf" ) file_item = FileStorage.get_file_by_name!("this_file_exists.pdf") assert file_item.name == "this_file_exists.pdf" assert file_item.type == "application/pdf" assert file_item.title == "My File" File.rm("this_file_exists.pdf") end test "overwrites a already existing file" do File.touch("dublicate.pdf") FileStorage.store_file( "dublicate.pdf", "dublicate.pdf", "application/pdf", "Old Title" ) File.touch("dublicate.pdf") FileStorage.store_file( "dublicate.pdf", "dublicate.pdf", "application/pdf", "New Title" ) assert FileStorage.exists?("dublicate.pdf") assert File.exists?( "./file_storage/E32843258ACB50D059D0/24866FBF6EBC275A48B0/9574A0799EF0263055AC/6343/dublicate.pdf" ) file_item = FileStorage.get_file_by_name!("dublicate.pdf") assert file_item.name == "dublicate.pdf" assert file_item.type == "application/pdf" assert file_item.title == "New Title" File.rm("dublicate.pdf") end end describe "exists?/1" do test "returns true if file exists" do File.mkdir_p( "file_storage/66BDAB382A1B0B067304/0380AE4D395D729A885F/5CF09F2B0ABD552AA123/CF60" ) File.touch( "file_storage/66BDAB382A1B0B067304/0380AE4D395D729A885F/5CF09F2B0ABD552AA123/CF60/filename.txt" ) assert FileStorage.exists?("filename.txt") end test "returns false if the file does not exist" do refute FileStorage.exists?("no_filename.txt") end end end
31.820896
132
0.666979
08efce60dba1aeadfb71a6c2480b8a7dca524f0a
567
ex
Elixir
test/support/person.ex
instinctscience/versioned
2352464c5c148d85f04fa31c02ab58001a1531f1
[ "MIT" ]
4
2021-09-25T20:11:59.000Z
2022-03-07T20:57:44.000Z
test/support/person.ex
instinctscience/versioned
2352464c5c148d85f04fa31c02ab58001a1531f1
[ "MIT" ]
2
2021-09-22T19:29:26.000Z
2021-10-04T17:31:17.000Z
test/support/person.ex
instinctscience/versioned
2352464c5c148d85f04fa31c02ab58001a1531f1
[ "MIT" ]
3
2021-08-08T10:37:25.000Z
2022-03-07T20:57:32.000Z
defmodule Versioned.Test.Person do @moduledoc false use Versioned.Schema, singular: :person import Ecto.Changeset alias Versioned.Test.{Car, Hobby} versioned_schema "people" do field :name, :string belongs_to :car, Car, type: :binary_id, versioned: true has_many :fancy_hobbies, Hobby, on_replace: :delete, versioned: :fancy_hobby_versions end def changeset(car_or_changeset, params) do car_or_changeset |> cast(params, [:name]) |> validate_required([:name]) |> cast_assoc(:fancy_hobbies) |> cast_assoc(:car) end end
27
89
0.714286
08f04bb858f7da46cf1ceb8a5ec1f3a3024a5db2
2,110
ex
Elixir
lib/arp_server/service.ex
arpnetwork/arp_server
4f3ed266ca68f7d6db5db6839067dd810079075a
[ "Apache-2.0" ]
3
2018-07-23T01:50:50.000Z
2018-08-13T13:12:05.000Z
lib/arp_server/service.ex
arpnetwork/arp_server
4f3ed266ca68f7d6db5db6839067dd810079075a
[ "Apache-2.0" ]
null
null
null
lib/arp_server/service.ex
arpnetwork/arp_server
4f3ed266ca68f7d6db5db6839067dd810079075a
[ "Apache-2.0" ]
null
null
null
defmodule ARP.Service do @moduledoc """ Service supervisor """ alias ARP.API.JSONRPC2.{Account, App, Device, Nonce, Server} alias ARP.API.TCP.DeviceProtocol alias ARP.{CheckTask, Config, DeviceManager} use GenServer def start_link(_opts) do GenServer.start_link(__MODULE__, [], name: __MODULE__) end def start_service do GenServer.call(__MODULE__, :start_service) end def stop_service do GenServer.cast(__MODULE__, :stop_service) end def init(_arg) do {:ok, pid} = DynamicSupervisor.start_link(strategy: :one_for_one, name: :dynamic_services) {:ok, %{pid: pid}} end def handle_call(:start_service, _from, %{pid: pid} = state) do tcp_port = Config.get(:port) jsonrpc_port = tcp_port + 1 # tcp service tcp_spec = :ranch.child_spec( :tcp_device, 50, :ranch_tcp, [port: tcp_port], DeviceProtocol, [] ) # start jsonrpc service jsonrpc2_opts = {JSONRPC2.Server.ModuleHandler, [Server, Device, Account, Nonce, App]} jsonrpc_spec = Plug.Cowboy.child_spec( scheme: :http, plug: {JSONRPC2.Server.Plug, jsonrpc2_opts}, options: [port: jsonrpc_port] ) # start check timer check_task_spec = CheckTask res = with {:ok, _} <- DynamicSupervisor.start_child(pid, tcp_spec), {:ok, _} <- DynamicSupervisor.start_child(pid, jsonrpc_spec), {:ok, _} <- DynamicSupervisor.start_child(pid, check_task_spec) do :ok else err -> stop_service() err end {:reply, res, state} end def handle_cast(:stop_service, %{pid: pid} = state) do # offline all device devices = DeviceManager.get_all() Enum.each(devices, fn {_, _, dev} -> DeviceManager.offline(dev.address) end) # stop all service children = DynamicSupervisor.which_children(pid) Enum.each(children, fn {_, child, _, _} -> if child != :restarting do DynamicSupervisor.terminate_child(pid, child) end end) {:noreply, state} end end
23.186813
94
0.627962
08f053e8fba8606432a5edb368d1c94377b2a0b9
453
ex
Elixir
test/support/models/comment.ex
kianmeng/cldr_trans
da3f01eb16cd25e8936d30805bfff5e3ab589409
[ "Apache-2.0" ]
1
2022-03-10T06:54:28.000Z
2022-03-10T06:54:28.000Z
test/support/models/comment.ex
kianmeng/cldr_trans
da3f01eb16cd25e8936d30805bfff5e3ab589409
[ "Apache-2.0" ]
1
2022-03-14T01:10:20.000Z
2022-03-20T14:35:05.000Z
test/support/models/comment.ex
kianmeng/cldr_trans
da3f01eb16cd25e8936d30805bfff5e3ab589409
[ "Apache-2.0" ]
1
2022-03-13T15:38:40.000Z
2022-03-13T15:38:40.000Z
defmodule Cldr.Trans.Comment do @moduledoc false use Ecto.Schema use Cldr.Trans, translates: [:comment], container: :transcriptions import Ecto.Changeset schema "comments" do field(:comment, :string) field(:transcriptions, :map) belongs_to(:article, Cldr.Trans.Article) end def changeset(comment, params \\ %{}) do comment |> cast(params, [:comment, :transcriptions]) |> validate_required([:comment]) end end
21.571429
68
0.688742
08f061a760b46d589ec446e805ba1b9109f6099e
204
ex
Elixir
src/dguweb/web/controllers/page_controller.ex
datagovuk/dgu2
3e24bdf27b30c22791efc19029ead05488c8f571
[ "MIT" ]
2
2016-08-09T16:46:52.000Z
2016-08-09T16:46:59.000Z
src/dguweb/web/controllers/page_controller.ex
datagovuk/dgu2
3e24bdf27b30c22791efc19029ead05488c8f571
[ "MIT" ]
48
2016-07-14T15:12:41.000Z
2016-09-27T16:19:54.000Z
src/dguweb/web/controllers/page_controller.ex
datagovuk/dgu2
3e24bdf27b30c22791efc19029ead05488c8f571
[ "MIT" ]
1
2021-04-10T21:23:44.000Z
2021-04-10T21:23:44.000Z
defmodule DGUWeb.PageController do use DGUWeb.Web, :controller alias DGUWeb.Theme def index(conn, _params) do themes = Repo.all(Theme) render conn, "index.html", themes: themes end end
17
45
0.710784
08f08690893ab238782bef7acf973dce33573241
1,488
exs
Elixir
mix.exs
eigr/wasmex
5e692a16ef1d82a1ea8586d5678011736927abab
[ "MIT" ]
1
2022-03-13T02:24:17.000Z
2022-03-13T02:24:17.000Z
mix.exs
eigr/wasmex
5e692a16ef1d82a1ea8586d5678011736927abab
[ "MIT" ]
null
null
null
mix.exs
eigr/wasmex
5e692a16ef1d82a1ea8586d5678011736927abab
[ "MIT" ]
null
null
null
defmodule Wasmex.MixProject do use Mix.Project def project do [ app: :wasmex, version: "0.3.0", elixir: "~> 1.11", start_permanent: Mix.env() == :prod, compilers: [:rustler] ++ Mix.compilers(), rustler_crates: [ wasmex: [ mode: if(Mix.env() == :prod, do: :release, else: :debug) ] ], name: "Wasmex", description: description(), package: package(), 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 [ {:rustler, "~> 0.21.1"}, {:ex_doc, "~> 0.23.0", only: [:dev, :test]}, {:dialyxir, "~> 1.1.0", only: [:dev, :test], runtime: false}, {:credo, "~> 1.3", only: [:dev, :test], runtime: false} ] end defp description() do "Wasmex is an Elixir library for executing WebAssembly binaries." end defp package() do [ # These are the default files included in the package files: ~w(lib native/wasmex/src native/wasmex/Cargo.* native/wasmex/README.md native/wasmex/.cargo .formatter.exs mix.exs README.md LICENSE.md CHANGELOG.md), licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/tessi/wasmex", "Docs" => "https://hexdocs.pm/wasmex" }, source_url: "https://github.com/tessi/wasmex" ] end end
25.655172
158
0.567204
08f0b9c9b424946a097d26e78e314730bf7c96ef
1,256
ex
Elixir
lib/grizzly/zwave/commands/zwave_long_range_channel_report.ex
smartrent/grizzly
65a397ea7bfedb5518fe63a3f058a0b6af473e39
[ "Apache-2.0" ]
76
2019-09-04T16:56:58.000Z
2022-03-29T06:54:36.000Z
lib/grizzly/zwave/commands/zwave_long_range_channel_report.ex
smartrent/grizzly
65a397ea7bfedb5518fe63a3f058a0b6af473e39
[ "Apache-2.0" ]
124
2019-09-05T14:01:24.000Z
2022-02-28T22:58:14.000Z
lib/grizzly/zwave/commands/zwave_long_range_channel_report.ex
smartrent/grizzly
65a397ea7bfedb5518fe63a3f058a0b6af473e39
[ "Apache-2.0" ]
10
2019-10-23T19:25:45.000Z
2021-11-17T13:21:20.000Z
defmodule Grizzly.ZWave.Commands.ZWaveLongRangeChannelReport do @moduledoc """ Command to advertise the configured Z-Wave Long Range Channel Params: * `:channel` - which channel that is used for Z-Wave long range """ @typedoc """ The long range channel """ @type long_range_channel() :: :primary | :secondary @typedoc """ Parameters to the command """ @type param() :: {:channel, long_range_channel()} @behaviour Grizzly.ZWave.Command alias Grizzly.ZWave.Command alias Grizzly.ZWave.CommandClasses.NetworkManagementInstallationMaintenance @impl Grizzly.ZWave.Command @spec new([param()]) :: {:ok, Command.t()} def new(params \\ []) do command = %Command{ name: :zwave_long_range_channel_report, command_byte: 0x0E, command_class: NetworkManagementInstallationMaintenance, impl: __MODULE__, params: params } {:ok, command} end @impl Grizzly.ZWave.Command def decode_params(<<0x01>>), do: {:ok, [channel: :primary]} def decode_params(<<0x02>>), do: {:ok, [channel: :secondary]} @impl Grizzly.ZWave.Command def encode_params(command) do case Command.param!(command, :channel) do :primary -> <<0x01>> :secondary -> <<0x02>> end end end
24.627451
77
0.676752
08f0c9356d3173852857e0787f54a2bb58b4c90c
581
exs
Elixir
examples/lwm 66 - Doctests/unit_test_app/mix.exs
Maultasche/LwmElixirProjects
4b962230c9b5b3cf6cc8b34ef2161ca6fde4412c
[ "MIT" ]
38
2018-12-31T10:51:42.000Z
2022-03-25T18:18:10.000Z
examples/lwm 66 - Doctests/unit_test_app/mix.exs
Maultasche/LwmElixirProjects
4b962230c9b5b3cf6cc8b34ef2161ca6fde4412c
[ "MIT" ]
null
null
null
examples/lwm 66 - Doctests/unit_test_app/mix.exs
Maultasche/LwmElixirProjects
4b962230c9b5b3cf6cc8b34ef2161ca6fde4412c
[ "MIT" ]
6
2019-08-19T03:21:36.000Z
2021-07-16T09:34:49.000Z
defmodule UnitTestApp.MixProject do use Mix.Project def project do [ app: :unit_test_app, version: "0.1.0", elixir: "~> 1.8", 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"} ] end end
20.034483
87
0.583477
08f0e27bfd4c1d5d2cf8261d95652ba4039c2261
2,309
ex
Elixir
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_entity_type_entity.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_entity_type_entity.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_entity_type_entity.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.Dialogflow.V2.Model.GoogleCloudDialogflowV2EntityTypeEntity do @moduledoc """ An **entity entry** for an associated entity type. ## Attributes * `synonyms` (*type:* `list(String.t)`, *default:* `nil`) - Required. A collection of value synonyms. For example, if the entity type is *vegetable*, and `value` is *scallions*, a synonym could be *green onions*. For `KIND_LIST` entity types: * This collection must contain exactly one synonym equal to `value`. * `value` (*type:* `String.t`, *default:* `nil`) - Required. The primary value associated with this entity entry. For example, if the entity type is *vegetable*, the value could be *scallions*. For `KIND_MAP` entity types: * A canonical value to be used in place of synonyms. For `KIND_LIST` entity types: * A string that can contain references to other entity types (with or without aliases). """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :synonyms => list(String.t()), :value => String.t() } field(:synonyms, type: :list) field(:value) end defimpl Poison.Decoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2EntityTypeEntity do def decode(value, options) do GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2EntityTypeEntity.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2EntityTypeEntity do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.462687
137
0.715461
08f0e51fc643236e4fd4097e49004dca11cdc813
22,192
exs
Elixir
test/ecto/adapters/mysql_test.exs
ashneyderman/ecto
16f27f64c5ca2480568fad10e40c26522ffbf793
[ "Apache-2.0" ]
null
null
null
test/ecto/adapters/mysql_test.exs
ashneyderman/ecto
16f27f64c5ca2480568fad10e40c26522ffbf793
[ "Apache-2.0" ]
null
null
null
test/ecto/adapters/mysql_test.exs
ashneyderman/ecto
16f27f64c5ca2480568fad10e40c26522ffbf793
[ "Apache-2.0" ]
null
null
null
Code.require_file "../../../integration_test/support/types.exs", __DIR__ defmodule Ecto.Adapters.MySQLTest do use ExUnit.Case, async: true import Ecto.Query alias Ecto.Queryable alias Ecto.Adapters.MySQL.Connection, as: SQL defmodule Model do use Ecto.Model schema "model" do field :x, :integer field :y, :integer has_many :comments, Ecto.Adapters.MySQLTest.Model2, references: :x, foreign_key: :z has_one :permalink, Ecto.Adapters.MySQLTest.Model3, references: :y, foreign_key: :id end end defmodule Model2 do use Ecto.Model schema "model2" do belongs_to :post, Ecto.Adapters.MySQLTest.Model, references: :x, foreign_key: :z end end defmodule Model3 do use Ecto.Model schema "model3" do field :binary, :binary end end defp normalize(query, operation \\ :all) do {query, _params} = Ecto.Query.Planner.prepare(query, operation, [], %{}) Ecto.Query.Planner.normalize(query, operation, []) end test "from" do query = Model |> select([r], r.x) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` FROM `model` AS m0} end test "from without model" do query = "posts" |> select([r], r.x) |> normalize assert SQL.all(query) == ~s{SELECT p0.`x` FROM `posts` AS p0} assert_raise ArgumentError, ~r"MySQL requires a model", fn -> SQL.all from(p in "posts", select: p) |> normalize() end end test "from with schema source" do query = "public.posts" |> select([r], r.x) |> normalize assert SQL.all(query) == ~s{SELECT p0.`x` FROM `public`.`posts` AS p0} end test "select" do query = Model |> select([r], {r.x, r.y}) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x`, m0.`y` FROM `model` AS m0} query = Model |> select([r], [r.x, r.y]) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x`, m0.`y` FROM `model` AS m0} end test "distinct" do query = Model |> distinct([r], true) |> select([r], {r.x, r.y}) |> normalize assert SQL.all(query) == ~s{SELECT DISTINCT m0.`x`, m0.`y` FROM `model` AS m0} query = Model |> distinct([r], false) |> select([r], {r.x, r.y}) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x`, m0.`y` FROM `model` AS m0} query = Model |> distinct(true) |> select([r], {r.x, r.y}) |> normalize assert SQL.all(query) == ~s{SELECT DISTINCT m0.`x`, m0.`y` FROM `model` AS m0} query = Model |> distinct(false) |> select([r], {r.x, r.y}) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x`, m0.`y` FROM `model` AS m0} assert_raise ArgumentError, "DISTINCT with multiple columns is not supported by MySQL", fn -> query = Model |> distinct([r], [r.x, r.y]) |> select([r], {r.x, r.y}) |> normalize SQL.all(query) end end test "where" do query = Model |> where([r], r.y != 43) |> where([r], r.x == 42) |> select([r], r.x) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` FROM `model` AS m0 WHERE (m0.`x` = 42) AND (m0.`y` != 43)} end test "order by" do query = Model |> order_by([r], r.x) |> select([r], r.x) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` FROM `model` AS m0 ORDER BY m0.`x`} query = Model |> order_by([r], [r.x, r.y]) |> select([r], r.x) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` FROM `model` AS m0 ORDER BY m0.`x`, m0.`y`} query = Model |> order_by([r], [asc: r.x, desc: r.y]) |> select([r], r.x) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` FROM `model` AS m0 ORDER BY m0.`x`, m0.`y` DESC} query = Model |> order_by([r], []) |> select([r], r.x) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` FROM `model` AS m0} end test "limit and offset" do query = Model |> limit([r], 3) |> select([], 0) |> normalize assert SQL.all(query) == ~s{SELECT 0 FROM `model` AS m0 LIMIT 3} query = Model |> offset([r], 5) |> select([], 0) |> normalize assert SQL.all(query) == ~s{SELECT 0 FROM `model` AS m0 OFFSET 5} query = Model |> offset([r], 5) |> limit([r], 3) |> select([], 0) |> normalize assert SQL.all(query) == ~s{SELECT 0 FROM `model` AS m0 LIMIT 3 OFFSET 5} end test "lock" do query = Model |> lock("LOCK IN SHARE MODE") |> select([], 0) |> normalize assert SQL.all(query) == ~s{SELECT 0 FROM `model` AS m0 LOCK IN SHARE MODE} end test "string escape" do query = Model |> select([], "'\\ ") |> normalize assert SQL.all(query) == ~s{SELECT '''\\\\ ' FROM `model` AS m0} query = Model |> select([], "'") |> normalize assert SQL.all(query) == ~s{SELECT '''' FROM `model` AS m0} end test "binary ops" do query = Model |> select([r], r.x == 2) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` = 2 FROM `model` AS m0} query = Model |> select([r], r.x != 2) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` != 2 FROM `model` AS m0} query = Model |> select([r], r.x <= 2) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` <= 2 FROM `model` AS m0} query = Model |> select([r], r.x >= 2) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` >= 2 FROM `model` AS m0} query = Model |> select([r], r.x < 2) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` < 2 FROM `model` AS m0} query = Model |> select([r], r.x > 2) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` > 2 FROM `model` AS m0} end test "is_nil" do query = Model |> select([r], is_nil(r.x)) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` IS NULL FROM `model` AS m0} query = Model |> select([r], not is_nil(r.x)) |> normalize assert SQL.all(query) == ~s{SELECT NOT (m0.`x` IS NULL) FROM `model` AS m0} end test "fragments" do query = Model |> select([r], fragment("lcase(?)", r.x)) |> normalize assert SQL.all(query) == ~s{SELECT lcase(m0.`x`) FROM `model` AS m0} value = 13 query = Model |> select([r], fragment("lcase(?, ?)", r.x, ^value)) |> normalize assert SQL.all(query) == ~s{SELECT lcase(m0.`x`, ?) FROM `model` AS m0} query = Model |> select([], fragment(title: 2)) |> normalize assert_raise ArgumentError, fn -> SQL.all(query) end end test "literals" do query = Model |> select([], nil) |> normalize assert SQL.all(query) == ~s{SELECT NULL FROM `model` AS m0} query = Model |> select([], true) |> normalize assert SQL.all(query) == ~s{SELECT TRUE FROM `model` AS m0} query = Model |> select([], false) |> normalize assert SQL.all(query) == ~s{SELECT FALSE FROM `model` AS m0} query = Model |> select([], "abc") |> normalize assert SQL.all(query) == ~s{SELECT 'abc' FROM `model` AS m0} query = Model |> select([], 123) |> normalize assert SQL.all(query) == ~s{SELECT 123 FROM `model` AS m0} query = Model |> select([], 123.0) |> normalize assert SQL.all(query) == ~s{SELECT (0 + 123.0) FROM `model` AS m0} end test "tagged type" do query = Model |> select([], type(^"601d74e4-a8d3-4b6e-8365-eddb4c893327", Ecto.UUID)) |> normalize assert SQL.all(query) == ~s{SELECT CAST(? AS binary(16)) FROM `model` AS m0} end test "nested expressions" do z = 123 query = from(r in Model, []) |> select([r], r.x > 0 and (r.y > ^(-z)) or true) |> normalize assert SQL.all(query) == ~s{SELECT ((m0.`x` > 0) AND (m0.`y` > ?)) OR TRUE FROM `model` AS m0} end test "in expression" do query = Model |> select([e], 1 in []) |> normalize assert SQL.all(query) == ~s{SELECT false FROM `model` AS m0} query = Model |> select([e], 1 in [1,e.x,3]) |> normalize assert SQL.all(query) == ~s{SELECT 1 IN (1,m0.`x`,3) FROM `model` AS m0} query = Model |> select([e], 1 in ^[]) |> normalize assert SQL.all(query) == ~s{SELECT false FROM `model` AS m0} query = Model |> select([e], 1 in ^[1, 2, 3]) |> normalize assert SQL.all(query) == ~s{SELECT 1 IN (?,?,?) FROM `model` AS m0} query = Model |> select([e], 1 in [1, ^2, 3]) |> normalize assert SQL.all(query) == ~s{SELECT 1 IN (1,?,3) FROM `model` AS m0} query = Model |> select([e], 1 in fragment("foo")) |> normalize assert SQL.all(query) == ~s{SELECT 1 = ANY(foo) FROM `model` AS m0} end test "having" do query = Model |> having([p], p.x == p.x) |> select([p], p.x) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` FROM `model` AS m0 HAVING (m0.`x` = m0.`x`)} query = Model |> having([p], p.y == p.y) |> having([p], p.x == p.x) |> select([p], [p.y, p.x]) |> normalize assert SQL.all(query) == ~s{SELECT m0.`y`, m0.`x` FROM `model` AS m0 HAVING (m0.`x` = m0.`x`) AND (m0.`y` = m0.`y`)} end test "group by" do query = Model |> group_by([r], r.x) |> select([r], r.x) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` FROM `model` AS m0 GROUP BY m0.`x`} query = Model |> group_by([r], 2) |> select([r], r.x) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` FROM `model` AS m0 GROUP BY 2} query = Model |> group_by([r], [r.x, r.y]) |> select([r], r.x) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` FROM `model` AS m0 GROUP BY m0.`x`, m0.`y`} query = Model |> group_by([r], []) |> select([r], r.x) |> normalize assert SQL.all(query) == ~s{SELECT m0.`x` FROM `model` AS m0} end test "interpolated values" do query = Model |> select([], ^0) |> join(:inner, [], Model2, ^true) |> join(:inner, [], Model2, ^false) |> where([], ^true) |> where([], ^false) |> group_by([], ^1) |> group_by([], ^2) |> having([], ^true) |> having([], ^false) |> order_by([], fragment("?", ^3)) |> order_by([], ^:x) |> limit([], ^4) |> offset([], ^5) |> normalize result = "SELECT ? FROM `model` AS m0 INNER JOIN `model2` AS m1 ON ? " <> "INNER JOIN `model2` AS m2 ON ? WHERE (?) AND (?) " <> "GROUP BY ?, ? HAVING (?) AND (?) " <> "ORDER BY ?, m0.`x` LIMIT ? OFFSET ?" assert SQL.all(query) == String.rstrip(result) end ## *_all test "update all" do query = from(m in Model, update: [set: [x: 0]]) |> normalize(:update_all) assert SQL.update_all(query) == ~s{UPDATE `model` AS m0 SET `x` = 0} query = from(m in Model, update: [set: [x: 0], inc: [y: 1, z: -3]]) |> normalize(:update_all) assert SQL.update_all(query) == ~s{UPDATE `model` AS m0 SET `x` = 0, `y` = `y` + 1, `z` = `z` + -3} query = from(e in Model, where: e.x == 123, update: [set: [x: 0]]) |> normalize(:update_all) assert SQL.update_all(query) == ~s{UPDATE `model` AS m0 SET `x` = 0 WHERE (m0.`x` = 123)} query = from(m in Model, update: [set: [x: 0, y: "123"]]) |> normalize(:update_all) assert SQL.update_all(query) == ~s{UPDATE `model` AS m0 SET `x` = 0, `y` = '123'} query = from(m in Model, update: [set: [x: ^0]]) |> normalize(:update_all) assert SQL.update_all(query) == ~s{UPDATE `model` AS m0 SET `x` = ?} query = Model |> join(:inner, [p], q in Model2, p.x == q.z) |> update([_], set: [x: 0]) |> normalize(:update_all) assert SQL.update_all(query) == ~s{UPDATE `model` AS m0 INNER JOIN `model2` AS m1 ON m0.`x` = m1.`z` SET `x` = 0} query = from(e in Model, where: e.x == 123, update: [set: [x: 0]], join: q in Model2, on: e.x == q.z) |> normalize(:update_all) assert SQL.update_all(query) == ~s{UPDATE `model` AS m0 INNER JOIN `model2` AS m1 ON m0.`x` = m1.`z` } <> ~s{SET `x` = 0 WHERE (m0.`x` = 123)} end test "delete all" do query = Model |> Queryable.to_query |> normalize assert SQL.delete_all(query) == ~s{DELETE m0.* FROM `model` AS m0} query = from(e in Model, where: e.x == 123) |> normalize assert SQL.delete_all(query) == ~s{DELETE m0.* FROM `model` AS m0 WHERE (m0.`x` = 123)} query = Model |> join(:inner, [p], q in Model2, p.x == q.z) |> normalize assert SQL.delete_all(query) == ~s{DELETE m0.* FROM `model` AS m0 INNER JOIN `model2` AS m1 ON m0.`x` = m1.`z`} query = from(e in Model, where: e.x == 123, join: q in Model2, on: e.x == q.z) |> normalize assert SQL.delete_all(query) == ~s{DELETE m0.* FROM `model` AS m0 } <> ~s{INNER JOIN `model2` AS m1 ON m0.`x` = m1.`z` WHERE (m0.`x` = 123)} end ## Joins test "join" do query = Model |> join(:inner, [p], q in Model2, p.x == q.z) |> select([], 0) |> normalize assert SQL.all(query) == ~s{SELECT 0 FROM `model` AS m0 INNER JOIN `model2` AS m1 ON m0.`x` = m1.`z`} query = Model |> join(:inner, [p], q in Model2, p.x == q.z) |> join(:inner, [], Model, true) |> select([], 0) |> normalize assert SQL.all(query) == ~s{SELECT 0 FROM `model` AS m0 INNER JOIN `model2` AS m1 ON m0.`x` = m1.`z` } <> ~s{INNER JOIN `model` AS m2 ON TRUE} end test "join with nothing bound" do query = Model |> join(:inner, [], q in Model2, q.z == q.z) |> select([], 0) |> normalize assert SQL.all(query) == ~s{SELECT 0 FROM `model` AS m0 INNER JOIN `model2` AS m1 ON m1.`z` = m1.`z`} end test "join without model" do query = "posts" |> join(:inner, [p], q in "comments", p.x == q.z) |> select([], 0) |> normalize assert SQL.all(query) == ~s{SELECT 0 FROM `posts` AS p0 INNER JOIN `comments` AS c1 ON p0.`x` = c1.`z`} end ## Associations test "association join belongs_to" do query = Model2 |> join(:inner, [c], p in assoc(c, :post)) |> select([], 0) |> normalize assert SQL.all(query) == "SELECT 0 FROM `model2` AS m0 INNER JOIN `model` AS m1 ON m1.`x` = m0.`z`" end test "association join has_many" do query = Model |> join(:inner, [p], c in assoc(p, :comments)) |> select([], 0) |> normalize assert SQL.all(query) == "SELECT 0 FROM `model` AS m0 INNER JOIN `model2` AS m1 ON m1.`z` = m0.`x`" end test "association join has_one" do query = Model |> join(:inner, [p], pp in assoc(p, :permalink)) |> select([], 0) |> normalize assert SQL.all(query) == "SELECT 0 FROM `model` AS m0 INNER JOIN `model3` AS m1 ON m1.`id` = m0.`y`" end test "join produces correct bindings" do query = from(p in Model, join: c in Model2, on: true) query = from(p in query, join: c in Model2, on: true, select: {p.id, c.id}) query = normalize(query) assert SQL.all(query) == "SELECT m0.`id`, m2.`id` FROM `model` AS m0 INNER JOIN `model2` AS m1 ON TRUE INNER JOIN `model2` AS m2 ON TRUE" end # Model based test "insert" do query = SQL.insert("model", [:x, :y], []) assert query == ~s{INSERT INTO `model` (`x`, `y`) VALUES (?, ?)} query = SQL.insert("model", [], []) assert query == ~s{INSERT INTO `model` () VALUES ()} end test "update" do query = SQL.update("model", [:id], [:x, :y], []) assert query == ~s{UPDATE `model` SET `id` = ? WHERE `x` = ? AND `y` = ?} end test "delete" do query = SQL.delete("model", [:x, :y], []) assert query == ~s{DELETE FROM `model` WHERE `x` = ? AND `y` = ?} end # DDL import Ecto.Migration, only: [table: 1, table: 2, index: 2, index: 3, references: 1, references: 2] test "executing a string during migration" do assert SQL.execute_ddl("example") == "example" end test "create table" do create = {:create, table(:posts), [{:add, :id, :serial, [primary_key: true]}, {:add, :title, :string, []}, {:add, :created_at, :datetime, []}]} assert SQL.execute_ddl(create) == ~s|CREATE TABLE `posts` (`id` serial , PRIMARY KEY(`id`), `title` varchar(255), `created_at` datetime) ENGINE = INNODB| end test "create table with engine" do create = {:create, table(:posts, engine: :myisam), [{:add, :id, :serial, [primary_key: true]}, {:add, :title, :string, []}, {:add, :created_at, :datetime, []}]} assert SQL.execute_ddl(create) == ~s|CREATE TABLE `posts` (`id` serial , PRIMARY KEY(`id`), `title` varchar(255), `created_at` datetime) ENGINE = MYISAM| end test "create table with reference" do create = {:create, table(:posts), [{:add, :id, :serial, [primary_key: true]}, {:add, :category_id, references(:categories), []} ]} assert SQL.execute_ddl(create) == ~s|CREATE TABLE `posts` (`id` serial , PRIMARY KEY(`id`), `category_id` BIGINT UNSIGNED , FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)) ENGINE = INNODB| end test "create table with reference and on_delete: :nothing clause" do create = {:create, table(:posts), [{:add, :id, :serial, [primary_key: true]}, {:add, :category_id, references(:categories, on_delete: :nothing), []} ]} assert SQL.execute_ddl(create) == ~s|CREATE TABLE `posts` (`id` serial , PRIMARY KEY(`id`), `category_id` BIGINT UNSIGNED , FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)) ENGINE = INNODB| end test "create table with reference and on_delete: :nilify_all clause" do create = {:create, table(:posts), [{:add, :id, :serial, [primary_key: true]}, {:add, :category_id, references(:categories, on_delete: :nilify_all), []} ]} assert SQL.execute_ddl(create) == ~s|CREATE TABLE `posts` (`id` serial , PRIMARY KEY(`id`), `category_id` BIGINT UNSIGNED , FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE SET NULL) ENGINE = INNODB| end test "create table with reference and on_delete: :delete_all clause" do create = {:create, table(:posts), [{:add, :id, :serial, [primary_key: true]}, {:add, :category_id, references(:categories, on_delete: :delete_all), []} ]} assert SQL.execute_ddl(create) == ~s|CREATE TABLE `posts` (`id` serial , PRIMARY KEY(`id`), `category_id` BIGINT UNSIGNED , FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE) ENGINE = INNODB| end test "create table with column options" do create = {:create, table(:posts), [{:add, :name, :string, [default: "Untitled", size: 20, null: false]}, {:add, :price, :numeric, [precision: 8, scale: 2, default: {:fragment, "expr"}]}, {:add, :on_hand, :integer, [default: 0, null: true]}, {:add, :is_active, :boolean, [default: true]}]} assert SQL.execute_ddl(create) == """ CREATE TABLE `posts` (`name` varchar(20) DEFAULT 'Untitled' NOT NULL, `price` numeric(8,2) DEFAULT expr, `on_hand` integer DEFAULT 0, `is_active` boolean DEFAULT true) ENGINE = INNODB """ |> String.strip |> String.replace("\n", " ") end test "create table with options" do create = {:create, table(:posts, options: "WITH FOO=BAR"), [{:add, :id, :serial, [primary_key: true]}, {:add, :created_at, :datetime, []}]} assert SQL.execute_ddl(create) == ~s|CREATE TABLE `posts` (`id` serial , PRIMARY KEY(`id`), `created_at` datetime) ENGINE = INNODB WITH FOO=BAR| end test "create table with both: engine and options" do create = {:create, table(:posts, engine: :myisam, options: "WITH FOO=BAR"), [{:add, :id, :serial, [primary_key: true]}, {:add, :created_at, :datetime, []}]} assert SQL.execute_ddl(create) == ~s|CREATE TABLE `posts` (`id` serial , PRIMARY KEY(`id`), `created_at` datetime) ENGINE = MYISAM WITH FOO=BAR| end test "drop table" do drop = {:drop, table(:posts)} assert SQL.execute_ddl(drop) == ~s|DROP TABLE `posts`| end test "alter table" do alter = {:alter, table(:posts), [{:add, :title, :string, [default: "Untitled", size: 100, null: false]}, {:modify, :price, :numeric, [precision: 8, scale: 2]}, {:remove, :summary}]} assert SQL.execute_ddl(alter) == """ ALTER TABLE `posts` ADD `title` varchar(100) DEFAULT 'Untitled' NOT NULL, MODIFY `price` numeric(8,2), DROP `summary` """ |> String.strip |> String.replace("\n", " ") end test "create index" do create = {:create, index(:posts, [:category_id, :permalink])} assert SQL.execute_ddl(create) == ~s|CREATE INDEX `posts_category_id_permalink_index` ON `posts` (`category_id`, `permalink`)| create = {:create, index(:posts, ["lower(permalink)"], name: "posts$main")} assert SQL.execute_ddl(create) == ~s|CREATE INDEX `posts$main` ON `posts` (`lower(permalink)`)| end test "create index asserting concurrency" do create = {:create, index(:posts, ["lower(permalink)"], name: "posts$main", concurrently: true)} assert SQL.execute_ddl(create) == ~s|CREATE INDEX `posts$main` ON `posts` (`lower(permalink)`) LOCK=NONE| end test "create unique index" do create = {:create, index(:posts, [:permalink], unique: true)} assert SQL.execute_ddl(create) == ~s|CREATE UNIQUE INDEX `posts_permalink_index` ON `posts` (`permalink`)| end test "create an index using a different type" do create = {:create, index(:posts, [:permalink], using: :hash)} assert SQL.execute_ddl(create) == ~s|CREATE INDEX `posts_permalink_index` ON `posts` (`permalink`) USING hash| end test "drop index" do drop = {:drop, index(:posts, [:id], name: "posts$main")} assert SQL.execute_ddl(drop) == ~s|DROP INDEX `posts$main` ON `posts`| end test "drop index asserting concurrency" do drop = {:drop, index(:posts, [:id], name: "posts$main", concurrently: true)} assert SQL.execute_ddl(drop) == ~s|DROP INDEX `posts$main` ON `posts` LOCK=NONE| end # Unsupported types and clauses test "arrays" do assert_raise ArgumentError, "Array type is not supported by MySQL", fn -> query = Model |> select([], fragment("?", [1, 2, 3])) |> normalize SQL.all(query) end end end
39.417407
196
0.57354
08f0f45d4a4897343e0fdebc327c908515047ecd
1,056
ex
Elixir
apps/sue_web/test/support/conn_case.ex
inculi/Sue
42e249aec1d9c467db63526966d9690d5c58f346
[ "MIT" ]
9
2018-03-23T11:18:21.000Z
2021-08-06T18:38:37.000Z
apps/sue_web/test/support/conn_case.ex
inculi/Sue
42e249aec1d9c467db63526966d9690d5c58f346
[ "MIT" ]
21
2017-12-01T05:57:10.000Z
2021-06-06T18:53:25.000Z
apps/sue_web/test/support/conn_case.ex
inculi/Sue
42e249aec1d9c467db63526966d9690d5c58f346
[ "MIT" ]
6
2018-03-23T11:24:21.000Z
2021-08-06T18:40:28.000Z
defmodule SueWeb.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 data structures and query the data layer. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use SueWeb.ConnCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections import Plug.Conn import Phoenix.ConnTest import SueWeb.ConnCase alias SueWeb.Router.Helpers, as: Routes # The default endpoint for testing @endpoint SueWeb.Endpoint end end setup _tags do {:ok, conn: Phoenix.ConnTest.build_conn()} end end
27.789474
60
0.729167
08f0f93fcc9bb61c57e0b94b6cc06719a171ffaa
3,491
exs
Elixir
config/config.exs
haldihri3/lowendinsight-get
b414f288e7a9f409a1ec408b6515fd1cb95e6316
[ "BSD-3-Clause" ]
null
null
null
config/config.exs
haldihri3/lowendinsight-get
b414f288e7a9f409a1ec408b6515fd1cb95e6316
[ "BSD-3-Clause" ]
null
null
null
config/config.exs
haldihri3/lowendinsight-get
b414f288e7a9f409a1ec408b6515fd1cb95e6316
[ "BSD-3-Clause" ]
null
null
null
# Copyright (C) 2020 by the Georgia Tech Research Institute (GTRI) # This software may be modified and distributed under the terms of # the BSD 3-Clause license. See the LICENSE file for details. use Mix.Config config :lowendinsight_get, LowendinsightGet.Endpoint, port: String.to_integer(System.get_env("PORT") || "4000") ## Set the cache TTL period for keeping reports config :lowendinsight_get, cache_ttl: String.to_integer(System.get_env("LEI_CACHE_TTL") || "30"), cache_clean_enable: String.to_atom(System.get_env("LEI_CACHE_CLEAN_ENABLE") || "true"), check_repo_size?: String.to_atom(System.get_env("LEI_CHECK_REPO_SIZE") || "true"), languages: [ "elixir", "python", "go", "rust", "java", "javascript", "ruby", "c", "c++", "c#", "haskell", "php", "scala", "swift", "objective-c", "kotlin", "shell", "typescript" ] config :lowendinsight, ## Contributor in terms of discrete users ## NOTE: this currently doesn't discern same user with different email critical_contributor_level: String.to_integer(System.get_env("LEI_CRITICAL_CONTRIBUTOR_LEVEL") || "2"), high_contributor_level: System.get_env("LEI_HIGH_CONTRIBUTOR_LEVEL") || 3, medium_contributor_level: System.get_env("LEI_CRITICAL_CONTRIBUTOR_LEVEL") || 5, ## Commit currency in weeks - is the project active. This by itself ## may not indicate anything other than the repo is stable. The reason ## we're reporting it is relative to the likelihood vulnerabilities ## getting fix in a timely manner critical_currency_level: String.to_integer(System.get_env("LEI_CRITICAL_CURRENCY_LEVEL") || "104"), high_currency_level: String.to_integer(System.get_env("LEI_HIGH_CURRENCY_LEVEL") || "52"), medium_currency_level: String.to_integer(System.get_env("LEI_MEDIUM_CURRENCY_LEVEL") || "26"), ## Percentage of changes to repo in recent commit - is the codebase ## volatile in terms of quantity of source being changed critical_large_commit_level: String.to_float(System.get_env("LEI_CRITICAL_LARGE_COMMIT_LEVEL") || "0.30"), high_large_commit_level: String.to_float(System.get_env("LEI_HIGH_LARGE_COMMIT_LEVEL") || "0.15"), medium_large_commit_level: String.to_float(System.get_env("LEI_MEDIUM_LARGE_COMMIT_LEVEL") || "0.05"), ## Bell curve contributions - if there are 30 contributors ## but 90% of the contributions are from 2... critical_functional_contributors_level: String.to_integer(System.get_env("LEI_CRITICAL_FUNCTIONAL_CONTRIBUTORS_LEVEL") || "2"), high_functional_contributors_level: String.to_integer(System.get_env("LEI_HIGH_FUNCTIONAL_CONTRIBUTORS_LEVEL") || "3"), medium_functional_contributors_level: String.to_integer(System.get_env("LEI_MEDIUM_FUNCTIONAL_CONTRIBUTORS_LEVEL") || "5"), ## Jobs per available core for defining max concurrency. This value ## will be used to set the max_concurrency value. jobs_per_core_max: String.to_integer(System.get_env("LEI_JOBS_PER_CORE_MAX") || "1"), ## Base directory structure for temp clones base_temp_dir: System.get_env("LEI_BASE_TEMP_DIR") || "/tmp" import_config "#{Mix.env()}.exs" config :redix, redis_url: System.get_env("REDIS_URL") || "redis://localhost:6379/5" config :lowendinsight_get, LowendinsightGet.Scheduler, jobs: [ # Every 5 minutes {"*/5 * * * *", {LowendinsightGet.CacheCleaner, :clean, []}}, {"0 0 * * *", {LowendinsightGet.GithubTrending, :analyze, []}} ]
38.788889
96
0.729304
08f0fdf051c3ff2c3b8cbfa7e0ceb31859cc4f9f
2,882
ex
Elixir
lib/tilex/notifications/notifications.ex
BobrImperator/tilex
0222602b6b7f4d868a4036bc5c94bf8d84dc12f5
[ "MIT" ]
null
null
null
lib/tilex/notifications/notifications.ex
BobrImperator/tilex
0222602b6b7f4d868a4036bc5c94bf8d84dc12f5
[ "MIT" ]
null
null
null
lib/tilex/notifications/notifications.ex
BobrImperator/tilex
0222602b6b7f4d868a4036bc5c94bf8d84dc12f5
[ "MIT" ]
null
null
null
defmodule Tilex.Notifications do use GenServer alias Ecto.Changeset alias Tilex.{Post, Repo} alias TilexWeb.Endpoint alias TilexWeb.Router.Helpers alias Tilex.Notifications.NotifiersSupervisor ### Client API def start_link([]) do GenServer.start_link(__MODULE__, :ok, name: __MODULE__) end @doc """ Alert the notification system that a new post has been created """ def post_created(%Post{} = post) do GenServer.cast(__MODULE__, {:post_created, post}) end def page_views_report(report) do GenServer.call(__MODULE__, {:page_views_report, report}) end @doc """ Alert the notification system that a post has been liked """ def post_liked(%Post{} = post, max_likes_changed) do GenServer.cast(__MODULE__, {:post_liked, post, max_likes_changed}) end ### Server API def init(_) do schedule_report() {:ok, :nostate} end def handle_info(:generate_page_views_report, :nostate) do schedule_report() with {:ok, report} <- Tilex.PageViewsReport.report() do notifiers() |> Enum.each(& &1.page_views_report(report)) end {:noreply, :nostate} end def handle_cast({:post_created, %Post{} = post}, :nostate) do developer = Repo.one(Ecto.assoc(post, :developer)) channel = Repo.one(Ecto.assoc(post, :channel)) url = "#{Application.get_env(:tilex, :edge_url)}/posts/#{post.slug}" notifiers() |> Enum.each(& &1.post_created(post, developer, channel, url)) post_changeset = post |> Changeset.change(%{tweeted_at: DateTime.truncate(DateTime.utc_now(), :second)}) Repo.update!(post_changeset) {:noreply, :nostate} end def handle_cast({:post_liked, %Post{max_likes: max_likes} = post, max_likes_changed}, :nostate) do if rem(max_likes, 10) == 0 and max_likes_changed do developer = Repo.one(Ecto.assoc(post, :developer)) url = Helpers.post_url(Endpoint, :show, post) notifiers() |> Enum.each(& &1.post_liked(post, developer, url)) end {:noreply, :nostate} end def handle_call({:page_views_report, report}, from, :nostate) do notifiers() |> Enum.each(& &1.page_views_report(report)) {:reply, from, true} end def notifiers(notifiers_supervisor \\ NotifiersSupervisor) do notifiers_supervisor.children() end def next_report_time(now \\ now!()) do dt = now |> Timex.beginning_of_week(:monday) |> Timex.shift(hours: 9) case DateTime.compare(dt, now) do :gt -> dt _ -> Timex.shift(dt, days: 7) end end defp schedule_report do next_report_in_ms = Timex.diff(next_report_time(), now!(), :milliseconds) Process.send_after(__MODULE__, :generate_page_views_report, next_report_in_ms) end defp now!(time_zone \\ get_time_zone()), do: DateTime.now!(time_zone) defp get_time_zone, do: Application.get_env(:tilex, :date_display_tz) end
26.2
100
0.681818
08f1060dbe311d1c6942bf26b71a663c8eefa6af
482
ex
Elixir
lib/payroll/hours/hours.ex
will-wow/ex-payroll
7b60cc578b091fa669629c433806787db5f926dc
[ "MIT" ]
1
2020-11-11T19:57:31.000Z
2020-11-11T19:57:31.000Z
lib/payroll/hours/hours.ex
will-wow/ex-payroll
7b60cc578b091fa669629c433806787db5f926dc
[ "MIT" ]
null
null
null
lib/payroll/hours/hours.ex
will-wow/ex-payroll
7b60cc578b091fa669629c433806787db5f926dc
[ "MIT" ]
null
null
null
defmodule Payroll.Hours do alias Payroll.Hours.WorkDay alias Payroll.Hours.Overtime @spec calculate_overtime([number], number) :: WorkDay.t() defdelegate calculate_overtime(previous_hours, current_hours), to: Overtime @spec work_day_to_pay_hours(WorkDay.t()) :: number defdelegate work_day_to_pay_hours(work_day), to: WorkDay, as: :to_pay_hours @spec work_day_to_list(WorkDay.t()) :: [number] defdelegate work_day_to_list(work_day), to: WorkDay, as: :to_list end
34.428571
77
0.771784
08f13e44287a7ef53d5187e6f07cbf1956568175
1,263
exs
Elixir
mix.exs
bushman77/ecto3_mnesia
c0ba8af22e3b1c684e6fd3826206272f7c1df03b
[ "MIT" ]
null
null
null
mix.exs
bushman77/ecto3_mnesia
c0ba8af22e3b1c684e6fd3826206272f7c1df03b
[ "MIT" ]
null
null
null
mix.exs
bushman77/ecto3_mnesia
c0ba8af22e3b1c684e6fd3826206272f7c1df03b
[ "MIT" ]
null
null
null
defmodule EctoMnesia.MixProject do use Mix.Project def project do [ name: "Ecto3 Mnesia", app: :ecto3_mnesia, version: "0.2.2", elixir: "~> 1.9", start_permanent: Mix.env() == :prod, deps: deps(), dialyzer: [ plt_add_apps: [:mnesia] ], source_url: "https://gitlab.com/patatoid/ecto3_mnesia", description: description(), package: package(), docs: [ main: "Ecto.Adapters.Mnesia", extras: ["README.md"] ], elixirc_paths: elixirc_paths(Mix.env()) ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(:dev), do: ["lib", "lib_support"] defp elixirc_paths(:prod), do: ["lib"] def application do [ extra_applications: [:logger] ] end defp deps do [ {:ecto, "~> 3.0"}, {:qlc, "~> 1.0"}, {:ex_doc, "~> 0.21", only: :dev, runtime: false}, {:dialyxir, "~> 1.0.0-rc.7", only: [:dev], runtime: false} ] end defp package do %{ name: "ecto3_mnesia", licenses: ["MIT"], links: %{ "Gitlab" => "https://gitlab.com/patatoid/ecto3_mnesia" } } end defp description do """ Mnesia adapter for Ecto 3 """ end end
20.704918
64
0.536025
08f1417817078e6124030218e88c228f6e3299bc
1,916
exs
Elixir
test/fixtures/google/discovery_document.exs
haakonst/openid_connect
e8dfd0033bb3420c1af43653406ccd870900032e
[ "MIT" ]
48
2017-08-27T11:16:42.000Z
2022-02-25T22:51:36.000Z
test/fixtures/google/discovery_document.exs
haakonst/openid_connect
e8dfd0033bb3420c1af43653406ccd870900032e
[ "MIT" ]
26
2017-10-17T14:56:17.000Z
2022-02-17T10:15:31.000Z
test/fixtures/google/discovery_document.exs
haakonst/openid_connect
e8dfd0033bb3420c1af43653406ccd870900032e
[ "MIT" ]
33
2018-05-16T12:32:53.000Z
2021-12-08T22:41:18.000Z
%HTTPoison.Response{ body: %{ "authorization_endpoint" => "https://accounts.google.com/o/oauth2/v2/auth", "claims_supported" => [ "aud", "email", "email_verified", "exp", "family_name", "given_name", "iat", "iss", "locale", "name", "picture", "sub" ], "code_challenge_methods_supported" => ["plain", "S256"], "id_token_signing_alg_values_supported" => ["RS256"], "issuer" => "https://accounts.google.com", "jwks_uri" => "https://www.googleapis.com/oauth2/v3/certs", "response_types_supported" => [ "code", "token", "id_token", "code token", "code id_token", "token id_token", "code token id_token", "none" ], "revocation_endpoint" => "https://accounts.google.com/o/oauth2/revoke", "scopes_supported" => ["openid", "email", "profile"], "subject_types_supported" => ["public"], "token_endpoint" => "https://www.googleapis.com/oauth2/v4/token", "token_endpoint_auth_methods_supported" => ["client_secret_post", "client_secret_basic"], "userinfo_endpoint" => "https://www.googleapis.com/oauth2/v3/userinfo" }, headers: [ {"Accept-Ranges", "none"}, {"Vary", "Accept-Encoding"}, {"Content-Type", "application/json"}, {"Access-Control-Allow-Origin", "*"}, {"Date", "Mon, 30 Apr 2018 06:25:58 GMT"}, {"Expires", "Mon, 30 Apr 2018 07:25:58 GMT"}, {"Last-Modified", "Mon, 01 Feb 2016 19:53:44 GMT"}, {"X-Content-Type-Options", "nosniff"}, {"Server", "sffe"}, {"X-XSS-Protection", "1; mode=block"}, {"Age", "700"}, {"Cache-Control", "public, max-age=3600"}, {"Alt-Svc", "hq=\":443\"; ma=2592000; quic=51303433; quic=51303432; quic=51303431; quic=51303339; quic=51303335,quic=\":443\"; ma=2592000; v=\"43,42,41,39,35\""}, {"Transfer-Encoding", "chunked"} ], status_code: 200 }
33.034483
155
0.586117
08f149035066244e7726b64bac4c3bab2b63d00f
616
ex
Elixir
sense_wrapper/lib/app.ex
damnever/completor-elixir
f4210d15c128167f7a857669f1a2d8e548373a40
[ "MIT" ]
1
2018-02-22T14:32:52.000Z
2018-02-22T14:32:52.000Z
sense_wrapper/lib/app.ex
damnever/completor-elixir
f4210d15c128167f7a857669f1a2d8e548373a40
[ "MIT" ]
null
null
null
sense_wrapper/lib/app.ex
damnever/completor-elixir
f4210d15c128167f7a857669f1a2d8e548373a40
[ "MIT" ]
null
null
null
defmodule SenseWrapper.App do @moduledoc false use Application use Supervisor alias ElixirSense.Server.ContextLoader def start(_type, _args) do children = [ {ContextLoader, ["dev"]}, ] opts = [strategy: :one_for_one, name: SenseWrapper.Supervisor] Supervisor.start_link(children, opts) run() end defp run() do readline() |> String.trim() |> SenseWrapper.process() |> IO.puts() run() end defp readline() do case IO.read(:line) do :eof -> System.halt(0) {:error, reason} -> System.halt(reason) data -> data end end end
17.111111
66
0.61526
08f1751ee7d37f74c0ff22c873cf931f41bdf79c
881
ex
Elixir
debian/prerm.ex
MacroFab/SVG-Stacker
b6051ac9076d2da90dc8bbf786c876264ed33092
[ "MIT" ]
1
2016-07-17T11:02:34.000Z
2016-07-17T11:02:34.000Z
debian/prerm.ex
MacroFab/SVG-Stacker
b6051ac9076d2da90dc8bbf786c876264ed33092
[ "MIT" ]
1
2019-02-11T22:30:41.000Z
2019-02-11T23:00:24.000Z
debian/prerm.ex
MacroFab/SVG-Stacker
b6051ac9076d2da90dc8bbf786c876264ed33092
[ "MIT" ]
null
null
null
#!/bin/sh # prerm script for svg-stacker # # see: dh_installdeb(1) set -e # summary of how this script can be called: # * <prerm> `remove' # * <old-prerm> `upgrade' <new-version> # * <new-prerm> `failed-upgrade' <old-version> # * <conflictor's-prerm> `remove' `in-favour' <package> <new-version> # * <deconfigured's-prerm> `deconfigure' `in-favour' # <package-being-installed> <version> `removing' # <conflicting-package> <version> # for details, see http://www.debian.org/doc/debian-policy/ or # the debian-policy package case "$1" in remove|upgrade|deconfigure) ;; failed-upgrade) ;; *) echo "prerm called with unknown argument \`$1'" >&2 exit 1 ;; esac # dh_installdeb will replace this with shell code automatically # generated by other debhelper scripts. #DEBHELPER# exit 0
22.589744
76
0.626561
08f1876383f8a98002cbae53a66d67416fd1ae1d
1,728
ex
Elixir
clients/chat/lib/google_api/chat/v1/model/button.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/chat/lib/google_api/chat/v1/model/button.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/chat/lib/google_api/chat/v1/model/button.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Chat.V1.Model.Button do @moduledoc """ A button. Can be a text button or an image button. ## Attributes - imageButton (ImageButton): A button with image and onclick action. Defaults to: `null`. - textButton (TextButton): A button with text and onclick action. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :imageButton => GoogleApi.Chat.V1.Model.ImageButton.t(), :textButton => GoogleApi.Chat.V1.Model.TextButton.t() } field(:imageButton, as: GoogleApi.Chat.V1.Model.ImageButton) field(:textButton, as: GoogleApi.Chat.V1.Model.TextButton) end defimpl Poison.Decoder, for: GoogleApi.Chat.V1.Model.Button do def decode(value, options) do GoogleApi.Chat.V1.Model.Button.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Chat.V1.Model.Button do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.882353
91
0.736111
08f1a85cefe378eb2984f33d3f7ab50037cc78af
1,545
exs
Elixir
apps/service_receive/mix.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
12
2020-01-27T19:43:02.000Z
2021-07-28T19:46:29.000Z
apps/service_receive/mix.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
81
2020-01-28T18:07:23.000Z
2021-11-22T02:12:13.000Z
apps/service_receive/mix.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
10
2020-02-13T21:24:09.000Z
2020-05-21T18:39:35.000Z
defmodule Receive.MixProject do use Mix.Project def project do [ app: :service_receive, version: "0.1.0", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", lockfile: "../../mix.lock", elixir: "~> 1.9", start_permanent: Mix.env() == :prod, deps: deps(), elixirc_paths: elixirc_paths(Mix.env()) ] end def application do [ extra_applications: [:logger], mod: {Receive.Application, []} ] end defp deps do [ {:accept_udp, in_umbrella: true}, {:accept_websocket, in_umbrella: true}, {:annotated_retry, in_umbrella: true}, {:brook, "~> 0.6"}, {:definition_accept, in_umbrella: true}, {:definition_dictionary, in_umbrella: true}, {:definition_events, in_umbrella: true}, {:elsa, "~> 0.12", override: true}, {:extractor, in_umbrella: true}, {:initializer, in_umbrella: true}, {:management, in_umbrella: true}, {:metrics_reporter, in_umbrella: true}, {:plugins, in_umbrella: true}, {:properties, in_umbrella: true}, {:transformer, in_umbrella: true}, {:credo, "~> 1.3", only: [:dev]}, {:dialyxir, "~> 1.0.0-rc.7", only: [:dev], runtime: false}, {:mox, "~> 0.5.1", only: [:test]}, {:placebo, "~> 2.0.0-rc2", only: [:dev, :test]}, {:testing, in_umbrella: true, only: [:test]} ] end defp elixirc_paths(:test), do: ["test/support", "lib"] defp elixirc_paths(_), do: ["lib"] end
28.611111
65
0.565049
08f1c111e52cd898a0844f6cadd97d0f0f5c43c8
3,438
exs
Elixir
test/ecto/query/builder/windows_test.exs
marpo60/ecto
2c2e1b467ec5de87ee41508070f6670288cd2a32
[ "Apache-2.0" ]
1
2019-05-03T08:51:16.000Z
2019-05-03T08:51:16.000Z
test/ecto/query/builder/windows_test.exs
marpo60/ecto
2c2e1b467ec5de87ee41508070f6670288cd2a32
[ "Apache-2.0" ]
null
null
null
test/ecto/query/builder/windows_test.exs
marpo60/ecto
2c2e1b467ec5de87ee41508070f6670288cd2a32
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.Query.Builder.WindowsTest do use ExUnit.Case, async: true import Ecto.Query.Builder.Windows doctest Ecto.Query.Builder.Windows import Ecto.Query describe "escape" do test "handles expressions and params" do assert {Macro.escape(quote do [partition_by: [&0.y]] end), {[], :acc}} == escape(quote do [partition_by: x.y] end, {[], :acc}, [x: 0], __ENV__) assert {Macro.escape(quote do [partition_by: [&0.y]] end), {[], :acc}} == escape(quote do [partition_by: :y] end, {[], :acc}, [x: 0], __ENV__) assert {Macro.escape(quote do [order_by: [asc: &0.y]] end), {[], :acc}} == escape(quote do [order_by: x.y] end, {[], :acc}, [x: 0], __ENV__) assert {Macro.escape(quote do [order_by: [asc: &0.y]] end), {[], :acc}} == escape(quote do [order_by: :y] end, {[], :acc}, [x: 0], __ENV__) end test "supports frames" do assert {Macro.escape(quote(do: [frame: fragment({:raw, "ROWS 3 PRECEDING EXCLUDE CURRENT ROW"})])), {[], :acc}} == escape(quote do [frame: fragment("ROWS 3 PRECEDING EXCLUDE CURRENT ROW")] end, {[], :acc}, [], __ENV__) assert {Macro.escape(quote(do: [frame: fragment({:raw, "ROWS "}, {:expr, ^0}, {:raw, " PRECEDING"})])), {[{quote(do: start_frame), :any}], :acc}} == escape(quote do [frame: fragment("ROWS ? PRECEDING", ^start_frame)] end, {[], :acc}, [], __ENV__) assert_raise Ecto.Query.CompileError, ~r"expected a fragment in `:frame`", fn -> escape(quote do [frame: [rows: -3, exclude: :current]] end, {[], :acc}, [], __ENV__) end end end describe "at runtime" do test "raises on duplicate window" do query = "q" |> windows([p], w: [partition_by: p.x]) assert_raise Ecto.Query.CompileError, ~r"window with name w is already defined", fn -> query |> windows([p], w: [partition_by: p.y]) end end test "allows interpolation on partition by" do fields = [:x] query = "q" |> windows([p], w: [partition_by: ^fields]) assert query.windows[:w].expr[:partition_by] == [{{:., [], [{:&, [], [0]}, :x]}, [], []}] end test "raises on invalid partition by" do assert_raise ArgumentError, ~r"expected a list of fields in `partition_by`", fn -> windows("q", w: [partition_by: ^[1]]) end end test "allows interpolation on order by" do fields = [asc: :x] query = "q" |> windows([p], w: [order_by: ^fields]) assert query.windows[:w].expr[:order_by] == [asc: {{:., [], [{:&, [], [0]}, :x]}, [], []}] end test "raises on invalid order by" do assert_raise ArgumentError, ~r"expected a field as an atom, a list or keyword list in `order_by`", fn -> windows("q", w: [order_by: ^[1]]) end end test "allows interpolation on frame" do bound = 3 query = "q" |> windows([p], w: [frame: fragment("ROWS ? PRECEDING EXCLUDE CURRENT ROW", ^bound)]) assert query.windows[:w].expr[:frame] == {:fragment, [], [raw: "ROWS ", expr: {:^, [], [0]}, raw: " PRECEDING EXCLUDE CURRENT ROW"]} end test "frame works with over clause" do query = "q" |> select([p], over(avg(p.field), [frame: fragment("ROWS 3 PRECEDING")])) {:over, [], [_, frame]} = query.select.expr assert frame == [frame: {:fragment, [], [raw: "ROWS 3 PRECEDING"]}] end end end
40.447059
120
0.566899
08f1c6c5d9fb734a934285d12c267d32f1b33cba
3,614
ex
Elixir
lib/ecto/pools/poolboy/worker.ex
rbishop/ecto
a8a3215c9e2e35f7556f54c8d47d78a3670796d8
[ "Apache-2.0" ]
1
2015-08-24T06:01:51.000Z
2015-08-24T06:01:51.000Z
deps/ecto/lib/ecto/pools/poolboy/worker.ex
Thrashmandicoot/my-first-phoenix-app
7cdfe34a1d874cbce8dba17e9824a5c91e3b47da
[ "MIT" ]
null
null
null
deps/ecto/lib/ecto/pools/poolboy/worker.ex
Thrashmandicoot/my-first-phoenix-app
7cdfe34a1d874cbce8dba17e9824a5c91e3b47da
[ "MIT" ]
null
null
null
defmodule Ecto.Pools.Poolboy.Worker do @moduledoc false use GenServer use Behaviour alias Ecto.Adapters.Connection @type modconn :: {module :: atom, conn :: pid} @spec start_link({module, Keyword.t}) :: {:ok, pid} def start_link({module, params}) do GenServer.start_link(__MODULE__, {module, params}, []) end @spec checkout(pid, fun, timeout) :: {:ok, modconn} | {:error, Exception.t} when fun: :run | :transaction def checkout(worker, fun, timeout) do GenServer.call(worker, {:checkout, fun}, timeout) end @spec checkin(pid) :: :ok def checkin(worker) do GenServer.cast(worker, :checkin) end @spec break(pid, timeout) :: :ok def break(worker, timeout) do GenServer.call(worker, :break, timeout) end ## Callbacks def init({module, opts}) do Process.flag(:trap_exit, true) {opts, params} = Keyword.split(opts, [:lazy, :shutdown]) lazy? = Keyword.get(opts, :lazy, true) shutdown = Keyword.get(opts, :shutdown, 5_000) unless lazy? do case Connection.connect(module, params) do {:ok, conn} -> conn = conn _ -> :ok end end {:ok, %{conn: conn, params: params, shutdown: shutdown, transaction: nil, module: module}} end ## Break def handle_call(:break, _from, s) do s = s |> demonitor() |> disconnect() {:reply, :ok, s} end ## Lazy connection handling def handle_call(request, from, %{conn: nil, params: params, module: module} = s) do case Connection.connect(module, params) do {:ok, conn} -> handle_call(request, from, %{s | conn: conn}) {:error, err} -> {:reply, {:error, err}, s} end end ## Checkout def handle_call({:checkout, :run}, _, s) do {:reply, {:ok, modconn(s)}, s} end ## Open transaction def handle_call({:checkout, :transaction}, from, %{transaction: nil} = s) do {pid, _} = from {:reply, {:ok, modconn(s)}, monitor(pid, s)} end def handle_call({:checkout, :transaction} = checkout, from, s) do {client, _} = s.transaction if Process.is_alive?(client) do handle_call(checkout, from, demonitor(s)) else s = s |> demonitor() |> disconnect() handle_call(checkout, from, s) end end ## Close transaction def handle_cast(:checkin, %{transaction: nil} = s) do {:stop, :notransaction, s} end def handle_cast(:checkin, s) do {:noreply, demonitor(s)} end ## Info # The connection crashed. We don't need to notify # the client if we have an open transaction because # it will fail with noproc anyway. def handle_info({:EXIT, conn, _reason}, %{conn: conn} = s) do s = %{s | conn: nil} |> disconnect() {:noreply, s} end # The transaction owner crashed without closing. # We need to assume we don't know the connection state. def handle_info({:DOWN, ref, _, _, _}, %{transaction: {_, ref}} = s) do {:noreply, disconnect(%{s | transaction: nil})} end def handle_info(_info, s) do {:noreply, s} end def terminate(_reason, s), do: disconnect(s) ## Helpers defp modconn(%{conn: conn, module: module}) do {module, conn} end defp monitor(pid,s) do ref = Process.monitor(pid) %{s | transaction: {pid, ref}} end defp demonitor(%{transaction: nil} = s), do: s defp demonitor(%{transaction: {_, ref}} = s) do Process.demonitor(ref, [:flush]) %{s | transaction: nil} end defp disconnect(%{conn: conn, shutdown: shutdown} = s) do _ = conn && Connection.shutdown(conn, shutdown) %{s | conn: nil} end end
23.933775
85
0.612341
08f1d62169612f57c039665beb36bab0816d273e
2,463
exs
Elixir
config/prod.exs
cesium/safira
10dd45357c20e8afc22563f114f49ccb74008114
[ "MIT" ]
40
2018-07-04T19:13:45.000Z
2021-12-16T23:53:43.000Z
config/prod.exs
cesium/safira
10dd45357c20e8afc22563f114f49ccb74008114
[ "MIT" ]
94
2018-07-25T13:13:39.000Z
2022-02-15T04:09:42.000Z
config/prod.exs
cesium/safira
10dd45357c20e8afc22563f114f49ccb74008114
[ "MIT" ]
5
2018-11-26T17:19:03.000Z
2021-02-23T08:09:37.000Z
use Mix.Config # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :safira, SafiraWeb.Endpoint, load_from_system_env: true, url: [scheme: "https", host: System.get_env("URL"), port: 443], force_ssl: [rewrite_on: [:x_forwarded_proto]], cache_static_manifest: "priv/static/cache_manifest.json", secret_key_base: Map.fetch!(System.get_env(), "SECRET_KEY_BASE") # Configure your database config :safira, Safira.Repo, adapter: Ecto.Adapters.Postgres, url: System.get_env("DATABASE_URL"), pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"), ssl: true # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :safira, SafiraWeb.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [:inet6, # port: 443, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH")] # # Where those two env variables return an absolute path to # the key and cert in disk or a relative path inside priv, # for example "priv/ssl/server.key". # # We also recommend setting `force_ssl`, ensuring no data is # ever sent via http, always redirecting to https: # # config :safira, SafiraWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # ## Using releases # # If you are doing OTP releases, you need to instruct Phoenix # to start the server for all endpoints: # # config :phoenix, :serve_endpoints, true # # Alternatively, you can configure exactly which server to # start per endpoint: # # config :safira, SafiraWeb.Endpoint, server: true # config :safira, Safira.Mailer, adapter: Bamboo.SendGridAdapter, api_key: Map.fetch!(System.get_env(), "EMAIL_API_KEY"), hackney_opts: [ recv_timeout: :timer.minutes(1) ] # Finally import the config/prod.secret.exs # which should be versioned separately. # import_config "prod.secret.exs"
31.987013
68
0.712952
08f1fa8ec5a35abad2dd615314d0b32db3190e02
2,215
ex
Elixir
lib/milbase/account.ex
suryakun/milbase-skeleton
1483142bd9ef70a9cf07504c8f03314f2cb7b7d0
[ "Apache-2.0" ]
1
2020-07-14T03:27:30.000Z
2020-07-14T03:27:30.000Z
lib/milbase/account.ex
suryakun/milbase-skeleton
1483142bd9ef70a9cf07504c8f03314f2cb7b7d0
[ "Apache-2.0" ]
null
null
null
lib/milbase/account.ex
suryakun/milbase-skeleton
1483142bd9ef70a9cf07504c8f03314f2cb7b7d0
[ "Apache-2.0" ]
null
null
null
defmodule Milbase.Account do @moduledoc """ The Account context. """ import Ecto.Query, warn: false alias Milbase.Repo alias Milbase.Account.User @doc """ Data source for dataloader library """ def data(), do: Dataloader.Ecto.new(Milbase.Repo, query: &query/2) @doc """ Data query for dataloader library """ def query(queryable, _params) do queryable end @doc """ Returns the list of users. ## Examples iex> list_users() [%User{}, ...] """ def list_users do Repo.all(User) end @doc """ Gets a single user. Raises `Ecto.NoResultsError` if the User does not exist. ## Examples iex> get_user!(123) %User{} iex> get_user!(456) ** (Ecto.NoResultsError) """ def get_user!(id), do: Repo.get!(User, id) @doc """ Creates a user. ## Examples iex> create_user(%{field: value}) {:ok, %User{}} iex> create_user(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ def create_user(attrs \\ %{}) do %User{} |> User.changeset(attrs) |> Repo.insert() end @doc """ Updates a user. ## Examples iex> update_user(user, %{field: new_value}) {:ok, %User{}} iex> update_user(user, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ def update_user(%User{} = user, attrs) do user |> User.changeset(attrs) |> Repo.update() end @doc """ Deletes a User. ## Examples iex> delete_user(user) {:ok, %User{}} iex> delete_user(user) {:error, %Ecto.Changeset{}} """ def delete_user(%User{} = user) do Repo.delete(user) end @doc """ Returns an `%Ecto.Changeset{}` for tracking user changes. ## Examples iex> change_user(user) %Ecto.Changeset{source: %User{}} """ def change_user(%User{} = user) do User.changeset(user, %{}) end @doc """ Return an `%Ecto.Changeset{}` by user email ## Example iex> get_by_email(email) iex> {:ok, %User{}} """ def get_by_email(email) do query = from u in User, where: u.email == ^email, select: u case Repo.one(query) do nil -> {:error, nil} user -> {:ok, user} end end end
16.908397
68
0.571558
08f200aed337de48e3df917cf5e7d35baa3061d1
13,463
ex
Elixir
lib/livebook/intellisense/completion.ex
danhuynhdev/livebook
d20d4f6bf123d58e4666c064027b55e3b300702f
[ "Apache-2.0" ]
null
null
null
lib/livebook/intellisense/completion.ex
danhuynhdev/livebook
d20d4f6bf123d58e4666c064027b55e3b300702f
[ "Apache-2.0" ]
null
null
null
lib/livebook/intellisense/completion.ex
danhuynhdev/livebook
d20d4f6bf123d58e4666c064027b55e3b300702f
[ "Apache-2.0" ]
null
null
null
defmodule Livebook.Intellisense.Completion do @moduledoc false # This module provides basic completion based on code # and runtime information (binding, environment). # # The implementation is based primarly on `IEx.Autocomplete`. # It also takes insights from `ElixirSense.Providers.Suggestion.Complete`, # which is a very extensive implementation used in the # Elixir Language Server. @type completion_item :: {:variable, name(), value()} | {:map_field, name(), value()} | {:module, name(), doc_content()} | {:function, module(), name(), arity(), doc_content(), list(signature()), spec()} | {:type, module(), name(), arity(), doc_content()} | {:module_attribute, name(), doc_content()} @type name :: String.t() @type value :: term() @type doc_content :: {format :: String.t(), content :: String.t()} | nil @type signature :: String.t() @type spec :: tuple() | nil @exact_matcher &Kernel.==/2 @prefix_matcher &String.starts_with?/2 @doc """ Returns a list of identifiers matching the given `hint` together with relevant information. Evaluation binding and environment is used to expand aliases, imports, nested maps, etc. `hint` may be a single token or line fragment like `if Enum.m`. ## Options * `exact` - whether the hint must match exactly the given identifier. Defaults to `false`, resulting in prefix matching. """ @spec get_completion_items(String.t(), Code.binding(), Macro.Env.t(), keyword()) :: list(completion_item()) def get_completion_items(hint, binding, env, opts \\ []) do matcher = if opts[:exact], do: @exact_matcher, else: @prefix_matcher complete(hint, %{binding: binding, env: env, matcher: matcher}) end defp complete(hint, ctx) do case Code.cursor_context(hint) do {:alias, alias} -> complete_alias(List.to_string(alias), ctx) {:unquoted_atom, unquoted_atom} -> complete_erlang_module(List.to_string(unquoted_atom), ctx) {:dot, path, hint} -> complete_dot(path, List.to_string(hint), ctx) {:dot_arity, path, hint} -> complete_dot(path, List.to_string(hint), %{ctx | matcher: @exact_matcher}) {:dot_call, _path, _hint} -> complete_default(ctx) :expr -> complete_default(ctx) {:local_or_var, local_or_var} -> complete_local_or_var(List.to_string(local_or_var), ctx) {:local_arity, local} -> complete_local(List.to_string(local), %{ctx | matcher: @exact_matcher}) {:local_call, _local} -> complete_default(ctx) {:operator, operator} -> complete_local_or_var(List.to_string(operator), ctx) {:operator_arity, operator} -> complete_local(List.to_string(operator), %{ctx | matcher: @exact_matcher}) {:operator_call, _operator} -> complete_default(ctx) {:module_attribute, attribute} -> complete_module_attribute(List.to_string(attribute), ctx) # :none _ -> [] end end ## Complete dot defp complete_dot(path, hint, ctx) do case expand_dot_path(path, ctx) do {:ok, mod} when is_atom(mod) and hint == "" -> complete_module_member(mod, hint, ctx) ++ complete_module(mod, hint, ctx) {:ok, mod} when is_atom(mod) -> complete_module_member(mod, hint, ctx) {:ok, map} when is_map(map) -> complete_map_field(map, hint, ctx) _ -> [] end end defp expand_dot_path({:var, var}, ctx) do Keyword.fetch(ctx.binding, List.to_atom(var)) end defp expand_dot_path({:alias, alias}, ctx) do {:ok, expand_alias(List.to_string(alias), ctx)} end defp expand_dot_path({:unquoted_atom, var}, _ctx) do {:ok, List.to_atom(var)} end defp expand_dot_path({:module_attribute, _attribute}, _ctx) do :error end defp expand_dot_path({:dot, parent, call}, ctx) do case expand_dot_path(parent, ctx) do {:ok, %{} = map} -> Map.fetch(map, List.to_atom(call)) _ -> :error end end defp complete_default(ctx) do complete_local_or_var("", ctx) end defp complete_alias(hint, ctx) do case split_at_last_occurrence(hint, ".") do {hint, ""} -> complete_elixir_root_module(hint, ctx) ++ complete_env_alias(hint, ctx) {alias, hint} -> mod = expand_alias(alias, ctx) complete_module(mod, hint, ctx) end end defp complete_module_member(mod, hint, ctx) do complete_module_function(mod, hint, ctx) ++ complete_module_type(mod, hint, ctx) end defp complete_local_or_var(hint, ctx) do complete_local(hint, ctx) ++ complete_variable(hint, ctx) end defp complete_local(hint, ctx) do imports = ctx.env |> imports_from_env() |> Enum.flat_map(fn {mod, funs} -> complete_module_function(mod, hint, ctx, funs) end) special_forms = complete_module_function(Kernel.SpecialForms, hint, ctx) imports ++ special_forms end defp complete_variable(hint, ctx) do for {key, value} <- ctx.binding, is_atom(key), name = Atom.to_string(key), ctx.matcher.(name, hint), do: {:variable, name, value} end defp complete_map_field(map, hint, ctx) do # Note: we need Map.to_list/1 in case this is a struct for {key, value} <- Map.to_list(map), is_atom(key), name = Atom.to_string(key), ctx.matcher.(name, hint), do: {:map_field, name, value} end defp complete_erlang_module(hint, ctx) do for mod <- get_matching_modules(hint, ctx), usable_as_unquoted_module?(mod), name = ":" <> Atom.to_string(mod), do: {:module, name, get_module_doc_content(mod)} end # Converts alias string to module atom with regard to the given env defp expand_alias(alias, ctx) do [name | rest] = alias |> String.split(".") |> Enum.map(&String.to_atom/1) case Keyword.fetch(ctx.env.aliases, Module.concat(Elixir, name)) do {:ok, name} when rest == [] -> name {:ok, name} -> Module.concat([name | rest]) :error -> Module.concat([name | rest]) end end defp complete_env_alias(hint, ctx) do for {alias, mod} <- ctx.env.aliases, [name] = Module.split(alias), ctx.matcher.(name, hint), do: {:module, name, get_module_doc_content(mod)} end defp complete_module(base_mod, hint, ctx) do # Note: we specifically don't want further completion # if `base_mod` is an Erlang module. if base_mod == Elixir or elixir_module?(base_mod) do complete_elixir_module(base_mod, hint, ctx) else [] end end defp elixir_module?(mod) do mod |> Atom.to_string() |> String.starts_with?("Elixir.") end defp complete_elixir_root_module(hint, ctx) do items = complete_elixir_module(Elixir, hint, ctx) # `Elixir` is not a existing module name, but `Elixir.Enum` is, # so if the user types `Eli` the completion should include `Elixir`. if ctx.matcher.("Elixir", hint) do [{:module, "Elixir", nil} | items] else items end end defp complete_elixir_module(base_mod, hint, ctx) do # Note: `base_mod` may be `Elixir`, even though it's not a valid module match_prefix = "#{base_mod}.#{hint}" depth = match_prefix |> Module.split() |> length() for mod <- get_matching_modules(match_prefix, ctx), parts = Module.split(mod), length(parts) >= depth, name = Enum.at(parts, depth - 1), # Note: module can be defined dynamically and its name # may not be a valid alias (e.g. :"Elixir.My.module"). # That's why we explicitly check if the name part makes # for a alias piece. valid_alias_piece?("." <> name), mod = parts |> Enum.take(depth) |> Module.concat(), uniq: true, do: {:module, name, get_module_doc_content(mod)} end defp valid_alias_piece?(<<?., char, rest::binary>>) when char in ?A..?Z, do: valid_alias_rest?(rest) defp valid_alias_piece?(_), do: false defp valid_alias_rest?(<<char, rest::binary>>) when char in ?A..?Z when char in ?a..?z when char in ?0..?9 when char == ?_, do: valid_alias_rest?(rest) defp valid_alias_rest?(<<>>), do: true defp valid_alias_rest?(rest), do: valid_alias_piece?(rest) defp usable_as_unquoted_module?(mod) do Code.Identifier.classify(mod) != :other end defp get_matching_modules(hint, ctx) do get_modules() |> Enum.filter(&ctx.matcher.(Atom.to_string(&1), hint)) |> Enum.uniq() end defp get_modules() do modules = Enum.map(:code.all_loaded(), &elem(&1, 0)) case :code.get_mode() do :interactive -> modules ++ get_modules_from_applications() _otherwise -> modules end end defp get_modules_from_applications do for [app] <- loaded_applications(), {:ok, modules} = :application.get_key(app, :modules), module <- modules, do: module end defp loaded_applications do # If we invoke :application.loaded_applications/0, # it can error if we don't call safe_fixtable before. # Since in both cases we are reaching over the # application controller internals, we choose to match # for performance. :ets.match(:ac_tab, {{:loaded, :"$1"}, :_}) end defp complete_module_function(mod, hint, ctx, funs \\ nil) do if ensure_loaded?(mod) do {format, docs} = get_docs(mod, [:function, :macro]) specs = get_specs(mod) funs = funs || exports(mod) funs_with_base_arity = funs_with_base_arity(docs) funs |> Enum.filter(fn {name, _arity} -> name = Atom.to_string(name) ctx.matcher.(name, hint) end) |> Enum.map(fn {name, arity} -> base_arity = Map.get(funs_with_base_arity, {name, arity}, arity) doc = find_doc(docs, {name, base_arity}) spec = find_spec(specs, {name, base_arity}) doc_content = doc_content(doc, format) signatures = doc_signatures(doc) {:function, mod, Atom.to_string(name), arity, doc_content, signatures, spec} end) else [] end end # If a function has default arguments it generates less-arity functions, # but they have the same docs/specs as the original function. # Here we build a map that given function {name, arity} returns its base arity. defp funs_with_base_arity(docs) do for {{_, fun_name, arity}, _, _, _, metadata} <- docs, count = Map.get(metadata, :defaults, 0), count > 0, new_arity <- (arity - count)..(arity - 1), into: %{}, do: {{fun_name, new_arity}, arity} end defp get_docs(mod, kinds) do case Code.fetch_docs(mod) do {:docs_v1, _, _, format, _, _, docs} -> docs = for {{kind, _, _}, _, _, _, _} = doc <- docs, kind in kinds, do: doc {format, docs} _ -> {nil, []} end end defp get_module_doc_content(mod) do case Code.fetch_docs(mod) do {:docs_v1, _, _, format, %{"en" => docstring}, _, _} -> {format, docstring} _ -> nil end end defp find_doc(docs, {name, arity}) do Enum.find(docs, &match?({{_, ^name, ^arity}, _, _, _, _}, &1)) end defp get_specs(mod) do case Code.Typespec.fetch_specs(mod) do {:ok, specs} -> specs :error -> [] end end defp find_spec(specs, {name, arity}) do Enum.find(specs, &match?({{^name, ^arity}, _}, &1)) end defp doc_signatures({_, _, signatures, _, _}), do: signatures defp doc_signatures(_), do: [] defp doc_content({_, _, _, %{"en" => docstr}, _}, format), do: {format, docstr} defp doc_content(_doc, _format), do: nil defp exports(mod) do if Code.ensure_loaded?(mod) and function_exported?(mod, :__info__, 1) do mod.__info__(:macros) ++ (mod.__info__(:functions) -- [__info__: 1]) else mod.module_info(:exports) -- [module_info: 0, module_info: 1] end end defp complete_module_type(mod, hint, ctx) do {format, docs} = get_docs(mod, [:type]) types = get_module_types(mod) types |> Enum.filter(fn {name, _arity} -> name = Atom.to_string(name) ctx.matcher.(name, hint) end) |> Enum.map(fn {name, arity} -> doc = find_doc(docs, {name, arity}) doc_content = doc_content(doc, format) {:type, mod, Atom.to_string(name), arity, doc_content} end) end defp get_module_types(mod) do with true <- ensure_loaded?(mod), {:ok, types} <- Code.Typespec.fetch_types(mod) do for {kind, {name, _, args}} <- types, kind in [:type, :opaque] do {name, length(args)} end else _ -> [] end end defp ensure_loaded?(Elixir), do: false defp ensure_loaded?(mod), do: Code.ensure_loaded?(mod) defp imports_from_env(env), do: env.functions ++ env.macros defp split_at_last_occurrence(string, pattern) do case :binary.matches(string, pattern) do [] -> {string, ""} parts -> {start, _} = List.last(parts) size = byte_size(string) {binary_part(string, 0, start), binary_part(string, start + 1, size - start - 1)} end end defp complete_module_attribute(hint, ctx) do for {attribute, info} <- Module.reserved_attributes(), name = Atom.to_string(attribute), ctx.matcher.(name, hint), do: {:module_attribute, name, {"text/markdown", info.doc}} end end
29.589011
92
0.625863
08f218b363e887d9b78a85e73595e03acd803580
107
exs
Elixir
elixir/12.exs
merxer/kata
5dbbca8b4173029f9311398148de9437a329cf9a
[ "MIT" ]
null
null
null
elixir/12.exs
merxer/kata
5dbbca8b4173029f9311398148de9437a329cf9a
[ "MIT" ]
null
null
null
elixir/12.exs
merxer/kata
5dbbca8b4173029f9311398148de9437a329cf9a
[ "MIT" ]
null
null
null
a = 1 IO.puts a [^a, 2, 3] = [1, 2, 3] IO.puts a a = 2 IO.puts a #[^a, 2] = [1, 2] #Raise Match Error
8.230769
36
0.46729
08f233a07a905477a56de8513c6e5945dcbc7305
1,773
ex
Elixir
clients/discovery/lib/google_api/discovery/v1/model/rest_method_media_upload_protocols_simple.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/discovery/lib/google_api/discovery/v1/model/rest_method_media_upload_protocols_simple.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/discovery/lib/google_api/discovery/v1/model/rest_method_media_upload_protocols_simple.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2018 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.Discovery.V1.Model.RestMethodMediaUploadProtocolsSimple do @moduledoc """ Supports uploading as a single HTTP request. ## Attributes - multipart (boolean()): True if this endpoint supports upload multipart media. Defaults to: `null`. - path (String.t): The URI path to be used for upload. Should be used in conjunction with the basePath property at the api-level. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :multipart => any(), :path => any() } field(:multipart) field(:path) end defimpl Poison.Decoder, for: GoogleApi.Discovery.V1.Model.RestMethodMediaUploadProtocolsSimple do def decode(value, options) do GoogleApi.Discovery.V1.Model.RestMethodMediaUploadProtocolsSimple.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Discovery.V1.Model.RestMethodMediaUploadProtocolsSimple do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.764706
152
0.749577
08f246a55e2a62e62426cdd3296cf1677443f9c2
3,480
ex
Elixir
lib/mix/lib/mix/shell.ex
jovannypcg/elixir
de3f5df7fdcda79e2661f9cee6005707e7e8d030
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/shell.ex
jovannypcg/elixir
de3f5df7fdcda79e2661f9cee6005707e7e8d030
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/shell.ex
jovannypcg/elixir
de3f5df7fdcda79e2661f9cee6005707e7e8d030
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Shell do @moduledoc """ Defines `Mix.Shell` contract. """ @doc """ Informs the given message. """ @callback info(message :: IO.ANSI.ansidata) :: any @doc """ Warns about the given error message. """ @callback error(message :: IO.ANSI.ansidata) :: any @doc """ Prompts the user for input. """ @callback prompt(message :: String.t) :: String.t @doc """ Asks the user for confirmation. """ @callback yes?(message :: String.t) :: boolean @doc """ Executes the given command and returns its exit status. """ @callback cmd(command :: String.t) :: integer @doc """ Executes the given command and returns its exit status. ## Options * `:print_app` - when `false`, does not print the app name when the command outputs something * `:stderr_to_stdout` - when `false`, does not redirect stderr to stdout * `:quiet` - when `true`, do not print the command output * `:env` - environment options to the executed command """ @callback cmd(command :: String.t, options :: Keyword.t) :: integer @doc """ Prints the current application to shell if it was not printed yet. """ @callback print_app() :: any @doc """ Returns the printable app name. This function returns the current application name but only if the application name should be printed. Calling this function automatically toggles its value to `false` until the current project is re-entered. The goal is to exactly avoid printing the application name multiple times. """ def printable_app_name do Mix.ProjectStack.printable_app_name end @doc """ An implementation of the command callback that is shared across different shells. """ def cmd(command, options \\ [], callback) do env = validate_env(Keyword.get(options, :env, [])) args = if Keyword.get(options, :stderr_to_stdout, true) do [:stderr_to_stdout] else [] end callback = if Keyword.get(options, :quiet, false) do fn x -> x end else callback end port = Port.open({:spawn, shell_command(command)}, [:stream, :binary, :exit_status, :hide, :use_stdio, {:env, env}|args]) do_cmd(port, callback) end defp do_cmd(port, callback) do receive do {^port, {:data, data}} -> callback.(data) do_cmd(port, callback) {^port, {:exit_status, status}} -> status end end # Finding shell command logic from :os.cmd in OTP # https://github.com/erlang/otp/blob/8deb96fb1d017307e22d2ab88968b9ef9f1b71d0/lib/kernel/src/os.erl#L184 defp shell_command(command) do case :os.type do {:unix, _} -> command = command |> String.replace("\"", "\\\"") |> String.to_char_list 'sh -c "' ++ command ++ '"' {:win32, osname} -> command = '"' ++ String.to_char_list(command) ++ '"' case {System.get_env("COMSPEC"), osname} do {nil, :windows} -> 'command.com /s /c ' ++ command {nil, _} -> 'cmd /s /c ' ++ command {cmd, _} -> '#{cmd} /s /c ' ++ command end end end defp validate_env(enum) do Enum.map enum, fn {k, nil} -> {String.to_char_list(k), false} {k, v} -> {String.to_char_list(k), String.to_char_list(v)} other -> raise ArgumentError, "invalid environment key-value #{inspect other}" end end end
25.217391
106
0.606609
08f26b08e493b901db69f1907f7feeee4f35031a
1,365
ex
Elixir
lib/nodeping/helpers.ex
stratacast/nodeping_elixir
11ad20e7da3a43dfe6c8322223c6a54c1025c405
[ "MIT" ]
null
null
null
lib/nodeping/helpers.ex
stratacast/nodeping_elixir
11ad20e7da3a43dfe6c8322223c6a54c1025c405
[ "MIT" ]
null
null
null
lib/nodeping/helpers.ex
stratacast/nodeping_elixir
11ad20e7da3a43dfe6c8322223c6a54c1025c405
[ "MIT" ]
null
null
null
defmodule NodePing.Helpers do @moduledoc """ Helper functions for the inner workings of of elixir library for the NodePing API """ @doc """ Takes querystrings for a URL and merges them into a single string ## Parameters - `querystrings` - A list of tuples where the first value is an `Atom` for the key, and the second is the value ## Examples iex> NodePing.Helpers.merge_querystrings([{:hello, "world"}, {:sample, "data"}]) "?hello=world&sample=data" """ def merge_querystrings(querystrings) when is_list(querystrings) do querystrings |> Enum.filter(fn {_k, v} -> is_nil(v) == false end) |> Enum.reduce("", fn {k, v}, acc -> "&#{Atom.to_string(k)}=#{v}#{acc}" end) |> String.replace_leading("&", "?") end @doc """ Add the customerid to a list if it is not nil """ def add_cust_id(list, customerid) do if is_nil(customerid) do list else list ++ [{:customerid, customerid}] end end @doc """ Combine a struct from a map """ def combine_map_struct(struct, map) when is_map(map) do accepted_user_keys = Map.from_struct(struct) |> Map.keys() |> Enum.filter(fn x -> map[x] end) Enum.filter(map, fn {k, _v} -> Enum.member?(accepted_user_keys, k) end) |> Map.new() |> (&Map.merge(Map.from_struct(struct), &1)).() |> Map.new() end end
27.3
113
0.627106
08f2d65d768a9d78235cf9c95569e6a20e824281
731
ex
Elixir
web/gettext.ex
max-konin/a2billing-rest-api
3f8430caa2b9cbedfbe842e81030c861aa25dd89
[ "MIT" ]
1
2017-08-01T04:31:38.000Z
2017-08-01T04:31:38.000Z
web/gettext.ex
max-konin/a2billing-rest-api
3f8430caa2b9cbedfbe842e81030c861aa25dd89
[ "MIT" ]
null
null
null
web/gettext.ex
max-konin/a2billing-rest-api
3f8430caa2b9cbedfbe842e81030c861aa25dd89
[ "MIT" ]
1
2020-05-05T15:21:59.000Z
2020-05-05T15:21:59.000Z
defmodule A2billingRestApi.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. By using [Gettext](https://hexdocs.pm/gettext), your module gains a set of macros for translations, for example: import A2billingRestApi.Gettext # Simple translation gettext "Here is the string to translate" # Plural translation ngettext "Here is the string to translate", "Here are the strings to translate", 3 # Domain-based translation dgettext "errors", "Here is the error message to translate" See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. """ use Gettext, otp_app: :a2billing_rest_api end
29.24
72
0.690834
08f2fc6c3e1e9602ac87e8c2c9655df12f1e012a
1,611
ex
Elixir
apps/discordbot/lib/discordbot/config_provider.ex
alexweav/discordbot
1ee138f7c42a6901ab769e2ce59a6878bf603290
[ "MIT" ]
4
2018-11-19T06:10:52.000Z
2022-02-03T01:50:23.000Z
apps/discordbot/lib/discordbot/config_provider.ex
alexweav/discordbot
1ee138f7c42a6901ab769e2ce59a6878bf603290
[ "MIT" ]
254
2018-11-19T06:08:51.000Z
2021-07-22T13:47:26.000Z
apps/discordbot/lib/discordbot/config_provider.ex
alexweav/discordbot
1ee138f7c42a6901ab769e2ce59a6878bf603290
[ "MIT" ]
null
null
null
defmodule DiscordBot.ConfigProvider do @moduledoc false # This is a modification of the default Elixir config provider that # ships with Distillery, which allows for optional config files use Distillery.Releases.Config.Provider @impl Provider def init([path]) do started? = ensure_started() try do case Provider.expand_path(path) do {:ok, path} -> if File.exists?(path) do path |> eval!() |> merge_config() |> Mix.Config.persist() else :ok end {:error, _} -> :ok end else _ -> :ok after unless started? do :ok = Application.stop(:mix) end end end def merge_config(runtime_config) do Enum.flat_map(runtime_config, fn {app, app_config} -> all_env = Application.get_all_env(app) Mix.Config.merge([{app, all_env}], [{app, app_config}]) end) end def eval!(path, imported_paths \\ []) Code.ensure_loaded(Mix.Config) if function_exported?(Mix.Config, :eval!, 2) do def eval!(path, imported_paths) do {config, _} = Mix.Config.eval!(path, imported_paths) config end else def eval!(path, imported_paths), do: Mix.Config.read!(path, imported_paths) end defp ensure_started do started? = List.keymember?(Application.started_applications(), :mix, 0) unless started? do :ok = Application.start(:mix) env = System.get_env("MIX_ENV") || "prod" System.put_env("MIX_ENV", env) Mix.env(String.to_atom(env)) end started? end end
23.014286
79
0.607076
08f310eb2ddc6c72a64f250d3d48dbd7e52dfbdd
3,044
ex
Elixir
lib/ash_admin/components/resource/nav.ex
ash-project/ash_admin
d542ca9760ec9ecc9d94ce8d50663214938bce40
[ "MIT" ]
19
2021-03-16T09:01:22.000Z
2022-03-07T06:16:56.000Z
lib/ash_admin/components/resource/nav.ex
ash-project/ash_admin
d542ca9760ec9ecc9d94ce8d50663214938bce40
[ "MIT" ]
11
2021-03-29T15:46:33.000Z
2022-03-17T03:35:57.000Z
lib/ash_admin/components/resource/nav.ex
ash-project/ash_admin
d542ca9760ec9ecc9d94ce8d50663214938bce40
[ "MIT" ]
6
2021-03-27T19:24:52.000Z
2022-03-15T10:19:31.000Z
defmodule AshAdmin.Components.Resource.Nav do @moduledoc false use Surface.Component alias Surface.Components.LiveRedirect alias AshAdmin.Components.TopNav.Dropdown prop(resource, :any, required: true) prop(api, :any, required: true) prop(tab, :string, required: true) prop(action, :any) prop(table, :any, default: nil) prop(prefix, :any, default: nil) def render(assigns) do ~F""" <nav class="bg-gray-800 w-full"> <div class="px-4 sm:px-6 lg:px-8 w-full"> <div class="flex items-center justify-between h-16 w-full"> <div class="flex items-center w-full"> <div class="flex-shrink-0"> <h3 class="text-white text-lg"> <LiveRedirect to={"#{@prefix}?api=#{AshAdmin.Api.name(@api)}&resource=#{AshAdmin.Resource.name(@resource)}"}> {AshAdmin.Resource.name(@resource)} </LiveRedirect> </h3> </div> <div class="w-full"> <div class="ml-12 flex items-center space-x-1"> <div :if={has_create_action?(@resource)} class="relative"> <LiveRedirect to={"#{@prefix}?api=#{AshAdmin.Api.name(@api)}&resource=#{AshAdmin.Resource.name(@resource)}&action_type=create&action=#{Ash.Resource.Info.primary_action(@resource, :create).name}&tab=create&table=#{@table}"} class="inline-flex justify-center w-full rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-100 focus:ring-indigo-500" > Create </LiveRedirect> </div> <Dropdown name="Read" id={"#{@resource}_data_dropdown"} active={@tab == "data"} groups={data_groups(@prefix, @api, @resource, @action, @table)} /> </div> </div> </div> </div> </div> </nav> """ end defp data_groups(prefix, api, resource, current_action, table) do read_actions = AshAdmin.Resource.read_actions(resource) [ resource |> Ash.Resource.Info.actions() |> Enum.filter(&(&1.type == :read)) |> Enum.filter(&(is_nil(read_actions) || &1.name in read_actions)) |> Enum.map(fn action -> %{ text: action_name(action), to: "#{prefix}?api=#{AshAdmin.Api.name(api)}&resource=#{AshAdmin.Resource.name(resource)}&table=#{table}&action_type=read&action=#{action.name}", active: current_action == action } end) ] end defp has_create_action?(resource) do resource |> Ash.Resource.Info.actions() |> Enum.any?(&(&1.type == :create)) end defp action_name(action) do action.name |> to_string() |> String.split("_") |> Enum.map(&String.capitalize/1) |> Enum.join(" ") end end
35.395349
276
0.56636
08f32f5acecf62ef1c926de07031908f1258ca51
2,317
exs
Elixir
programming_elixir_1.3_snippets/enum.exs
benjohns1/elixer-app
6e866ec084c5e75442c0b70f66e35f61b5b74d34
[ "MIT" ]
null
null
null
programming_elixir_1.3_snippets/enum.exs
benjohns1/elixer-app
6e866ec084c5e75442c0b70f66e35f61b5b74d34
[ "MIT" ]
null
null
null
programming_elixir_1.3_snippets/enum.exs
benjohns1/elixer-app
6e866ec084c5e75442c0b70f66e35f61b5b74d34
[ "MIT" ]
null
null
null
# print helper defmodule Debug do def print(value) when is_binary(value), do: IO.puts value def print(value), do: IO.puts "#{inspect value}" def print(value, prefix) when is_binary(value), do: IO.puts "#{prefix}: #{value}" def print(value, prefix), do: IO.puts "#{prefix}: #{inspect value}" end import Debug # concatenate/map list = Enum.to_list 1..5 print(list) Enum.concat([1,2,3], [4,5,6]) |> print Enum.concat([1,2,3], 'abc') |> print Enum.map(list, &(&1 * 10)) |> print Enum.map(list, &String.duplicate("*", &1)) |> print # select elements Enum.at(10..20, 3) |> print Enum.at(10..20, 20) |> print Enum.at(10..20, 20, :no_one_here) |> print Enum.filter(list, &(&1 > 2)) |> print require Integer Enum.filter(list, &Integer.is_even/1) |> print Enum.reject(list, &Integer.is_even/1) |> print # sort and compare sort_list = ["there", "was", "a", "crooked", "man"] Enum.sort(sort_list) |> print Enum.sort(sort_list, &(String.length(&1) <= String.length(&2))) |> print Enum.max(sort_list) |> print Enum.max_by(sort_list, &String.length/1) |> print # split collections Enum.take(list, 3) |> print Enum.take_every(list, 2) |> print Enum.take_while(list, &(&1 < 4)) |> print Enum.split(list, 2) |> print Enum.split_while(list, &(&1 < 4)) |> print list2 = list ++ [4,3,2,1] print(list2) Enum.split_while(list2, &(&1 < 4)) |> print Enum.split_with(list2, &(&1 < 4)) |> print # join collections Enum.join(list) |> print Enum.join(list, ",") |> print # predicate operations Enum.all?(list, &(&1 < 4)) |> print Enum.any?(list, &(&1 < 4)) |> print Enum.member?(list, 4) |> print Enum.empty?(list) |> print # merge operations Enum.zip(list, [:a, :b, :c]) |> print Enum.with_index(["once", "upon", "a", "time"]) |> print # fold elements into single value Enum.reduce(1..100, &(&1 + &2)) |> print Enum.reduce(["now", "is", "the", "time"], fn word, longest -> if String.length(word) > String.length(longest) do word else longest end end) |> print Enum.reduce(["now", "is", "the", "time"], 0, fn word, longest -> if String.length(word) > longest, do: String.length(word), else: longest end) |> print # deal hand of cards import Enum deck = for rank <- '23456789TJQKA', suit <- 'CDHS', do: [suit, rank] print deck deck |> shuffle |> take(13) |> print hands = deck |> shuffle |> chunk(13) print hands
29.329114
83
0.642641
08f3398380255e9795c512dbbe4a0e305199045e
2,623
ex
Elixir
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/client_user.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/client_user.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/client_user.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AdExchangeBuyer.V2beta1.Model.ClientUser do @moduledoc """ A client user is created under a client buyer and has restricted access to the Ad Exchange Marketplace and certain other sections of the Ad Exchange Buyer UI based on the role granted to the associated client buyer. The only way a new client user can be created is via accepting an email invitation (see the accounts.clients.invitations.create method). All fields are required unless otherwise specified. ## Attributes - clientAccountId (String.t): Numerical account ID of the client buyer with which the user is associated; the buyer must be a client of the current sponsor buyer. The value of this field is ignored in an update operation. Defaults to: `null`. - email (String.t): User&#39;s email address. The value of this field is ignored in an update operation. Defaults to: `null`. - status (String.t): The status of the client user. Defaults to: `null`. - Enum - one of [USER_STATUS_UNSPECIFIED, PENDING, ACTIVE, DISABLED] - userId (String.t): The unique numerical ID of the client user that has accepted an invitation. The value of this field is ignored in an update operation. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :clientAccountId => any(), :email => any(), :status => any(), :userId => any() } field(:clientAccountId) field(:email) field(:status) field(:userId) end defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.ClientUser do def decode(value, options) do GoogleApi.AdExchangeBuyer.V2beta1.Model.ClientUser.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.ClientUser do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
45.224138
408
0.743805
08f33d34a3c5a3dce07bc68cf8ef2264c6c6b794
2,020
ex
Elixir
clients/private_ca/lib/google_api/private_ca/v1beta1/model/reusable_config_wrapper.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/private_ca/lib/google_api/private_ca/v1beta1/model/reusable_config_wrapper.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/private_ca/lib/google_api/private_ca/v1beta1/model/reusable_config_wrapper.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.PrivateCA.V1beta1.Model.ReusableConfigWrapper do @moduledoc """ A ReusableConfigWrapper describes values that may assist in creating an X.509 certificate, or a reference to a pre-defined set of values. ## Attributes * `reusableConfig` (*type:* `String.t`, *default:* `nil`) - Required. A resource path to a ReusableConfig in the format `projects/*/locations/*/reusableConfigs/*`. * `reusableConfigValues` (*type:* `GoogleApi.PrivateCA.V1beta1.Model.ReusableConfigValues.t`, *default:* `nil`) - Required. A user-specified inline ReusableConfigValues. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :reusableConfig => String.t() | nil, :reusableConfigValues => GoogleApi.PrivateCA.V1beta1.Model.ReusableConfigValues.t() | nil } field(:reusableConfig) field(:reusableConfigValues, as: GoogleApi.PrivateCA.V1beta1.Model.ReusableConfigValues) end defimpl Poison.Decoder, for: GoogleApi.PrivateCA.V1beta1.Model.ReusableConfigWrapper do def decode(value, options) do GoogleApi.PrivateCA.V1beta1.Model.ReusableConfigWrapper.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.PrivateCA.V1beta1.Model.ReusableConfigWrapper do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.607843
173
0.751485
08f362fa66cb0cb29f7d5e17d30d96b639108356
591
ex
Elixir
apps/service_acquire/lib/acquire/query/where/literal.ex
kennyatpillar/hindsight
e90e2150a14218e5d6fdf5874f57eb055fd2dd07
[ "Apache-2.0" ]
null
null
null
apps/service_acquire/lib/acquire/query/where/literal.ex
kennyatpillar/hindsight
e90e2150a14218e5d6fdf5874f57eb055fd2dd07
[ "Apache-2.0" ]
null
null
null
apps/service_acquire/lib/acquire/query/where/literal.ex
kennyatpillar/hindsight
e90e2150a14218e5d6fdf5874f57eb055fd2dd07
[ "Apache-2.0" ]
null
null
null
defmodule Acquire.Query.Where.Literal do use Definition, schema: Acquire.Query.Where.Literal.V1 @type t :: %__MODULE__{ value: String.Chars.t() } defstruct [:value] defimpl Acquire.Queryable, for: __MODULE__ do def parse_statement(%{value: value}) when is_binary(value) do "'#{value}'" end def parse_statement(%{value: value}) do "#{value}" end def parse_input(_) do [] end end end defmodule Acquire.Query.Where.Literal.V1 do use Definition.Schema def s do schema(%Acquire.Query.Where.Literal{}) end end
18.46875
65
0.646362
08f3962060c7cf715dbb704ef2ee0fcb74be13ad
1,029
ex
Elixir
lib/credo/check/readability/trailing_blank_line.ex
codeclimate-community/credo
b960a25d604b4499a2577321f9d61b39dc4b0437
[ "MIT" ]
null
null
null
lib/credo/check/readability/trailing_blank_line.ex
codeclimate-community/credo
b960a25d604b4499a2577321f9d61b39dc4b0437
[ "MIT" ]
null
null
null
lib/credo/check/readability/trailing_blank_line.ex
codeclimate-community/credo
b960a25d604b4499a2577321f9d61b39dc4b0437
[ "MIT" ]
1
2020-09-25T11:48:49.000Z
2020-09-25T11:48:49.000Z
defmodule Credo.Check.Readability.TrailingBlankLine do @moduledoc false @checkdoc """ Files should end in a trailing blank line. This is mostly for historical reasons: every text file should end with a \\n, or newline since this acts as `eol` or the end of the line character. See also: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_206 Most text editors ensure this "final newline" automatically. """ @explanation [check: @checkdoc] use Credo.Check, base_priority: :low @doc false def run(source_file, params \\ []) do issue_meta = IssueMeta.for(source_file, params) {line_no, last_line} = source_file |> SourceFile.lines() |> List.last() if String.trim(last_line) == "" do [] else [issue_for(issue_meta, line_no)] end end defp issue_for(issue_meta, line_no) do format_issue( issue_meta, message: "There should be a final \\n at the end of each file.", line_no: line_no ) end end
24.5
94
0.6793
08f3eb7b10b7f6c7521fe23917a75d04a2575f91
1,358
ex
Elixir
apps/customer/lib/customer/web/queries/job_title_alias.ex
JaiMali/job_search-1
5fe1afcd80aa5d55b92befed2780cd6721837c88
[ "MIT" ]
102
2017-05-21T18:24:04.000Z
2022-03-10T12:53:20.000Z
apps/customer/lib/customer/web/queries/job_title_alias.ex
JaiMali/job_search-1
5fe1afcd80aa5d55b92befed2780cd6721837c88
[ "MIT" ]
2
2017-05-21T01:53:30.000Z
2017-12-01T00:27:06.000Z
apps/customer/lib/customer/web/queries/job_title_alias.ex
JaiMali/job_search-1
5fe1afcd80aa5d55b92befed2780cd6721837c88
[ "MIT" ]
18
2017-05-22T09:51:36.000Z
2021-09-24T00:57:01.000Z
defmodule Customer.Web.Query.JobTitleAlias do use Customer.Query, model: JobTitleAlias alias Customer.Web.{JobTitle, JobTitleAlias} def get_or_find_approximate_job_title(repo, name) when is_nil(name), do: {:error, name} def get_or_find_approximate_job_title(repo, raw_name) do name = transform_to_string(raw_name) case repo.get_by(JobTitle, name: name) do %JobTitle{id: id} -> {:ok, id} _ -> case repo.get_by(JobTitleAlias, name: name) do %JobTitleAlias{job_title_id: job_title_id} -> {:ok, job_title_id} _ -> find_approximate_job_title(repo.all(JobTitleAlias), name) end end end defp find_approximate_job_title([], name) do {:error, name} end defp find_approximate_job_title([%JobTitleAlias{name: name, job_title_id: job_title_id}| remaining], job_title_name) do if approximate_word?(transform_to_string(name), job_title_name) do {:ok, job_title_id} else find_approximate_job_title(remaining, job_title_name) end end def transform_to_string(word) do word |> String.replace(~r/((,|\(|\.|_|:|\/).*|\s+.(-|–).*| – .*|-\s+.*)/,"") |> String.trim |> String.downcase end @approximate_word_threshold 0.95 defp approximate_word?(word1, word2) do String.jaro_distance(word1, word2) >= @approximate_word_threshold end end
31.581395
121
0.687776
08f3fd186306d309bf85b3db8fce51ca26f43ac4
1,135
ex
Elixir
test/support/conn_case.ex
hrobeers/fran-planner
1f049ad65f5d18991a8abeeb6ba7fb583463630a
[ "BSD-2-Clause" ]
3
2015-07-18T22:21:30.000Z
2015-07-19T16:25:35.000Z
test/support/conn_case.ex
hrobeers/fran-planner
1f049ad65f5d18991a8abeeb6ba7fb583463630a
[ "BSD-2-Clause" ]
null
null
null
test/support/conn_case.ex
hrobeers/fran-planner
1f049ad65f5d18991a8abeeb6ba7fb583463630a
[ "BSD-2-Clause" ]
null
null
null
defmodule FranAppBackend.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 imports other functionality to make it easier to build and query models. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest # Alias the data repository and import query/model functions alias FranAppBackend.Repo import Ecto.Model import Ecto.Query, only: [from: 2] # Import URL helpers from the router import FranAppBackend.Router.Helpers # The default endpoint for testing @endpoint FranAppBackend.Endpoint end end setup tags do unless tags[:async] do Ecto.Adapters.SQL.restart_test_transaction(FranAppBackend.Repo, []) end :ok end end
25.795455
73
0.7163
08f414dfa90abf49db2afd8974d7f82eb1f94787
1,125
exs
Elixir
config/config.exs
EssenceOfChaos/exmarket
b4500efdb3fa4ffa2394d2f020102c1932a8416f
[ "MIT" ]
2
2019-04-24T02:58:12.000Z
2019-04-24T19:40:43.000Z
config/config.exs
mkwalker4/exmarket
d5227654f1b57c281cffc07f348477dc6abbfb84
[ "MIT" ]
null
null
null
config/config.exs
mkwalker4/exmarket
d5227654f1b57c281cffc07f348477dc6abbfb84
[ "MIT" ]
1
2019-04-24T03:07:43.000Z
2019-04-24T03:07:43.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 # third-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :exmarket, key: :value # # and access this configuration in your application as: # # Application.get_env(:exmarket, :key) # # You can also configure a third-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # import_config "#{Mix.env()}.exs"
36.290323
73
0.755556
08f41e449caa9ac12505397b9964716aa99a341f
2,326
ex
Elixir
clients/billing_budgets/lib/google_api/billing_budgets/v1beta1/model/google_cloud_billing_budgets_v1beta1_threshold_rule.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/billing_budgets/lib/google_api/billing_budgets/v1beta1/model/google_cloud_billing_budgets_v1beta1_threshold_rule.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/billing_budgets/lib/google_api/billing_budgets/v1beta1/model/google_cloud_billing_budgets_v1beta1_threshold_rule.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.BillingBudgets.V1beta1.Model.GoogleCloudBillingBudgetsV1beta1ThresholdRule do @moduledoc """ ThresholdRule contains a definition of a threshold which triggers an alert (a notification of a threshold being crossed) to be sent when spend goes above the specified amount. Alerts are automatically e-mailed to users with the Billing Account Administrator role or the Billing Account User role. The thresholds here have no effect on notifications sent to anything configured under `Budget.all_updates_rule`. ## Attributes * `spendBasis` (*type:* `String.t`, *default:* `nil`) - Optional. The type of basis used to determine if spend has passed the threshold. Behavior defaults to CURRENT_SPEND if not set. * `thresholdPercent` (*type:* `float()`, *default:* `nil`) - Required. Send an alert when this threshold is exceeded. This is a 1.0-based percentage, so 0.5 = 50%. Validation: non-negative number. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :spendBasis => String.t(), :thresholdPercent => float() } field(:spendBasis) field(:thresholdPercent) end defimpl Poison.Decoder, for: GoogleApi.BillingBudgets.V1beta1.Model.GoogleCloudBillingBudgetsV1beta1ThresholdRule do def decode(value, options) do GoogleApi.BillingBudgets.V1beta1.Model.GoogleCloudBillingBudgetsV1beta1ThresholdRule.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.BillingBudgets.V1beta1.Model.GoogleCloudBillingBudgetsV1beta1ThresholdRule do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.290909
411
0.759243
08f41fc54aabca83a1559d72fa58231df5bc16d2
978
ex
Elixir
lib/speak/backends/espeak_backend.ex
ConnorRigby/elixir_speak
d800864f2aeeaf7440d81045185ca37913e96e0a
[ "MIT" ]
1
2018-03-08T23:46:40.000Z
2018-03-08T23:46:40.000Z
lib/speak/backends/espeak_backend.ex
ConnorRigby/elixir_speak
d800864f2aeeaf7440d81045185ca37913e96e0a
[ "MIT" ]
null
null
null
lib/speak/backends/espeak_backend.ex
ConnorRigby/elixir_speak
d800864f2aeeaf7440d81045185ca37913e96e0a
[ "MIT" ]
null
null
null
defmodule Speak.EspeakBackend do @moduledoc """ Simple espeak port wrapper. """ require Logger @behaviour Speak.Backend @impl Speak.Backend def open(opts) do exe = Keyword.get(opts, :executable, System.find_executable("espeak")) if exe do port_opts = [ :binary, :exit_status, :stderr_to_stdout ] port = Port.open({:spawn_executable, exe}, port_opts) pid = spawn(__MODULE__, :handle_espeak, [port]) {:ok, pid} else {:error, :no_exe} end end @impl Speak.Backend def close(backend) do send(backend, :close) :ok end @impl Speak.Backend def speak(backend, text) do send(backend, {:speak, text}) :ok end def handle_espeak(port) do receive do {:speak, text} -> Port.command(port, text <> "\n") handle_espeak(port) info -> Logger.info("Unhandled info: #{inspect(info)}") handle_espeak(port) end end end
19.176471
74
0.59816
08f44aeb33c4687afcd788c346dbffb4f08eeed7
55
ex
Elixir
web/views/layout_view.ex
diegoangel/todo-app-elixir
7dc8d1734a6435f78a243dc621766f523177eea0
[ "Apache-2.0" ]
1
2017-07-20T17:41:13.000Z
2017-07-20T17:41:13.000Z
web/views/layout_view.ex
robot-overlord/todo-example
2877bf3dc94e857a576fdc922c040c6af2f68ec0
[ "MIT" ]
null
null
null
web/views/layout_view.ex
robot-overlord/todo-example
2877bf3dc94e857a576fdc922c040c6af2f68ec0
[ "MIT" ]
null
null
null
defmodule Todo.LayoutView do use Todo.Web, :view end
13.75
28
0.763636
08f4c81d2092879fc6d47dedd250d71aa42c25b5
426
ex
Elixir
lib/boilertalk_web/views/error_view.ex
matthewess/boilertalk
f8382108e6e029e5cc04f6420d60dd1adafa4c30
[ "MIT" ]
null
null
null
lib/boilertalk_web/views/error_view.ex
matthewess/boilertalk
f8382108e6e029e5cc04f6420d60dd1adafa4c30
[ "MIT" ]
null
null
null
lib/boilertalk_web/views/error_view.ex
matthewess/boilertalk
f8382108e6e029e5cc04f6420d60dd1adafa4c30
[ "MIT" ]
null
null
null
defmodule BoilertalkWeb.ErrorView do use BoilertalkWeb, :view def render("404.json", _assigns) do %{errors: %{detail: "Page not found"}} end def render("500.json", _assigns) do %{errors: %{detail: "Internal server error"}} end # In case no render clause matches or no # template is found, let's render it as 500 def template_not_found(_template, assigns) do render "500.json", assigns end end
23.666667
49
0.690141
08f4dd2e02d3499d48ba4be48595bded083c3307
2,197
ex
Elixir
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/find_devices_by_owner_request.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/find_devices_by_owner_request.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/find_devices_by_owner_request.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AndroidDeviceProvisioning.V1.Model.FindDevicesByOwnerRequest do @moduledoc """ Request to find devices by customers. ## Attributes - customerId ([String.t]): Required. The list of customer IDs to search for. Defaults to: `null`. - limit (String.t): Required. The maximum number of devices to show in a page of results. Must be between 1 and 100 inclusive. Defaults to: `null`. - pageToken (String.t): A token specifying which result page to return. Defaults to: `null`. - sectionType (String.t): Required. The section type of the device&#39;s provisioning record. Defaults to: `null`. - Enum - one of [SECTION_TYPE_UNSPECIFIED, SECTION_TYPE_ZERO_TOUCH] """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :customerId => list(any()), :limit => any(), :pageToken => any(), :sectionType => any() } field(:customerId, type: :list) field(:limit) field(:pageToken) field(:sectionType) end defimpl Poison.Decoder, for: GoogleApi.AndroidDeviceProvisioning.V1.Model.FindDevicesByOwnerRequest do def decode(value, options) do GoogleApi.AndroidDeviceProvisioning.V1.Model.FindDevicesByOwnerRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AndroidDeviceProvisioning.V1.Model.FindDevicesByOwnerRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.616667
149
0.736004
08f52b1df7efcfa704f5be4609c289fed6960599
458
exs
Elixir
integration_test/cases/browser/hover_test.exs
shiroyasha/wallaby
a81c66c143cd4827735c0d708ceae8bde91668c0
[ "MIT" ]
null
null
null
integration_test/cases/browser/hover_test.exs
shiroyasha/wallaby
a81c66c143cd4827735c0d708ceae8bde91668c0
[ "MIT" ]
null
null
null
integration_test/cases/browser/hover_test.exs
shiroyasha/wallaby
a81c66c143cd4827735c0d708ceae8bde91668c0
[ "MIT" ]
null
null
null
defmodule Wallaby.Integration.Browser.HoverTest do use Wallaby.Integration.SessionCase, async: true setup %{session: session} do {:ok, page: visit(session, "hover.html")} end describe "hover/2" do test "hovers over the specified element", %{page: page} do refute page |> visible?(Query.text("HI")) assert page |> hover(Query.css(".group")) |> visible?(Query.text("HI")) end end end
24.105263
62
0.60917
08f578b337440dcde762f616a222323c9968e680
779
ex
Elixir
lib/phoenix_tutorial/endpoint.ex
kenshin23/phoenix_tutorial
d6118d0c2a1077b9e39438c1e8fff3cb2965551d
[ "MIT" ]
null
null
null
lib/phoenix_tutorial/endpoint.ex
kenshin23/phoenix_tutorial
d6118d0c2a1077b9e39438c1e8fff3cb2965551d
[ "MIT" ]
null
null
null
lib/phoenix_tutorial/endpoint.ex
kenshin23/phoenix_tutorial
d6118d0c2a1077b9e39438c1e8fff3cb2965551d
[ "MIT" ]
null
null
null
defmodule PhoenixTutorial.Endpoint do use Phoenix.Endpoint, otp_app: :phoenix_tutorial # Serve at "/" the given assets from "priv/static" directory plug Plug.Static, at: "/", from: :phoenix_tutorial, only: ~w(css images js favicon.ico robots.txt) plug Plug.Logger # Code reloading will only work if the :code_reloader key of # the :phoenix application is set to true in your config file. plug Phoenix.CodeReloader plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Poison plug Plug.MethodOverride plug Plug.Head plug Plug.Session, store: :cookie, key: "_phoenix_tutorial_key", signing_salt: "vKYtZ4ik", encryption_salt: "Uz16uB7E" plug :router, PhoenixTutorial.Router end
25.129032
64
0.707317