hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequence
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequence
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequence
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
031a42ed5eb6a7f09fecee4cec3f56b3006781ee
75
ex
Elixir
web/views/layout_view.ex
matsubara0507/pastry-chef-test
05c0fc3a3864e5469690da980e7bf3d2dbdb3919
[ "MIT" ]
1
2017-09-20T23:46:35.000Z
2017-09-20T23:46:35.000Z
web/views/layout_view.ex
matsubara0507/pastry-chef-test
05c0fc3a3864e5469690da980e7bf3d2dbdb3919
[ "MIT" ]
null
null
null
web/views/layout_view.ex
matsubara0507/pastry-chef-test
05c0fc3a3864e5469690da980e7bf3d2dbdb3919
[ "MIT" ]
null
null
null
defmodule PastryChefTest.LayoutView do use PastryChefTest.Web, :view end
18.75
38
0.826667
031a5809549cdde4e691aeb1b223b343a29411c1
2,809
ex
Elixir
year_2019/lib/day_10/asteroids.ex
bschmeck/advent_of_code
cbec98019c6c00444e0f4c7e15e01b1ed9ae6145
[ "MIT" ]
null
null
null
year_2019/lib/day_10/asteroids.ex
bschmeck/advent_of_code
cbec98019c6c00444e0f4c7e15e01b1ed9ae6145
[ "MIT" ]
null
null
null
year_2019/lib/day_10/asteroids.ex
bschmeck/advent_of_code
cbec98019c6c00444e0f4c7e15e01b1ed9ae6145
[ "MIT" ]
null
null
null
defmodule Day10.Asteroids do def run(1) do 10 |> InputFile.contents_of |> String.split("\n") |> Day10.Asteroids.parse |> Day10.Asteroids.counts |> Enum.map(fn({loc, set}) -> {MapSet.size(set), loc} end) |> Enum.max |> IO.puts end def run(2) do 10 |> InputFile.contents_of |> String.split("\n") |> Day10.Asteroids.parse |> Day10.Asteroids.vaporize({22, 25}, 200) |> IO.inspect end def parse(lines), do: parse(lines, 0, []) def parse([], _lnum, locs), do: locs def parse([line | rest], lnum, locs), do: parse(rest, lnum + 1, parse_line(line, lnum, 0, locs)) def parse_line("", _lnum, _pos, locs), do: locs def parse_line("." <> rest, lnum, pos, locs), do: parse_line(rest, lnum, pos + 1, locs) def parse_line("#" <> rest, lnum, pos, locs), do: parse_line(rest, lnum, pos + 1, [{pos, lnum} | locs]) def pairs([elt | rest]), do: pairs(elt, rest, rest, []) defp pairs(_elt, [], [], ret), do: ret defp pairs(_, [], [elt | rest], ret), do: pairs(elt, rest, rest, ret) defp pairs(elt, [p | rest], next, ret), do: pairs(elt, rest, next, [{elt, p} | ret]) def counts(locations) do locations |> Enum.sort |> pairs |> compute_counts(%{}) end def vaporize(locations, origin, n) do map = coord_map(origin, locations, %{}) angles = Map.keys(map) |> Enum.sort |> Enum.reverse do_vaporize(angles, [], map, n) end defp do_vaporize([], next, map, n), do: do_vaporize(Enum.reverse(next), [], map, n) defp do_vaporize([angle | rest], next, map, n) do case Map.get(map, angle) do [] -> do_vaporize(rest, next, map, n) [{_distance, point} | asteroids] -> if n == 1 do point else map = Map.put(map, angle, asteroids) do_vaporize(rest, [angle | next], map, n - 1) end end end def coord_map(_origin, [], map), do: map def coord_map(origin, [origin | rest], map), do: coord_map(origin, rest, map) def coord_map(origin, [p | rest], map) do {angle, distance} = coords_of(origin, p) l = [{distance, p} | Map.get(map, angle, [])] |> Enum.sort coord_map(origin, rest, Map.put(map, angle, l)) end def coords_of({o_x, o_y} = origin, {p_x, p_y} = point) do { angle_of(origin, point), :math.sqrt(:math.pow(p_x - o_x, 2) + :math.pow(p_y - o_y, 2)) } end defp compute_counts([], map), do: map defp compute_counts([{a, b} | rest], map) do a_to_b = angle_of(a, b) b_to_a = angle_of(b, a) map = map |> Map.update(a, MapSet.new([a_to_b]), &(MapSet.put(&1, a_to_b))) |> Map.update(b, MapSet.new([b_to_a]), &(MapSet.put(&1, b_to_a))) compute_counts(rest, map) end defp angle_of({origin_x, origin_y}, {p_x, p_y}) do ElixirMath.atan2(p_x - origin_x, p_y - origin_y) end end
31.920455
105
0.589534
031a5d9cd4b495575caf61c4abf14090db1f3ec5
467
exs
Elixir
config/test.exs
spawnfest/spawn_api
e99dbc20dfc5ff18747efc0c2dafbecdf577707c
[ "MIT" ]
2
2018-12-19T16:12:41.000Z
2020-01-20T17:37:15.000Z
config/test.exs
spawnfest/spawn_api
e99dbc20dfc5ff18747efc0c2dafbecdf577707c
[ "MIT" ]
null
null
null
config/test.exs
spawnfest/spawn_api
e99dbc20dfc5ff18747efc0c2dafbecdf577707c
[ "MIT" ]
null
null
null
use Mix.Config # We don't run a server during test. If one is required, # you can enable the server option below. config :spawn_api, SpawnApiWeb.Endpoint, http: [port: 4002], server: false # Print only warnings and errors during test config :logger, level: :warn # Configure your database config :spawn_api, SpawnApi.Repo, username: "postgres", password: "postgres", database: "spawn_api_test", hostname: "localhost", pool: Ecto.Adapters.SQL.Sandbox
24.578947
56
0.736617
031a62b812d8fdeb9daf26ac45a3653e953d66d8
15,801
exs
Elixir
apps/ewallet_api/test/ewallet_api/v1/controllers/transaction_request_controller_test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
322
2018-02-28T07:38:44.000Z
2020-05-27T23:09:55.000Z
apps/ewallet_api/test/ewallet_api/v1/controllers/transaction_request_controller_test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
643
2018-02-28T12:05:20.000Z
2020-05-22T08:34:38.000Z
apps/ewallet_api/test/ewallet_api/v1/controllers/transaction_request_controller_test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
63
2018-02-28T10:57:06.000Z
2020-05-27T23:10:38.000Z
# Copyright 2018-2019 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule EWalletAPI.V1.TransactionRequestControllerTest do use EWalletAPI.ConnCase, async: true alias EWallet.Web.V1.{TokenSerializer, UserSerializer} alias EWalletDB.{Repo, TransactionRequest, User} alias Utils.Helpers.DateFormatter describe "/me.create_transaction_request" do test "creates a transaction request with all the params" do user = get_test_user() token = insert(:token) wallet = User.get_primary_wallet(user) response = client_request("/me.create_transaction_request", %{ type: "send", token_id: token.id, correlation_id: "123", amount: 1_000, address: wallet.address, max_consumptions: 3, max_consumptions_per_user: 1 }) request = TransactionRequest |> Repo.all() |> Enum.at(0) assert response == %{ "success" => true, "version" => "1", "data" => %{ "object" => "transaction_request", "amount" => 1_000, "address" => wallet.address, "correlation_id" => "123", "id" => request.id, "formatted_id" => request.id, "socket_topic" => "transaction_request:#{request.id}", "token_id" => token.id, "token" => token |> TokenSerializer.serialize() |> stringify_keys(), "type" => "send", "status" => "valid", "user_id" => user.id, "user" => user |> UserSerializer.serialize() |> stringify_keys(), "account_id" => nil, "account" => nil, "exchange_account" => nil, "exchange_account_id" => nil, "exchange_wallet" => nil, "exchange_wallet_address" => nil, "allow_amount_override" => true, "require_confirmation" => false, "consumption_lifetime" => nil, "metadata" => %{}, "encrypted_metadata" => %{}, "expiration_date" => nil, "expiration_reason" => nil, "expired_at" => nil, "max_consumptions" => 3, "max_consumptions_per_user" => 1, "max_consumptions_per_interval" => nil, "max_consumptions_per_interval_per_user" => nil, "consumption_interval_duration" => nil, "current_consumptions_count" => 0, "created_at" => DateFormatter.to_iso8601(request.inserted_at), "updated_at" => DateFormatter.to_iso8601(request.updated_at) } } end test "creates a transaction request with the minimum params" do user = get_test_user() token = insert(:token) wallet = User.get_primary_wallet(user) response = client_request("/me.create_transaction_request", %{ type: "send", token_id: token.id }) request = TransactionRequest |> Repo.all() |> Enum.at(0) assert response == %{ "success" => true, "version" => "1", "data" => %{ "object" => "transaction_request", "amount" => nil, "address" => wallet.address, "correlation_id" => nil, "id" => request.id, "formatted_id" => request.id, "socket_topic" => "transaction_request:#{request.id}", "token_id" => token.id, "token" => token |> TokenSerializer.serialize() |> stringify_keys(), "allow_amount_override" => true, "require_confirmation" => false, "consumption_lifetime" => nil, "metadata" => %{}, "encrypted_metadata" => %{}, "expiration_date" => nil, "expiration_reason" => nil, "expired_at" => nil, "max_consumptions" => nil, "max_consumptions_per_user" => nil, "max_consumptions_per_interval" => nil, "max_consumptions_per_interval_per_user" => nil, "consumption_interval_duration" => nil, "current_consumptions_count" => 0, "type" => "send", "status" => "valid", "user_id" => user.id, "user" => user |> UserSerializer.serialize() |> stringify_keys(), "account_id" => nil, "account" => nil, "exchange_account" => nil, "exchange_account_id" => nil, "exchange_wallet" => nil, "exchange_wallet_address" => nil, "created_at" => DateFormatter.to_iso8601(request.inserted_at), "updated_at" => DateFormatter.to_iso8601(request.updated_at) } } end test "creates a transaction request with nil address" do user = get_test_user() token = insert(:token) wallet = User.get_primary_wallet(user) response = client_request("/me.create_transaction_request", %{ type: "send", token_id: token.id, address: nil }) request = TransactionRequest |> Repo.all() |> Enum.at(0) assert response == %{ "success" => true, "version" => "1", "data" => %{ "object" => "transaction_request", "amount" => nil, "address" => wallet.address, "correlation_id" => nil, "id" => request.id, "formatted_id" => request.id, "socket_topic" => "transaction_request:#{request.id}", "token_id" => token.id, "token" => token |> TokenSerializer.serialize() |> stringify_keys(), "allow_amount_override" => true, "require_confirmation" => false, "consumption_lifetime" => nil, "metadata" => %{}, "encrypted_metadata" => %{}, "expiration_date" => nil, "expiration_reason" => nil, "expired_at" => nil, "max_consumptions" => nil, "max_consumptions_per_user" => nil, "max_consumptions_per_interval" => nil, "max_consumptions_per_interval_per_user" => nil, "consumption_interval_duration" => nil, "current_consumptions_count" => 0, "type" => "send", "status" => "valid", "user_id" => user.id, "user" => user |> UserSerializer.serialize() |> stringify_keys(), "account_id" => nil, "account" => nil, "exchange_account" => nil, "exchange_account_id" => nil, "exchange_wallet" => nil, "exchange_wallet_address" => nil, "created_at" => DateFormatter.to_iso8601(request.inserted_at), "updated_at" => DateFormatter.to_iso8601(request.updated_at) } } end test "receives an error when the type is invalid" do token = insert(:token) response = client_request("/me.create_transaction_request", %{ type: "fake", token_id: token.id, correlation_id: nil, amount: nil, address: nil }) assert response == %{ "success" => false, "version" => "1", "data" => %{ "code" => "client:invalid_parameter", "description" => "Invalid parameter provided. `type` is invalid.", "messages" => %{"type" => ["inclusion"]}, "object" => "error" } } end test "receives an 'unauthorized' error when the address is invalid" do token = insert(:token) response = client_request("/me.create_transaction_request", %{ type: "send", token_id: token.id, correlation_id: nil, amount: nil, address: "fake000000000000" }) refute response["success"] assert response["data"]["code"] == "unauthorized" end test "receives an 'unauthorized' error when the address does not belong to the user" do token = insert(:token) wallet = insert(:wallet) response = client_request("/me.create_transaction_request", %{ type: "send", token_id: token.id, correlation_id: nil, amount: nil, address: wallet.address }) refute response["success"] assert response["data"]["code"] == "unauthorized" end test "receives an 'unauthorized' error when the token ID is not found" do response = client_request("/me.create_transaction_request", %{ type: "send", token_id: "123", correlation_id: nil, amount: nil, address: nil }) refute response["success"] assert response["data"]["code"] == "unauthorized" end test "generates an activity log" do user = get_test_user() token = insert(:token) wallet = User.get_primary_wallet(user) timestamp = DateTime.utc_now() response = client_request("/me.create_transaction_request", %{ type: "send", token_id: token.id }) assert response["success"] == true request = TransactionRequest.get(response["data"]["id"]) logs = get_all_activity_logs_since(timestamp) assert Enum.count(logs) == 2 logs |> Enum.at(0) |> assert_activity_log( action: "insert", originator: user, target: request, changes: %{ "token_uuid" => token.uuid, "type" => "send", "user_uuid" => user.uuid, "wallet_address" => wallet.address }, encrypted_changes: %{} ) logs |> Enum.at(1) |> assert_activity_log( action: "update", originator: :system, target: request, changes: %{"consumptions_count" => 0}, encrypted_changes: %{} ) end end describe "/me.get_transaction_request" do test "returns the transaction request" do transaction_request = insert(:transaction_request) response = client_request("/me.get_transaction_request", %{ formatted_id: transaction_request.id }) assert response["success"] == true assert response["data"]["id"] == transaction_request.id end test "returns :invalid_parameter error when id is not given" do response = client_request("/me.get_transaction_request", %{}) refute response["success"] assert response["data"]["object"] == "error" assert response["data"]["code"] == "client:invalid_parameter" assert response["data"]["description"] == "Invalid parameter provided. `formatted_id` is required." end test "returns an 'unauthorized' error when the request ID is not found" do response = client_request("/me.get_transaction_request", %{ formatted_id: "123" }) assert response["success"] == false assert response["data"]["code"] == "unauthorized" end end describe "/me.cancel_transaction_request" do test "receives a transaction_request if the owner cancel with valid transaction_request's id" do user = get_test_user() transaction_request = insert(:transaction_request, user_uuid: user.uuid) before_execution = NaiveDateTime.utc_now() response = client_request("/me.cancel_transaction_request", %{ formatted_id: transaction_request.id }) # Assert the transaction request is valid assert response["success"] == true assert response["data"]["id"] == transaction_request.id assert response["data"]["status"] == TransactionRequest.expired() # Assert there's 1 activity log has been inserted. assert [log] = get_all_activity_logs_since(before_execution) # Assert changes assert log.target_changes == %{ "status" => TransactionRequest.expired(), "expiration_reason" => TransactionRequest.cancelled_transaction_request(), "expired_at" => log.target_changes["expired_at"] } end test "receives an error if the owner cancel with invalid transaction_request's id" do before_execution = NaiveDateTime.utc_now() response = client_request("/me.cancel_transaction_request", %{ formatted_id: "invalid_id" }) assert response == %{ "data" => %{ "code" => "unauthorized", "description" => "You are not allowed to perform the requested operation.", "messages" => nil, "object" => "error" }, "success" => false, "version" => "1" } # Assert there's no activity log. assert get_all_activity_logs_since(before_execution) == [] end test "receives an error if the id is not given" do before_execution = NaiveDateTime.utc_now() response = client_request("/me.cancel_transaction_request", %{}) assert response == %{ "data" => %{ "code" => "client:invalid_parameter", "description" => "Invalid parameter provided. `formatted_id` is required.", "messages" => nil, "object" => "error" }, "success" => false, "version" => "1" } # Assert there's no activity log. assert get_all_activity_logs_since(before_execution) == [] end test "receives an error if the transaction request does not belong to the user" do # Create a transaction request belongs to another user. user_tx_request_owner = insert(:user, %{email: "[email protected]"}) transaction_request = insert(:transaction_request, user_uuid: user_tx_request_owner.uuid) before_execution = NaiveDateTime.utc_now() # The current user request to cancel the transaction request response = client_request("/me.cancel_transaction_request", %{ formatted_id: transaction_request.id }) # Assert the request should failed assert response == %{ "data" => %{ "code" => "unauthorized", "description" => "You are not allowed to perform the requested operation.", "messages" => nil, "object" => "error" }, "success" => false, "version" => "1" } # Assert there's no activity log. assert get_all_activity_logs_since(before_execution) == [] end end end
35.113333
100
0.540599
031a77041e0ce959a4f7fd712105703d4771dfd2
401
ex
Elixir
lib/rocketpay/accounts/deposit.ex
paulop2/Rocketpay-NLW4-Elixir
815b225494077431753f6fec5f09a70392d6a53b
[ "MIT" ]
null
null
null
lib/rocketpay/accounts/deposit.ex
paulop2/Rocketpay-NLW4-Elixir
815b225494077431753f6fec5f09a70392d6a53b
[ "MIT" ]
null
null
null
lib/rocketpay/accounts/deposit.ex
paulop2/Rocketpay-NLW4-Elixir
815b225494077431753f6fec5f09a70392d6a53b
[ "MIT" ]
null
null
null
defmodule Rocketpay.Accounts.Deposit do alias Rocketpay.Accounts.Operation alias Rocketpay.Repo def call(params) do params |> Operation.call(:deposit) |> run_transaction() end defp run_transaction(multi) do case Repo.transaction(multi) do {:error, _operation, reason, _chances} -> {:error, reason} {:ok, %{deposit: account}} -> {:ok, account} end end end
22.277778
64
0.670823
031aab209aa32185f229b9c289d627ab3d67b5b4
2,204
ex
Elixir
clients/you_tube/lib/google_api/you_tube/v3/model/video_content_details_region_restriction.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/you_tube/lib/google_api/you_tube/v3/model/video_content_details_region_restriction.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/you_tube/lib/google_api/you_tube/v3/model/video_content_details_region_restriction.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.YouTube.V3.Model.VideoContentDetailsRegionRestriction do @moduledoc """ DEPRECATED Region restriction of the video. ## Attributes * `allowed` (*type:* `list(String.t)`, *default:* `nil`) - A list of region codes that identify countries where the video is viewable. If this property is present and a country is not listed in its value, then the video is blocked from appearing in that country. If this property is present and contains an empty list, the video is blocked in all countries. * `blocked` (*type:* `list(String.t)`, *default:* `nil`) - A list of region codes that identify countries where the video is blocked. If this property is present and a country is not listed in its value, then the video is viewable in that country. If this property is present and contains an empty list, the video is viewable in all countries. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :allowed => list(String.t()) | nil, :blocked => list(String.t()) | nil } field(:allowed, type: :list) field(:blocked, type: :list) end defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.VideoContentDetailsRegionRestriction do def decode(value, options) do GoogleApi.YouTube.V3.Model.VideoContentDetailsRegionRestriction.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.VideoContentDetailsRegionRestriction do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
44.08
361
0.74637
031ab377a17165c5af379b5ace31ec1e362bcdc0
1,239
ex
Elixir
lib/consul/watch/handler.ex
kiopro/exconsul
a74843ab06e5211380ce1847957b6ed42c1d7941
[ "MIT" ]
3
2018-07-11T08:20:22.000Z
2018-07-21T23:33:44.000Z
lib/consul/watch/handler.ex
kiopro/exconsul
a74843ab06e5211380ce1847957b6ed42c1d7941
[ "MIT" ]
null
null
null
lib/consul/watch/handler.ex
kiopro/exconsul
a74843ab06e5211380ce1847957b6ed42c1d7941
[ "MIT" ]
null
null
null
# # The MIT License (MIT) # # Copyright (c) 2014-2015 Undead Labs, LLC # defmodule Consul.Watch.Handler do @type on_return :: {:ok, term} | :remove_handler @doc """ Handle notifications of Consul Events. When the handler is initially added all prior events will be notified to the handler, subsequent notifications will occur only upon change. See: http://www.consul.io/docs/agent/http.html#event """ @callback handle_consul_events([Consul.Event.t], any) :: on_return defmacro __using__(_) do quote do @behaviour Consul.Watch.Handler use GenEvent @doc false def handle_event({:consul_events, events}, state) do handle_consul_events(events, state) end @doc false def handle_consul_events(_events, state) do {:ok, state} end defoverridable [handle_consul_events: 2] end end # # Public API # @doc """ Notifies handlers attached a Watch's event manager of Consul Events. """ @spec notify_events(GenEvent.manager, [Consul.Event.t]) :: :ok def notify_events(_, []), do: :ok def notify_events(manager, events) when is_pid(manager) and is_list(events) do GenEvent.ack_notify(manager, {:consul_events, events}) end end
24.78
93
0.683616
031abf7704b20f55043e382963d8b17b0098e2ff
3,333
exs
Elixir
test/mix/tasks/ua_inspector/download_test.exs
lessless/ua_inspector
6c01e12f80c629916de0c53ae5950a89dbd5de17
[ "Apache-2.0" ]
null
null
null
test/mix/tasks/ua_inspector/download_test.exs
lessless/ua_inspector
6c01e12f80c629916de0c53ae5950a89dbd5de17
[ "Apache-2.0" ]
null
null
null
test/mix/tasks/ua_inspector/download_test.exs
lessless/ua_inspector
6c01e12f80c629916de0c53ae5950a89dbd5de17
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.UaInspector.DownloadTest do use ExUnit.Case, async: false import ExUnit.CaptureIO alias Mix.Tasks.UaInspector.Download, as: MixTask setup_all do # setup internal testing webserver Application.ensure_all_started(:inets) fixture_path = Path.expand("../../../fixtures", __DIR__) httpd_opts = [ port: 0, server_name: 'ua_inspector_test', server_root: String.to_charlist(fixture_path), document_root: String.to_charlist(fixture_path) ] {:ok, httpd_pid} = :inets.start(:httpd, httpd_opts) # configure app to use testing webserver remote_paths = Application.get_env(:ua_inspector, :remote_path) remote_internal = "http://localhost:#{:httpd.info(httpd_pid)[:port]}/" test_remote_path = [ bot: remote_internal, browser_engine: remote_internal, client: remote_internal, device: remote_internal, os: remote_internal, short_code_map: remote_internal, vendor_fragment: remote_internal ] :ok = Application.put_env(:ua_inspector, :remote_path, test_remote_path) on_exit(fn -> Application.put_env(:ua_inspector, :remote_path, remote_paths) end) end test "aborted download" do Mix.shell(Mix.Shell.IO) console = capture_io(fn -> MixTask.run([]) IO.write("n") end) assert String.contains?(console, "Download aborted") end test "aborted download (quiet)" do Mix.shell(Mix.Shell.IO) console = capture_io(fn -> MixTask.run(["--quiet"]) IO.write("n") end) assert console == "Download databases? [Yn] n" end test "confirmed download" do Mix.shell(Mix.Shell.IO) console = capture_io([capture_prompt: true], fn -> MixTask.run([]) end) assert String.contains?(console, "Download databases? [Yn]") end test "forceable download" do Mix.shell(Mix.Shell.IO) orig_path = Application.get_env(:ua_inspector, :database_path) test_path = Path.expand("../../downloads", __DIR__) console = capture_io(fn -> Application.put_env(:ua_inspector, :database_path, test_path) MixTask.run(["--force"]) Application.put_env(:ua_inspector, :database_path, orig_path) databases = [ UAInspector.Database.Bots, UAInspector.Database.BrowserEngines, UAInspector.Database.Clients, UAInspector.Database.DevicesHbbTV, UAInspector.Database.DevicesRegular, UAInspector.Database.OSs, UAInspector.Database.VendorFragments ] for database <- databases do for {_type, local, _remote} <- database.sources do [test_path, local] |> Path.join() |> File.exists?() |> assert end end maps = [ UAInspector.ShortCodeMap.ClientBrowsers, UAInspector.ShortCodeMap.DeviceBrands, UAInspector.ShortCodeMap.MobileBrowsers, UAInspector.ShortCodeMap.OSs ] for map <- maps do {local, _} = map.source() [test_path, local] |> Path.join() |> File.exists?() |> assert end end) assert String.contains?(console, test_path) File.rm_rf!(test_path) end end
25.06015
76
0.624662
031ac4db2f0d9a24b79175835779b018994b4b4e
6,092
ex
Elixir
lib/confex/resolver.ex
fossabot/confex
dbb08c3755d2813faffb91dd37141aa5374658ee
[ "MIT" ]
null
null
null
lib/confex/resolver.ex
fossabot/confex
dbb08c3755d2813faffb91dd37141aa5374658ee
[ "MIT" ]
null
null
null
lib/confex/resolver.ex
fossabot/confex
dbb08c3755d2813faffb91dd37141aa5374658ee
[ "MIT" ]
null
null
null
defmodule Confex.Resolver do @moduledoc """ This module provides API to recursively resolve system tuples in a `Map` or `Keyword` structures. """ alias Confex.Adapter alias Confex.Type @known_types [:string, :integer, :float, :boolean, :atom, :module, :list] @known_adapter_aliases [:system, :system_file] @doc """ Resolves all system tuples in a structure. ## Example iex> #{__MODULE__}.resolve(nil) {:ok, nil} iex> :ok = System.delete_env("SOME_TEST_ENV") ...> {:error, {:unresolved, _message}} = #{__MODULE__}.resolve([test: {:system, "DOES_NOT_EXIST"}]) ...> :ok = System.put_env("SOME_TEST_ENV", "some_value") ...> #{__MODULE__}.resolve([test: {:system, "SOME_TEST_ENV", "defaults"}]) {:ok, [test: "some_value"]} iex> #{__MODULE__}.resolve([test: {:system, "DOES_NOT_EXIST", "defaults"}]) {:ok, [test: "defaults"]} """ @spec resolve(config :: any()) :: {:ok, any()} | {:error, any()} def resolve(nil), do: {:ok, nil} def resolve(config) when is_list(config) do case Enum.reduce_while(config, [], &reduce_list/2) do {:error, reason} -> {:error, reason} result -> {:ok, result} end end def resolve(%{__struct__: _type} = config) do {:ok, config} end def resolve(config) when is_map(config) do case Enum.reduce_while(config, %{}, &reduce_map/2) do {:error, reason} -> {:error, reason} result -> {:ok, result} end end def resolve(config), do: maybe_resolve_with_adapter(config) @doc """ Same as `resolve/1` but will raise `ArgumentError` if one of system tuples can not be resolved. """ @spec resolve!(config :: any()) :: any() | no_return def resolve!(config) do case resolve(config) do {:ok, config} -> config {:error, {_reason, message}} -> raise ArgumentError, message end end defp reduce_map({key, nil}, acc) do {:cont, Map.put(acc, key, nil)} end defp reduce_map({key, list}, acc) when is_list(list) do case Enum.reduce_while(list, [], &reduce_list/2) do {:error, reason} -> {:halt, {:error, reason}} result -> {:cont, Map.put(acc, key, result)} end end defp reduce_map({key, %{__struct__: _type} = struct}, acc) do {:cont, Map.put(acc, key, struct)} end defp reduce_map({key, map}, acc) when is_map(map) do case Enum.reduce_while(map, %{}, &reduce_map/2) do {:error, reason} -> {:halt, {:error, reason}} result -> {:cont, Map.put(acc, key, result)} end end defp reduce_map({key, value}, acc) do case maybe_resolve_with_adapter(value) do {:ok, value} -> {:cont, Map.put(acc, key, value)} {:error, reason} -> {:halt, {:error, reason}} end end defp reduce_list({key, nil}, acc) do {:cont, [{key, nil}] ++ acc} end defp reduce_list({key, list}, acc) when is_list(list) do case Enum.reduce_while(list, [], &reduce_list/2) do {:error, reason} -> {:halt, {:error, reason}} result -> {:cont, acc ++ [{key, result}]} end end defp reduce_list({key, %{__struct__: _type} = struct}, acc) do {:cont, acc ++ [{key, struct}]} end defp reduce_list({key, map}, acc) when is_map(map) do case Enum.reduce_while(map, %{}, &reduce_map/2) do {:error, reason} -> {:halt, {:error, reason}} result -> {:cont, acc ++ [{key, result}]} end end defp reduce_list({key, value}, acc) when is_tuple(value) do case maybe_resolve_with_adapter(value) do {:ok, value} -> {:cont, acc ++ [{key, value}]} {:error, reason} -> {:halt, {:error, reason}} end end defp reduce_list(value, acc) do {:cont, acc ++ [value]} end defp maybe_resolve_with_adapter({{:via, adapter}, type, key, default_value}) when is_atom(adapter) and (type in @known_types or is_tuple(type)) do resolve_value(adapter, type, key, default_value) end defp maybe_resolve_with_adapter({adapter_alias, type, key, default_value}) when adapter_alias in @known_adapter_aliases and (type in @known_types or is_tuple(type)) do adapter_alias |> Adapter.to_module() |> resolve_value(type, key, default_value) end defp maybe_resolve_with_adapter({{:via, adapter}, type, key}) when is_atom(adapter) and (type in @known_types or is_tuple(type)) do resolve_value(adapter, type, key) end defp maybe_resolve_with_adapter({adapter_alias, type, key}) when adapter_alias in @known_adapter_aliases and (type in @known_types or is_tuple(type)) do adapter_alias |> Adapter.to_module() |> resolve_value(type, key) end defp maybe_resolve_with_adapter({{:via, adapter}, key, default_value}) when is_atom(adapter) and is_binary(key) do resolve_value(adapter, :string, key, default_value) end defp maybe_resolve_with_adapter({adapter_alias, key, default_value}) when adapter_alias in @known_adapter_aliases do adapter_alias |> Adapter.to_module() |> resolve_value(:string, key, default_value) end defp maybe_resolve_with_adapter({{:via, adapter}, key}) when is_atom(adapter) do resolve_value(adapter, :string, key) end defp maybe_resolve_with_adapter({adapter_alias, key}) when adapter_alias in @known_adapter_aliases do adapter_alias |> Adapter.to_module() |> resolve_value(:string, key) end defp maybe_resolve_with_adapter(value) do {:ok, value} end defp resolve_value(adapter, type, key, default_value) do with {:ok, value} <- adapter.fetch_value(key), {:ok, value} <- Type.cast(value, type) do {:ok, value} else {:error, reason} -> {:error, {:invalid, reason}} :error -> {:ok, default_value} end end defp resolve_value(adapter, type, key) do with {:ok, value} <- adapter.fetch_value(key), {:ok, value} <- Type.cast(value, type) do {:ok, value} else {:error, reason} -> {:error, {:invalid, reason}} :error -> { :error, {:unresolved, "can not resolve key #{key} value via adapter #{to_string(adapter)}"} } end end end
30.923858
105
0.632797
031ae4c0d0616edb15b929b769ed0f4d3ef05c83
2,644
ex
Elixir
lib/advent_of_code/day_1_a.ex
rob-brown/AdventOfCode2017
cb8a56fba4b1999820b3aec4c4f03d7094836484
[ "MIT" ]
3
2017-12-26T20:51:47.000Z
2019-05-14T04:59:38.000Z
lib/advent_of_code/day_1_a.ex
rob-brown/AdventOfCode2017
cb8a56fba4b1999820b3aec4c4f03d7094836484
[ "MIT" ]
null
null
null
lib/advent_of_code/day_1_a.ex
rob-brown/AdventOfCode2017
cb8a56fba4b1999820b3aec4c4f03d7094836484
[ "MIT" ]
null
null
null
defmodule AdventOfCode.Day1A do def sum(input) do input |> wrap_first |> calculate_sum(0) end def solve do sum "9513446799636685297929646689682997114316733445451534532351778534251427172168183621874641711534917291674333857423799375512628489423332297538215855176592633692631974822259161766238385922277893623911332569448978771948316155868781496698895492971356383996932885518732997624253678694279666572149831616312497994856288871586777793459926952491318336997159553714584541897294117487641872629796825583725975692264125865827534677223541484795877371955124463989228886498682421539667224963783616245646832154384756663251487668681425754536722827563651327524674183443696227523828832466473538347472991998913211857749878157579176457395375632995576569388455888156465451723693767887681392547189273391948632726499868313747261828186732986628365773728583387184112323696592536446536231376615949825166773536471531487969852535699774113163667286537193767515119362865141925612849443983484245268194842563154567638354645735331855896155142741664246715666899824364722914296492444672653852387389477634257768229772399416521198625393426443499223611843766134883441223328256883497423324753229392393974622181429913535973327323952241674979677481518733692544535323219895684629719868384266425386835539719237716339198485163916562434854579365958111931354576991558771236977242668756782139961638347251644828724786827751748399123668854393894787851872256667336215726674348886747128237416273154988619267824361227888751562445622387695218161341884756795223464751862965655559143779425283154533252573949165492138175581615176611845489857169132936848668646319955661492488428427435269169173654812114842568381636982389224236455633316898178163297452453296667661849622174541778669494388167451186352488555379581934999276412919598411422973399319799937518713422398874326665375216437246445791623283898584648278989674418242112957668397484671119761553847275799873495363759266296477844157237423239163559391553961176475377151369399646747881452252547741718734949967752564774161341784833521492494243662658471121369649641815562327698395293573991648351369767162642763475561544795982183714447737149239846151871434656618825566387329765118727515699213962477996399781652131918996434125559698427945714572488376342126989157872118279163127742349" end defp wrap_first(input = <<first::utf8, _::binary>>) do input <> <<first>> end defp calculate_sum(<<>>, total), do: total defp calculate_sum(<<c, c, rest::binary>>, total) do calculate_sum(<<c>> <> rest, total + c - ?0) end defp calculate_sum(<<_, rest::binary>>, total) do calculate_sum(rest, total) end end
105.76
2,174
0.93003
031b4da1f210e0b18aad6ae8a9a26f3105e4fbac
49
exs
Elixir
test/guachiman_test.exs
gmtprime/guachiman
32df4cb37617aadf6f98b6b2bbe7ba628b8815cc
[ "MIT" ]
1
2019-01-09T10:04:10.000Z
2019-01-09T10:04:10.000Z
test/guachiman_test.exs
gmtprime/guachiman
32df4cb37617aadf6f98b6b2bbe7ba628b8815cc
[ "MIT" ]
null
null
null
test/guachiman_test.exs
gmtprime/guachiman
32df4cb37617aadf6f98b6b2bbe7ba628b8815cc
[ "MIT" ]
null
null
null
defmodule GuachimanTest do use ExUnit.Case end
12.25
26
0.816327
031b56efe369e93157c14c348154c3727e6dfed7
1,761
exs
Elixir
clients/apigee/mix.exs
mopp/elixir-google-api
d496227d17600bccbdf8f6be9ad1b7e7219d7ec6
[ "Apache-2.0" ]
null
null
null
clients/apigee/mix.exs
mopp/elixir-google-api
d496227d17600bccbdf8f6be9ad1b7e7219d7ec6
[ "Apache-2.0" ]
null
null
null
clients/apigee/mix.exs
mopp/elixir-google-api
d496227d17600bccbdf8f6be9ad1b7e7219d7ec6
[ "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.Mixfile do use Mix.Project @version "0.39.0" def project() do [ app: :google_api_apigee, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/apigee" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Apigee API client library. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/apigee", "Homepage" => "https://cloud.google.com/apigee-api-management/" } ] end end
26.283582
97
0.646224
031b5e288af76422c95439055ca03dd686631ac2
996
ex
Elixir
apps/muster_web/lib/muster_web/live/game_monitor.ex
eugenebolshakov/muster
dd5465da2c9c1a64817e271b297de95fa31c07d9
[ "Unlicense" ]
null
null
null
apps/muster_web/lib/muster_web/live/game_monitor.ex
eugenebolshakov/muster
dd5465da2c9c1a64817e271b297de95fa31c07d9
[ "Unlicense" ]
null
null
null
apps/muster_web/lib/muster_web/live/game_monitor.ex
eugenebolshakov/muster
dd5465da2c9c1a64817e271b297de95fa31c07d9
[ "Unlicense" ]
null
null
null
defmodule MusterWeb.GameMonitor do use GenServer @impl true def init(processes) do {:ok, processes} end def start_link(opts \\ []) do GenServer.start_link(__MODULE__, %{}, opts) end def monitor(callback) do GenServer.call(__MODULE__, {:monitor, callback}) end def demonitor() do GenServer.call(__MODULE__, :demonitor) end @impl true def handle_call({:monitor, callback}, {pid, _ref}, processes) do ref = Process.monitor(pid) {:reply, :ok, Map.put(processes, pid, %{ref: ref, callback: callback})} end @impl true def handle_call(:demonitor, {pid, _ref}, processes) do {process, processes} = Map.pop(processes, pid) if process do Process.demonitor(process.ref) end {:reply, :ok, processes} end @impl true def handle_info({:DOWN, _ref, :process, pid, _reason}, processes) do {process, processes} = Map.pop(processes, pid) Task.start(fn -> process.callback.() end) {:noreply, processes} end end
22.133333
75
0.660643
031be2ef83ab7377d17d3d86aec8063f197f8de3
721
ex
Elixir
lib/expug/runtime.ex
rstacruz/expug
683eb34abd9465f42d42cbe359fa9ae848f9ec3d
[ "MIT" ]
89
2016-06-27T07:06:23.000Z
2022-03-15T18:21:50.000Z
lib/expug/runtime.ex
rstacruz/exslim
683eb34abd9465f42d42cbe359fa9ae848f9ec3d
[ "MIT" ]
11
2016-07-28T17:12:39.000Z
2021-01-22T02:54:58.000Z
lib/expug/runtime.ex
rstacruz/exslim
683eb34abd9465f42d42cbe359fa9ae848f9ec3d
[ "MIT" ]
4
2016-07-26T15:50:35.000Z
2019-09-16T22:49:21.000Z
defmodule Expug.Runtime do @moduledoc """ Functions used by Expug-compiled templates at runtime. ```eex <div class=<%= raw(Expug.Runtime.attr_value(str)) %>></div> ``` """ @doc """ Quotes a given `str` for use as an HTML attribute. """ def attr_value(str) do "\"#{attr_value_escape(str)}\"" end def attr_value_escape(str) do str |> String.replace("&", "&amp;") |> String.replace("\"", "&quot;") |> String.replace("<", "&lt;") |> String.replace(">", "&gt;") end def attr(key, true) do " " <> key end def attr(_key, false) do "" end def attr(_key, nil) do "" end def attr(key, value) do " " <> key <> "=" <> attr_value(value) end end
17.585366
61
0.553398
031bf1abe5d9a876408d667ff89c75040cd34dd1
648
exs
Elixir
astreux/mix.exs
wesleimp/Astreu
4d430733e7ecc8b3eba8e27811a152aa2c6d79c1
[ "Apache-2.0" ]
null
null
null
astreux/mix.exs
wesleimp/Astreu
4d430733e7ecc8b3eba8e27811a152aa2c6d79c1
[ "Apache-2.0" ]
null
null
null
astreux/mix.exs
wesleimp/Astreu
4d430733e7ecc8b3eba8e27811a152aa2c6d79c1
[ "Apache-2.0" ]
null
null
null
defmodule Astreux.MixProject do use Mix.Project def project do [ app: :astreux, version: "0.1.0", elixir: "~> 1.11", start_permanent: Mix.env() == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger], mod: {Astreux.Application, []} ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:google_protos, "~> 0.1.0"}, {:grpc, github: "elixir-grpc/grpc", override: true}, {:cowlib, "~> 2.9.0", override: true}, {:uuid, "~> 1.1"}, ] end end
20.25
59
0.554012
031bf9623202824ae6b6bd954ff1e38ca61cab68
1,645
exs
Elixir
mix.exs
nsidnev/edgedb-elixir
bade2b9daba2e83bfaa5915b2addb74f41610968
[ "MIT" ]
30
2021-05-19T08:54:44.000Z
2022-03-11T22:52:25.000Z
mix.exs
nsidnev/edgedb-elixir
bade2b9daba2e83bfaa5915b2addb74f41610968
[ "MIT" ]
3
2021-11-17T21:26:01.000Z
2022-03-12T09:49:25.000Z
mix.exs
nsidnev/edgedb-elixir
bade2b9daba2e83bfaa5915b2addb74f41610968
[ "MIT" ]
3
2021-08-29T14:55:41.000Z
2022-03-12T01:30:35.000Z
defmodule EdgeDB.MixProject do use Mix.Project def project do [ app: :edgedb, version: "0.0.0", elixir: "~> 1.10", deps: deps(), elixirc_paths: elixirc_paths(Mix.env()), elixirc_options: [ warnings_as_errors: true ], consolidate_protocols: Mix.env() != :test, test_coverage: [tool: ExCoveralls], preferred_cli_env: [ dialyzer: :test, credo: :test, coveralls: :test, "coveralls.detail": :test, "coveralls.github": :test, "coveralls.html": :test ], dialyzer: [ plt_add_apps: [:ex_unit], plt_file: {:no_warn, "priv/plts/dialyzer.plt"} ], aliases: aliases() ] end def application do [ mod: {EdgeDB.Application, []}, extra_applications: [ :crypto, :logger, :ssl ] ] end defp deps do [ # core {:db_connection, "~> 2.0"}, {:elixir_uuid, "~> 1.2"}, {:decimal, "~> 2.0"}, {:jason, "~> 1.2"}, # dev/test {:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false}, {:credo, "~> 1.2", only: [:dev, :test], runtime: false}, {:excoveralls, "~> 0.14", only: :test}, {:mox, "~> 1.0", only: :test} ] end defp elixirc_paths(:test) do ["lib", "test/support"] end defp elixirc_paths(_env) do ["lib"] end defp aliases do [ "edgedb.roles.setup": [ "cmd priv/scripts/setup-roles.sh" ], "edgedb.roles.reset": [ "cmd priv/scripts/drop-roles.sh", "cmd priv/scripts/setup-roles.sh" ] ] end end
21.089744
65
0.507599
031c273ed9a3aa8c884e3b7dfc05db9c7edf5723
1,015
ex
Elixir
phoenix_trello/web/views/error_helpers.ex
hectorip/TrelloPhoenix
343e0730c294d8e590ed04e23c3c5a682ffb7ff9
[ "MIT" ]
1
2020-07-24T17:13:26.000Z
2020-07-24T17:13:26.000Z
phoenix_trello/web/views/error_helpers.ex
hectorip/TrelloPhoenix
343e0730c294d8e590ed04e23c3c5a682ffb7ff9
[ "MIT" ]
null
null
null
phoenix_trello/web/views/error_helpers.ex
hectorip/TrelloPhoenix
343e0730c294d8e590ed04e23c3c5a682ffb7ff9
[ "MIT" ]
null
null
null
defmodule PhoenixTrello.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do if error = form.errors[field] do content_tag :span, translate_error(error), class: "help-block" end end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # Because error messages were defined within Ecto, we must # call the Gettext module passing our Gettext backend. We # also use the "errors" domain as translations are placed # in the errors.po file. On your own code and templates, # this could be written simply as: # # dngettext "errors", "1 file", "%{count} files", count # Gettext.dngettext(PhoenixTrello.Gettext, "errors", msg, msg, opts[:count], opts) end def translate_error(msg) do Gettext.dgettext(PhoenixTrello.Gettext, "errors", msg) end end
28.194444
84
0.684729
031c289e748f923981f7720cc49e207c8b5b2cbc
1,166
ex
Elixir
clients/policy_troubleshooter/lib/google_api/policy_troubleshooter/v1beta/connection.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/policy_troubleshooter/lib/google_api/policy_troubleshooter/v1beta/connection.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/policy_troubleshooter/lib/google_api/policy_troubleshooter/v1beta/connection.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.PolicyTroubleshooter.V1beta.Connection do @moduledoc """ Handle Tesla connections for GoogleApi.PolicyTroubleshooter.V1beta. """ @type t :: Tesla.Env.client() use GoogleApi.Gax.Connection, scopes: [ # View and manage your data across Google Cloud Platform services "https://www.googleapis.com/auth/cloud-platform" ], otp_app: :google_api_policy_troubleshooter, base_url: "https://policytroubleshooter.googleapis.com/" end
35.333333
74
0.751286
031c30683caa46cde1a9d2be25f2b876f7d24775
555
ex
Elixir
lib/weebo/request.ex
stevenschobert/weebo
630084458fbd6a1adad0296c4752fdd5f6a00490
[ "MIT" ]
6
2015-06-08T07:34:57.000Z
2019-03-30T06:49:02.000Z
lib/weebo/request.ex
stevenschobert/weebo
630084458fbd6a1adad0296c4752fdd5f6a00490
[ "MIT" ]
null
null
null
lib/weebo/request.ex
stevenschobert/weebo
630084458fbd6a1adad0296c4752fdd5f6a00490
[ "MIT" ]
null
null
null
defmodule Weebo.Request do @moduledoc "Struct used to represent an XML-RPC request." defstruct method: nil, params: [] @type t :: %Weebo.Request{method: String.t, params: list} end defimpl Weebo.Formattable, for: Weebo.Request do @spec format(Weebo.Request.t) :: Weebo.xml_tree def format(%Weebo.Request{method: name, params: params}) do formatted_params = Enum.map params, fn(param) -> {:param, [{:value, [Weebo.Formattable.format(param)]}]} end {:methodCall, [{:methodName, [name]}, {:params, formatted_params}]} end end
32.647059
71
0.691892
031c7d9ee4bbe8c7f30438670bb4dabc5952022f
549
ex
Elixir
authentication/lib/authentication_web/views/error_view.ex
hbobenicio/phoenix-examples
dd2adc8887a341b50d192bc31c61ee528e896672
[ "MIT" ]
null
null
null
authentication/lib/authentication_web/views/error_view.ex
hbobenicio/phoenix-examples
dd2adc8887a341b50d192bc31c61ee528e896672
[ "MIT" ]
null
null
null
authentication/lib/authentication_web/views/error_view.ex
hbobenicio/phoenix-examples
dd2adc8887a341b50d192bc31c61ee528e896672
[ "MIT" ]
null
null
null
defmodule AuthenticationWeb.ErrorView do use AuthenticationWeb, :view # If you want to customize a particular status code # for a certain format, you may uncomment below. # def render("500.json", _assigns) do # %{errors: %{detail: "Internal Server Error"}} # end # By default, Phoenix returns the status message from # the template name. For example, "404.json" becomes # "Not Found". def template_not_found(template, _assigns) do %{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}} end end
32.294118
83
0.726776
031cb08cb0a5c2a13c0faabfd313e6b6e53ecacc
1,121
exs
Elixir
config/config.exs
xronos-i-am/tarantool.ex
929ee9dd3da1b6dd3e38961870e758fba3e6aa8c
[ "MIT" ]
27
2016-02-11T08:38:46.000Z
2022-02-23T21:48:13.000Z
config/config.exs
xronos-i-am/tarantool.ex
929ee9dd3da1b6dd3e38961870e758fba3e6aa8c
[ "MIT" ]
5
2016-06-04T18:32:00.000Z
2019-04-14T08:14:46.000Z
config/config.exs
xronos-i-am/tarantool.ex
929ee9dd3da1b6dd3e38961870e758fba3e6aa8c
[ "MIT" ]
6
2016-03-01T08:34:09.000Z
2019-02-09T17:29:56.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :tarantool, key: :value # # And access this configuration in your application as: # # Application.get_env(:tarantool, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
36.16129
73
0.752007
031cda1e8ed2563549a0276b958cd666b178fa02
329
exs
Elixir
config/config.exs
jgaviria/symmetric_encryption
f9790a3df02795a50af0975635390e5284e9c5b1
[ "Apache-2.0" ]
null
null
null
config/config.exs
jgaviria/symmetric_encryption
f9790a3df02795a50af0975635390e5284e9c5b1
[ "Apache-2.0" ]
null
null
null
config/config.exs
jgaviria/symmetric_encryption
f9790a3df02795a50af0975635390e5284e9c5b1
[ "Apache-2.0" ]
null
null
null
use Mix.Config # Test keys config :symmetric_encryption, key: [ key: "ABCDEF1234567890ABCDEF1234567890", iv: "ABCDEF1234567890", version: 2 ] config :symmetric_encryption, old_keys: [ [key: "1234567890ABCDEF1234567890ABCDEF", iv: "1234567890ABCDEF", version: 1] ]
23.5
86
0.6231
031ce0293001702cca0ba4617e585c1824ff875f
447
ex
Elixir
web/controllers/plugs/require_auth.ex
leomindez/Discuss
f1f720dccb331f4f8606d8403416f91b4d5a287d
[ "MIT" ]
null
null
null
web/controllers/plugs/require_auth.ex
leomindez/Discuss
f1f720dccb331f4f8606d8403416f91b4d5a287d
[ "MIT" ]
null
null
null
web/controllers/plugs/require_auth.ex
leomindez/Discuss
f1f720dccb331f4f8606d8403416f91b4d5a287d
[ "MIT" ]
null
null
null
defmodule Discuss.Plugs.RequireAuth do import Plug.Conn import Phoenix.Controller alias Discuss.Router.Helpers def init(_params) do end def call(conn, _params) do if conn.assigns[:user] do conn else conn |> put_flash(:error, "You must be logged in") |> redirect(to: Helpers.topic_path(conn, :index)) |> halt() end end end
21.285714
61
0.550336
031ce9cc6327661ae2b613b157fc6d271aeb0511
280
exs
Elixir
test/phoenix_hello_web/views/layout_view_test.exs
haojiwu/phoenix_hello
aee3d40a018e73b24767de1be5692a9cd9cf2017
[ "MIT" ]
6
2019-06-11T22:16:47.000Z
2021-05-19T10:32:58.000Z
test/phoenix_hello_web/views/layout_view_test.exs
haojiwu/phoenix_hello
aee3d40a018e73b24767de1be5692a9cd9cf2017
[ "MIT" ]
2
2021-08-22T19:41:42.000Z
2021-12-16T15:26:14.000Z
test/phoenix_hello_web/views/layout_view_test.exs
haojiwu/phoenix_hello
aee3d40a018e73b24767de1be5692a9cd9cf2017
[ "MIT" ]
16
2019-06-12T19:39:41.000Z
2022-03-26T07:34:44.000Z
defmodule PhoenixHelloWeb.LayoutViewTest do use PhoenixHelloWeb.ConnCase, async: true # When testing helpers, you may want to import Phoenix.HTML and # use functions such as safe_to_string() to convert the helper # result into an HTML string. # import Phoenix.HTML end
31.111111
65
0.775
031cf68be36fdaf1ba555b5d2c2f1d4b98430154
1,455
exs
Elixir
test/hexpm_web/controllers/tfa_auth_controller_test.exs
Benjamin-Philip/hexpm
6f38244f81bbabd234c660f46ea973849ba77a7f
[ "Apache-2.0" ]
691
2017-03-08T09:15:45.000Z
2022-03-23T22:04:47.000Z
test/hexpm_web/controllers/tfa_auth_controller_test.exs
Benjamin-Philip/hexpm
6f38244f81bbabd234c660f46ea973849ba77a7f
[ "Apache-2.0" ]
491
2017-03-07T12:58:42.000Z
2022-03-29T23:32:54.000Z
test/hexpm_web/controllers/tfa_auth_controller_test.exs
Benjamin-Philip/hexpm
6f38244f81bbabd234c660f46ea973849ba77a7f
[ "Apache-2.0" ]
200
2017-03-12T23:03:39.000Z
2022-03-05T17:55:52.000Z
defmodule HexpmWeb.TFAAuthControllerTest do use HexpmWeb.ConnCase, async: true setup do %{user: insert(:user_with_tfa)} end describe "get /two_factor_auth" do test "shows auth code form", c do conn = build_conn() |> test_login(c.user) |> put_session("tfa_user_id", c.user.id) |> get("/two_factor_auth") result = response(conn, 200) assert result =~ "Two-factor authentication" end test "redirects to homepage if tfa_user_id isn't not in the session", c do conn = build_conn() |> test_login(c.user) |> get("/two_factor_auth") assert redirected_to(conn) == "/" end end describe "post /two_factor_auth" do test "with invalid token", c do conn = build_conn() |> test_login(c.user) |> put_session("tfa_user_id", %{"uid" => c.user.id, "return" => "/"}) |> post("/two_factor_auth", %{"code" => "000000"}) assert response(conn, 200) =~ "The verification code you provided is incorrect. Please try again." end test "with valid token", c do token = Hexpm.Accounts.TFA.time_based_token(c.user.tfa.secret) conn = build_conn() |> test_login(c.user) |> put_session("tfa_user_id", %{"uid" => c.user.id, "return" => "/"}) |> post("/two_factor_auth", %{"code" => token}) assert redirected_to(conn) == "/" end end end
26.454545
83
0.582818
031cf8199167b64faaabbf39303805c9b175c9c3
2,330
exs
Elixir
config/dev.exs
chenxsan/telegram-bot-for-twitter
892107c7609123028ac2375342cd7b2329931635
[ "MIT" ]
14
2018-03-23T04:13:29.000Z
2021-07-26T06:15:50.000Z
config/dev.exs
chenxsan/telegram-bot-for-twitter
892107c7609123028ac2375342cd7b2329931635
[ "MIT" ]
2
2021-03-08T18:20:20.000Z
2021-05-06T22:47:09.000Z
config/dev.exs
chenxsan/telegram-bot-for-twitter
892107c7609123028ac2375342cd7b2329931635
[ "MIT" ]
3
2020-11-04T08:11:47.000Z
2022-01-13T17:41:42.000Z
use Mix.Config # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with brunch.io to recompile .js and .css sources. config :tweet_bot, TweetBotWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [ node: [ "node_modules/brunch/bin/brunch", "watch", "--stdin", cd: Path.expand("../assets", __DIR__) ] ] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # command from your terminal: # # openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem # # The `http:` config above can be replaced with: # # https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :tweet_bot, TweetBotWeb.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{priv/gettext/.*(po)$}, ~r{lib/tweet_bot_web/views/.*(ex)$}, ~r{lib/tweet_bot_web/templates/.*(eex)$} ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Configure your database config :tweet_bot, TweetBot.Repo, adapter: Ecto.Adapters.Postgres, username: "postgres", password: "postgres", database: "tweet_bot_dev", hostname: "localhost", pool_size: 10 # Configures token for telegram bot config :telegram_bot, token: System.get_env("TELEGRAM_TOKEN") # Configures extwitter oauth config :extwitter, :oauth, consumer_key: System.get_env("TWITTER_CONSUMER_KEY"), consumer_secret: System.get_env("TWITTER_CONSUMER_SECRET") # Configures extwitter proxy config :extwitter, :proxy, server: "127.0.0.1", port: 1087
29.493671
170
0.709871
031d06a469c58c11344c1a483c577e87a4f57370
1,164
ex
Elixir
web/channels/user_socket.ex
dkarter/exblog
3bc2c52dc6b8263506d5fc5e842436f64414d9c7
[ "MIT" ]
null
null
null
web/channels/user_socket.ex
dkarter/exblog
3bc2c52dc6b8263506d5fc5e842436f64414d9c7
[ "MIT" ]
null
null
null
web/channels/user_socket.ex
dkarter/exblog
3bc2c52dc6b8263506d5fc5e842436f64414d9c7
[ "MIT" ]
null
null
null
defmodule Exblog.UserSocket do use Phoenix.Socket ## Channels # channel "rooms:*", Exblog.RoomChannel ## Transports transport :websocket, Phoenix.Transports.WebSocket # transport :longpoll, Phoenix.Transports.LongPoll # Socket params are passed from the client and can # be used to verify and authenticate a user. After # verification, you can put default assigns into # the socket that will be set for all channels, ie # # {:ok, assign(socket, :user_id, verified_user_id)} # # To deny connection, return `:error`. # # See `Phoenix.Token` documentation for examples in # performing token verification on connect. def connect(_params, socket) do {:ok, socket} end # Socket id's are topics that allow you to identify all sockets for a given user: # # def id(socket), do: "users_socket:#{socket.assigns.user_id}" # # Would allow you to broadcast a "disconnect" event and terminate # all active sockets and channels for a given user: # # Exblog.Endpoint.broadcast("users_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. def id(_socket), do: nil end
30.631579
83
0.701031
031d21221bfd20fec609b9bfaea8ac1b206f0185
541
ex
Elixir
lib/guitarbot/user.ex
dariodf/GuitarBotex
a8e4d9244dca7e90fedbb0db9c7376a156d220db
[ "MIT" ]
1
2018-07-26T00:59:45.000Z
2018-07-26T00:59:45.000Z
lib/guitarbot/user.ex
dariodf/GuitarBotex
a8e4d9244dca7e90fedbb0db9c7376a156d220db
[ "MIT" ]
null
null
null
lib/guitarbot/user.ex
dariodf/GuitarBotex
a8e4d9244dca7e90fedbb0db9c7376a156d220db
[ "MIT" ]
null
null
null
defmodule GuitarBot.User do use Ecto.Schema import Ecto.Changeset schema "users" do field :chat_id, :integer field :first_name, :string field :last_name, :string field :username, :string field :language_code, :string field :is_bot, :boolean timestamps() end def changeset(user, params) do user |> cast(params, [:chat_id, :first_name, :last_name, :username,:language_code, :is_bot]) |> validate_required([:chat_id]) |> unique_constraint(:chat_id, name: :unique_users_chat_id) end end
24.590909
91
0.687616
031d331c9aec604f11c9e999d07eb4ec97204ed5
2,384
ex
Elixir
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_rpc_status.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_rpc_status.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_rpc_status.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DocumentAI.V1beta2.Model.GoogleRpcStatus do @moduledoc """ The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). ## Attributes * `code` (*type:* `integer()`, *default:* `nil`) - The status code, which should be an enum value of google.rpc.Code. * `details` (*type:* `list(map())`, *default:* `nil`) - A list of messages that carry the error details. There is a common set of message types for APIs to use. * `message` (*type:* `String.t`, *default:* `nil`) - A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :code => integer() | nil, :details => list(map()) | nil, :message => String.t() | nil } field(:code) field(:details, type: :list) field(:message) end defimpl Poison.Decoder, for: GoogleApi.DocumentAI.V1beta2.Model.GoogleRpcStatus do def decode(value, options) do GoogleApi.DocumentAI.V1beta2.Model.GoogleRpcStatus.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DocumentAI.V1beta2.Model.GoogleRpcStatus do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
44.981132
427
0.726091
031d5f16493223767afd121d324a802f141fe331
2,078
ex
Elixir
clients/document_ai/lib/google_api/document_ai/v1/model/google_cloud_documentai_v1beta2_document_provenance_parent.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/document_ai/lib/google_api/document_ai/v1/model/google_cloud_documentai_v1beta2_document_provenance_parent.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/document_ai/lib/google_api/document_ai/v1/model/google_cloud_documentai_v1beta2_document_provenance_parent.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1beta2DocumentProvenanceParent do @moduledoc """ The parent element the current element is based on. Used for referencing/aligning, removal and replacement operations. ## Attributes * `id` (*type:* `integer()`, *default:* `nil`) - The id of the parent provenance. * `index` (*type:* `integer()`, *default:* `nil`) - The index of the parent item in the corresponding item list (eg. list of entities, properties within entities, etc.) in the parent revision. * `revision` (*type:* `integer()`, *default:* `nil`) - The index of the index into current revision's parent_ids list. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :id => integer() | nil, :index => integer() | nil, :revision => integer() | nil } field(:id) field(:index) field(:revision) end defimpl Poison.Decoder, for: GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1beta2DocumentProvenanceParent do def decode(value, options) do GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1beta2DocumentProvenanceParent.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1beta2DocumentProvenanceParent do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.827586
196
0.727141
031d7cc51c40b2629c97e9638db70f9af9471601
4,824
ex
Elixir
apps/data/lib/grapevine_data/games/images.ex
sb8244/grapevine
effaaa01294d30114090c20f9cc40b8665d834f2
[ "MIT" ]
107
2018-10-05T18:20:32.000Z
2022-02-28T04:02:50.000Z
apps/data/lib/grapevine_data/games/images.ex
sb8244/grapevine
effaaa01294d30114090c20f9cc40b8665d834f2
[ "MIT" ]
33
2018-10-05T14:11:18.000Z
2022-02-10T22:19:18.000Z
apps/data/lib/grapevine_data/games/images.ex
sb8244/grapevine
effaaa01294d30114090c20f9cc40b8665d834f2
[ "MIT" ]
18
2019-02-03T03:08:20.000Z
2021-12-28T04:29:36.000Z
defmodule GrapevineData.Games.Images do @moduledoc """ Handle uploading images to remote storage for games """ alias GrapevineData.Games.Game alias GrapevineData.Images alias GrapevineData.Repo alias Stein.Storage @doc """ If present, upload a cover and/or hero image for a game Only uploads a cover if the key "cover" is present, and only uploads a hero image if the key "hero" is present. Deletes previous images on new uploads. """ def maybe_upload_images(game, params) do params = for {key, val} <- params, into: %{}, do: {to_string(key), val} with {:ok, game} <- maybe_upload_cover_image(game, params), {:ok, game} <- maybe_upload_hero_image(game, params) do {:ok, game} end end @doc """ Get a storage path for uploading and viewing the cover image """ def cover_path(game, size) do cover_path(game.id, size, game.cover_key, game.cover_extension) end defp cover_path(game_id, "thumbnail", key, extension) when extension != ".png" do cover_path(game_id, "thumbnail", key, ".png") end defp cover_path(game_id, size, key, extension) do "/" <> Path.join(["games", to_string(game_id), "cover", "#{size}-#{key}#{extension}"]) end @doc """ Get a storage path for uploading and viewing the hero image """ def hero_path(game, size) do hero_path(game.id, size, game.hero_key, game.hero_extension) end defp hero_path(game_id, "thumbnail", key, extension) when extension != ".png" do hero_path(game_id, "thumbnail", key, ".png") end defp hero_path(game_id, size, key, extension) do "/" <> Path.join(["games", to_string(game_id), "hero", "#{size}-#{key}#{extension}"]) end @doc """ Delete the old images for the cover or hero Deletes original and thumbnail sizes if present. """ def maybe_delete_old_images(game, key, path_fun) do case is_nil(Map.get(game, key)) do true -> game false -> Storage.delete(path_fun.(game, "original")) Storage.delete(path_fun.(game, "thumbnail")) game end end @doc """ Generate an upload key """ def generate_key(), do: UUID.uuid4() @doc """ Upload the file to the path in storage """ def upload(file, path) do Storage.upload(file, path, extensions: [".jpg", ".png"], public: true) end def maybe_upload_cover_image(game, %{"cover" => file}) do game = maybe_delete_old_images(game, :cover_key, &cover_path/2) file = Storage.prep_file(file) key = generate_key() path = cover_path(game.id, "original", key, file.extension) changeset = Game.cover_changeset(game, key, file.extension) with :ok <- upload(file, path), {:ok, game} <- Repo.update(changeset) do generate_cover_versions(game, file) else :error -> game |> Ecto.Changeset.change() |> Ecto.Changeset.add_error(:cover, "could not upload, please try again") |> Ecto.Changeset.apply_action(:update) end end def maybe_upload_cover_image(game, _), do: {:ok, game} @doc """ Generate a thumbnail for the cover image """ def generate_cover_versions(game, file) do path = cover_path(game, "thumbnail") case Images.convert(file, [extname: ".png", thumbnail: "600x400"]) do {:ok, temp_path} -> upload(%{path: temp_path}, path) {:ok, game} {:error, :convert} -> {:ok, game} end end @doc """ If the `hero` param is available upload to storage """ def maybe_upload_hero_image(game, %{"hero" => file}) do game = maybe_delete_old_images(game, :hero_key, &hero_path/2) file = Storage.prep_file(file) key = generate_key() path = hero_path(game.id, "original", key, file.extension) changeset = Game.hero_changeset(game, key, file.extension) with :ok <- upload(file, path), {:ok, game} <- Repo.update(changeset) do generate_hero_versions(game, file) else :error -> game |> Ecto.Changeset.change() |> Ecto.Changeset.add_error(:hero, "could not upload, please try again") |> Ecto.Changeset.apply_action(:update) end end def maybe_upload_hero_image(game, _), do: {:ok, game} @doc """ Generate a thumbnail for the hero image """ def generate_hero_versions(game, file) do path = hero_path(game, "thumbnail") case Images.convert(file, [extname: ".png", thumbnail: "600x400"]) do {:ok, temp_path} -> upload(%{path: temp_path}, path) {:ok, game} {:error, :convert} -> {:ok, game} end end @doc """ Regenerate the cover image for a game """ def regenerate_cover(game) do case Storage.download(cover_path(game, "original")) do {:ok, temp_path} -> generate_cover_versions(game, %{path: temp_path}) end end end
27.409091
90
0.638474
031d8f1569089a44552e79cee410f83649fd15bd
14,900
ex
Elixir
lib/aws/generated/dev_ops_guru.ex
kw7oe/aws-elixir
4ba60502dde270c83143822c9964018c7770bad7
[ "Apache-2.0" ]
341
2018-04-04T19:06:19.000Z
2022-03-25T21:34:23.000Z
lib/aws/generated/dev_ops_guru.ex
kw7oe/aws-elixir
4ba60502dde270c83143822c9964018c7770bad7
[ "Apache-2.0" ]
82
2018-04-04T17:32:33.000Z
2022-03-24T15:12:04.000Z
lib/aws/generated/dev_ops_guru.ex
kw7oe/aws-elixir
4ba60502dde270c83143822c9964018c7770bad7
[ "Apache-2.0" ]
76
2018-04-10T20:19:44.000Z
2022-03-15T13:49:19.000Z
# WARNING: DO NOT EDIT, AUTO-GENERATED CODE! # See https://github.com/aws-beam/aws-codegen for more details. defmodule AWS.DevOpsGuru do @moduledoc """ Amazon DevOps Guru is a fully managed service that helps you identify anomalous behavior in business critical operational applications. You specify the AWS resources that you want DevOps Guru to cover, then the Amazon CloudWatch metrics and AWS CloudTrail events related to those resources are analyzed. When anomalous behavior is detected, DevOps Guru creates an *insight* that includes recommendations, related events, and related metrics that can help you improve your operational applications. For more information, see [What is Amazon DevOps Guru](https://docs.aws.amazon.com/devops-guru/latest/userguide/welcome.html). You can specify 1 or 2 Amazon Simple Notification Service topics so you are notified every time a new insight is created. You can also enable DevOps Guru to generate an OpsItem in AWS Systems Manager for each insight to help you manage and track your work addressing insights. To learn about the DevOps Guru workflow, see [How DevOps Guru works](https://docs.aws.amazon.com/devops-guru/latest/userguide/welcome.html#how-it-works). To learn about DevOps Guru concepts, see [Concepts in DevOps Guru](https://docs.aws.amazon.com/devops-guru/latest/userguide/concepts.html). """ alias AWS.Client alias AWS.Request def metadata do %AWS.ServiceMetadata{ abbreviation: nil, api_version: "2020-12-01", content_type: "application/x-amz-json-1.1", credential_scope: nil, endpoint_prefix: "devops-guru", global?: false, protocol: "rest-json", service_id: "DevOps Guru", signature_version: "v4", signing_name: "devops-guru", target_prefix: nil } end @doc """ Adds a notification channel to DevOps Guru. A notification channel is used to notify you about important DevOps Guru events, such as when an insight is generated. If you use an Amazon SNS topic in another account, you must attach a policy to it that grants DevOps Guru permission to it notifications. DevOps Guru adds the required policy on your behalf to send notifications using Amazon SNS in your account. For more information, see [Permissions for cross account Amazon SNS topics](https://docs.aws.amazon.com/devops-guru/latest/userguide/sns-required-permissions.html). If you use an Amazon SNS topic that is encrypted by an AWS Key Management Service customer-managed key (CMK), then you must add permissions to the CMK. For more information, see [Permissions for AWS KMS–encrypted Amazon SNS topics](https://docs.aws.amazon.com/devops-guru/latest/userguide/sns-kms-permissions.html). """ def add_notification_channel(%Client{} = client, input, options \\ []) do url_path = "/channels" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Returns the number of open reactive insights, the number of open proactive insights, and the number of metrics analyzed in your AWS account. Use these numbers to gauge the health of operations in your AWS account. """ def describe_account_health(%Client{} = client, options \\ []) do url_path = "/accounts/health" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ For the time range passed in, returns the number of open reactive insight that were created, the number of open proactive insights that were created, and the Mean Time to Recover (MTTR) for all closed reactive insights. """ def describe_account_overview(%Client{} = client, input, options \\ []) do url_path = "/accounts/overview" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Returns details about an anomaly that you specify using its ID. """ def describe_anomaly(%Client{} = client, id, options \\ []) do url_path = "/anomalies/#{AWS.Util.encode_uri(id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns the most recent feedback submitted in the current AWS account and Region. """ def describe_feedback(%Client{} = client, input, options \\ []) do url_path = "/feedback" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Returns details about an insight that you specify using its ID. """ def describe_insight(%Client{} = client, id, options \\ []) do url_path = "/insights/#{AWS.Util.encode_uri(id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns the number of open proactive insights, open reactive insights, and the Mean Time to Recover (MTTR) for all closed insights in resource collections in your account. You specify the type of AWS resources collection. The one type of AWS resource collection supported is AWS CloudFormation stacks. DevOps Guru can be configured to analyze only the AWS resources that are defined in the stacks. You can specify up to 500 AWS CloudFormation stacks. """ def describe_resource_collection_health( %Client{} = client, resource_collection_type, next_token \\ nil, options \\ [] ) do url_path = "/accounts/health/resource-collection/#{AWS.Util.encode_uri(resource_collection_type)}" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"NextToken", next_token} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns the integration status of services that are integrated with DevOps Guru. The one service that can be integrated with DevOps Guru is AWS Systems Manager, which can be used to create an OpsItem for each generated insight. """ def describe_service_integration(%Client{} = client, options \\ []) do url_path = "/service-integrations" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns an estimate of the monthly cost for DevOps Guru to analyze your AWS resources. For more information, see [Estimate your Amazon DevOps Guru costs](https://docs.aws.amazon.com/devops-guru/latest/userguide/cost-estimate.html) and [Amazon DevOps Guru pricing](http://aws.amazon.com/devops-guru/pricing/). """ def get_cost_estimation(%Client{} = client, next_token \\ nil, options \\ []) do url_path = "/cost-estimation" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"NextToken", next_token} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns lists AWS resources that are of the specified resource collection type. The one type of AWS resource collection supported is AWS CloudFormation stacks. DevOps Guru can be configured to analyze only the AWS resources that are defined in the stacks. You can specify up to 500 AWS CloudFormation stacks. """ def get_resource_collection( %Client{} = client, resource_collection_type, next_token \\ nil, options \\ [] ) do url_path = "/resource-collections/#{AWS.Util.encode_uri(resource_collection_type)}" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"NextToken", next_token} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Returns a list of the anomalies that belong to an insight that you specify using its ID. """ def list_anomalies_for_insight(%Client{} = client, insight_id, input, options \\ []) do url_path = "/anomalies/insight/#{AWS.Util.encode_uri(insight_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Returns a list of the events emitted by the resources that are evaluated by DevOps Guru. You can use filters to specify which events are returned. """ def list_events(%Client{} = client, input, options \\ []) do url_path = "/events" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Returns a list of insights in your AWS account. You can specify which insights are returned by their start time and status (`ONGOING`, `CLOSED`, or `ANY`). """ def list_insights(%Client{} = client, input, options \\ []) do url_path = "/insights" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Returns a list of notification channels configured for DevOps Guru. Each notification channel is used to notify you when DevOps Guru generates an insight that contains information about how to improve your operations. The one supported notification channel is Amazon Simple Notification Service (Amazon SNS). """ def list_notification_channels(%Client{} = client, input, options \\ []) do url_path = "/channels" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Returns a list of a specified insight's recommendations. Each recommendation includes a list of related metrics and a list of related events. """ def list_recommendations(%Client{} = client, input, options \\ []) do url_path = "/recommendations" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Collects customer feedback about the specified insight. """ def put_feedback(%Client{} = client, input, options \\ []) do url_path = "/feedback" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Removes a notification channel from DevOps Guru. A notification channel is used to notify you when DevOps Guru generates an insight that contains information about how to improve your operations. """ def remove_notification_channel(%Client{} = client, id, input, options \\ []) do url_path = "/channels/#{AWS.Util.encode_uri(id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 200 ) end @doc """ Returns a list of insights in your AWS account. You can specify which insights are returned by their start time, one or more statuses (`ONGOING`, `CLOSED`, and `CLOSED`), one or more severities (`LOW`, `MEDIUM`, and `HIGH`), and type (`REACTIVE` or `PROACTIVE`). Use the `Filters` parameter to specify status and severity search parameters. Use the `Type` parameter to specify `REACTIVE` or `PROACTIVE` in your search. """ def search_insights(%Client{} = client, input, options \\ []) do url_path = "/insights/search" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 200 ) end @doc """ Starts the creation of an estimate of the monthly cost to analyze your AWS resources. """ def start_cost_estimation(%Client{} = client, input, options \\ []) do url_path = "/cost-estimation" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates the collection of resources that DevOps Guru analyzes. The one type of AWS resource collection supported is AWS CloudFormation stacks. DevOps Guru can be configured to analyze only the AWS resources that are defined in the stacks. You can specify up to 500 AWS CloudFormation stacks. This method also creates the IAM role required for you to use DevOps Guru. """ def update_resource_collection(%Client{} = client, input, options \\ []) do url_path = "/resource-collections" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end @doc """ Enables or disables integration with a service that can be integrated with DevOps Guru. The one service that can be integrated with DevOps Guru is AWS Systems Manager, which can be used to create an OpsItem for each generated insight. """ def update_service_integration(%Client{} = client, input, options \\ []) do url_path = "/service-integrations" headers = [] query_params = [] Request.request_rest( client, metadata(), :put, url_path, query_params, headers, input, options, 200 ) end end
25.297114
175
0.643624
031da3fbdea67060e356da0fd1634a177debd9f0
2,074
ex
Elixir
lib/kafka_ex/utils/murmur.ex
Zarathustra2/kafka_ex
436a84c7a32bee40f1dbffc17a3c1a0f2fc98c30
[ "MIT" ]
536
2015-08-10T03:14:39.000Z
2022-03-24T15:07:33.000Z
lib/kafka_ex/utils/murmur.ex
Zarathustra2/kafka_ex
436a84c7a32bee40f1dbffc17a3c1a0f2fc98c30
[ "MIT" ]
349
2015-09-16T21:27:42.000Z
2022-03-28T08:51:56.000Z
lib/kafka_ex/utils/murmur.ex
Zarathustra2/kafka_ex
436a84c7a32bee40f1dbffc17a3c1a0f2fc98c30
[ "MIT" ]
180
2015-09-01T22:58:26.000Z
2022-03-25T16:47:49.000Z
defmodule KafkaEx.Utils.Murmur do @moduledoc """ Utility module that provides Murmur hashing algorithm. """ use Bitwise # Arbitrary constant for murmur2 hashing # https://github.com/aappleby/smhasher/blob/master/src/MurmurHash2.cpp#L39-L43 @m 0x5BD1E995 @r 24 # Default seed to hashing, copied form Java implementation # https://github.com/apache/kafka/blob/809be928f1ae004e11d65c307ea322bef126c834/clients/src/main/java/org/apache/kafka/common/utils/Utils.java#L382 @seed 0x9747B28C @doc """ Calculates murmur2 hash for given binary """ @spec murmur2(key :: binary) :: integer def murmur2(key) do <<seed::signed-size(32)>> = <<@seed::size(32)>> len = byte_size(key) _murmur2(key, seed ^^^ len) end @doc """ Calculates murmur2 hash for given binary as unsigned 32-bit integer """ @spec umurmur2(key :: binary) :: integer def umurmur2(key) do key |> murmur2() |> band(0x7FFFFFFF) end @doc """ Calculates murmur2 hash for given binary as unsigned 32-bit integer This is to support the legacy default partitioner implementation. """ @spec umurmur2_legacy(key :: binary) :: integer def umurmur2_legacy(key) do key |> murmur2() |> band(0xFFFFFFFF) end defp mask32(num) do <<signed::signed-size(32)>> = <<num &&& 0xFFFFFFFF::size(32)>> signed end # Unsigned Bitwise right shift on 32 bits defp ubsr32(num, shift) do (num &&& 0xFFFFFFFF) >>> shift end defp _murmur2(<<a::little-size(32), rest::binary>>, h) do k = mask32(a * @m) k = k ^^^ ubsr32(k, @r) k = mask32(k * @m) h = mask32(h * @m) _murmur2(rest, h ^^^ k) end defp _murmur2(<<a1::size(8), a2::size(8), a3::size(8)>>, h) do _murmur2(<<a1, a2>>, h ^^^ mask32(a3 <<< 16)) end defp _murmur2(<<a1::size(8), a2::size(8)>>, h) do _murmur2(<<a1>>, h ^^^ mask32(a2 <<< 8)) end defp _murmur2(<<a1::size(8)>>, h) do _murmur2("", mask32((h ^^^ a1) * @m)) end defp _murmur2("", h) do h = h ^^^ ubsr32(h, 13) h = mask32(h * @m) h ^^^ ubsr32(h, 15) end end
25.604938
149
0.627772
031dd7a803c25a9e56dd0b2486a4aeb00f9ff15f
1,033
exs
Elixir
mix.exs
eryx67/elixir-keycloak
8fa4d3bdf0686965b36aed47fa69ba0b6aa99221
[ "MIT" ]
null
null
null
mix.exs
eryx67/elixir-keycloak
8fa4d3bdf0686965b36aed47fa69ba0b6aa99221
[ "MIT" ]
null
null
null
mix.exs
eryx67/elixir-keycloak
8fa4d3bdf0686965b36aed47fa69ba0b6aa99221
[ "MIT" ]
1
2021-07-23T14:42:44.000Z
2021-07-23T14:42:44.000Z
defmodule Keycloak.Mixfile do use Mix.Project def project do [ app: :keycloak, version: "0.2.2", elixir: "~> 1.6", name: "keycloak", description: "Library for interacting with a Keycloak authorization server", package: package(), deps: deps(), docs: [extras: ["README.md"], main: "readme"], source_url: "https://github.com/vanetix/elixir-keycloak" ] end # Configuration for the OTP application def application do [extra_applications: [:logger, :oauth2]] end defp deps do [ {:joken, "~> 2.0"}, {:oauth2, "~> 2.0"}, {:plug, "~> 1.4"}, {:poison, "~> 4.0"}, {:credo, "~> 1.4", only: [:dev, :test], runtime: false}, {:ex_doc, "~> 0.21.3", only: :dev, runtime: false}, {:rexbug, "~> 1.0", only: :dev, runtime: false} ] end defp package do [ maintainers: ["Matthew McFarland"], licenses: ["MIT"], links: %{"Github" => "https://github.com/vanetix/elixir-keycloak"} ] end end
24.023256
82
0.548887
031dfc7a69641876c73191c77260e4c7f22de7f1
27,058
ex
Elixir
clients/compute/lib/google_api/compute/v1/api/networks.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/compute/lib/google_api/compute/v1/api/networks.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/networks.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.Compute.V1.Api.Networks do @moduledoc """ API calls for all endpoints tagged `Networks`. """ alias GoogleApi.Compute.V1.Connection alias GoogleApi.Gax.{Request, Response} @doc """ Adds a peering to the specified network. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `network` (*type:* `String.t`) - Name of the network resource to add peering to. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `:body` (*type:* `GoogleApi.Compute.V1.Model.NetworksAddPeeringRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_networks_add_peering( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def compute_networks_add_peering( connection, project, network, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{project}/global/networks/{network}/addPeering", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "network" => URI.encode(network, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end @doc """ Deletes the specified network. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `network` (*type:* `String.t`) - Name of the network to delete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_networks_delete(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def compute_networks_delete(connection, project, network, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/{project}/global/networks/{network}", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "network" => URI.encode(network, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end @doc """ Returns the specified network. Gets a list of available networks by making a list() request. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `network` (*type:* `String.t`) - Name of the network to return. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Network{}}` on success * `{:error, info}` on failure """ @spec compute_networks_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Network.t()} | {:error, Tesla.Env.t()} def compute_networks_get(connection, project, network, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{project}/global/networks/{network}", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "network" => URI.encode(network, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Network{}]) end @doc """ Creates a network in the specified project using the data included in the request. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `:body` (*type:* `GoogleApi.Compute.V1.Model.Network.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_networks_insert(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def compute_networks_insert(connection, project, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{project}/global/networks", %{ "project" => URI.encode(project, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end @doc """ Retrieves the list of networks available to the specified project. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). * `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) * `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by name or creationTimestamp desc is supported. * `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.NetworkList{}}` on success * `{:error, info}` on failure """ @spec compute_networks_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.NetworkList.t()} | {:error, Tesla.Env.t()} def compute_networks_list(connection, project, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :filter => :query, :maxResults => :query, :orderBy => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{project}/global/networks", %{ "project" => URI.encode(project, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.NetworkList{}]) end @doc """ Patches the specified network with the data included in the request. Only the following fields can be modified: routingConfig.routingMode. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `network` (*type:* `String.t`) - Name of the network to update. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `:body` (*type:* `GoogleApi.Compute.V1.Model.Network.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_networks_patch(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def compute_networks_patch(connection, project, network, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/{project}/global/networks/{network}", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "network" => URI.encode(network, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end @doc """ Removes a peering from the specified network. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `network` (*type:* `String.t`) - Name of the network resource to remove peering from. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `:body` (*type:* `GoogleApi.Compute.V1.Model.NetworksRemovePeeringRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_networks_remove_peering( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def compute_networks_remove_peering( connection, project, network, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{project}/global/networks/{network}/removePeering", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "network" => URI.encode(network, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end @doc """ Switches the network mode from auto subnet mode to custom subnet mode. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `network` (*type:* `String.t`) - Name of the network to be updated. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_networks_switch_to_custom_mode( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def compute_networks_switch_to_custom_mode( connection, project, network, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query } request = Request.new() |> Request.method(:post) |> Request.url("/{project}/global/networks/{network}/switchToCustomMode", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "network" => URI.encode(network, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end end
52.336557
414
0.656848
031dfd3aef635d5b2ccf386cc918570e8e6fadd6
334
ex
Elixir
lib/supabase_surface/components/icons/icon_box.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
5
2021-06-08T08:02:43.000Z
2022-02-09T23:13:46.000Z
lib/supabase_surface/components/icons/icon_box.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
null
null
null
lib/supabase_surface/components/icons/icon_box.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
1
2021-07-14T05:20:31.000Z
2021-07-14T05:20:31.000Z
defmodule SupabaseSurface.Components.Icons.IconBox do use SupabaseSurface.Components.Icon @impl true def render(assigns) do icon_size = IconContainer.get_size(assigns.size) ~F""" <IconContainer assigns={assigns}> {Feathericons.box(width: icon_size, height: icon_size)} </IconContainer> """ end end
22.266667
61
0.712575
031e003d172b1cb658b9998071cad1bfbe03a5dc
334
ex
Elixir
lib/hl7/2.5/segments/qak.ex
calvinb/elixir-hl7
5e953fa11f9184857c0ec4dda8662889f35a6bec
[ "Apache-2.0" ]
null
null
null
lib/hl7/2.5/segments/qak.ex
calvinb/elixir-hl7
5e953fa11f9184857c0ec4dda8662889f35a6bec
[ "Apache-2.0" ]
null
null
null
lib/hl7/2.5/segments/qak.ex
calvinb/elixir-hl7
5e953fa11f9184857c0ec4dda8662889f35a6bec
[ "Apache-2.0" ]
null
null
null
defmodule HL7.V2_5.Segments.QAK do @moduledoc false require Logger alias HL7.V2_5.{DataTypes} use HL7.Segment, fields: [ segment: nil, query_tag: nil, query_response_status: nil, message_query_name: DataTypes.Ce, hit_count: nil, this_payload: nil, hits_remaining: nil ] end
18.555556
39
0.652695
031e0418825349f9f21372bd69b0a6fa749e1aad
663
ex
Elixir
lib/spectre/api.ex
ijzer/spectre
1f23c60b5e6add3e9dd2aaf54e234efb5438355d
[ "MIT" ]
null
null
null
lib/spectre/api.ex
ijzer/spectre
1f23c60b5e6add3e9dd2aaf54e234efb5438355d
[ "MIT" ]
1
2017-04-13T18:27:31.000Z
2017-04-13T18:27:31.000Z
lib/spectre/api.ex
ijzer/spectre
1f23c60b5e6add3e9dd2aaf54e234efb5438355d
[ "MIT" ]
null
null
null
defmodule Spectre.API do @moduledoc """ Main entry point into the Spectre API. Requests to /api/* are for the Spectre API and are forwarded to Spectre.API.Spectre, requests to /subsonic/rest/* are for the Subsonic API layer and are forwarded to Spectre.API.Subsonic. The Subsonic API includes /rest/ because that is the location of the API in the Subsonic server and most clients have it hardcoded. """ use Plug.Router plug Plug.Logger plug :match plug :dispatch forward "/api", to: Spectre.API.Spectre forward "/subsonic/rest", to: Spectre.API.Subsonic match _ do send_resp(conn, 404, Atom.to_string(__MODULE__)) end end
28.826087
73
0.730015
031e31f833b848018dffabf03d6e34dce8f129be
3,165
ex
Elixir
lib/mix/lib/mix/generator.ex
TurtleAI/elixir
2fb41ebef4d06315dd6c05ee00899572b27ee50a
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/generator.ex
TurtleAI/elixir
2fb41ebef4d06315dd6c05ee00899572b27ee50a
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/generator.ex
TurtleAI/elixir
2fb41ebef4d06315dd6c05ee00899572b27ee50a
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Generator do @moduledoc """ Conveniences for working with paths and generating content. All of these functions are verbose, in the sense they log the action to be performed via `Mix.shell/0`. """ @doc """ Creates a file with the given contents. If the file already exists, asks for user confirmation. ## Options * `:force` - forces installation without a shell prompt. ## Examples iex> Mix.Generator.create_file ".gitignore", "_build\ndeps\n" * creating .gitignore :ok """ @spec create_file(Path.t, iodata, Keyword.t) :: any def create_file(path, contents, opts \\ []) when is_binary(path) do Mix.shell.info [:green, "* creating ", :reset, Path.relative_to_cwd(path)] if opts[:force] || Mix.Utils.can_write?(path) do File.mkdir_p!(Path.dirname(path)) File.write!(path, contents) end end @doc """ Creates a directory if one does not exist yet. This function does nothing if the given directory already exists; in this case, it still logs the directory creation. ## Examples iex> Mix.Generator.create_directory "path/to/dir" * creating path/to/dir :ok """ @spec create_directory(Path.t) :: any def create_directory(path) when is_binary(path) do Mix.shell.info [:green, "* creating ", :reset, Path.relative_to_cwd(path)] File.mkdir_p! path end @doc """ Embeds a template given by `contents` into the current module. It will define a private function with the `name` followed by `_template` that expects assigns as arguments. This function must be invoked passing a keyword list. Each key in the keyword list can be accessed in the template using the `@` macro. For more information, check `EEx.SmartEngine`. ## Examples defmodule Mix.Tasks.MyTask do require Mix.Generator Mix.Generator.embed_template(:log, "Log: <%= @log %>") end """ defmacro embed_template(name, contents) do quote bind_quoted: binding() do contents = case contents do [from_file: file] -> @file file File.read!(file) c when is_binary(c) -> @file {__ENV__.file, __ENV__.line+1} c _ -> raise ArgumentError, "expected string or from_file: file" end require EEx EEx.function_from_string :defp, :"#{name}_template", "<% _ = assigns %>" <> contents, [:assigns] end end @doc """ Embeds a text given by `contents` into the current module. It will define a private function with the `name` followed by `_text` that expects no arguments. ## Examples defmodule Mix.Tasks.MyTask do require Mix.Generator Mix.Generator.embed_text(:error, "There was an error!") end """ defmacro embed_text(name, contents) do quote bind_quoted: binding() do contents = case contents do [from_file: f] -> File.read!(f) c when is_binary(c) -> c _ -> raise ArgumentError, "expected string or from_file: file" end defp unquote(:"#{name}_text")(), do: unquote(contents) end end end
26.822034
102
0.641706
031e97af35eef5081306c909fb9c084620981094
917
ex
Elixir
lib/diff_web/views/render_view.ex
dbernheisel/diff
18db7395ec0661230e13f40b2bc65e909641dba8
[ "Apache-2.0" ]
null
null
null
lib/diff_web/views/render_view.ex
dbernheisel/diff
18db7395ec0661230e13f40b2bc65e909641dba8
[ "Apache-2.0" ]
null
null
null
lib/diff_web/views/render_view.ex
dbernheisel/diff
18db7395ec0661230e13f40b2bc65e909641dba8
[ "Apache-2.0" ]
null
null
null
defmodule DiffWeb.RenderView do use DiffWeb, :view def file_header(patch, status) do from = patch.from to = patch.to case status do "changed" -> from "renamed" -> "#{from} -> #{to}" "removed" -> from "added" -> to end end def patch_status(patch) do from = patch.from to = patch.to cond do !from -> "added" !to -> "removed" from == to -> "changed" true -> "renamed" end end def line_number(ln) when is_nil(ln), do: "" def line_number(ln), do: to_string(ln) def line_id(patch, line) do hash = :erlang.phash2({patch.from, patch.to}) ln = "-#{line.from_line_number}-#{line.to_line_number}" [to_string(hash), ln] end def line_type(line), do: to_string(line.type) def line_text("+" <> text), do: "+ " <> text def line_text("-" <> text), do: "- " <> text def line_text(text), do: " " <> text end
20.377778
59
0.570338
031e9e7c2f944118af68da0d69a4685c3359e8fd
248
ex
Elixir
web/channels/run_channel.ex
austinschwartz/docker_frontend_demo
5f6d0bb3db91db93d032b59cec95998bbb1935d8
[ "MIT" ]
null
null
null
web/channels/run_channel.ex
austinschwartz/docker_frontend_demo
5f6d0bb3db91db93d032b59cec95998bbb1935d8
[ "MIT" ]
null
null
null
web/channels/run_channel.ex
austinschwartz/docker_frontend_demo
5f6d0bb3db91db93d032b59cec95998bbb1935d8
[ "MIT" ]
null
null
null
defmodule Demo.RunChannel do use Phoenix.Channel def join("run", _payload, socket) do {:ok, socket} end def handle_in("run_instance", payload, socket) do broadcast! socket, "run_instance", payload {:noreply, socket} end end
19.076923
51
0.689516
031ea81a20ea0132bb9fed917006d090820aee48
1,425
ex
Elixir
apps/web_server/lib/web_server.ex
wajsel/shout_it_out_loud
f2b8a77a5cd2d158ed9ca65404ee2a18a7ab0cf3
[ "MIT" ]
null
null
null
apps/web_server/lib/web_server.ex
wajsel/shout_it_out_loud
f2b8a77a5cd2d158ed9ca65404ee2a18a7ab0cf3
[ "MIT" ]
null
null
null
apps/web_server/lib/web_server.ex
wajsel/shout_it_out_loud
f2b8a77a5cd2d158ed9ca65404ee2a18a7ab0cf3
[ "MIT" ]
null
null
null
defmodule WebServer do use Application # See http://elixir-lang.org/docs/stable/elixir/Application.html # for more information on OTP Applications def start(_type, _args) do #TODO: separate the webserver and the supervisor. # Put the webserver in a genserver as a WebServer.Worker # ¿ perhaps the IcyHandler be put in its own server? # and on startup deployed on different node, I.e. load balancing import Supervisor.Spec, warn: false dispatch = :cowboy_router.compile([ { :_, [ {"/", :cowboy_static, {:priv_file, :web_server, "index.html"}}, {"/static/[...]", :cowboy_static, {:priv_dir, :web_server, "static"}}, {"/shout/:id", IcyHandler, []}, {"/websocket", WebsocketHandler, []} ]} ]) #TODO: fetch port and number of connecton handlers from environment {:ok, _} = :cowboy.start_http(:http, 100, [{:port, 2050}], [{:env, [{:dispatch, dispatch}]}]) children = [ # Define workers and child supervisors to be supervised # worker(WebServer.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: WebServer.Supervisor] Supervisor.start_link(children, opts) end end
38.513514
80
0.607018
031ee312e2f73f32c8e459936c7f0b5f6c2fd70a
2,162
ex
Elixir
lib/codes/codes_g52.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_g52.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_g52.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_G52 do alias IcdCode.ICDCode def _G520 do %ICDCode{full_code: "G520", category_code: "G52", short_code: "0", full_name: "Disorders of olfactory nerve", short_name: "Disorders of olfactory nerve", category_name: "Disorders of olfactory nerve" } end def _G521 do %ICDCode{full_code: "G521", category_code: "G52", short_code: "1", full_name: "Disorders of glossopharyngeal nerve", short_name: "Disorders of glossopharyngeal nerve", category_name: "Disorders of glossopharyngeal nerve" } end def _G522 do %ICDCode{full_code: "G522", category_code: "G52", short_code: "2", full_name: "Disorders of vagus nerve", short_name: "Disorders of vagus nerve", category_name: "Disorders of vagus nerve" } end def _G523 do %ICDCode{full_code: "G523", category_code: "G52", short_code: "3", full_name: "Disorders of hypoglossal nerve", short_name: "Disorders of hypoglossal nerve", category_name: "Disorders of hypoglossal nerve" } end def _G527 do %ICDCode{full_code: "G527", category_code: "G52", short_code: "7", full_name: "Disorders of multiple cranial nerves", short_name: "Disorders of multiple cranial nerves", category_name: "Disorders of multiple cranial nerves" } end def _G528 do %ICDCode{full_code: "G528", category_code: "G52", short_code: "8", full_name: "Disorders of other specified cranial nerves", short_name: "Disorders of other specified cranial nerves", category_name: "Disorders of other specified cranial nerves" } end def _G529 do %ICDCode{full_code: "G529", category_code: "G52", short_code: "9", full_name: "Cranial nerve disorder, unspecified", short_name: "Cranial nerve disorder, unspecified", category_name: "Cranial nerve disorder, unspecified" } end end
30.885714
70
0.609621
031ef1e1376a70d02d7b9e9fc55dcefcb9902a20
1,039
ex
Elixir
lib/level_web/controllers/user_controller.ex
pradyumna2905/level
186878a128521074923edd7171eda2f1b181b4f4
[ "Apache-2.0" ]
null
null
null
lib/level_web/controllers/user_controller.ex
pradyumna2905/level
186878a128521074923edd7171eda2f1b181b4f4
[ "Apache-2.0" ]
null
null
null
lib/level_web/controllers/user_controller.ex
pradyumna2905/level
186878a128521074923edd7171eda2f1b181b4f4
[ "Apache-2.0" ]
null
null
null
defmodule LevelWeb.UserController do @moduledoc false use LevelWeb, :controller import Level.FeatureFlags alias Level.Users alias Level.Users.User plug :check_feature_flag def new(conn, _params) do case conn.assigns[:current_user] do %User{} -> conn |> redirect(to: main_path(conn, :index, ["spaces"])) _ -> conn |> assign(:changeset, Users.create_user_changeset(%User{})) |> render("new.html") end end def create(conn, %{"user" => user_params}) do case Users.create_user(user_params) do {:ok, user} -> conn |> LevelWeb.Auth.sign_in(user) |> redirect(to: main_path(conn, :index, ["spaces", "new"])) {:error, changeset} -> conn |> assign(:changeset, changeset) |> render("new.html") end end defp check_feature_flag(conn, _opts) do if signups_enabled?(Mix.env()) do conn else conn |> redirect(to: page_path(conn, :index)) |> halt() end end end
20.78
67
0.588065
031ef504fa1465be58835f3ccbd7d081550a9dd1
3,837
ex
Elixir
clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/google_cloud_datacatalog_v1beta1_search_catalog_request_scope.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/google_cloud_datacatalog_v1beta1_search_catalog_request_scope.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/google_cloud_datacatalog_v1beta1_search_catalog_request_scope.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogRequestScope do @moduledoc """ The criteria that select the subspace used for query matching. ## Attributes * `includeGcpPublicDatasets` (*type:* `boolean()`, *default:* `nil`) - If `true`, include Google Cloud Platform (GCP) public datasets in the search results. Info on GCP public datasets is available at https://cloud.google.com/public-datasets/. By default, GCP public datasets are excluded. * `includeOrgIds` (*type:* `list(String.t)`, *default:* `nil`) - The list of organization IDs to search within. To find your organization ID, follow instructions in https://cloud.google.com/resource-manager/docs/creating-managing-organization. * `includeProjectIds` (*type:* `list(String.t)`, *default:* `nil`) - The list of project IDs to search within. To learn more about the distinction between project names/IDs/numbers, go to https://cloud.google.com/docs/overview/#projects. * `restrictedLocations` (*type:* `list(String.t)`, *default:* `nil`) - Optional. The list of locations to search within. 1. If empty, search will be performed in all locations; 2. If any of the locations are NOT in the valid locations list, error will be returned; 3. Otherwise, search only the given locations for matching results. Typical usage is to leave this field empty. When a location is unreachable as returned in the `SearchCatalogResponse.unreachable` field, users can repeat the search request with this parameter set to get additional information on the error. Valid locations: * asia-east1 * asia-east2 * asia-northeast1 * asia-northeast2 * asia-northeast3 * asia-south1 * asia-southeast1 * australia-southeast1 * eu * europe-north1 * europe-west1 * europe-west2 * europe-west3 * europe-west4 * europe-west6 * global * northamerica-northeast1 * southamerica-east1 * us * us-central1 * us-east1 * us-east4 * us-west1 * us-west2 """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :includeGcpPublicDatasets => boolean(), :includeOrgIds => list(String.t()), :includeProjectIds => list(String.t()), :restrictedLocations => list(String.t()) } field(:includeGcpPublicDatasets) field(:includeOrgIds, type: :list) field(:includeProjectIds, type: :list) field(:restrictedLocations, type: :list) end defimpl Poison.Decoder, for: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogRequestScope do def decode(value, options) do GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogRequestScope.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogRequestScope do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.617647
144
0.699765
031f36ae5c697ef3b211da62e169c1b680d241f9
1,613
ex
Elixir
lib/web/controllers/document_controller.ex
smartlogic/Challenge_gov
b4203d1fcfb742dd17ecfadb9e9c56ad836d4254
[ "CC0-1.0" ]
9
2020-02-26T20:24:38.000Z
2022-03-22T21:14:52.000Z
lib/web/controllers/document_controller.ex
smartlogic/Challenge_gov
b4203d1fcfb742dd17ecfadb9e9c56ad836d4254
[ "CC0-1.0" ]
15
2020-04-22T19:33:24.000Z
2022-03-26T15:11:17.000Z
lib/web/controllers/document_controller.ex
smartlogic/Challenge_gov
b4203d1fcfb742dd17ecfadb9e9c56ad836d4254
[ "CC0-1.0" ]
4
2020-04-27T22:58:57.000Z
2022-01-14T13:42:09.000Z
defmodule Web.DocumentController do use Web, :controller alias ChallengeGov.Challenges alias ChallengeGov.SupportingDocuments alias Web.ErrorView action_fallback(Web.FallbackController) def create(conn, %{"challenge_id" => challenge_id, "document" => params}) do with {:ok, challenge} <- Challenges.get(challenge_id), {:ok, document} <- SupportingDocuments.upload(challenge.user, params), {:ok, document} <- SupportingDocuments.attach_to_challenge( document, challenge, Map.get(params, "section"), Map.get(params, "name") ) do conn |> put_flash(:info, "Document uploaded and attached") |> redirect(to: Routes.challenge_path(conn, :show, document.challenge_id)) end end def create(conn, %{"document" => params}) do %{current_user: user} = conn.assigns case SupportingDocuments.upload(user, params) do {:ok, document} -> conn |> assign(:document, document) |> put_status(:created) |> render("show.json") {:error, changeset} -> conn |> assign(:changeset, changeset) |> put_status(:unprocessable_entity) |> put_view(ErrorView) |> render("errors.json") end end def delete(conn, %{"id" => id}) do with {:ok, document} <- SupportingDocuments.get(id), {:ok, document} <- SupportingDocuments.delete(document) do conn |> put_flash(:info, "Document removed") |> redirect(to: Routes.challenge_path(conn, :show, document.challenge_id)) end end end
29.87037
80
0.618103
031f3f18feef9c2eccb0ee09ecd73013eee8bc41
1,343
ex
Elixir
lib/session.ex
rob05c/exedra
550091d95739959f2587f1245c105f2561caf1ab
[ "MIT" ]
1
2020-11-20T01:58:11.000Z
2020-11-20T01:58:11.000Z
lib/session.ex
rob05c/exedra
550091d95739959f2587f1245c105f2561caf1ab
[ "MIT" ]
null
null
null
lib/session.ex
rob05c/exedra
550091d95739959f2587f1245c105f2561caf1ab
[ "MIT" ]
null
null
null
defmodule Exedra.SessionManager do use GenServer @spec get(GenServer.server, String.t) :: {:ok, pid} | :error def get(server, player) do GenServer.call server, {:get, player} end @spec set(GenServer.server, String.t, pid) :: :ok def set(server, player, pid) do GenServer.cast server, {:set, player, pid} end @spec delete(GenServer.server, String.t) :: :ok def delete(server, player) do GenServer.cast server, {:delete, player} end @spec init([]) :: {:ok, %{}} def init([]) do {:ok, %{}} end # @spec start_link(String.t) :: GenServer.on_start @spec start_link(atom | {:global, any} | {:via, atom, any}) :: :ignore | {:error, any} | {:ok, pid} def start_link(name) do GenServer.start_link __MODULE__, [], name: name end @spec handle_call({:get, String.t}, any, %{}) :: {:reply, {:ok, pid} | :error, %{}} def handle_call({:get, player}, _from, data) do reply = Map.fetch(data, player) {:reply, reply, data} end @spec handle_cast({:set, String.t, pid}, %{}) :: {:noreply, %{}} def handle_cast({:set, player, pid}, data) do data = Map.put data, player, pid {:noreply, data} end @spec handle_cast({:delete, String.t}, %{}) :: {:noreply, %{}} def handle_cast({:delete, player}, data) do data = Map.delete(data, player) {:noreply, data} end end
27.408163
101
0.610573
031f7af9bb96cf9bc70d310c91494bd93611bc55
4,327
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/api/cities.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/api/cities.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/api/cities.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DFAReporting.V33.Api.Cities do @moduledoc """ API calls for all endpoints tagged `Cities`. """ alias GoogleApi.DFAReporting.V33.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Retrieves a list of cities, possibly filtered. ## Parameters * `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server * `profile_id` (*type:* `String.t`) - User profile ID associated with this request. * `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"). * `:countryDartIds` (*type:* `list(String.t)`) - Select only cities from these countries. * `:dartIds` (*type:* `list(String.t)`) - Select only cities with these DART IDs. * `:namePrefix` (*type:* `String.t`) - Select only cities with names starting with this prefix. * `:regionDartIds` (*type:* `list(String.t)`) - Select only cities from these regions. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.DFAReporting.V33.Model.CitiesListResponse{}}` on success * `{:error, info}` on failure """ @spec dfareporting_cities_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.DFAReporting.V33.Model.CitiesListResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def dfareporting_cities_list(connection, profile_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, :countryDartIds => :query, :dartIds => :query, :namePrefix => :query, :regionDartIds => :query } request = Request.new() |> Request.method(:get) |> Request.url("/dfareporting/v3.3/userprofiles/{profileId}/cities", %{ "profileId" => URI.encode(profile_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.DFAReporting.V33.Model.CitiesListResponse{}]) end end
45.072917
196
0.648024
031f80fa5a190bd0dde337a66c0fbbc36c7da24b
1,283
ex
Elixir
backend/test/support/conn_case.ex
azhi/cpsim
a10a3e068a8a319e66cc9cf8a6c9c97457d9bf8b
[ "MIT" ]
null
null
null
backend/test/support/conn_case.ex
azhi/cpsim
a10a3e068a8a319e66cc9cf8a6c9c97457d9bf8b
[ "MIT" ]
null
null
null
backend/test/support/conn_case.ex
azhi/cpsim
a10a3e068a8a319e66cc9cf8a6c9c97457d9bf8b
[ "MIT" ]
null
null
null
defmodule CPSIM.BackendWeb.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 CPSIM.BackendWeb.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 CPSIM.BackendWeb.ConnCase alias CPSIM.BackendWeb.Router.Helpers, as: Routes # The default endpoint for testing @endpoint CPSIM.BackendWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(CPSIM.Backend.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(CPSIM.Backend.Repo, {:shared, self()}) end {:ok, conn: Phoenix.ConnTest.build_conn()} end end
29.159091
75
0.727981
031fc3fc2d21a3d48b475e38bc3bf336942b7739
257
exs
Elixir
test/wow/jobs/scheduler_test.exs
DrPandemic/expressive-broker
66a8da94ede2c101db9e1841e17898b5bae5df49
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
null
null
null
test/wow/jobs/scheduler_test.exs
DrPandemic/expressive-broker
66a8da94ede2c101db9e1841e17898b5bae5df49
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
null
null
null
test/wow/jobs/scheduler_test.exs
DrPandemic/expressive-broker
66a8da94ede2c101db9e1841e17898b5bae5df49
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
null
null
null
defmodule Wow.Jobs.SchedulerTest do use ExUnit.Case, async: true setup do Mock.Toniq.clear :ok end test "schedule/0 enqueues 2 jobs" do Wow.Jobs.Scheduler.schedule(Mock.Toniq) assert Enum.count(Mock.Toniq.enqueued) == 2 end end
17.133333
47
0.696498
031fd280ef56ede194ecdd4dedc1667b6c773125
1,293
ex
Elixir
lib/jaya_currency_converter/exchanges.ex
franknfjr/jaya_currency_converter
56dfcf40b2ed2c9307fa39d7a5d1121cf4a1a37e
[ "MIT" ]
null
null
null
lib/jaya_currency_converter/exchanges.ex
franknfjr/jaya_currency_converter
56dfcf40b2ed2c9307fa39d7a5d1121cf4a1a37e
[ "MIT" ]
null
null
null
lib/jaya_currency_converter/exchanges.ex
franknfjr/jaya_currency_converter
56dfcf40b2ed2c9307fa39d7a5d1121cf4a1a37e
[ "MIT" ]
null
null
null
defmodule JayaCurrencyConverter.Exchanges do @moduledoc """ The Exchanges context. """ import Ecto.Query, warn: false alias JayaCurrencyConverter.Repo alias JayaCurrencyConverter.Accounts.User alias JayaCurrencyConverter.Exchanges.Transaction @doc """ Returns the list of transactions. ## Examples iex> list_transactions() [%Transaction{}, ...] """ def list_transactions(user \\ nil) do if user do query = from t in Transaction, where: t.user_id == ^user.id Repo.all(query) else Repo.all(Transaction) end end @doc """ Gets a single transaction. Raises `Ecto.NoResultsError` if the Transaction does not exist. ## Examples iex> get_transaction!(123) %Transaction{} iex> get_transaction!(456) ** (Ecto.NoResultsError) """ def get_transaction!(id), do: Repo.get!(Transaction, id) @doc """ Creates a transaction. ## Examples iex> create_transaction(%{field: value}) {:ok, %Transaction{}} iex> create_transaction(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ def create_transaction(%User{} = user, attrs \\ %{}) do user |> Ecto.build_assoc(:transactions, attrs) |> Transaction.changeset(attrs) |> Repo.insert() end end
19.892308
65
0.645012
031fd60684f9c75f519eb756444228392a9859a2
507
ex
Elixir
lib/ash/error/invalid/no_such_action.ex
elbow-jason/ash
eb63bc9d4d24187ad07d9892088b4e55ad6258e4
[ "MIT" ]
1
2021-12-27T09:43:29.000Z
2021-12-27T09:43:29.000Z
lib/ash/error/invalid/no_such_action.ex
elbow-jason/ash
eb63bc9d4d24187ad07d9892088b4e55ad6258e4
[ "MIT" ]
null
null
null
lib/ash/error/invalid/no_such_action.ex
elbow-jason/ash
eb63bc9d4d24187ad07d9892088b4e55ad6258e4
[ "MIT" ]
null
null
null
defmodule Ash.Error.Invalid.NoSuchAction do @moduledoc "Used when an action name is provided that doesn't exist" use Ash.Error def_ash_error([:resource, :action, :type], class: :invalid) defimpl Ash.ErrorKind do def id(_), do: Ecto.UUID.generate() def code(_), do: "no_such_action" def message(%{resource: resource, action: action, type: type}) do "No such action #{inspect(action)} of type #{inspect(type)} for resource #{ inspect(resource) }" end end end
26.684211
81
0.670611
031fe0b58f5a7d5b85305c86380b169e404c8f0d
3,248
ex
Elixir
clients/partners/lib/google_api/partners/v2/model/historical_offer.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/partners/lib/google_api/partners/v2/model/historical_offer.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/partners/lib/google_api/partners/v2/model/historical_offer.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.Partners.V2.Model.HistoricalOffer do @moduledoc """ Historical information about a Google Partners Offer. ## Attributes - adwordsUrl (String.t): Client&#39;s AdWords page URL. Defaults to: `null`. - clientEmail (String.t): Email address for client. Defaults to: `null`. - clientId (String.t): ID of client. Defaults to: `null`. - clientName (String.t): Name of the client. Defaults to: `null`. - creationTime (DateTime.t): Time offer was first created. Defaults to: `null`. - expirationTime (DateTime.t): Time this offer expires. Defaults to: `null`. - lastModifiedTime (DateTime.t): Time last action was taken. Defaults to: `null`. - offerCode (String.t): Offer code. Defaults to: `null`. - offerCountryCode (String.t): Country Code for the offer country. Defaults to: `null`. - offerType (String.t): Type of offer. Defaults to: `null`. - Enum - one of [OFFER_TYPE_UNSPECIFIED, OFFER_TYPE_SPEND_X_GET_Y, OFFER_TYPE_VIDEO, OFFER_TYPE_SPEND_MATCH] - senderName (String.t): Name (First + Last) of the partners user to whom the incentive is allocated. Defaults to: `null`. - status (String.t): Status of the offer. Defaults to: `null`. - Enum - one of [OFFER_STATUS_UNSPECIFIED, OFFER_STATUS_DISTRIBUTED, OFFER_STATUS_REDEEMED, OFFER_STATUS_AWARDED, OFFER_STATUS_EXPIRED] """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :adwordsUrl => any(), :clientEmail => any(), :clientId => any(), :clientName => any(), :creationTime => DateTime.t(), :expirationTime => DateTime.t(), :lastModifiedTime => DateTime.t(), :offerCode => any(), :offerCountryCode => any(), :offerType => any(), :senderName => any(), :status => any() } field(:adwordsUrl) field(:clientEmail) field(:clientId) field(:clientName) field(:creationTime, as: DateTime) field(:expirationTime, as: DateTime) field(:lastModifiedTime, as: DateTime) field(:offerCode) field(:offerCountryCode) field(:offerType) field(:senderName) field(:status) end defimpl Poison.Decoder, for: GoogleApi.Partners.V2.Model.HistoricalOffer do def decode(value, options) do GoogleApi.Partners.V2.Model.HistoricalOffer.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Partners.V2.Model.HistoricalOffer do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.13253
139
0.703202
031fe1925e08199256a4abd69859f4055aa0a005
16,848
exs
Elixir
test/oli/institutions_test.exs
chrislawson/oli-torus
94165b211ab74fac3e7c8a14110a394fa9a6f320
[ "MIT" ]
null
null
null
test/oli/institutions_test.exs
chrislawson/oli-torus
94165b211ab74fac3e7c8a14110a394fa9a6f320
[ "MIT" ]
null
null
null
test/oli/institutions_test.exs
chrislawson/oli-torus
94165b211ab74fac3e7c8a14110a394fa9a6f320
[ "MIT" ]
null
null
null
defmodule Oli.InstitutionsTest do use Oli.DataCase import Oli.Factory alias Oli.Institutions alias Oli.Institutions.Institution alias Oli.Institutions.PendingRegistration alias Oli.Lti_1p3.Tool.Registration describe "institutions" do test "get_institution_by!/1 with existing data returns an institution" do %Institution{name: name} = insert(:institution) institution = Institutions.get_institution_by!(%{name: name}) assert institution.name == name end test "get_institution_by!/1 with invalid data returns nil" do refute Institutions.get_institution_by!(%{name: "invalid_name"}) end test "get_institution_by!/1 with multiple results raises an error" do insert_pair(:institution) assert_raise Ecto.MultipleResultsError, fn -> Institutions.get_institution_by!(%{country_code: "US"}) end end end describe "registrations" do setup do institution = institution_fixture() jwk = jwk_fixture() registration = registration_fixture(%{institution_id: institution.id, tool_jwk_id: jwk.id}) # registration = registration |> Repo.preload([:deployments]) %{institution: institution, jwk: jwk, registration: registration} end @valid_attrs %{ auth_login_url: "some auth_login_url", auth_server: "some auth_server", auth_token_url: "some auth_token_url", client_id: "some client_id", issuer: "some issuer", key_set_url: "some key_set_url" } @update_attrs %{ auth_login_url: "some updated auth_login_url", auth_server: "some updated auth_server", auth_token_url: "some updated auth_token_url", client_id: "some updated client_id", issuer: "some updated issuer", key_set_url: "some updated key_set_url" } @invalid_attrs %{ auth_login_url: nil, auth_server: nil, auth_token_url: nil, client_id: nil, issuer: nil, key_set_url: nil } test "list_registrations/0 returns all registrations", %{registration: registration} do assert Institutions.list_registrations() |> Enum.map(& &1.id) == [registration.id] end test "get_registration!/1 returns the registration with given id", %{ registration: registration } do assert Institutions.get_registration!(registration.id) == registration end test "create_registration/1 with valid data creates a registration", %{ institution: institution, jwk: jwk } do assert {:ok, %Registration{} = registration} = Institutions.create_registration( Enum.into( %{ institution_id: institution.id, tool_jwk_id: jwk.id, issuer: "some other issuer" }, @valid_attrs ) ) assert registration.auth_login_url == "some auth_login_url" assert registration.auth_server == "some auth_server" assert registration.auth_token_url == "some auth_token_url" assert registration.client_id == "some client_id" assert registration.issuer == "some other issuer" assert registration.key_set_url == "some key_set_url" end test "create_registration/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Institutions.create_registration(@invalid_attrs) end test "update_registration/2 with valid data updates the registration", %{ registration: registration } do assert {:ok, %Registration{} = registration} = Institutions.update_registration(registration, @update_attrs) assert registration.auth_login_url == "some updated auth_login_url" assert registration.auth_server == "some updated auth_server" assert registration.auth_token_url == "some updated auth_token_url" assert registration.client_id == "some updated client_id" assert registration.issuer == "some updated issuer" assert registration.key_set_url == "some updated key_set_url" end test "update_registration/2 with invalid data returns error changeset", %{ registration: registration } do assert {:error, %Ecto.Changeset{}} = Institutions.update_registration(registration, @invalid_attrs) assert registration == Institutions.get_registration!(registration.id) end test "delete_registration/1 deletes the registration", %{registration: registration} do assert {:ok, %Registration{}} = Institutions.delete_registration(registration) assert_raise Ecto.NoResultsError, fn -> Institutions.get_registration!(registration.id) end end test "change_registration/1 returns a registration changeset", %{registration: registration} do assert %Ecto.Changeset{} = Institutions.change_registration(registration) end end describe "deployments" do alias Oli.Lti_1p3.Tool.Deployment setup do institution = institution_fixture() jwk = jwk_fixture() registration = registration_fixture(%{tool_jwk_id: jwk.id}) deployment = deployment_fixture(%{institution_id: institution.id, registration_id: registration.id}) registration = registration |> Repo.preload([:deployments]) %{institution: institution, jwk: jwk, registration: registration, deployment: deployment} end @valid_attrs %{deployment_id: "some deployment_id"} @update_attrs %{deployment_id: "some updated deployment_id"} @invalid_attrs %{deployment_id: nil, registration_id: nil} test "list_deployments/0 returns all deployments", %{deployment: deployment} do assert Institutions.list_deployments() == [deployment] end test "get_deployment!/1 returns the deployment with given id", %{deployment: deployment} do assert Institutions.get_deployment!(deployment.id) == deployment end test "create_deployment/1 with valid data creates a deployment", %{ institution: institution, registration: registration } do assert {:ok, %Deployment{} = deployment} = Institutions.create_deployment( @valid_attrs |> Enum.into(%{institution_id: institution.id, registration_id: registration.id}) ) assert deployment.deployment_id == "some deployment_id" end test "create_deployment/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Institutions.create_deployment(@invalid_attrs) end test "update_deployment/2 with valid data updates the deployment", %{deployment: deployment} do assert {:ok, %Deployment{} = deployment} = Institutions.update_deployment(deployment, @update_attrs) assert deployment.deployment_id == "some updated deployment_id" end test "update_deployment/2 with invalid data returns error changeset", %{ deployment: deployment } do assert {:error, %Ecto.Changeset{}} = Institutions.update_deployment(deployment, @invalid_attrs) assert deployment == Institutions.get_deployment!(deployment.id) end test "delete_deployment/1 deletes the deployment", %{deployment: deployment} do assert {:ok, %Deployment{}} = Institutions.delete_deployment(deployment) assert_raise Ecto.NoResultsError, fn -> Institutions.get_deployment!(deployment.id) end end test "change_deployment/1 returns a deployment changeset", %{deployment: deployment} do assert %Ecto.Changeset{} = Institutions.change_deployment(deployment) end end describe "pending_registration" do alias Lti_1p3.Tool.Deployment setup do institution = institution_fixture() jwk = jwk_fixture() registration = registration_fixture(%{tool_jwk_id: jwk.id}) deployment = deployment_fixture(%{institution_id: institution.id, registration_id: registration.id}) pending_registration = pending_registration_fixture() registration = registration |> Repo.preload([:deployments]) %{ institution: institution, jwk: jwk, registration: registration, deployment: deployment, pending_registration: pending_registration } end @valid_attrs %{ name: "some institution", country_code: "some country_code", institution_email: "some institution_email", institution_url: "some institution_url", timezone: "some timezone", issuer: "some issuer", client_id: "some client_id", key_set_url: "some key_set_url", auth_token_url: "some auth_token_url", auth_login_url: "some auth_login_url", auth_server: "some auth_server" } @update_attrs %{ name: "some updated institution", country_code: "some updated country_code", institution_email: "some updated institution_email", institution_url: "some updated institution_url", timezone: "some updated timezone", issuer: "some updated issuer", client_id: "some updated client_id", key_set_url: "some updated key_set_url", auth_token_url: "some updated auth_token_url", auth_login_url: "some updated auth_login_url", auth_server: "some updated auth_server" } @invalid_attrs %{ name: nil, country_code: nil, institution_email: nil, institution_url: nil, timezone: nil, issuer: nil, client_id: nil, key_set_url: nil, auth_token_url: nil, auth_login_url: nil, auth_server: nil } test "list_pending_registrations/0 returns all pending_registrations", %{ pending_registration: pending_registration } do assert Institutions.list_pending_registrations() == [pending_registration] end test "count_pending_registrations/0 returns the total count of pending registrations" do assert Institutions.count_pending_registrations() == 1 Institutions.create_pending_registration(@valid_attrs) assert Institutions.count_pending_registrations() == 2 end test "get_pending_registration!/1 returns the pending_registration with given id", %{ pending_registration: pending_registration } do assert Institutions.get_pending_registration!(pending_registration.id) == pending_registration end test "create_pending_registration/1 with valid data creates a pending_registration" do assert {:ok, %PendingRegistration{} = pending_registration} = Institutions.create_pending_registration(@valid_attrs) assert pending_registration.name == "some institution" end test "create_pending_registration/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Institutions.create_pending_registration(@invalid_attrs) end test "update_pending_registration/2 with valid data updates the pending_registration", %{ pending_registration: pending_registration } do assert {:ok, %PendingRegistration{} = pending_registration} = Institutions.update_pending_registration(pending_registration, @update_attrs) assert pending_registration.name == "some updated institution" end test "update_pending_registration/2 with invalid data returns error changeset", %{ pending_registration: pending_registration } do assert {:error, %Ecto.Changeset{}} = Institutions.update_pending_registration(pending_registration, @invalid_attrs) assert pending_registration == Institutions.get_pending_registration!(pending_registration.id) end test "delete_pending_registration/1 deletes the pending_registration", %{ pending_registration: pending_registration } do assert {:ok, %PendingRegistration{}} = Institutions.delete_pending_registration(pending_registration) assert_raise Ecto.NoResultsError, fn -> Institutions.get_pending_registration!(pending_registration.id) end end test "change_pending_registration/1 returns a pending_registration changeset", %{ pending_registration: pending_registration } do assert %Ecto.Changeset{} = Institutions.change_pending_registration(pending_registration) end test "find_or_create_institution_by_normalized_url/1 find an institution with a similar url", %{institution: institution} do {:ok, same_institution} = Institutions.find_or_create_institution_by_normalized_url(%{ country_code: "US", institution_email: "[email protected]", institution_url: "https://institution.example.edu/", name: "Example Institution", timezone: "US/Eastern" }) assert same_institution.id == institution.id {:ok, same_institution} = Institutions.find_or_create_institution_by_normalized_url(%{ country_code: "US", institution_email: "[email protected]", institution_url: "http://institution.example.edu", name: "Example Institution", timezone: "US/Eastern" }) assert same_institution.id == institution.id {:ok, different_institution} = Institutions.find_or_create_institution_by_normalized_url(%{ country_code: "US", institution_email: "[email protected]", institution_url: "http://different.example.edu", name: "Example Institution", timezone: "US/Eastern" }) assert different_institution.id != institution.id end test "find_or_create_institution_by_normalized_url/1 uses the first existing institution if multiple institutions with similar urls exist", %{institution: first_institution} do _second_institution = institution_fixture() {:ok, result_institution} = Institutions.find_or_create_institution_by_normalized_url(%{ country_code: "US", institution_email: "[email protected]", institution_url: "https://institution.example.edu/", name: "Example Institution", timezone: "US/Eastern" }) assert result_institution.id == first_institution.id end test "approve_pending_registration/1 creates a new institution and registration and removes pending registration" do {:ok, %PendingRegistration{} = pending_registration} = Institutions.create_pending_registration(%{ name: "New Institution", country_code: "US", institution_email: "[email protected]", institution_url: "http://new.example.edu", timezone: "US/Eastern", issuer: "new issuer", client_id: "new client_id", key_set_url: "new key_set_url", auth_token_url: "new auth_token_url", auth_login_url: "new auth_login_url", auth_server: "new auth_server" }) {:ok, {%Institution{}, %Registration{}, _deployment}} = Institutions.approve_pending_registration(pending_registration) assert Institutions.list_institutions() |> Enum.find(fn i -> i.institution_url == "http://new.example.edu" end) != nil assert Institutions.list_registrations() |> Enum.find(fn r -> r.issuer == "new issuer" end) != nil assert Institutions.get_pending_registration( "some issuer", "some client_id", "some deployment_id" ) == nil end test "approve_pending_registration/1 creates registration using existing institution for similar institution_url and removes pending registration" do {:ok, %PendingRegistration{} = pending_registration} = Institutions.create_pending_registration(%{ name: "New Institution", country_code: "US", institution_email: "[email protected]", institution_url: "http://institution.example.edu", timezone: "US/Eastern", issuer: "new issuer", client_id: "new client_id", key_set_url: "new key_set_url", auth_token_url: "new auth_token_url", auth_login_url: "new auth_login_url", auth_server: "new auth_server" }) {:ok, {%Institution{}, %Registration{}, _deployment}} = Institutions.approve_pending_registration(pending_registration) assert Institutions.list_institutions() |> Enum.count() == 1 assert Institutions.list_registrations() |> Enum.find(fn r -> r.issuer == "new issuer" end) != nil assert Institutions.get_pending_registration( "some issuer", "some client_id", "some deployment_id" ) == nil end end end
36.626087
153
0.679487
031fe330a03e7ec528245c669012367ed85447bb
181
ex
Elixir
apps/local_ledger/lib/local_ledger/errors/invalid_amount_error.ex
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
1
2018-12-07T06:21:21.000Z
2018-12-07T06:21:21.000Z
apps/local_ledger/lib/local_ledger/errors/invalid_amount_error.ex
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
apps/local_ledger/lib/local_ledger/errors/invalid_amount_error.ex
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
defmodule LocalLedger.Errors.InvalidAmountError do defexception message: "Transaction could not be created. Debit and Credit amounts were different." end
36.2
66
0.718232
031fef341feeea4459bb60171f239605d30a3c95
527
ex
Elixir
traceme/lib/traceme/avatar.ex
derailed/ex_ray_tracers
a687baedde8c472ce426afba02902a336a403a7f
[ "Apache-2.0" ]
9
2017-10-29T17:35:14.000Z
2020-04-19T14:06:50.000Z
traceme/lib/traceme/avatar.ex
derailed/ex_ray_tracers
a687baedde8c472ce426afba02902a336a403a7f
[ "Apache-2.0" ]
null
null
null
traceme/lib/traceme/avatar.ex
derailed/ex_ray_tracers
a687baedde8c472ce426afba02902a336a403a7f
[ "Apache-2.0" ]
null
null
null
defmodule Traceme.Avatar do use ExRay, pre: :pre_call, post: :post_call @trace kind: :function def get_icon(_req_id, _p_span, castle) do :timer.sleep(500) castle.name av = castle.name |> String.replace(" ", "") |> String.downcase |> Macro.underscore av <> ".png" end defp pre_call(ctx) do ctx.target |> ExRay.Span.open(ctx.args |> List.first, ctx.args |> Enum.at(1)) end defp post_call(ctx, p_span, _res) do p_span |> ExRay.Span.close(ctx.args |> List.first) end end
21.08
70
0.631879
031ff09bf95e82122f4cfa5cffc4b184f1926dc3
5,089
ex
Elixir
backend/lib/getaways_web/schema/schema.ex
Prumme/Projet_phx_ex_gql
6324af91f94f96ee1f8403d5397ab930347e3e4f
[ "Unlicense" ]
null
null
null
backend/lib/getaways_web/schema/schema.ex
Prumme/Projet_phx_ex_gql
6324af91f94f96ee1f8403d5397ab930347e3e4f
[ "Unlicense" ]
6
2020-01-31T19:44:15.000Z
2021-09-02T04:26:49.000Z
backend/lib/getaways_web/schema/schema.ex
Prumme/Projet_phx_ex_gql
6324af91f94f96ee1f8403d5397ab930347e3e4f
[ "Unlicense" ]
null
null
null
defmodule GetawaysWeb.Schema.Schema do use Absinthe.Schema alias Getaways.{Accounts, Vacation} import_types Absinthe.Type.Custom import Absinthe.Resolution.Helpers, only: [dataloader: 1, dataloader: 3] alias GetawaysWeb.Resolvers alias GetawaysWeb.Schema.Middleware query do @desc "Get a place by its slug" field :place, :place do arg :slug, non_null(:string) resolve &Resolvers.Vacation.place/3 end @desc "Get a list of places" field :places, list_of(:place) do arg :limit, :integer arg :order, type: :sort_order, default_value: :asc arg :filter, :place_filter resolve &Resolvers.Vacation.places/3 end @desc "Get the currently signed-in user" field :me, :user do resolve &Resolvers.Accounts.me/3 end end mutation do @desc "Create a booking for a place" field :create_booking, :booking do arg :place_id, non_null(:id) arg :start_date, non_null(:date) arg :end_date, non_null(:date) middleware Middleware.Authenticate resolve &Resolvers.Vacation.create_booking/3 end @desc "Cancel a booking" field :cancel_booking, :booking do arg :booking_id, non_null(:id) middleware Middleware.Authenticate resolve &Resolvers.Vacation.cancel_booking/3 end @desc "Create a review for a place" field :create_review, :review do arg :place_id, non_null(:id) arg :comment, :string arg :rating, non_null(:integer) middleware Middleware.Authenticate resolve &Resolvers.Vacation.create_review/3 end @desc "Create a user account" field :signup, :session do arg :username, non_null(:string) arg :email, non_null(:string) arg :password, non_null(:string) resolve &Resolvers.Accounts.signup/3 end @desc "Sign in a user" field :signin, :session do arg :username, non_null(:string) arg :password, non_null(:string) resolve &Resolvers.Accounts.signin/3 end end subscription do @desc "Subscribe to booking changes for a place" field :booking_change, :booking do arg :place_id, non_null(:id) config fn args, _res -> {:ok, topic: args.place_id} end end end # # Object Types # object :place do field :id, non_null(:id) field :name, non_null(:string) field :location, non_null(:string) field :slug, non_null(:string) field :description, non_null(:string) field :max_guests, non_null(:integer) field :pet_friendly, non_null(:boolean) field :pool, non_null(:boolean) field :wifi, non_null(:boolean) field :price_per_night, non_null(:decimal) field :image, non_null(:string) field :image_thumbnail, non_null(:string) field :bookings, list_of(:booking) do arg :limit, type: :integer, default_value: 100 resolve dataloader(Vacation, :bookings, args: %{scope: :place}) end field :reviews, list_of(:review), resolve: dataloader(Vacation) end object :booking do field :id, non_null(:id) field :start_date, non_null(:date) field :end_date, non_null(:date) field :state, non_null(:string) field :total_price, non_null(:decimal) field :user, non_null(:user), resolve: dataloader(Accounts) field :place, non_null(:place), resolve: dataloader(Vacation) end object :review do field :id, non_null(:id) field :rating, non_null(:integer) field :comment, non_null(:string) field :inserted_at, non_null(:naive_datetime) field :user, non_null(:user), resolve: dataloader(Accounts) field :place, non_null(:place), resolve: dataloader(Vacation) end object :user do field :username, non_null(:string) field :email, non_null(:string) field :bookings, list_of(:booking), resolve: dataloader(Vacation, :bookings, args: %{scope: :user}) field :reviews, list_of(:review), resolve: dataloader(Vacation) end object :session do field :user, non_null(:user) field :token, non_null(:string) end # # Input Object Types # @desc "Filters for the list of places" input_object :place_filter do @desc "Matching a name, location, or description" field :matching, :string @desc "Has wifi" field :wifi, :boolean @desc "Allows pets" field :pet_friendly, :boolean @desc "Has a pool" field :pool, :boolean @desc "Number of guests" field :guest_count, :integer @desc "Available for booking between a start and end date" field :available_between, :date_range end @desc "Start and end dates" input_object :date_range do field :start_date, non_null(:date) field :end_date, non_null(:date) end enum :sort_order do value :asc value :desc end def context(ctx) do loader = Dataloader.new |> Dataloader.add_source(Vacation, Vacation.datasource()) |> Dataloader.add_source(Accounts, Accounts.datasource()) Map.put(ctx, :loader, loader) end def plugins do [Absinthe.Middleware.Dataloader] ++ Absinthe.Plugin.defaults() end end
26.925926
74
0.672431
031ffcf40f09f0111dfe4e9b6f8cdc4ef4afe526
347
ex
Elixir
lib/supabase_surface/components/icons/icon_chevron_up.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
5
2021-06-08T08:02:43.000Z
2022-02-09T23:13:46.000Z
lib/supabase_surface/components/icons/icon_chevron_up.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
null
null
null
lib/supabase_surface/components/icons/icon_chevron_up.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
1
2021-07-14T05:20:31.000Z
2021-07-14T05:20:31.000Z
defmodule SupabaseSurface.Components.Icons.IconChevronUp do use SupabaseSurface.Components.Icon @impl true def render(assigns) do icon_size = IconContainer.get_size(assigns.size) ~F""" <IconContainer assigns={assigns}> {Feathericons.chevron_up(width: icon_size, height: icon_size)} </IconContainer> """ end end
23.133333
68
0.723343
03201346e46234a0630bde968c56f56c5332be3c
8,776
ex
Elixir
lib/mix/tasks/phx.gen.html.ex
oskarrough/phoenix
43c9829511cf2836dda4128b5101005bd2cc0ab9
[ "MIT" ]
null
null
null
lib/mix/tasks/phx.gen.html.ex
oskarrough/phoenix
43c9829511cf2836dda4128b5101005bd2cc0ab9
[ "MIT" ]
null
null
null
lib/mix/tasks/phx.gen.html.ex
oskarrough/phoenix
43c9829511cf2836dda4128b5101005bd2cc0ab9
[ "MIT" ]
null
null
null
defmodule Mix.Tasks.Phx.Gen.Html do @shortdoc "Generates controller, views, and context for an HTML resource" @moduledoc """ Generates controller, views, and context for an HTML resource. mix phx.gen.html Accounts User users name:string age:integer The first argument is the context module followed by the schema module and its plural name (used as the schema table name). The context is an Elixir module that serves as an API boundary for the given resource. A context often holds many related resources. Therefore, if the context already exists, it will be augmented with functions for the given resource. Note a resource may also be split over distinct contexts (such as Accounts.User and Payments.User). The schema is responsible for mapping the database fields into an Elixir struct. Overall, this generator will add the following files to `lib/`: * a context module in lib/app/accounts/accounts.ex for the accounts API * a schema in lib/app/accounts/user.ex, with an `users` table * a view in lib/app_web/views/user_view.ex * a controller in lib/app_web/controllers/user_controller.ex * default CRUD templates in lib/app_web/templates/user A migration file for the repository and test files for the context and controller features will also be generated. The location of the web files (controllers, views, templates, etc) in an umbrella application will vary based on the `:context_app` config located in your applications `:generators` configuration. When set, the Phoenix generators will generate web files directly in your lib and test folders since the application is assumed to be isolated to web specific functionality. If `:context_app` is not set, the generators will place web related lib and test files in a `web/` directory since the application is assumed to be handling both web and domain specific functionality. Example configuration: config :my_app_web, :generators, context_app: :my_app Alternatively, the `--context-app` option may be supplied to the generator: mix phx.gen.html Sales User users --context-app warehouse ## Web namespace By default, the controller and view will be namespaced by the schema name. You can customize the web module namespace by passing the `--web` flag with a module name, for example: mix phx.gen.html Sales User users --web Sales Which would generate a `lib/app_web/controllers/sales/user_controller.ex` and `lib/app_web/views/sales/user_view.ex`. ## Generating without a schema or context file In some cases, you may wish to bootstrap HTML templates, controllers, and controller tests, but leave internal implementation of the context or schema to yourself. You can use the `--no-context` and `--no-schema` flags for file generation control. ## table By default, the table name for the migration and schema will be the plural name provided for the resource. To customize this value, a `--table` option may be provided. For example: mix phx.gen.html Accounts User users --table cms_users ## binary_id Generated migration can use `binary_id` for schema's primary key and its references with option `--binary-id`. ## Default options This generator uses default options provided in the `:generators` configuration of your application. These are the defaults: config :your_app, :generators, migration: true, binary_id: false, sample_binary_id: "11111111-1111-1111-1111-111111111111" You can override those options per invocation by providing corresponding switches, e.g. `--no-binary-id` to use normal ids despite the default configuration or `--migration` to force generation of the migration. Read the documentation for `phx.gen.schema` for more information on attributes. """ use Mix.Task alias Mix.Phoenix.{Context, Schema} alias Mix.Tasks.Phx.Gen @doc false def run(args) do if Mix.Project.umbrella? do Mix.raise "mix phx.gen.html can only be run inside an application directory" end {context, schema} = Gen.Context.build(args) Gen.Context.prompt_for_code_injection(context) binding = [context: context, schema: schema, inputs: inputs(schema)] paths = Mix.Phoenix.generator_paths() prompt_for_conflicts(context) context |> copy_new_files(paths, binding) |> print_shell_instructions() end defp prompt_for_conflicts(context) do context |> files_to_be_generated() |> Kernel.++(context_files(context)) |> Mix.Phoenix.prompt_for_conflicts() end defp context_files(%Context{generate?: true} = context) do Gen.Context.files_to_be_generated(context) end defp context_files(%Context{generate?: false}) do [] end @doc false def files_to_be_generated(%Context{schema: schema, context_app: context_app}) do web_prefix = Mix.Phoenix.web_path(context_app) test_prefix = Mix.Phoenix.web_test_path(context_app) web_path = to_string(schema.web_path) [ {:eex, "controller.ex", Path.join([web_prefix, "controllers", web_path, "#{schema.singular}_controller.ex"])}, {:eex, "edit.html.eex", Path.join([web_prefix, "templates", web_path, schema.singular, "edit.html.eex"])}, {:eex, "form.html.eex", Path.join([web_prefix, "templates", web_path, schema.singular, "form.html.eex"])}, {:eex, "index.html.eex", Path.join([web_prefix, "templates", web_path, schema.singular, "index.html.eex"])}, {:eex, "new.html.eex", Path.join([web_prefix, "templates", web_path, schema.singular, "new.html.eex"])}, {:eex, "show.html.eex", Path.join([web_prefix, "templates", web_path, schema.singular, "show.html.eex"])}, {:eex, "view.ex", Path.join([web_prefix, "views", web_path, "#{schema.singular}_view.ex"])}, {:eex, "controller_test.exs", Path.join([test_prefix, "controllers", web_path, "#{schema.singular}_controller_test.exs"])}, ] end @doc false def copy_new_files(%Context{} = context, paths, binding) do files = files_to_be_generated(context) Mix.Phoenix.copy_from(paths, "priv/templates/phx.gen.html", binding, files) if context.generate?, do: Gen.Context.copy_new_files(context, paths, binding) context end @doc false def print_shell_instructions(%Context{schema: schema, context_app: ctx_app} = context) do if schema.web_namespace do Mix.shell.info """ Add the resource to your #{schema.web_namespace} :browser scope in #{Mix.Phoenix.web_path(ctx_app)}/router.ex: scope "/#{schema.web_path}", #{inspect Module.concat(context.web_module, schema.web_namespace)}, as: :#{schema.web_path} do pipe_through :browser ... resources "/#{schema.plural}", #{inspect schema.alias}Controller end """ else Mix.shell.info """ Add the resource to your browser scope in #{Mix.Phoenix.web_path(ctx_app)}/router.ex: resources "/#{schema.plural}", #{inspect schema.alias}Controller """ end if context.generate?, do: Gen.Context.print_shell_instructions(context) end defp inputs(%Schema{} = schema) do Enum.map(schema.attrs, fn {_, {:references, _}} -> {nil, nil, nil} {key, :integer} -> {label(key), ~s(<%= number_input f, #{inspect(key)} %>), error(key)} {key, :float} -> {label(key), ~s(<%= number_input f, #{inspect(key)}, step: "any" %>), error(key)} {key, :decimal} -> {label(key), ~s(<%= number_input f, #{inspect(key)}, step: "any" %>), error(key)} {key, :boolean} -> {label(key), ~s(<%= checkbox f, #{inspect(key)} %>), error(key)} {key, :text} -> {label(key), ~s(<%= textarea f, #{inspect(key)} %>), error(key)} {key, :date} -> {label(key), ~s(<%= date_select f, #{inspect(key)} %>), error(key)} {key, :time} -> {label(key), ~s(<%= time_select f, #{inspect(key)} %>), error(key)} {key, :utc_datetime} -> {label(key), ~s(<%= datetime_select f, #{inspect(key)} %>), error(key)} {key, :naive_datetime} -> {label(key), ~s(<%= datetime_select f, #{inspect(key)} %>), error(key)} {key, {:array, :integer}} -> {label(key), ~s(<%= multiple_select f, #{inspect(key)}, ["1": 1, "2": 2] %>), error(key)} {key, {:array, _}} -> {label(key), ~s(<%= multiple_select f, #{inspect(key)}, ["Option 1": "option1", "Option 2": "option2"] %>), error(key)} {key, _} -> {label(key), ~s(<%= text_input f, #{inspect(key)} %>), error(key)} end) end defp label(key) do ~s(<%= label f, #{inspect(key)} %>) end defp error(field) do ~s(<%= error_tag f, #{inspect(field)} %>) end end
39.531532
133
0.673883
03201f9cdb06f2c30f06607a6958f3772c3b6334
947
exs
Elixir
test/lz_string_test.exs
koudelka/elixir-lz-string
59130abee4ddd67b634888a069744a517d620c3e
[ "MIT" ]
13
2016-02-10T06:00:47.000Z
2019-10-23T06:49:41.000Z
test/lz_string_test.exs
koudelka/elixir-lz-string
59130abee4ddd67b634888a069744a517d620c3e
[ "MIT" ]
null
null
null
test/lz_string_test.exs
koudelka/elixir-lz-string
59130abee4ddd67b634888a069744a517d620c3e
[ "MIT" ]
3
2017-06-24T02:13:29.000Z
2019-09-19T19:36:24.000Z
defmodule LzStringTest do use ExUnit.Case, async: true import TestHelper import LZString doctest LZString test "roundtrip repeated single-bute strings" do Enum.each 1..2000, &(assert_roundtrip String.ljust("", &1, ?a)) end test "roundtrip repeated multi-byte char strings" do Enum.each 1..2000, &(assert_roundtrip String.ljust("", &1, ?猫)) end test "roundtrip random high entropy strings" do Enum.each 1..1000, fn _ -> 1000 |> random_string |> assert_roundtrip end end test "roundtrip random large low entropy string" do 1_000_000 |> :crypto.strong_rand_bytes |> Base.encode16 |> assert_roundtrip end test "compress/1 should be able to handle every valid utf8 character that fits in two bytes" do valid_utf8_char_ranges() |> Enum.flat_map(fn range -> Enum.map(range, &(<< &1 :: utf8 >>)) end) |> :erlang.list_to_binary |> assert_roundtrip end end
24.921053
97
0.676874
03202fc3a8e538f0d8098bda0a353558a12e1d25
1,790
exs
Elixir
clients/sheets/mix.exs
dsdshcym/elixir-google-api
2d9eef7207bb422d7ecfc1ec780721c6abd0ac81
[ "Apache-2.0" ]
null
null
null
clients/sheets/mix.exs
dsdshcym/elixir-google-api
2d9eef7207bb422d7ecfc1ec780721c6abd0ac81
[ "Apache-2.0" ]
null
null
null
clients/sheets/mix.exs
dsdshcym/elixir-google-api
2d9eef7207bb422d7ecfc1ec780721c6abd0ac81
[ "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.Sheets.Mixfile do use Mix.Project @version "0.29.1" def project() do [ app: :google_api_sheets, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/sheets" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Google Sheets API client library. Reads and writes Google Sheets. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/sheets", "Homepage" => "https://developers.google.com/sheets/" } ] end end
26.716418
97
0.649162
03207ca849b358f6c4fa9cd43dc7883cf23b61c5
3,509
ex
Elixir
lib/phoenix_component.ex
phaleth/phoenix_live_view
84108603663f546871dcbb9b32c2dfeb2f6afda5
[ "MIT" ]
null
null
null
lib/phoenix_component.ex
phaleth/phoenix_live_view
84108603663f546871dcbb9b32c2dfeb2f6afda5
[ "MIT" ]
null
null
null
lib/phoenix_component.ex
phaleth/phoenix_live_view
84108603663f546871dcbb9b32c2dfeb2f6afda5
[ "MIT" ]
null
null
null
defmodule Phoenix.Component do @moduledoc """ API for function components. A function component is any function that receives an assigns map as argument and returns a rendered struct built with [the `~H` sigil](`Phoenix.LiveView.Helpers.sigil_H/2`). Here is an example: defmodule MyComponent do use Phoenix.Component # Optionally also bring the HTML helpers # use Phoenix.HTML def greet(assigns) do ~H"\"" <p>Hello, <%= assigns.name %></p> "\"" end end The component can be invoked as a regular function: MyComponent.greet(%{name: "Jane"}) But it is typically invoked using the function component syntax from the `~H` sigil: ~H"\"" <MyComponent.greet name="Jane" /> "\"" If the `MyComponent` module is imported or if the function is defined locally, you can skip the module name: ~H"\"" <.greet name="Jane" /> "\"" Learn more about the `~H` sigil [in its documentation](`Phoenix.LiveView.Helpers.sigil_H/2`). ## `use Phoenix.Component` Modules that have to define function components should call `use Phoenix.Component` at the top. Doing so will import the functions from both `Phoenix.LiveView` and `Phoenix.LiveView.Helpers` modules. Note it is not necessary to `use Phoenix.Component` inside `Phoenix.LiveView` and `Phoenix.LiveComponent`. ## Assigns While inside a function component, it is recommended to use the functions in `Phoenix.LiveView` to manipulate assigns. For example, let's imagine a component that receives the first name and last name and must compute the name assign. One option would be: def show_name(assigns) do assigns = assign(assigns, :name, assigns.first_name <> assigns.last_name) ~H"\"" <p>Your name is: <%= @name %></p> "\"" end However, when possible, it may be cleaner to break the logic over function calls instead of precomputed assigns: def show_name(assigns) do ~H"\"" <p>Your name is: <%= full_name(@first_name, @last_name) %></p> "\"" end defp full_name(first_name, last_name), do: first_name <> last_name ## Blocks It is also possible to give HTML blocks to function components as in regular HTML tags. For example, you could create a button component that looks like this: def button(assigns) do ~H"\"" <button class="btn"> <%= render_block(@inner_block) %> </button> "\"" end and now you can invoke it as: <.button> This renders <strong>inside</strong> the button! </.button> In a nutshell, the block given to the component is assigned to `@inner_block` and then we use [`render_block`](`Phoenix.LiveView.Helpers.render_block/2`) to render it. You can even have the component give a value back to the caller, by using `let`. Imagine this component: def unordered_list(assigns) do ~H"\"" <ul> <%= for entry <- @entries do %> <li><%= render_block(@inner_block, entry) %></li> <% end %> </ul> "\"" end And now you can invoke it as: <.unordered_list let={entry} entries={~w(apple banana cherry)}> I like <%= entry %> </.unordered_list> """ @doc false defmacro __using__(_) do quote do import Phoenix.LiveView import Phoenix.LiveView.Helpers end end end
26.186567
95
0.630664
03209a82b7a4a886c3c17a012fe905926a61b241
1,807
ex
Elixir
clients/poly/lib/google_api/poly/v1/model/quaternion.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/poly/lib/google_api/poly/v1/model/quaternion.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/poly/lib/google_api/poly/v1/model/quaternion.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.Poly.V1.Model.Quaternion do @moduledoc """ A [Quaternion](//en.wikipedia.org/wiki/Quaternion). Please note: if in the response you see "w: 1" and nothing else this is the default value of [0, 0, 0, 1] where x,y, and z are 0. ## Attributes * `w` (*type:* `float()`, *default:* `nil`) - The scalar component. * `x` (*type:* `float()`, *default:* `nil`) - The x component. * `y` (*type:* `float()`, *default:* `nil`) - The y component. * `z` (*type:* `float()`, *default:* `nil`) - The z component. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :w => float() | nil, :x => float() | nil, :y => float() | nil, :z => float() | nil } field(:w) field(:x) field(:y) field(:z) end defimpl Poison.Decoder, for: GoogleApi.Poly.V1.Model.Quaternion do def decode(value, options) do GoogleApi.Poly.V1.Model.Quaternion.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Poly.V1.Model.Quaternion do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.267857
183
0.665744
0320a29c58e5404be59a8ec28d2cd8750971538a
9,424
ex
Elixir
lib/phoenix/live_dashboard/pages/os_mon_page.ex
vegg89/phoenix_live_dashboard
bedfa909fe5ba9f42723a6e29d7f4dcc98c86488
[ "MIT" ]
null
null
null
lib/phoenix/live_dashboard/pages/os_mon_page.ex
vegg89/phoenix_live_dashboard
bedfa909fe5ba9f42723a6e29d7f4dcc98c86488
[ "MIT" ]
null
null
null
lib/phoenix/live_dashboard/pages/os_mon_page.ex
vegg89/phoenix_live_dashboard
bedfa909fe5ba9f42723a6e29d7f4dcc98c86488
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveDashboard.OSMonPage do @moduledoc false use Phoenix.LiveDashboard.PageBuilder alias Phoenix.LiveDashboard.{ SystemInfo, ColorBarComponent, ColorBarLegendComponent, TitleBarComponent } @temporary_assigns [os_mon: nil, memory_usage: nil, cpu_total: nil, cpu_count: 0] @cpu_usage_sections [ {:kernel, "Kernel", "purple", "Executing code in kernel mode"}, {:user, "User", "blue", "Executing code in user mode"}, {:nice_user, "User nice", "green", "Executing code in low-priority (nice)"}, {:soft_irq, "Soft IRQ", "orange", "Executing soft interrupts"}, {:hard_irq, "Hard IRQ", "yellow", "Executing hard interrupts"}, {:steal, "Steal", "purple", "Stolen time spent in virtualized OSes"}, {:wait, "Waiting", "orange", nil}, {:idle, "Idle", "light-gray", nil} ] @memory_usage_sections [ {"Used", :used_memory, :system_total_memory, "The amount of memory used from the available memory"}, {"Buffered", :buffered_memory, :system_total_memory, "The amount of memory used for temporary storing raw disk blocks"}, {"Cached", :cached_memory, :system_total_memory, "The amount of memory used for cached files read from disk"}, {"Swap", :used_swap, :total_swap, "The amount of disk swap memory used from the available swap"} ] @menu_text "OS Data" @impl true def init(opts) do {:ok, opts, application: :os_mon} end @impl true def mount(_params, _session, socket) do socket = assign_os_mon(socket) {:ok, socket, temporary_assigns: @temporary_assigns} end defp assign_os_mon(socket) do os_mon = SystemInfo.fetch_os_mon_info(socket.assigns.page.node) cpu_count = length(os_mon.cpu_per_core) assign(socket, os_mon: os_mon, cpu_count: cpu_count, cpu_total: calculate_cpu_total(os_mon.cpu_per_core, cpu_count), memory_usage: calculate_memory_usage(os_mon.system_mem) ) end defp calculate_memory_usage(system_memory) do for {key, value_key, total_key, hint} <- @memory_usage_sections, total = system_memory[total_key], value = memory_value(system_memory, value_key, total) do {key, value, total, percentage(value, total), hint} end end defp memory_value(system_memory, :used_memory, total) do if free = Keyword.get(system_memory, :free_memory, 0) do total - (free + Keyword.get(system_memory, :cached_memory, 0) + Keyword.get(system_memory, :buffered_memory, 0)) end end defp memory_value(system_memory, :used_swap, total) do if free = Keyword.get(system_memory, :free_swap, 0) do total - free end end defp memory_value(system_memory, key, _total), do: system_memory[key] defp calculate_cpu_total([], _cpu_count), do: nil defp calculate_cpu_total([{_, core}], _cpu_count), do: core defp calculate_cpu_total([{_, keys} | _] = per_core, cpu_count) do keys |> Map.keys() |> Enum.map(fn key -> {key, avg_cpu_usage(per_core, key, cpu_count)} end) end defp avg_cpu_usage(map, key, count) do map |> Enum.map(fn {_n, values} -> values[key] end) |> Enum.sum() |> Kernel./(count) |> Float.ceil(1) end @impl true def menu_link(_, capabilities) do if :os_mon in capabilities.applications do {:ok, @menu_text} else {:disabled, @menu_text, "https://hexdocs.pm/phoenix_live_dashboard/os_mon.html"} end end @impl true def render_page(_assigns), do: raise("this page is special cased to use render/2 instead") def render(assigns) do ~L""" <div class="row"> <%= if @os_mon.cpu_nprocs > 0 do %> <div class="col-sm-6"> <h5 class="card-title"> CPU <%= hint do %> <p>The load panes show the CPU demand in the last 1, 5 and 15 minutes over all cores.</p> <%= if @cpu_count > 0 do %> <p>The avg panes show the same values averaged across all cores.</p> <% end %> <% end %> </h5> <div class="row"> <div class="col-md-4 mb-4"> <div class="banner-card"> <h6 class="banner-card-title"> Load 1 min </h6> <div class="banner-card-value"><%= rup(@os_mon.cpu_avg1) %></div> </div> </div> <div class="col-md-4 mb-4"> <div class="banner-card"> <h6 class="banner-card-title"> Load 5 min </h6> <div class="banner-card-value"><%= rup(@os_mon.cpu_avg5) %></div> </div> </div> <div class="col-md-4 mb-4"> <div class="banner-card"> <h6 class="banner-card-title"> Load 15 min </h6> <div class="banner-card-value"><%= rup(@os_mon.cpu_avg15) %></div> </div> </div> <%= if @cpu_count > 0 do %> <div class="col-md-4 mb-4"> <div class="banner-card"> <h6 class="banner-card-title"> Avg 1 min </h6> <div class="banner-card-value"><%= rup_avg(@os_mon.cpu_avg1, @cpu_count) %></div> </div> </div> <div class="col-md-4 mb-4"> <div class="banner-card"> <h6 class="banner-card-title"> Avg 5 min </h6> <div class="banner-card-value"><%= rup_avg(@os_mon.cpu_avg5, @cpu_count) %></div> </div> </div> <div class="col-md-4 mb-4"> <div class="banner-card"> <h6 class="banner-card-title"> Avg 15 min </h6> <div class="banner-card-value"><%= rup_avg(@os_mon.cpu_avg15, @cpu_count) %></div> </div> </div> </div> <% end %> <%= if @cpu_total do %> <div class="card mb-4"> <div class="card-body"> <div phx-hook="PhxColorBarHighlight" id="cpu-color-bars"> <%= for {num_cpu, usage} <- @os_mon.cpu_per_core do %> <div class="flex-grow-1 mb-3"> <%= live_component @socket, ColorBarComponent, dom_id: "cpu-#{num_cpu}", data: cpu_usage_sections(usage), title: "CPU #{num_cpu+1}", csp_nonces: @csp_nonces %> </div> <% end %> <div class="flex-grow-1 mb-3"> <%= live_component @socket, ColorBarComponent, dom_id: "cpu-total", data: cpu_usage_sections(@cpu_total), title: "TOTAL", csp_nonces: @csp_nonces %> </div> <%= live_component @socket, ColorBarLegendComponent, data: cpu_usage_sections(@cpu_total) %> <div class="resource-usage-total text-center py-1 mt-3"> Number of OS processes: <%= @os_mon.cpu_nprocs %> </div> </div> </div> </div> <% end %> </div> <% end %> <%= if @memory_usage != [] do %> <div class="<%= if @os_mon.cpu_nprocs > 0, do: "col-sm-6", else: "col-12" %>"> <h5 class="card-title">Memory</h5> <%= for {{title, value, total, percent, hint}, index} <- Enum.with_index(@memory_usage) do %> <div class="card mb-4"> <%= live_component @socket, TitleBarComponent, dom_id: "memory-#{index}", percent: percent, class: "card-body", csp_nonces: @csp_nonces do %> <div> <%= title %>&nbsp;<%= hint(do: hint) %> </div> <div> <small class="text-muted mr-2"> <%= format_bytes(value) %> of <%= format_bytes(total) %> </small> <strong><%= percent %>%</strong> </div> <% end %> </div> <% end %> </div> <% end %> <%= if @os_mon.disk != [] do %> <div class="col-12"> <h5 class="card-title">Disk</h5> <div class="card mb-4"> <div class="card-body"> <%= for {{mountpoint, kbytes, percent}, index} <- Enum.with_index(@os_mon.disk) do %> <%= live_component @socket, TitleBarComponent, dom_id: "disk-#{index}", percent: percent, class: "py-2", csp_nonces: @csp_nonces do %> <div> <%= mountpoint %> </div> <div> <span class="text-muted mt-2"> <%= format_percent(percent) %> of <%= format_bytes(kbytes * 1024) %> </span> </div> <% end %> <% end %> </div> </div> </div> <% end %> </div> """ end defp rup(value), do: Float.ceil(value / 256, 2) defp rup_avg(value, count), do: Float.ceil(value / 256 / count, 2) defp cpu_usage_sections(cpu_usage) do for {key, name, color, desc} <- @cpu_usage_sections, value = cpu_usage[key] do {name, value, color, desc} end end @impl true def handle_refresh(socket) do {:noreply, assign_os_mon(socket)} end end
35.164179
181
0.528438
0320b513f0ad7cb28b50d47284e1e3a23a9d5fc6
1,401
ex
Elixir
lib/bigcommerce/app.ex
mcampa/bigcommerce-elixir-app
f1fe40b2a456b49c09970a5317108316f054d5ec
[ "MIT" ]
1
2017-06-02T07:17:22.000Z
2017-06-02T07:17:22.000Z
lib/bigcommerce/app.ex
mcampa/bigcommerce-elixir-app
f1fe40b2a456b49c09970a5317108316f054d5ec
[ "MIT" ]
null
null
null
lib/bigcommerce/app.ex
mcampa/bigcommerce-elixir-app
f1fe40b2a456b49c09970a5317108316f054d5ec
[ "MIT" ]
null
null
null
defmodule Bigcommerce.App do def authorize(code, scope, context) do config = Application.get_env(:app, :bigcommerce) |> Enum.into(%{}) body = %{ client_id: config.client_id, client_secret: config.client_secret, grant_type: "authorization_code", redirect_uri: config.redirect_uri, code: code, scope: scope, context: context } case config.http_client.post(config.auth_url, body) do {:ok, response} -> %{ access_token: response["access_token"], context: response["context"], scope: response["scope"], user: %{ email: response["user"]["email"], user_id: response["user"]["id"], username: response["user"]["username"], }, } {:error, reason} -> raise reason end end def decrypt(signed_payload) do config = Application.get_env(:app, :bigcommerce) |> Enum.into(%{}) case Regex.run(~r/(.+?)\.(.+)/, signed_payload) do [_, payload, signature] -> signature = Base.decode64!(signature) json = Base.decode64!(payload) case :crypto.hmac(:sha256, config.client_secret, json) |> Base.encode16(case: :lower) do ^signature -> {:ok, Poison.decode!(json)} _ -> {:error, "Signature did not match"} end _ -> {:error, "Invalid payload"} end end end
28.591837
96
0.573162
0320d30326325dc23e34cfc31bebfd0e6263c809
264
exs
Elixir
test/dzen_web/views/layout_view_test.exs
d-led/d-zen
25aec2d78e3053df055c0be9cdfac5673dc94f0f
[ "Unlicense" ]
null
null
null
test/dzen_web/views/layout_view_test.exs
d-led/d-zen
25aec2d78e3053df055c0be9cdfac5673dc94f0f
[ "Unlicense" ]
null
null
null
test/dzen_web/views/layout_view_test.exs
d-led/d-zen
25aec2d78e3053df055c0be9cdfac5673dc94f0f
[ "Unlicense" ]
null
null
null
defmodule DzenWeb.LayoutViewTest do use DzenWeb.ConnCase, async: true # When testing helpers, you may want to import Phoenix.HTML and # use functions such as safe_to_string() to convert the helper # result into an HTML string. # import Phoenix.HTML end
29.333333
65
0.761364
0320d734cde8beceb325345a76674a7a9b752f6a
7,172
ex
Elixir
lib/graphql/resolver.ex
PedrOC20/ash_graphql
e4311f38e542726e7f900282ce1bb28cc4a21b3e
[ "MIT" ]
null
null
null
lib/graphql/resolver.ex
PedrOC20/ash_graphql
e4311f38e542726e7f900282ce1bb28cc4a21b3e
[ "MIT" ]
null
null
null
lib/graphql/resolver.ex
PedrOC20/ash_graphql
e4311f38e542726e7f900282ce1bb28cc4a21b3e
[ "MIT" ]
null
null
null
defmodule AshGraphql.Graphql.Resolver do @moduledoc false def resolve( %{arguments: %{id: id}, context: context} = resolution, {api, resource, :get, action} ) do opts = [ actor: Map.get(context, :actor), authorize?: AshGraphql.Api.authorize?(api), action: action ] result = api.get(resource, id, opts) Absinthe.Resolution.put_result(resolution, to_resolution(result)) end def resolve( %{arguments: %{limit: limit, offset: offset} = args, context: context} = resolution, {api, resource, :list, action} ) do opts = [ actor: Map.get(context, :actor), authorize?: AshGraphql.Api.authorize?(api), action: action ] query = resource |> Ash.Query.limit(limit) |> Ash.Query.offset(offset) query = case Map.fetch(args, :filter) do {:ok, filter} -> case Jason.decode(filter) do {:ok, decoded} -> Ash.Query.filter(query, to_snake_case(decoded)) {:error, error} -> raise "Error parsing filter: #{inspect(error)}" end _ -> query end result = query |> api.read(opts) |> case do {:ok, results} -> {:ok, %{results: results, count: Enum.count(results)}} error -> error end Absinthe.Resolution.put_result(resolution, to_resolution(result)) end def mutate( %{arguments: %{input: input}, context: context} = resolution, {api, resource, :create, action} ) do {attributes, relationships} = split_attrs_and_rels(input, resource) changeset = Ash.Changeset.new(resource, attributes) changeset_with_relationships = Enum.reduce(relationships, changeset, fn {relationship, replacement}, changeset -> Ash.Changeset.replace_relationship(changeset, relationship, replacement) end) opts = [ actor: Map.get(context, :actor), authorize?: AshGraphql.Api.authorize?(api), action: action ] result = case api.create(changeset_with_relationships, opts) do {:ok, value} -> {:ok, %{result: value, errors: []}} {:error, error} -> {:ok, %{result: nil, errors: to_errors(error)}} end Absinthe.Resolution.put_result(resolution, to_resolution(result)) end def mutate( %{arguments: %{id: id, input: input}, context: context} = resolution, {api, resource, :update, action} ) do case api.get(resource, id) do nil -> {:ok, %{result: nil, errors: [to_errors("not found")]}} initial -> {attributes, relationships} = split_attrs_and_rels(input, resource) changeset = Ash.Changeset.new(initial, attributes) changeset_with_relationships = Enum.reduce(relationships, changeset, fn {relationship, replacement}, changeset -> Ash.Changeset.replace_relationship(changeset, relationship, replacement) end) opts = [ actor: Map.get(context, :actor), authorize?: AshGraphql.Api.authorize?(api), action: action ] result = case api.update(changeset_with_relationships, opts) do {:ok, value} -> {:ok, %{result: value, errors: []}} {:error, error} -> {:ok, %{result: nil, errors: List.wrap(error)}} end Absinthe.Resolution.put_result(resolution, to_resolution(result)) end end def mutate(%{arguments: %{id: id}, context: context} = resolution, {api, resource, action}) do case api.get(resource, id) do nil -> {:ok, %{result: nil, errors: [to_errors("not found")]}} initial -> opts = if AshGraphql.Api.authorize?(api) do [actor: Map.get(context, :actor), action: action] else [action: action] end result = case api.destroy(initial, opts) do :ok -> {:ok, %{result: initial, errors: []}} {:error, error} -> {:ok, %{result: nil, errors: to_errors(error)}} end Absinthe.Resolution.put_result(resolution, to_resolution(result)) end end defp split_attrs_and_rels(input, resource) do Enum.reduce(input, {%{}, %{}}, fn {key, value}, {attrs, rels} -> if Ash.Resource.attribute(resource, key) do {Map.put(attrs, key, value), rels} else {attrs, Map.put(rels, key, value)} end end) end defp to_errors(errors) do errors |> List.wrap() |> Enum.map(fn error -> cond do is_binary(error) -> %{message: error} Exception.exception?(error) -> %{ message: Exception.message(error) } true -> %{message: "something went wrong"} end end) end def resolve_assoc( %{source: parent, arguments: args, context: %{ash_loader: loader} = context} = resolution, {api, relationship} ) do api_opts = [actor: Map.get(context, :actor), authorize?: AshGraphql.Api.authorize?(api)] opts = [ query: apply_load_arguments(args, Ash.Query.new(relationship.destination)), api_opts: api_opts ] {batch_key, parent} = {{relationship.name, opts}, parent} do_dataloader(resolution, loader, api, batch_key, args, parent) end defp do_dataloader( resolution, loader, api, batch_key, args, parent ) do loader = Dataloader.load(loader, api, batch_key, parent) fun = fn loader -> callback = default_callback(loader) loader |> Dataloader.get(api, batch_key, parent) |> callback.(parent, args) end Absinthe.Resolution.put_result( resolution, {:middleware, Absinthe.Middleware.Dataloader, {loader, fun}} ) end defp default_callback(%{options: loader_options}) do if loader_options[:get_policy] == :tuples do fn result, _parent, _args -> result end else fn result, _parent, _args -> {:ok, result} end end end defp apply_load_arguments(arguments, query) do Enum.reduce(arguments, query, fn {:limit, limit}, query -> Ash.Query.limit(query, limit) {:offset, offset}, query -> Ash.Query.offset(query, offset) {:filter, value}, query -> decode_and_filter(query, value) end) end defp decode_and_filter(query, value) do case Jason.decode(value) do {:ok, decoded} -> Ash.Query.filter(query, to_snake_case(decoded)) {:error, error} -> raise "Error parsing filter: #{inspect(error)}" end end defp to_snake_case(map) when is_map(map) do Enum.into(map, %{}, fn {key, value} -> {Macro.underscore(key), to_snake_case(value)} end) end defp to_snake_case(list) when is_list(list) do Enum.map(list, &to_snake_case/1) end defp to_snake_case(other), do: other defp to_resolution({:ok, value}), do: {:ok, value} defp to_resolution({:error, error}), do: {:error, error |> List.wrap() |> Enum.map(&Exception.message(&1))} end
26.66171
98
0.586168
0320dac3cdc40f792215a3ed4660d9ecf751f0b3
396
ex
Elixir
lib/idefix/refactor/rename_variable.ex
arjan/idefix
d6a2f074ed2b18b77c7058ce82ab73eed62feb26
[ "MIT" ]
1
2020-03-26T16:46:05.000Z
2020-03-26T16:46:05.000Z
lib/idefix/refactor/rename_variable.ex
arjan/idefix
d6a2f074ed2b18b77c7058ce82ab73eed62feb26
[ "MIT" ]
null
null
null
lib/idefix/refactor/rename_variable.ex
arjan/idefix
d6a2f074ed2b18b77c7058ce82ab73eed62feb26
[ "MIT" ]
null
null
null
defmodule Idefix.Refactor.RenameVariable do @moduledoc """ Rename a variable at the point """ alias Idefix.AST def rename_variable(input, {line, col}, newname) do ast = AST.parse(input) with {var, _meta, nil} <- Idefix.AST.find_node(ast, line, col) do IO.puts("Rename #{var} to #{newname}") input else _ -> {:error, "Not a variable"} end end end
19.8
69
0.623737
03210e55b498f683bec009b90f8baffd812bec97
1,106
ex
Elixir
apps/omg_watcher_info/lib/omg_watcher_info/db/types/atom_type.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher_info/lib/omg_watcher_info/db/types/atom_type.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher_info/lib/omg_watcher_info/db/types/atom_type.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
# Copyright 2019-2020 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule OMG.WatcherInfo.DB.Types.AtomType do @moduledoc """ Custom Ecto type that converts DB's string value into atom. """ @behaviour Ecto.Type def type(), do: :string def cast(value), do: {:ok, value} def load(value), do: {:ok, String.to_existing_atom(value)} def dump(value) when is_atom(value), do: {:ok, Atom.to_string(value)} def dump(_), do: :error # https://hexdocs.pm/ecto/Ecto.Type.html#c:embed_as/1 def embed_as(_), do: :self def equal?(value1, value2), do: value1 == value2 end
32.529412
74
0.722423
032116808f5c6052f4fe9d17bb5c270c920fdd04
5,301
ex
Elixir
lib/apache_passwd_md5.ex
kevinmontuori/Apache.PasswdMD5
bbb8fd49a28c601308a999f789b302529ffea543
[ "MIT", "Unlicense" ]
3
2015-10-02T11:39:17.000Z
2016-10-10T13:26:54.000Z
lib/apache_passwd_md5.ex
kevinmontuori/Apache.PasswdMD5
bbb8fd49a28c601308a999f789b302529ffea543
[ "MIT", "Unlicense" ]
null
null
null
lib/apache_passwd_md5.ex
kevinmontuori/Apache.PasswdMD5
bbb8fd49a28c601308a999f789b302529ffea543
[ "MIT", "Unlicense" ]
null
null
null
defmodule Apache.PasswdMD5 do @moduledoc """ Provides a means of generating an Apache style MD5 hash (as used by htaccess). This code was derived from the Crypt::PasswdMD5 Perl module which appears to have been based on http://svn.apache.org/viewvc/apr/apr/trunk/crypto/apr_md5.c?view=co Corrections or suggestions welcome. # Examples iex> {:ok, magic, salt, pw, htstring} = ...> Apache.PasswdMD5.crypt("password", "salt") {:ok, "$apr1$", "salt", "password", "$apr1$salt$Xxd1irWT9ycqoYxGFn4cb."} iex> {:ok, ^magic, ^salt, ^pw, ^htstring} = ...> Apache.PasswdMD5.crypt("password", htstring) {:ok, "$apr1$", "salt", "password", "$apr1$salt$Xxd1irWT9ycqoYxGFn4cb."} """ use Bitwise require Integer @magic_md5 "$1$" @magic_apr "$apr1$" @atoz "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def crypt(pw, salt \\ nil, magic \\ "$apr1$") do salt = case salt do nil -> extract_or_generate_salt pw str -> maybe_extract_salt str end hash = make_hash(pw, salt, magic) {:ok, magic, salt, pw, magic <> salt <> "$" <> hash} end def make_hash(pw, salt, magic) do final = final_hash(pw, salt) ctx = open_hash(pw, salt, magic) ctx = step_one(String.length(pw), ctx, final) finalized_ctx = step_two(String.length(pw), pw, ctx) last_round_ctx = step_three(finalized_ctx, salt, pw, 0) step_four(last_round_ctx) end def final_hash(pw, salt) do ctx = :crypto.hash_init :md5 ctx = :crypto.hash_update ctx, pw ctx = :crypto.hash_update ctx, salt ctx = :crypto.hash_update ctx, pw :crypto.hash_final ctx end def open_hash(pw, salt, magic) do # note that this isn't finalized. ctx = :crypto.hash_init(:md5) ctx = :crypto.hash_update ctx, pw ctx = :crypto.hash_update ctx, magic :crypto.hash_update ctx, salt end def step_one(place, ctx, _final) when place < 0, do: ctx def step_one(place, ctx, final) do length = if place > 16, do: 16, else: place addition = binary_part(final, 0, length) step_one(place - 16, :crypto.hash_update(ctx, addition), final) end def step_two(len, _pw, ctx) when len == 0, do: :crypto.hash_final ctx def step_two(len, pw, ctx) do ctx = if ((len &&& 1) != 0) do :crypto.hash_update(ctx, <<0>>) else :crypto.hash_update(ctx, String.first pw) end step_two((len >>> 1), pw, ctx) end def step_three(ctx, salt, pw, count) when count < 1000 do tmp = :crypto.hash_init(:md5) first_update = if Integer.is_odd(count), do: pw, else: binary_part(ctx, 0, 16) tmp = :crypto.hash_update tmp, first_update if (rem(count, 3) != 0), do: tmp = :crypto.hash_update(tmp, salt) if (rem(count, 7) != 0), do: tmp = :crypto.hash_update(tmp, pw) second_update = if Integer.is_odd(count), do: binary_part(ctx, 0, 16), else: pw tmp = :crypto.hash_update tmp, second_update step_three(:crypto.hash_final(tmp), salt, pw, (count + 1)) end def step_three(ctx, _, _, _), do: ctx defp step_four(ctx) do # XXX: stupidly naive implementation. << x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15 >> = ctx r1 = to_64 ( (x0 <<< 16) ||| (x6 <<< 8) ||| x12 ), 4 r2 = to_64 ( (x1 <<< 16) ||| (x7 <<< 8) ||| x13 ), 4 r3 = to_64 ( (x2 <<< 16) ||| (x8 <<< 8) ||| x14 ), 4 r4 = to_64 ( (x3 <<< 16) ||| (x9 <<< 8) ||| x15 ), 4 r5 = to_64 ( (x4 <<< 16) ||| (x10 <<< 8) ||| x5 ), 4 r6 = to_64 x11, 2 Enum.join [r1, r2, r3, r4, r5, r6] end def to_64(value, iterations, chars \\ "") def to_64(_, 0, chars), do: chars def to_64(value, iterations, chars) do to_64 (value >>> 6), (iterations - 1), chars <> String.at(@atoz, (value &&& 0x3f)) end def maybe_extract_salt(str) do case extract_salt(str) do {:ok, salt} -> salt _ -> str end end def extract_salt(str) do {_, salt, _} = parse_hash(str) if salt == nil, do: {:error, nil}, else: {:ok, salt} end def extract_salt!(str) do case extract_salt(str) do {:ok, salt} -> salt {:error, nil} -> raise "Valid salt not found in string #{ str }." end end def extract_or_generate_salt(str) do case extract_salt(str) do {:ok, salt} -> salt _ -> generate_salt end end defp generate_salt(length \\ 8, seed \\ :os.timestamp) do :random.seed(seed) len = String.length(@atoz) chr = for _ <- 1 .. length do String.at(@atoz, (:random.uniform(len) - 1)) end Enum.join chr end defp parse_hash(str) do magic_part = "(#{ Regex.escape @magic_md5 }|#{ Regex.escape @magic_apr })" salt_part = "([^\\$]{0,8})\\$" regex = Regex.compile! "^#{magic_part}#{salt_part}(.+)$" case Regex.run(regex, str, capture: :all_but_first) do [@magic_md5, salt, crypted_pw] -> {:md5, salt, crypted_pw} [@magic_apr, salt, crypted_pw] -> {:apr, salt, crypted_pw} _ -> {:invalid_hash, nil, nil} end end def hexstring(<< x :: 128 >>) do List.to_string(:lists.flatten(:io_lib.format("~32.16.0b", [x]))) end end
31.366864
78
0.58687
03213483d6f2f78f88529b54aaf35281aaf34554
10,474
exs
Elixir
apps/omg/test/omg/state/persistence_test.exs
omgnetwork/omg-childchain-v1
1e2313029ece2282c22ce411edc078a17e6bba09
[ "Apache-2.0" ]
1
2020-10-06T03:07:47.000Z
2020-10-06T03:07:47.000Z
apps/omg/test/omg/state/persistence_test.exs
omgnetwork/omg-childchain-v1
1e2313029ece2282c22ce411edc078a17e6bba09
[ "Apache-2.0" ]
9
2020-09-16T15:31:17.000Z
2021-03-17T07:12:35.000Z
apps/omg/test/omg/state/persistence_test.exs
omgnetwork/omg-childchain-v1
1e2313029ece2282c22ce411edc078a17e6bba09
[ "Apache-2.0" ]
1
2020-09-30T17:17:27.000Z
2020-09-30T17:17:27.000Z
# Copyright 2019-2020 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule OMG.State.PersistenceTest do @moduledoc """ Test focused on the persistence bits of `OMG.State.Core` """ use ExUnitFixtures use ExUnit.Case, async: false use OMG.Utils.LoggerExt import OMG.TestHelper require OMG.Utxo alias OMG.Block alias OMG.Eth.Configuration alias OMG.State.Transaction alias OMG.Utxo alias Support.WaitFor @fee_claimer_address Base.decode16!("DEAD000000000000000000000000000000000000") @eth OMG.Eth.zero_address() @interval Configuration.child_block_interval() @blknum1 @interval setup do db_path = Briefly.create!(directory: true) Application.put_env(:omg_db, :path, db_path, persistent: true) :ok = OMG.DB.init() {:ok, started_apps} = Application.ensure_all_started(:omg_db) {:ok, bus_apps} = Application.ensure_all_started(:omg_bus) metrics_collection_interval = 60_000 {:ok, _} = Supervisor.start_link( [ {OMG.State, [ fee_claimer_address: @fee_claimer_address, child_block_interval: @interval, metrics_collection_interval: metrics_collection_interval ]} ], strategy: :one_for_one ) on_exit(fn -> Application.put_env(:omg_db, :path, nil) (started_apps ++ bus_apps) |> Enum.reverse() |> Enum.map(fn app -> :ok = Application.stop(app) end) end) {:ok, %{}} end @tag fixtures: [:alice, :bob] test "persists deposits and utxo is available after restart", %{alice: alice, bob: bob} do persist_deposit([ %{owner: bob, currency: @eth, amount: 10, blknum: 1}, %{owner: alice, currency: @eth, amount: 20, blknum: 2} ]) assert OMG.State.utxo_exists?(Utxo.position(2, 0, 0)) :ok = restart_state() assert OMG.State.utxo_exists?(Utxo.position(1, 0, 0)) assert OMG.State.utxo_exists?(Utxo.position(2, 0, 0)) end @tag fixtures: [:alice] test "utxos are persisted", %{alice: alice} do [%{owner: alice, currency: @eth, amount: 20, blknum: 1}] |> persist_deposit() |> exec(create_recovered([{1, 0, 0, alice}], @eth, [{alice, 19}])) |> persist_form() assert not OMG.State.utxo_exists?(Utxo.position(1, 0, 0)) assert OMG.State.utxo_exists?(Utxo.position(@blknum1, 0, 0)) end @tag fixtures: [:alice, :bob] test "utxos are available after restart", %{alice: alice, bob: bob} do [%{owner: alice, currency: @eth, amount: 20, blknum: 1}] |> persist_deposit() |> exec(create_recovered([{1, 0, 0, alice}], @eth, [{bob, 17}, {alice, 2}])) |> exec(create_recovered([{@blknum1, 0, 0, bob}, {@blknum1, 0, 1, alice}], @eth, [{bob, 18}])) |> persist_form() :ok = restart_state() assert not OMG.State.utxo_exists?(Utxo.position(@blknum1, 0, 0)) assert not OMG.State.utxo_exists?(Utxo.position(@blknum1, 0, 1)) assert OMG.State.utxo_exists?(Utxo.position(@blknum1, 1, 0)) end @tag fixtures: [:alice, :bob] test "utxos are available after restart using batch", %{alice: alice, bob: bob} do :ok = persist_deposit([%{owner: alice, currency: @eth, amount: 20, blknum: 1}]) [{_, 1000, 0}] = exec_batch([create_recovered([{1, 0, 0, alice}], @eth, [{bob, 17}, {alice, 2}])]) [{_, 1000, 1}] = exec_batch([create_recovered([{@blknum1, 0, 0, bob}, {@blknum1, 0, 1, alice}], @eth, [{bob, 18}])]) :ok = persist_form() :ok = restart_state() assert not OMG.State.utxo_exists?(Utxo.position(@blknum1, 0, 0)) assert not OMG.State.utxo_exists?(Utxo.position(@blknum1, 0, 1)) assert OMG.State.utxo_exists?(Utxo.position(@blknum1, 1, 0)) end @tag fixtures: [:alice, :bob] test "cannot double spend from the transactions within the same block", %{alice: alice, bob: bob} do :ok = persist_deposit([%{owner: alice, currency: @eth, amount: 10, blknum: 1}]) # after the restart newly up state won't have deposit's utxo in memory :ok = restart_state() assert :ok == exec(create_recovered([{1, 0, 0, alice}], @eth, [{bob, 6}, {alice, 3}])) assert :utxo_not_found == exec(create_recovered([{1, 0, 0, alice}], @eth, [{alice, 10}])) end @tag fixtures: [:alice, :bob] test "cannot double spend from the transactions within the same block in a batch", %{alice: alice, bob: bob} do :ok = persist_deposit([%{owner: alice, currency: @eth, amount: 10, blknum: 1}]) # after the restart newly up state won't have deposit's utxo in memory :ok = restart_state() [{:error, :utxo_not_found}, {:error, :utxo_not_found}, {_, 1000, 0}] = exec_batch([ create_recovered([{1, 0, 0, alice}], @eth, [{bob, 6}, {alice, 3}]), create_recovered([{1, 0, 0, alice}], @eth, [{bob, 6}, {alice, 3}]), create_recovered([{1, 0, 0, alice}], @eth, [{bob, 6}, {alice, 3}]) ]) end @tag fixtures: [:alice, :bob] test "hit the transaction limit in a block using batch", %{alice: alice, bob: bob} do :ok = persist_deposit([%{owner: alice, currency: @eth, amount: 10, blknum: 1}]) maximum_block_size = 6 :sys.replace_state(OMG.State, fn state -> %{state | available_block_size: maximum_block_size - (1 + OMG.State.Transaction.Payment.max_inputs())} end) [{:error, :too_many_transactions_in_block}, {:error, :too_many_transactions_in_block}, {_, 1000, 0}] = exec_batch([ create_recovered([{1, 0, 0, alice}], @eth, [{bob, 6}, {alice, 3}]), create_recovered([{1, 0, 0, alice}], @eth, [{bob, 6}, {alice, 3}]), create_recovered([{1, 0, 0, alice}], @eth, [{bob, 6}, {alice, 3}]) ]) end @tag fixtures: [:alice] test "blocks and spends are persisted", %{alice: alice} do tx = create_recovered([{1, 0, 0, alice}], @eth, [{alice, 19}]) [%{owner: alice, currency: @eth, amount: 20, blknum: 1}] |> persist_deposit() |> exec(tx) |> persist_form() assert {:ok, [hash]} = OMG.DB.block_hashes([@blknum1]) :ok = restart_state() assert {:ok, [db_block]} = OMG.DB.blocks([hash]) %Block{number: @blknum1, transactions: [payment_tx, _fee_tx], hash: ^hash} = Block.from_db_value(db_block) assert {:ok, tx} == Transaction.Recovered.recover_from(payment_tx) assert {:ok, 1000} == tx |> Transaction.get_inputs() |> hd() |> Utxo.Position.to_input_db_key() |> OMG.DB.spent_blknum() end @tag fixtures: [:alice] test "fee tx are persisted", %{alice: alice} do token1 = <<1::160>> tx = create_recovered( [{1, 0, 0, alice}, {2, 0, 0, alice}], [{alice, @eth, 19}, {alice, token1, 60}] ) [ %{owner: alice, currency: @eth, amount: 20, blknum: 1}, %{owner: alice, currency: token1, amount: 60, blknum: 2} ] |> persist_deposit() |> exec(tx) |> persist_form() assert {:ok, [hash]} = OMG.DB.block_hashes([@blknum1]) :ok = restart_state() assert {:ok, [db_block]} = OMG.DB.blocks([hash]) assert %Block{transactions: [_payment_tx, _eth_fee_tx]} = Block.from_db_value(db_block) assert OMG.State.utxo_exists?(Utxo.position(1000, 1, 0)) end @tag fixtures: [:alice] test "exiting utxo is deleted from state", %{alice: alice} do utxo_positions = [ Utxo.position(@blknum1, 0, 0), Utxo.position(@blknum1, 0, 1) ] [%{owner: alice, currency: @eth, amount: 20, blknum: 1}] |> persist_deposit() |> exec(create_recovered([{1, 0, 0, alice}], @eth, [{alice, 19}])) |> persist_form() |> persist_exit_utxos(utxo_positions) :ok = restart_state() assert not OMG.State.utxo_exists?(Utxo.position(@blknum1, 0, 0)) assert not OMG.State.utxo_exists?(Utxo.position(@blknum1, 0, 1)) end @tag fixtures: [:alice] test "cannot spend just exited utxo", %{alice: alice} do :ok = persist_deposit([%{owner: alice, currency: @eth, amount: 20, blknum: 1}]) {:ok, _, _} = OMG.State.exit_utxos([Utxo.position(1, 0, 0)]) # exit db_updates won't get persisted yet, but alice tries to spent it immediately assert :utxo_not_found == exec(create_recovered([{1, 0, 0, alice}], @eth, [{alice, 20}])) # retry above with empty in-memory utxoset :ok = restart_state() {:ok, _, _} = OMG.State.exit_utxos([Utxo.position(1, 0, 0)]) assert :utxo_not_found == exec(create_recovered([{1, 0, 0, alice}], @eth, [{alice, 20}])) end defp persist_deposit(deposits) do {:ok, db_updates} = deposits |> make_deposits() |> OMG.State.deposit() :ok = OMG.DB.multi_update(db_updates) end defp persist_form(:ok), do: persist_form() defp persist_form() do OMG.State.form_block() # because `form_block` is non-blocking operation we need to wait it finishes # easiest to do this is to schedule another operation on `OMG.State` which is blocking _ = OMG.State.utxo_exists?(Utxo.position(0, 0, 0)) :ok end defp exec(:ok, tx), do: exec(tx) defp exec(tx) do fee = %{@eth => [1]} case OMG.State.exec(tx, fee) do {:ok, _} -> :ok {:error, reason} -> reason end end defp exec_batch(txs) do fees = Enum.map(1..Enum.count(txs), fn _ -> %{@eth => [1]} end) OMG.State.exec_batch(Enum.zip(txs, fees)) end defp persist_exit_utxos(:ok, exit_infos), do: persist_exit_utxos(exit_infos) defp persist_exit_utxos(exit_infos) do {:ok, db_updates, _} = OMG.State.exit_utxos(exit_infos) :ok = OMG.DB.multi_update(db_updates) end defp make_deposits(list) do Enum.map(list, fn %{owner: owner, currency: currency, amount: amount, blknum: blknum} -> %{ root_chain_txhash: <<blknum::256>>, log_index: 0, owner: owner.addr, currency: currency, amount: amount, blknum: blknum } end) end defp restart_state() do GenServer.stop(OMG.State) WaitFor.ok(fn -> if(GenServer.whereis(OMG.State), do: :ok) end) _ = Logger.info("OMG.State restarted") :ok end end
32.32716
120
0.6308
0321576ba0856811478d506c573f95b88374aa61
2,391
exs
Elixir
test/controllers/video_controller_test.exs
joeletizia/rumbl
db213d5231927b0cf27d4f59341c370816099a0b
[ "MIT" ]
null
null
null
test/controllers/video_controller_test.exs
joeletizia/rumbl
db213d5231927b0cf27d4f59341c370816099a0b
[ "MIT" ]
null
null
null
test/controllers/video_controller_test.exs
joeletizia/rumbl
db213d5231927b0cf27d4f59341c370816099a0b
[ "MIT" ]
null
null
null
defmodule Rumbl.VideoControllerTest do use Rumbl.ConnCase alias Rumbl.Video @valid_attrs %{description: "some content", title: "some content", url: "some content"} @invalid_attrs %{} test "lists all entries on index", %{conn: conn} do conn = get conn, video_path(conn, :index) assert html_response(conn, 200) =~ "Listing videos" end test "renders form for new resources", %{conn: conn} do conn = get conn, video_path(conn, :new) assert html_response(conn, 200) =~ "New video" end test "creates resource and redirects when data is valid", %{conn: conn} do conn = post conn, video_path(conn, :create), video: @valid_attrs assert redirected_to(conn) == video_path(conn, :index) assert Repo.get_by(Video, @valid_attrs) end test "does not create resource and renders errors when data is invalid", %{conn: conn} do conn = post conn, video_path(conn, :create), video: @invalid_attrs assert html_response(conn, 200) =~ "New video" end test "shows chosen resource", %{conn: conn} do video = Repo.insert! %Video{} conn = get conn, video_path(conn, :show, video) assert html_response(conn, 200) =~ "Show video" end test "renders page not found when id is nonexistent", %{conn: conn} do assert_error_sent 404, fn -> get conn, video_path(conn, :show, -1) end end test "renders form for editing chosen resource", %{conn: conn} do video = Repo.insert! %Video{} conn = get conn, video_path(conn, :edit, video) assert html_response(conn, 200) =~ "Edit video" end test "updates chosen resource and redirects when data is valid", %{conn: conn} do video = Repo.insert! %Video{} conn = put conn, video_path(conn, :update, video), video: @valid_attrs assert redirected_to(conn) == video_path(conn, :show, video) assert Repo.get_by(Video, @valid_attrs) end test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do video = Repo.insert! %Video{} conn = put conn, video_path(conn, :update, video), video: @invalid_attrs assert html_response(conn, 200) =~ "Edit video" end test "deletes chosen resource", %{conn: conn} do video = Repo.insert! %Video{} conn = delete conn, video_path(conn, :delete, video) assert redirected_to(conn) == video_path(conn, :index) refute Repo.get(Video, video.id) end end
35.686567
98
0.682141
03215989ba85cef1d6444ab0d84f836d13501fe4
971
exs
Elixir
elixir/roman-numerals/roman.exs
bwheel/exercism
6648252bf61f0782ff0a0469ce0df6bf483b3d4d
[ "MIT" ]
null
null
null
elixir/roman-numerals/roman.exs
bwheel/exercism
6648252bf61f0782ff0a0469ce0df6bf483b3d4d
[ "MIT" ]
null
null
null
elixir/roman-numerals/roman.exs
bwheel/exercism
6648252bf61f0782ff0a0469ce0df6bf483b3d4d
[ "MIT" ]
null
null
null
defmodule Roman do @doc """ Convert the number to a roman number. """ @spec numerals(pos_integer) :: String.t() def numerals(number) do cond do number >= 1000 -> "M" <> numerals(number - 1000) number >= 900 -> "CM" <> numerals(number - 900) number >= 500 -> "D" <> numerals(number - 500) number >= 400 -> "CD" <> numerals(number - 400) number >= 100 -> "C" <> numerals(number - 100) number >= 90 -> "XC" <> numerals(number - 90) number >= 50 -> "L" <> numerals(number - 50) number >= 40 -> "XL" <> numerals(number - 40) number >= 10 -> "X" <> numerals(number - 10) number >= 9 -> "IX" <> numerals(number - 9) number >= 5 -> "V" <> numerals(number - 5) number == 4 -> "IV" <> numerals(number - 4) number >= 1 -> "I" <> numerals(number - 1) true -> "" end end end
25.552632
43
0.465499
0321702b08988187ca6104e848e1822d172c8f0c
379
ex
Elixir
lib/idvote/models/subscriber.ex
boisebrigade/idvote
fb1d3f348db094e0578d6976a0a349971bf7aab7
[ "ISC" ]
2
2018-08-15T02:03:36.000Z
2019-02-06T23:27:56.000Z
lib/idvote/models/subscriber.ex
boisebrigade/idvote
fb1d3f348db094e0578d6976a0a349971bf7aab7
[ "ISC" ]
14
2018-08-11T19:47:56.000Z
2018-08-29T22:44:22.000Z
lib/idvote/models/subscriber.ex
boisebrigade/idvote
fb1d3f348db094e0578d6976a0a349971bf7aab7
[ "ISC" ]
2
2018-08-11T16:44:02.000Z
2018-08-28T03:45:55.000Z
defmodule Idvote.Subscriber do alias Idvote.Precinct use Ecto.Schema import Ecto.Changeset schema "subscriber" do belongs_to(:precinct, Precinct) field(:email, :string) field(:phone_number, :string) timestamps() end @doc false def changeset(precinct, attrs) do precinct |> cast(attrs, [:name]) |> validate_required([:name]) end end
18.047619
35
0.6781
0321923c5a3c06492d125df35fd698f3d541b117
186
exs
Elixir
priv/repo/migrations/20210415085842_add_meta_to_article_comment.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
240
2018-11-06T09:36:54.000Z
2022-02-20T07:12:36.000Z
priv/repo/migrations/20210415085842_add_meta_to_article_comment.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
363
2018-07-11T03:38:14.000Z
2021-12-14T01:42:40.000Z
priv/repo/migrations/20210415085842_add_meta_to_article_comment.exs
mydearxym/mastani_server
f24034a4a5449200165cf4a547964a0961793eab
[ "Apache-2.0" ]
22
2019-01-27T11:47:56.000Z
2021-02-28T13:17:52.000Z
defmodule GroupherServer.Repo.Migrations.AddMetaToArticleComment do use Ecto.Migration def change do alter table(:articles_comments) do add(:meta, :map) end end end
18.6
67
0.736559
0321a4ccbc1e466c8cd149bff4ee969df2343f89
1,690
ex
Elixir
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/delete_order_deals_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/delete_order_deals_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/delete_order_deals_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AdExchangeBuyer.V14.Model.DeleteOrderDealsResponse do @moduledoc """ ## Attributes - deals (List[MarketplaceDeal]): List of deals deleted (in the same proposal as passed in the request) Defaults to: `null`. - proposalRevisionNumber (String): The updated revision number for the proposal. Defaults to: `null`. """ defstruct [ :"deals", :"proposalRevisionNumber" ] end defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V14.Model.DeleteOrderDealsResponse do import GoogleApi.AdExchangeBuyer.V14.Deserializer def decode(value, options) do value |> deserialize(:"deals", :list, GoogleApi.AdExchangeBuyer.V14.Model.MarketplaceDeal, options) end end defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V14.Model.DeleteOrderDealsResponse do def encode(value, options) do GoogleApi.AdExchangeBuyer.V14.Deserializer.serialize_non_nil(value, options) end end
33.8
125
0.763314
0321adc2a2de812d321cb34d46b0b2af0925ff7e
1,122
exs
Elixir
mix.exs
pcarvsilva/excaffolder
d3bda1e7a064dc1eb5312ca01728b208684bb503
[ "MIT" ]
3
2019-11-01T22:20:06.000Z
2020-02-09T22:53:13.000Z
mix.exs
pcarvsilva/excaffolder
d3bda1e7a064dc1eb5312ca01728b208684bb503
[ "MIT" ]
null
null
null
mix.exs
pcarvsilva/excaffolder
d3bda1e7a064dc1eb5312ca01728b208684bb503
[ "MIT" ]
null
null
null
defmodule Excaffolder.MixProject do use Mix.Project def project do [ app: :excaffolder, version: "0.1.0", elixir: "~> 1.9", start_permanent: Mix.env() == :prod, deps: deps(), package: package(), description: description() ] 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 [ {:phoenix, "~> 1.4.10"}, {:ex_doc, "~> 0.18", only: :dev} # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} ] end defp description do """ Library for generating code for phoenix live view adding tailwind.css and animate.css. """ end defp package do [ files: ["lib", "mix.exs", "README*"], maintainers: ["Pedro Carvalho"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/pcarvsilva/excaffolder"}, files: ~w(lib priv) ++ ~w(mix.exs README.md ) ] end end
22
90
0.567736
0321b771c8b3f8ee21c844be111d2b4fc7286907
1,094
exs
Elixir
mix.exs
martide/airports
d2fcc97bff555c066932ec53467e1435197ab9f3
[ "MIT" ]
1
2020-01-20T12:51:52.000Z
2020-01-20T12:51:52.000Z
mix.exs
martide/airports
d2fcc97bff555c066932ec53467e1435197ab9f3
[ "MIT" ]
3
2022-01-24T12:27:54.000Z
2022-03-01T09:06:35.000Z
mix.exs
martide/airports
d2fcc97bff555c066932ec53467e1435197ab9f3
[ "MIT" ]
2
2019-02-11T13:18:04.000Z
2021-12-21T05:20:29.000Z
defmodule Airports.Mixfile do use Mix.Project @project_url "https://github.com/nerds-and-company/airports" def project do [ app: :airports, version: "1.0.0", elixir: "~> 1.10", build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, deps: deps(), description: description(), package: package(), source_url: @project_url, test_coverage: [tool: ExCoveralls], preferred_cli_env: [ coveralls: :test ] ] end def application do [extra_applications: [:logger]] end defp deps do [ {:nimble_csv, "~> 1.1"}, {:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false}, {:excoveralls, "~> 0.12", only: :test}, {:ex_doc, ">= 0.0.0", only: :dev} ] end defp description do """ Airports is a collection of all known airports. Data source is https://davidmegginson.github.io/ourairports-data/airports.csv """ end defp package do [maintainers: ["Don Pinkster"], licenses: ["MIT"], links: %{"GitHub" => @project_url}] end end
23.276596
129
0.585923
0321c32be0cbabec534f178ce02bd6eb21702bd2
1,515
ex
Elixir
lib/vex/validators/absence.ex
jtmoulia/vex
78161e174777cb2d0d808326afe619fb893da8d1
[ "MIT" ]
null
null
null
lib/vex/validators/absence.ex
jtmoulia/vex
78161e174777cb2d0d808326afe619fb893da8d1
[ "MIT" ]
null
null
null
lib/vex/validators/absence.ex
jtmoulia/vex
78161e174777cb2d0d808326afe619fb893da8d1
[ "MIT" ]
null
null
null
defmodule Vex.Validators.Absence do @moduledoc """ Ensure a value is absent. Vex uses the `Vex.Blank` protocol to determine "absence." Notably, empty strings and collections are considered absent. ## Options * `:message`: Optional. A custom error message. May be in EEx format and use the fields described in "Custom Error Messages," below. ## Examples iex> Vex.Validators.Absence.validate(1, true) {:error, "must be absent"} iex> Vex.Validators.Absence.validate(nil, true) :ok iex> Vex.Validators.Absence.validate(false, true) :ok iex> Vex.Validators.Absence.validate("", true) :ok iex> Vex.Validators.Absence.validate([], true) :ok iex> Vex.Validators.Absence.validate([], true) :ok iex> Vex.Validators.Absence.validate([1], true) {:error, "must be absent"} iex> Vex.Validators.Absence.validate({1}, true) {:error, "must be absent"} ## Custom Error Messages Custom error messages (in EEx format), provided as :message, can use the following values: iex> Vex.Validators.Absence.__validator__(:message_fields) [value: "The bad value"] An example: iex> Vex.Validators.Absence.validate([1], message: "can't be <%= inspect value %>") {:error, "can't be [1]"} """ use Vex.Validator @message_fields [value: "The bad value"] def validate(value, options) do if Vex.Blank.blank?(value) do :ok else {:error, message(options, "must be absent", value: value)} end end end
27.545455
92
0.663366
0322101e3fb1d34ee85909fa492607f124fc6ebb
4,190
exs
Elixir
www/test/import_export_test.exs
Nagasaki45/krihelinator
243bfe476b8128dc2f0fcd913bebd8cf20b7deb6
[ "MIT" ]
47
2016-07-17T08:49:36.000Z
2020-11-06T14:12:15.000Z
www/test/import_export_test.exs
Nagasaki45/krihelinator
243bfe476b8128dc2f0fcd913bebd8cf20b7deb6
[ "MIT" ]
181
2016-07-11T13:20:40.000Z
2019-10-22T14:43:40.000Z
www/test/import_export_test.exs
Nagasaki45/krihelinator
243bfe476b8128dc2f0fcd913bebd8cf20b7deb6
[ "MIT" ]
2
2017-02-25T16:19:09.000Z
2017-12-24T20:22:32.000Z
# Some helper modules defmodule Person do defstruct name: nil, age: nil end defmodule FakedRepo do def all(Person) do [ %Person{name: "moshe", age: 25}, %Person{name: "jacob", age: 35}, %Person{name: "yossi", age: 45}, ] end end defmodule Krihelinator.ImportExportTest do use Krihelinator.ModelCase, async: true import Krihelinator.ImportExport test "export_data" do json = export_data([Person], FakedRepo) list = Poison.decode!(json) [%{"model" => model_name, "items" => items}] = list assert model_name == "Elixir.Person" first_person = hd(items) assert first_person["name"] == "moshe" assert first_person["age"] == 25 end test "export_krihelinator_data has data for each model" do json = export_krihelinator_data() list = Poison.decode!(json) model_names = list |> Enum.map(fn %{"model" => model_name} -> model_name end) |> Enum.into(MapSet.new()) for name <- ~w(Repo Language) do assert MapSet.member?(model_names, "Elixir.Krihelinator.Github." <> name) end assert MapSet.member?(model_names, "Elixir.Krihelinator.History.Language") end test "import fixture and then export create the same content" do fixture = Path.join(["test", "fixtures", "dump_sample.json"]) in_json = File.read!(fixture) import_data(in_json, Krihelinator.Repo) out_json = export_krihelinator_data() in_map = Poison.decode!(in_json) out_map = Poison.decode!(out_json) for {{in_model, in_items}, {out_model, out_items}} <- Enum.zip(in_map, out_map) do assert in_model == out_model assert length(in_items) == length(out_items) in_items = Enum.sort_by(in_items, fn x -> x["name"] end) out_items = Enum.sort_by(out_items, fn x -> x["name"] end) for {in_item, out_item} <- Enum.zip(in_items, out_items) do assert in_item == out_item end end end test "seed, export, delete all, and make sure import still works" do alias Krihelinator.Github, as: GH alias Krihelinator.History.Language, as: LanguageHistory # Seed elixir = %GH.Language{} |> GH.Language.changeset(%{name: "Elixir"}) |> Krihelinator.Repo.insert!() repo_params = %{ name: "my/repo", authors: 1, commits: 2, merged_pull_requests: 3, proposed_pull_requests: 4, closed_issues: 5, new_issues: 6, description: "my awesome project!", user_requested: true } %GH.Repo{} |> GH.Repo.changeset(repo_params) |> Ecto.Changeset.put_assoc(:language, elixir) |> Krihelinator.Repo.insert!() now = DateTime.utc_now() yesterday = Timex.shift(now, days: -1) for dt <- [now, yesterday] do %LanguageHistory{} |> LanguageHistory.changeset(%{krihelimeter: 100, timestamp: dt}) |> Ecto.Changeset.put_assoc(:language, elixir) |> Krihelinator.Repo.insert!() end # Export json = export_krihelinator_data() # Delete all for model <- [GH.Repo, LanguageHistory, GH.Language] do Krihelinator.Repo.delete_all(model) end # Import import_data(json, Krihelinator.Repo) # Basic asserts histories = Krihelinator.Repo.all(LanguageHistory) assert length(histories) == 2 [newer, older] = histories assert newer.timestamp == now assert older.timestamp == yesterday repo = GH.Repo |> Krihelinator.Repo.get_by(name: "my/repo") |> Krihelinator.Repo.preload(:language) assert repo.language.name == "Elixir" end test "insert new language succeeds after import. Bug #163" do # Reset the languages_id_seq to 1 Ecto.Adapters.SQL.query(Krihelinator.Repo, "SELECT setval('languages_id_seq', 1);", []) # Import one language with id 2 [ %{ model: "Elixir.Krihelinator.Github.Language", items: [ %{id: 2, name: "MosheLang", krihelimeter: 1000} ] } ] |> Poison.encode!() |> import_data(Krihelinator.Repo) # Try to create a language with auto generated id jacob_lang_struct = %Krihelinator.Github.Language{name: "JacobLang"} {:ok, _struct} = Krihelinator.Repo.insert(jacob_lang_struct) end end
28.896552
91
0.652983
03221da7af69bc4a5aed26387a84a1e8cb1192cc
1,383
ex
Elixir
test/support/data_case.ex
OrigamiApp/server
efbf185a33694b47fc94376c8ddc4b30f8e3d620
[ "Apache-2.0" ]
null
null
null
test/support/data_case.ex
OrigamiApp/server
efbf185a33694b47fc94376c8ddc4b30f8e3d620
[ "Apache-2.0" ]
null
null
null
test/support/data_case.ex
OrigamiApp/server
efbf185a33694b47fc94376c8ddc4b30f8e3d620
[ "Apache-2.0" ]
null
null
null
defmodule Origami.DataCase do @moduledoc """ This module defines the setup for tests requiring access to the application's data layer. You may define functions here to be used as helpers in your tests. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do alias Origami.Repo import Ecto import Ecto.Changeset import Ecto.Query import Origami.DataCase end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Origami.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Origami.Repo, {:shared, self()}) end :ok end @doc """ A helper that transform changeset errors to a map of messages. assert {:error, changeset} = Accounts.create_user(%{password: "short"}) assert "password is too short" in errors_on(changeset).password assert %{password: ["password is too short"]} = errors_on(changeset) """ def errors_on(changeset) do Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> Enum.reduce(opts, message, fn {key, value}, acc -> String.replace(acc, "%{#{key}}", to_string(value)) end) end) end end
25.611111
77
0.679682
03221e5c23b64c967420ddfa954e9c3fc4f6d766
315
ex
Elixir
web/controllers/api/current_user_controller.ex
Angarsk8/microscope.ex
dc4572ba8b9f1c7b7c94ee78f387e332ac0d936c
[ "MIT" ]
342
2017-01-10T16:13:45.000Z
2022-02-26T13:55:38.000Z
web/controllers/api/current_user_controller.ex
Angarsk8/microscope.ex
dc4572ba8b9f1c7b7c94ee78f387e332ac0d936c
[ "MIT" ]
6
2017-01-14T17:59:48.000Z
2018-03-25T21:35:50.000Z
web/controllers/api/current_user_controller.ex
Angarsk8/microscope.ex
dc4572ba8b9f1c7b7c94ee78f387e332ac0d936c
[ "MIT" ]
38
2017-01-11T00:18:21.000Z
2021-07-11T11:28:12.000Z
defmodule Microscope.CurrentUserController do use Microscope.Web, :controller plug Guardian.Plug.EnsureAuthenticated, handler: Microscope.SessionController def show(conn, _) do user = Guardian.Plug.current_resource(conn) conn |> put_status(:ok) |> render("show.json", user: user) end end
22.5
79
0.733333
03224449ef81bae675f254bf49aabb7f796fc0d7
1,073
exs
Elixir
apps/core/test/unit/medication_request_requests/medication_request_requests_test.exs
ehealth-ua/ehealth.api
4ffe26a464fe40c95fb841a4aa2e147068f65ca2
[ "Apache-2.0" ]
8
2019-06-14T11:34:49.000Z
2021-08-05T19:14:24.000Z
apps/core/test/unit/medication_request_requests/medication_request_requests_test.exs
edenlabllc/ehealth.api.public
4ffe26a464fe40c95fb841a4aa2e147068f65ca2
[ "Apache-2.0" ]
1
2019-07-08T15:20:22.000Z
2019-07-08T15:20:22.000Z
apps/core/test/unit/medication_request_requests/medication_request_requests_test.exs
ehealth-ua/ehealth.api
4ffe26a464fe40c95fb841a4aa2e147068f65ca2
[ "Apache-2.0" ]
6
2018-05-11T13:59:32.000Z
2022-01-19T20:15:22.000Z
defmodule Core.MedicationRequestRequestsTest do use Core.ConnCase, async: true alias Core.MedicationRequestRequests, as: API describe "medication_request_requests" do setup do legal_entity = insert(:prm, :legal_entity, id: "7cc91a5d-c02f-41e9-b571-1ea4f2375552") division = insert( :prm, :division, id: "b075f148-7f93-4fc2-b2ec-2d81b19a9b7b", legal_entity: legal_entity, is_active: true ) insert( :prm, :employee, id: "7488a646-e31f-11e4-aace-600308960662", legal_entity: legal_entity, division: division ) :ok end def medication_request_request_fixture do {:ok, medication_request_request} = API.create(test_request(), "7488a646-e31f-11e4-aace-600308960662", "7cc91a5d-c02f-41e9-b571-1ea4f2375552") medication_request_request end end def test_request do "test/data/medication_request_request/medication_request_request.json" |> File.read!() |> Jason.decode!() end end
24.386364
114
0.652377
03225e116f2b0a1e2f91c8a7ae51247744c0cf70
3,085
ex
Elixir
clients/api_gateway/lib/google_api/api_gateway/v1alpha2/model/apigateway_audit_config.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/api_gateway/lib/google_api/api_gateway/v1alpha2/model/apigateway_audit_config.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/api_gateway/lib/google_api/api_gateway/v1alpha2/model/apigateway_audit_config.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "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.APIGateway.V1alpha2.Model.ApigatewayAuditConfig do @moduledoc """ Specifies the audit configuration for a service. The configuration determines which permission types are logged, and what identities, if any, are exempted from logging. An AuditConfig must have one or more AuditLogConfigs. If there are AuditConfigs for both `allServices` and a specific service, the union of the two AuditConfigs is used for that service: the log_types specified in each AuditConfig are enabled, and the exempted_members in each AuditLogConfig are exempted. Example Policy with multiple AuditConfigs: { "audit_configs": [ { "service": "allServices", "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:[email protected]" ] }, { "log_type": "DATA_WRITE" }, { "log_type": "ADMIN_READ" } ] }, { "service": "sampleservice.googleapis.com", "audit_log_configs": [ { "log_type": "DATA_READ" }, { "log_type": "DATA_WRITE", "exempted_members": [ "user:[email protected]" ] } ] } ] } For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ logging. It also exempts [email protected] from DATA_READ logging, and [email protected] from DATA_WRITE logging. ## Attributes * `auditLogConfigs` (*type:* `list(GoogleApi.APIGateway.V1alpha2.Model.ApigatewayAuditLogConfig.t)`, *default:* `nil`) - The configuration for logging of each type of permission. * `service` (*type:* `String.t`, *default:* `nil`) - Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :auditLogConfigs => list(GoogleApi.APIGateway.V1alpha2.Model.ApigatewayAuditLogConfig.t()), :service => String.t() } field(:auditLogConfigs, as: GoogleApi.APIGateway.V1alpha2.Model.ApigatewayAuditLogConfig, type: :list ) field(:service) end defimpl Poison.Decoder, for: GoogleApi.APIGateway.V1alpha2.Model.ApigatewayAuditConfig do def decode(value, options) do GoogleApi.APIGateway.V1alpha2.Model.ApigatewayAuditConfig.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.APIGateway.V1alpha2.Model.ApigatewayAuditConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
56.090909
1,106
0.750081
032268b0600b95e631b654df2993b9cf930b25a5
2,282
ex
Elixir
lib/atom_tweaks_web/controllers/auth_controller.ex
amymariparker/atom-style-tweaks
9f17b626e4a527d17d2da85ac575029b52fb6a25
[ "MIT" ]
14
2017-01-08T14:51:25.000Z
2022-03-14T09:23:17.000Z
lib/atom_tweaks_web/controllers/auth_controller.ex
amymariparker/atom-style-tweaks
9f17b626e4a527d17d2da85ac575029b52fb6a25
[ "MIT" ]
654
2017-05-23T22:55:21.000Z
2022-03-30T09:02:25.000Z
lib/atom_tweaks_web/controllers/auth_controller.ex
amymariparker/atom-style-tweaks
9f17b626e4a527d17d2da85ac575029b52fb6a25
[ "MIT" ]
4
2019-07-10T23:09:25.000Z
2020-02-09T12:14:00.000Z
defmodule AtomTweaksWeb.AuthController do @moduledoc """ Handles authentication for the application via GitHub OAuth2 user flow. """ use AtomTweaksWeb, :controller alias AtomTweaks.Accounts.User alias AtomTweaksWeb.GitHub alias OAuth2.Client, as: OAuthClient require Logger @doc """ Signs the user in by redirecting to the GitHub authorization URL. """ @spec index(Plug.Conn.t(), Map.t()) :: Plug.Conn.t() def index(conn, params) def index(conn, %{"from" => return_to}) do Logger.debug(fn -> "Authorize user and return to #{return_to}" end) conn |> put_session(:return_to, return_to) |> redirect(external: GitHub.authorize_url!()) end def index(conn, _) do Logger.debug(fn -> "Authorize user and return to home page" end) redirect(conn, external: GitHub.authorize_url!()) end @doc """ Signs the user out by dropping the session, thereby throwing away the access token, and redirecting to the home page. """ @spec delete(Plug.Conn.t(), Map.t()) :: Plug.Conn.t() def delete(conn, _params) do conn |> configure_session(drop: true) |> redirect(to: Routes.page_path(conn, :index)) end @doc """ Handles the OAuth2 callback from GitHub. """ @spec callback(Plug.Conn.t(), Map.t()) :: Plug.Conn.t() def callback(conn, params) def callback(conn, %{"code" => code}) do token = GitHub.get_token!(code: code) github_user = get_user!(token) user = create_user(github_user) redirect_path = return_to_path(conn, get_session(conn, :return_to)) conn |> delete_session(:return_to) |> put_session(:current_user, user) |> put_session(:access_token, token.token) |> redirect(to: redirect_path) end defp create_user(github_user) do case Repo.get_by(User, name: github_user.name, github_id: github_user.github_id) do nil -> Repo.insert!(User.changeset(%User{}, github_user)) user -> Map.merge(user, github_user) end end defp get_user!(token) do {:ok, %{body: user}} = OAuthClient.get(token, "/user") %{ name: user["login"], avatar_url: user["avatar_url"], github_id: user["id"] } end defp return_to_path(conn, nil), do: Routes.page_path(conn, :index) defp return_to_path(_, path), do: path end
27.166667
87
0.66915
0322699c6041a97798a9aa054d6a1e4a46942534
256
ex
Elixir
lib/bitlog_web/open_api_spex/schema_helpers.ex
Soonad/Bitlog
17f41b591169dca7412b9790e8f20abf11b46313
[ "MIT" ]
2
2019-12-03T10:38:38.000Z
2019-12-04T23:52:11.000Z
lib/bitlog_web/open_api_spex/schema_helpers.ex
moonad/Bitlog
17f41b591169dca7412b9790e8f20abf11b46313
[ "MIT" ]
null
null
null
lib/bitlog_web/open_api_spex/schema_helpers.ex
moonad/Bitlog
17f41b591169dca7412b9790e8f20abf11b46313
[ "MIT" ]
null
null
null
defmodule BitlogWeb.OpenApiSpex.SchemaHelpers do @moduledoc false alias OpenApiSpex.Schema def object(properties) do %Schema{type: :object, properties: properties} end def enum(values) do %Schema{type: :string, enum: values} end end
18.285714
50
0.730469
03226aebf62b4abc49293d9b7c46650721384081
2,545
ex
Elixir
lib/codes/codes_n82.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_n82.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_n82.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_N82 do alias IcdCode.ICDCode def _N820 do %ICDCode{full_code: "N820", category_code: "N82", short_code: "0", full_name: "Vesicovaginal fistula", short_name: "Vesicovaginal fistula", category_name: "Vesicovaginal fistula" } end def _N821 do %ICDCode{full_code: "N821", category_code: "N82", short_code: "1", full_name: "Other female urinary-genital tract fistulae", short_name: "Other female urinary-genital tract fistulae", category_name: "Other female urinary-genital tract fistulae" } end def _N822 do %ICDCode{full_code: "N822", category_code: "N82", short_code: "2", full_name: "Fistula of vagina to small intestine", short_name: "Fistula of vagina to small intestine", category_name: "Fistula of vagina to small intestine" } end def _N823 do %ICDCode{full_code: "N823", category_code: "N82", short_code: "3", full_name: "Fistula of vagina to large intestine", short_name: "Fistula of vagina to large intestine", category_name: "Fistula of vagina to large intestine" } end def _N824 do %ICDCode{full_code: "N824", category_code: "N82", short_code: "4", full_name: "Other female intestinal-genital tract fistulae", short_name: "Other female intestinal-genital tract fistulae", category_name: "Other female intestinal-genital tract fistulae" } end def _N825 do %ICDCode{full_code: "N825", category_code: "N82", short_code: "5", full_name: "Female genital tract-skin fistulae", short_name: "Female genital tract-skin fistulae", category_name: "Female genital tract-skin fistulae" } end def _N828 do %ICDCode{full_code: "N828", category_code: "N82", short_code: "8", full_name: "Other female genital tract fistulae", short_name: "Other female genital tract fistulae", category_name: "Other female genital tract fistulae" } end def _N829 do %ICDCode{full_code: "N829", category_code: "N82", short_code: "9", full_name: "Female genital tract fistula, unspecified", short_name: "Female genital tract fistula, unspecified", category_name: "Female genital tract fistula, unspecified" } end end
32.21519
73
0.615324
0322df8848f6130b804bbc2059e6578489b30768
48
exs
Elixir
test/test_helper.exs
am-kantox/finitomata
7ebbcfe7ed4774ae4db1fc880045c6081a3c5d42
[ "MIT" ]
2
2022-03-31T11:57:45.000Z
2022-03-31T15:02:31.000Z
test/test_helper.exs
am-kantox/finitomata
7ebbcfe7ed4774ae4db1fc880045c6081a3c5d42
[ "MIT" ]
null
null
null
test/test_helper.exs
am-kantox/finitomata
7ebbcfe7ed4774ae4db1fc880045c6081a3c5d42
[ "MIT" ]
null
null
null
ExUnit.start(exclude: :skip, capture_log: true)
24
47
0.770833
0322e12afd7b1ca77039e8456af3353d336df069
68
ex
Elixir
lib/jean_grey/repo.ex
AgtLucas/jean-grey
2aa3de025de67124c0d2bc6621f7795b547011e5
[ "MIT" ]
null
null
null
lib/jean_grey/repo.ex
AgtLucas/jean-grey
2aa3de025de67124c0d2bc6621f7795b547011e5
[ "MIT" ]
null
null
null
lib/jean_grey/repo.ex
AgtLucas/jean-grey
2aa3de025de67124c0d2bc6621f7795b547011e5
[ "MIT" ]
null
null
null
defmodule JeanGrey.Repo do use Ecto.Repo, otp_app: :jean_grey end
17
36
0.779412
0323006c530ab703644d578f5fae1a45395a57ef
8,712
ex
Elixir
clients/partners/lib/google_api/partners/v2/api/offers.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/partners/lib/google_api/partners/v2/api/offers.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/partners/lib/google_api/partners/v2/api/offers.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.Partners.V2.Api.Offers do @moduledoc """ API calls for all endpoints tagged `Offers`. """ alias GoogleApi.Partners.V2.Connection alias GoogleApi.Gax.{Request, Response} @doc """ Lists the Historical Offers for the current user (or user&#39;s entire company) ## Parameters - connection (GoogleApi.Partners.V2.Connection): Connection to server - opts (KeywordList): [optional] Optional parameters - :access_token (String.t): OAuth access token. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :quotaUser (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. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :fields (String.t): Selector specifying which fields to include in a partial response. - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :callback (String.t): JSONP - :oauth_token (String.t): OAuth 2.0 token for the current user. - :$.xgafv (String.t): V1 error format. - :alt (String.t): Data format for response. - :requestMetadata.userOverrides.userId (String.t): Logged-in user ID to impersonate instead of the user&#39;s ID. - :requestMetadata.partnersSessionId (String.t): Google Partners session ID. - :pageToken (String.t): Token to retrieve a specific page. - :pageSize (integer()): Maximum number of rows to return per page. - :requestMetadata.trafficSource.trafficSourceId (String.t): Identifier to indicate where the traffic comes from. An identifier has multiple letters created by a team which redirected the traffic to us. - :requestMetadata.locale (String.t): Locale to use for the current request. - :requestMetadata.userOverrides.ipAddress (String.t): IP address to use instead of the user&#39;s geo-located IP address. - :requestMetadata.experimentIds ([String.t]): Experiment IDs the current request belongs to. - :entireCompany (boolean()): if true, show history for the entire company. Requires user to be admin. - :orderBy (String.t): Comma-separated list of fields to order by, e.g.: \&quot;foo,bar,baz\&quot;. Use \&quot;foo desc\&quot; to sort descending. List of valid field names is: name, offer_code, expiration_time, status, last_modified_time, sender_name, creation_time, country_code, offer_type. - :requestMetadata.trafficSource.trafficSubId (String.t): Second level identifier to indicate where the traffic comes from. An identifier has multiple letters created by a team which redirected the traffic to us. ## Returns {:ok, %GoogleApi.Partners.V2.Model.ListOffersHistoryResponse{}} on success {:error, info} on failure """ @spec partners_offers_history_list(Tesla.Env.client(), keyword()) :: {:ok, GoogleApi.Partners.V2.Model.ListOffersHistoryResponse.t()} | {:error, Tesla.Env.t()} def partners_offers_history_list(connection, opts \\ []) do optional_params = %{ :access_token => :query, :key => :query, :upload_protocol => :query, :quotaUser => :query, :prettyPrint => :query, :fields => :query, :uploadType => :query, :callback => :query, :oauth_token => :query, :"$.xgafv" => :query, :alt => :query, :"requestMetadata.userOverrides.userId" => :query, :"requestMetadata.partnersSessionId" => :query, :pageToken => :query, :pageSize => :query, :"requestMetadata.trafficSource.trafficSourceId" => :query, :"requestMetadata.locale" => :query, :"requestMetadata.userOverrides.ipAddress" => :query, :"requestMetadata.experimentIds" => :query, :entireCompany => :query, :orderBy => :query, :"requestMetadata.trafficSource.trafficSubId" => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v2/offers/history") |> Request.add_optional_params(optional_params, opts) connection |> Connection.execute(request) |> Response.decode(struct: %GoogleApi.Partners.V2.Model.ListOffersHistoryResponse{}) end @doc """ Lists the Offers available for the current user ## Parameters - connection (GoogleApi.Partners.V2.Connection): Connection to server - opts (KeywordList): [optional] Optional parameters - :access_token (String.t): OAuth access token. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :quotaUser (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. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :fields (String.t): Selector specifying which fields to include in a partial response. - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :callback (String.t): JSONP - :oauth_token (String.t): OAuth 2.0 token for the current user. - :$.xgafv (String.t): V1 error format. - :alt (String.t): Data format for response. - :requestMetadata.experimentIds ([String.t]): Experiment IDs the current request belongs to. - :requestMetadata.trafficSource.trafficSubId (String.t): Second level identifier to indicate where the traffic comes from. An identifier has multiple letters created by a team which redirected the traffic to us. - :requestMetadata.partnersSessionId (String.t): Google Partners session ID. - :requestMetadata.userOverrides.userId (String.t): Logged-in user ID to impersonate instead of the user&#39;s ID. - :requestMetadata.trafficSource.trafficSourceId (String.t): Identifier to indicate where the traffic comes from. An identifier has multiple letters created by a team which redirected the traffic to us. - :requestMetadata.locale (String.t): Locale to use for the current request. - :requestMetadata.userOverrides.ipAddress (String.t): IP address to use instead of the user&#39;s geo-located IP address. ## Returns {:ok, %GoogleApi.Partners.V2.Model.ListOffersResponse{}} on success {:error, info} on failure """ @spec partners_offers_list(Tesla.Env.client(), keyword()) :: {:ok, GoogleApi.Partners.V2.Model.ListOffersResponse.t()} | {:error, Tesla.Env.t()} def partners_offers_list(connection, opts \\ []) do optional_params = %{ :access_token => :query, :key => :query, :upload_protocol => :query, :quotaUser => :query, :prettyPrint => :query, :fields => :query, :uploadType => :query, :callback => :query, :oauth_token => :query, :"$.xgafv" => :query, :alt => :query, :"requestMetadata.experimentIds" => :query, :"requestMetadata.trafficSource.trafficSubId" => :query, :"requestMetadata.partnersSessionId" => :query, :"requestMetadata.userOverrides.userId" => :query, :"requestMetadata.trafficSource.trafficSourceId" => :query, :"requestMetadata.locale" => :query, :"requestMetadata.userOverrides.ipAddress" => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v2/offers") |> Request.add_optional_params(optional_params, opts) connection |> Connection.execute(request) |> Response.decode(struct: %GoogleApi.Partners.V2.Model.ListOffersResponse{}) end end
51.857143
305
0.700872
03231ee73cc186df1d0c04447b16f2e823d442b2
426
ex
Elixir
test/sample_apps/minimal_phoenix/lib/minimal_phoenix_web.ex
kayodeosagbemi/elixir-runtime
1746adf362444e3e0cc2daa5e461be24f1cb624a
[ "Apache-2.0" ]
170
2017-08-25T06:40:14.000Z
2022-01-10T22:18:51.000Z
test/sample_apps/minimal_phoenix/lib/minimal_phoenix_web.ex
kayodeosagbemi/elixir-runtime
1746adf362444e3e0cc2daa5e461be24f1cb624a
[ "Apache-2.0" ]
27
2017-09-07T05:57:37.000Z
2022-03-22T13:40:47.000Z
test/sample_apps/minimal_phoenix/lib/minimal_phoenix_web.ex
kayodeosagbemi/elixir-runtime
1746adf362444e3e0cc2daa5e461be24f1cb624a
[ "Apache-2.0" ]
16
2017-11-14T01:45:00.000Z
2021-10-09T03:26:39.000Z
defmodule MinimalPhoenixWeb do def controller do quote do use Phoenix.Controller, namespace: MinimalPhoenixWeb import Plug.Conn import MinimalPhoenixWeb.Router.Helpers end end def router do quote do use Phoenix.Router import Plug.Conn import Phoenix.Controller end end defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
18.521739
58
0.692488
032376e3e2d6d9709cc3e7fc85543c06d2acd31f
492
ex
Elixir
lib/abbr/url.ex
elvanja/abbr
b09954df2f68f71c03f308b01927f032bf692ac4
[ "MIT" ]
14
2020-03-25T22:10:42.000Z
2021-02-04T01:31:40.000Z
lib/abbr/url.ex
elvanja/abbr
b09954df2f68f71c03f308b01927f032bf692ac4
[ "MIT" ]
null
null
null
lib/abbr/url.ex
elvanja/abbr
b09954df2f68f71c03f308b01927f032bf692ac4
[ "MIT" ]
null
null
null
defmodule Abbr.Url do @moduledoc """ Represents a mapping between original and shortened URL. Parameters: - original - contains the full original URL - short - contains only the hash value of the shortened URL """ alias __MODULE__ @enforce_keys [ :short, :original ] defstruct [ :short, :original ] @type short :: String.t() @type original :: String.t() @type t :: %Url{ short: short(), original: original() } end
16.4
61
0.607724
0323a24c3189251d0bda89340fd40c3b14e7c9a2
78
exs
Elixir
apps/mishka_content/test/mishka_content_test.exs
mojtaba-naserei/mishka-cms
1f31f61347bab1aae6ba0d47c5515a61815db6c9
[ "Apache-2.0" ]
35
2021-06-26T09:05:50.000Z
2022-03-30T15:41:22.000Z
apps/mishka_content/test/mishka_content_test.exs
iArazar/mishka-cms
8b579101d607d91e80834527c1508fe5f4ceefef
[ "Apache-2.0" ]
101
2021-01-01T09:54:07.000Z
2022-03-28T10:02:24.000Z
apps/mishka_content/test/mishka_content_test.exs
iArazar/mishka-cms
8b579101d607d91e80834527c1508fe5f4ceefef
[ "Apache-2.0" ]
8
2021-01-17T17:08:07.000Z
2022-03-11T16:12:06.000Z
defmodule MishkaContentTest do use ExUnit.Case doctest MishkaContent end
13
30
0.820513
0323aab97c1b02ffd35d87a2fa64d379ccae8c81
2,212
ex
Elixir
clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1beta2__text_annotation.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1beta2__text_annotation.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1beta2__text_annotation.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.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1beta2_TextAnnotation do @moduledoc """ Annotations related to one detected OCR text snippet. This will contain the corresponding text, confidence value, and frame level information for each detection. ## Attributes * `segments` (*type:* `list(GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1beta2_TextSegment.t)`, *default:* `nil`) - All video segments where OCR detected text appears. * `text` (*type:* `String.t`, *default:* `nil`) - The detected text. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :segments => list( GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1beta2_TextSegment.t() ), :text => String.t() } field( :segments, as: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1beta2_TextSegment, type: :list ) field(:text) end defimpl Poison.Decoder, for: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1beta2_TextAnnotation do def decode(value, options) do GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1beta2_TextAnnotation.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1beta2_TextAnnotation do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.030769
193
0.745027
0323ba44c721d13b24eedb2c00ce5b73a59ef511
61
ex
Elixir
lib/hayago_web/views/layout_view.ex
jeffkreeftmeijer/hayago
f80e3204efc70fb4c144a75952534ef143ab584d
[ "Apache-2.0" ]
60
2019-06-14T02:38:33.000Z
2022-02-27T22:08:36.000Z
lib/hayago_web/views/layout_view.ex
jeffkreeftmeijer/hayago
f80e3204efc70fb4c144a75952534ef143ab584d
[ "Apache-2.0" ]
2
2020-01-05T09:09:58.000Z
2020-12-31T09:54:13.000Z
lib/hayago_web/views/layout_view.ex
jeffkreeftmeijer/hayago
f80e3204efc70fb4c144a75952534ef143ab584d
[ "Apache-2.0" ]
15
2019-06-14T02:38:39.000Z
2021-10-30T21:53:08.000Z
defmodule HayagoWeb.LayoutView do use HayagoWeb, :view end
15.25
33
0.803279
0323c05fcba0be44f789f7287ae1e5bc2b9823dd
8,135
ex
Elixir
lib/sanbase/clickhouse/labels.ex
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
81
2017-11-20T01:20:22.000Z
2022-03-05T12:04:25.000Z
lib/sanbase/clickhouse/labels.ex
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
359
2017-10-15T14:40:53.000Z
2022-01-25T13:34:20.000Z
lib/sanbase/clickhouse/labels.ex
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
16
2017-11-19T13:57:40.000Z
2022-02-07T08:13:02.000Z
defmodule Sanbase.Clickhouse.Label do @moduledoc """ Labeling addresses """ @type label :: %{ name: String.t(), metadata: String.t() } def list_all(:all = _blockchain) do query = """ SELECT DISTINCT(label) FROM blockchain_address_labels """ Sanbase.ClickhouseRepo.query_transform(query, [], fn [label] -> label end) end def list_all(blockchain) do query = """ SELECT DISTINCT(label) FROM blockchain_address_labels PREWHERE blockchain = ?1 """ Sanbase.ClickhouseRepo.query_transform(query, [blockchain], fn [label] -> label end) end def add_labels(_, []), do: {:ok, []} def add_labels(slug, maps) when is_list(maps) do addresses = get_list_of_addresses(maps) blockchain = slug_to_blockchain(slug) {query, args} = addresses_labels_query(slug, blockchain, addresses) Sanbase.ClickhouseRepo.query_reduce(query, args, %{}, fn [address, label, metadata], acc -> label = %{name: label, metadata: metadata, origin: "santiment"} Map.update(acc, address, [label], &[label | &1]) end) |> case do {:ok, labels_map} -> {:ok, do_add_labels(maps, labels_map)} {:error, reason} -> {:error, reason} end end def get_address_labels(_slug, []), do: {:ok, %{}} def get_address_labels(slug, addresses) when is_list(addresses) do blockchain = slug_to_blockchain(slug) {query, args} = addresses_labels_query(slug, blockchain, addresses) Sanbase.ClickhouseRepo.query_reduce(query, args, %{}, fn [address, label, metadata], acc -> label = %{name: label, metadata: metadata, origin: "santiment"} Map.update(acc, address, [label], &[label | &1]) end) end # Private functions # For backwards compatibility, if the slug is nil treat it as ethereum blockchain def slug_to_blockchain(nil), do: "ethereum" def slug_to_blockchain(slug), do: Sanbase.Model.Project.slug_to_blockchain(slug) defp addresses_labels_query(slug, "ethereum", addresses) do query = create_addresses_labels_query(slug) args = case slug do nil -> [addresses] _ -> [addresses, slug] end {query, args} end defp addresses_labels_query(_slug, blockchain, addresses) do query = """ SELECT address, label, metadata FROM blockchain_address_labels FINAL PREWHERE blockchain = ?1 AND address IN (?2) HAVING sign = 1 """ {query, [blockchain, addresses]} end defp get_list_of_addresses(maps) do maps |> Enum.flat_map(fn map -> [ Map.get(map, :address) && map.address.address, Map.get(map, :from_address) && map.from_address.address, Map.get(map, :to_address) && map.to_address.address ] end) |> Enum.uniq() |> Enum.reject(&is_nil/1) end defp do_add_labels(maps, labels_map) do add_labels = fn # In this case the address type does not exist, so the result is not used nil -> nil map -> Map.put(map, :labels, Map.get(labels_map, map.address, [])) end maps |> Enum.map(fn %{} = map -> map |> Map.replace(:address, add_labels.(Map.get(map, :address))) |> Map.replace(:from_address, add_labels.(Map.get(map, :from_address))) |> Map.replace(:to_address, add_labels.(Map.get(map, :to_address))) end) end defp create_addresses_labels_query(slug) do """ SELECT address, label, concat('\{', '"owner": "', owner, '"\}') as metadata FROM ( SELECT address, arrayJoin(labels_owners_filtered) as label_owner, label_owner.1 as label_raw, label_owner.2 as owner, multiIf( owner = 'uniswap router', 'Uniswap Router', label_raw='uniswap_ecosystem', 'Uniswap Ecosystem', label_raw='cex_dex_trader', 'CEX & DEX Trader', label_raw='centralized_exchange', 'CEX', label_raw='decentralized_exchange', 'DEX', label_raw='withdrawal', 'CEX Trader', label_raw='dex_trader', 'DEX Trader', #{whale_filter(slug, position: 2)} label_raw='deposit', 'CEX Deposit', label_raw='defi', 'DeFi', label_raw='deployer', 'Deployer', label_raw='stablecoin', 'Stablecoin', label_raw='uniswap_ecosystem', 'Uniswap', label_raw='makerdao-cdp-owner', 'MakerDAO CDP Owner', label_raw='makerdao-bite-keeper', 'MakerDAO Bite Keeper', label_raw='genesis', 'Genesis', label_raw='proxy', 'Proxy', label_raw='system', 'System', label_raw='miner', 'Miner', label_raw='contract_factory', 'Contract Factory', label_raw='derivative_token', 'Derivative Token', label_raw='eth2stakingcontract', 'ETH2 Staking Contract', label_raw ) as label FROM ( SELECT address_hash, address, asset_id, splitByChar(',', labels) as label_arr, splitByChar(',', owners) as owner_arr, arrayZip(label_arr, owner_arr) as labels_owners, multiIf( -- if there is the `system` label for an address, we exclude other labels has(label_arr, 'system'), arrayFilter(x -> x.1 = 'system', labels_owners), -- if an address has a `centralized_exchange` label and at least one of the `deposit` and -- `withdrawal` labels, we exclude the `deposit` and `withdrawal` labels. has(label_arr, 'centralized_exchange') AND hasAny(label_arr, ['deposit', 'withdrawal']), arrayFilter(x -> x.1 NOT IN ('deposit', 'withdrawal'), labels_owners), -- if there are the `dex_trader` and `decentralized_exchange` labels for an address, we exclude `dex_trader` label hasAll(label_arr, ['dex_trader', 'decentralized_exchange']), arrayFilter(x -> x.1 != 'dex_trader', labels_owners), -- if there are the `deposit` and `withdrawal` labels for an address, we exclude the `withdrawal` label hasAll(label_arr, ['deposit', 'withdrawal']), arrayFilter(x -> x.1 != 'withdrawal', labels_owners), -- if there are the `dex_trader` and `withdrawal` labels for an address, we replace these metrics to the `cex_dex_trader` label hasAll(label_arr, ['dex_trader', 'withdrawal']), arrayPushFront(arrayFilter(x -> x.1 NOT IN ['dex_trader', 'withdrawal'], labels_owners), ('cex_dex_trader', arrayFilter(x -> x.1 == 'withdrawal', labels_owners)[1].2)), labels_owners ) as labels_owners_filtered FROM eth_labels_final ANY INNER JOIN ( SELECT cityHash64(address) as address_hash, address FROM ( SELECT lower(arrayJoin([?1])) as address ) ) USING address_hash PREWHERE address_hash IN ( SELECT cityHash64(address) FROM ( SELECT lower(arrayJoin([?1])) as address ) ) ) ANY LEFT JOIN ( select asset_id, name from asset_metadata ) USING asset_id ) WHERE label != 'whale_wrong' """ end defp whale_filter(nil, _) do """ label_raw='whale', concat('Whale, token:', name), """ end defp whale_filter(slug, opts) when is_binary(slug) do position = Keyword.fetch!(opts, :position) """ label_raw='whale' AND asset_id = (SELECT asset_id FROM asset_metadata FINAL PREWHERE name = ?#{position}), 'Whale', label_raw='whale' AND asset_id != (SELECT asset_id FROM asset_metadata FINAL PREWHERE name = ?#{position}), 'whale_wrong', """ end end
38.372642
240
0.583036
0323f45a8d0161e5494c3edf72b0c5654e4e09b5
1,755
exs
Elixir
test/kvasir/offset_test.exs
IanLuites/kvasir
fb8e577763bff0736c75d5edd227eaff570e64ea
[ "MIT" ]
12
2019-11-28T10:58:51.000Z
2022-02-08T18:15:12.000Z
test/kvasir/offset_test.exs
IanLuites/kvasir
fb8e577763bff0736c75d5edd227eaff570e64ea
[ "MIT" ]
null
null
null
test/kvasir/offset_test.exs
IanLuites/kvasir
fb8e577763bff0736c75d5edd227eaff570e64ea
[ "MIT" ]
null
null
null
defmodule Kvasir.OffsetTest do use ExUnit.Case, async: true alias Kvasir.Offset describe "compare/2" do test "eq when exactly the same" do a = Offset.create(%{1 => 1, 2 => 2}) b = Offset.create(%{1 => 1, 2 => 2}) assert Offset.compare(a, b) == :eq end test "eq when exactly the same (to map)" do a = Offset.create(%{1 => 1, 2 => 2}) b = %{1 => 1, 2 => 2} assert Offset.compare(a, b) == :eq end test "eq when partition missing" do a = Offset.create(%{1 => 1, 2 => 2}) b = Offset.create(%{2 => 2}) assert Offset.compare(a, b) == :eq end test "eq when partition missing (to map)" do a = Offset.create(%{1 => 1, 2 => 2}) b = %{2 => 2} assert Offset.compare(a, b) == :eq end test "lt" do a = Offset.create(%{1 => 1, 2 => 1}) b = Offset.create(%{2 => 2}) assert Offset.compare(a, b) == :lt end test "lt (to map)" do a = Offset.create(%{1 => 1, 2 => 1}) b = %{2 => 2} assert Offset.compare(a, b) == :lt end test "gt" do a = Offset.create(%{1 => 1, 2 => 3}) b = Offset.create(%{2 => 2}) assert Offset.compare(a, b) == :gt end test "gt (to map)" do a = Offset.create(%{1 => 1, 2 => 3}) b = %{2 => 2} assert Offset.compare(a, b) == :gt end end describe "compare/2 with :earliest" do test "eq (earliest to earliest)" do assert Offset.compare(:earliest, :earliest) == :eq end test "lt (earliest to any)" do assert Offset.compare(:earliest, Offset.create(%{0 => 1})) == :lt end test "gt (any to earliest)" do assert Offset.compare(Offset.create(%{0 => 1}), :earliest) == :gt end end end
22.792208
71
0.51453
03240458eb816ccab7679ff5b12e0e0e19fcad7b
4,269
ex
Elixir
lib/remembrance.ex
brayhoward/remembrance
0b50d8afc9b37b1740beaf2e2ab492e82ed56da1
[ "Apache-2.0" ]
null
null
null
lib/remembrance.ex
brayhoward/remembrance
0b50d8afc9b37b1740beaf2e2ab492e82ed56da1
[ "Apache-2.0" ]
null
null
null
lib/remembrance.ex
brayhoward/remembrance
0b50d8afc9b37b1740beaf2e2ab492e82ed56da1
[ "Apache-2.0" ]
null
null
null
defmodule Remembrance do @moduledoc """ Documentation for Remembrance, a command-line app for setting timers. """ @doc """ Hello world. ## Examples iex> Remembrance.main ["0", "0", "4"] {:ok, "0 hours 0 minutes 4 seconds"} iex> Remembrance.main ["-h"] {:ok, :help_docs} iex> Remembrance.main ["0", "foo", "4"] {:ok, :help_docs} Remembrance.main [] {:ok, "0 hours 3 minutes 0 seconds"} Remembrance.main ["3"] {:ok, "0 hours 3 minutes 0 seconds"} Remembrance.main ["1", "3", "6"] {:ok, "1 hours 3 minutes 6 seconds"} Remembrance.main ["0", "5", "30"] {:ok, "0 hours 5 minutes 30 seondsc"} Remembrance.main ["1", "3"] {:ok, "1 hours 3 minutes 0 seconds"} """ def main(args) do case parse_args(args) do :error -> print_help_docs() {:ok, :help_docs} {:ok, time_map} -> time_map |> set_timeout |> indicate_time_elapsed end end # ## Private AF # defp set_timeout(time_map) do %{hr: hr, min: min, sec: sec} = time_map milliseconds = :timer.hms hr, min, sec print_timer_set_confirmation(time_map) :timer.sleep(milliseconds) time_map end defp indicate_time_elapsed(time_map) do print_alert_message(time_map) System.cmd "tput", ["\a"] System.cmd "say", ["timer elapsed"] {:ok, humanize_time_map(time_map)} end defp parse_args(args) do case List.first(args) === "-h" do true -> :error false -> process_args_list(args) end end defp process_args_list(args) do nums_list = map_to_ints(args) case Enum.any?( nums_list, &(:error === &1)) do true -> :error false -> {:ok, build_time_map(nums_list)} end end defp build_time_map([]) do IO.puts "No arguments given" # Default to 3 if no args passed build_time_map([3]) end defp build_time_map(nums) do case length nums do 1 -> %{hr: 0, min: List.first(nums), sec: 0} 2 -> [ hr | tail ] = nums %{hr: hr, min: List.first(tail), sec: 0} # Take top three args and ignore any others. _ -> [hr | tail] = nums [min | tail] = tail [sec | _] = tail %{hr: hr, min: min, sec: sec} end end defp map_to_ints(args) do Enum.map args, &(to_int &1) end defp to_int(arg) do case Integer.parse arg do {num, _} -> num :error -> :error end end # defp exit_gracfully do # offer_feedback() # exit(:shutdown) # end ### User messaging funcitons bellow ### defp humanize_time_map(%{hr: hr, min: min, sec: sec}), do: "#{hr} hours #{min} minutes #{sec} seconds" defp print_alert_message(time_map) do IO.puts """ Ding Ding ⏰ #{timer_elapsed_message(time_map)} """ end defp timer_elapsed_message(time_map) do "Your timer set for #{humanize_time_map(time_map)} has elapsed." end defp print_timer_set_confirmation(time_map) do %{hr: hr, min: min, sec: sec} = time_map time = humanize_time_map(time_map) IO.puts "Timer set for #{time}\n" if min === 3 && hr === 0 && sec === 0 do IO.puts "Don't oversteep that tea! 🍵" end {:ok, time} end defp print_help_docs() do IO.puts """ To set time pass whole numbers as arguments. First argument being the hours, second the minutes, and third the seconds. Example: `./remembrance 1 30 0` "Timer set for 1 hr 30 min 0 sec" If no arguments are passed the timer will default 3 minutes. Example: `./remembrance` "Timer set for 0 hr 3 min 0 sec" If only one argument is passed it timer will set for minutes. Example: `./remembrance 5` "Timer set for 0 hr 5 min 0 sec" If two arguments are passed the timer will set for hours and minutes Example: `./remembrance 1 30` "Timer set for 1 hr 30 min 0 sec" To set hours minutes and seconds pass three arguments. Example: `./remembrance 1 25 30` "Timer set for 1 hr 25 min 30 sec" Pass 0 for any time units that you do not want to set. Example: `./remembrance 0 0 45` "Timer set for 0 hr 0 min 45 sec" """ end end
21.560606
104
0.589365
0324108341d00ada48e0d0bcc22329bf1f04308d
3,662
ex
Elixir
apps/ewallet/lib/ewallet/web/v1/serializers/websocket_response_serializer.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
322
2018-02-28T07:38:44.000Z
2020-05-27T23:09:55.000Z
apps/ewallet/lib/ewallet/web/v1/serializers/websocket_response_serializer.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
643
2018-02-28T12:05:20.000Z
2020-05-22T08:34:38.000Z
apps/ewallet/lib/ewallet/web/v1/serializers/websocket_response_serializer.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
63
2018-02-28T10:57:06.000Z
2020-05-27T23:10:38.000Z
# Copyright 2018-2019 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule EWallet.Web.V1.WebsocketResponseSerializer do @moduledoc """ Serializes websocket data into V1 response format. """ @behaviour Phoenix.Transports.Serializer alias EWallet.Web.V1.ErrorHandler alias Phoenix.Socket.Broadcast alias Phoenix.Socket.Message alias Phoenix.Socket.Reply @doc """ Renders the given `data` into a V1 response format as JSON. """ def serialize(%{ data: data, error: error, msg: msg, success: success }) do %{ success: success, version: "1", data: data, error: error, topic: msg.topic, event: msg.event, ref: msg.ref } end @doc """ Translates a `Phoenix.Socket.Broadcast` into a `Phoenix.Socket.Message`. """ def fastlane!(%Broadcast{} = msg) do msg = msg |> build_message() |> encode_fields() {:socket_push, :text, msg} end @doc """ Encodes a `Phoenix.Socket.Message` struct to JSON string. """ def encode!(msg) do msg = msg |> build_message() |> encode_fields() {:socket_push, :text, msg} end @doc """ Decodes JSON String into `Phoenix.Socket.Message` struct. """ def decode!(message, _opts) do decoded = Poison.decode!(message) case decoded do %{} = decoded -> decoded |> Map.put("payload", decoded["data"]) |> Message.from_map!() _ -> build_error(:websocket_format_error) end end defp build_message(%Reply{} = reply) do case is_atom(reply.payload) do true -> reply |> Map.put(:payload, %{ error: reply.payload, data: nil, reason: nil }) |> format() false -> format(reply) end end defp build_message(msg), do: format(msg) defp format(data) do data = Map.from_struct(data) %{ topic: data[:topic], event: data[:event] || "phx_reply", ref: data[:ref] || nil, status: data[:status] || data[:payload][:status], data: data[:payload][:data], error: data[:payload][:error], reason: data[:payload][:reason] } end defp encode_fields(%{reason: reason} = msg) when not is_nil(reason) do encode_fields(msg, build_reason(msg.reason)) end defp encode_fields(msg) do encode_fields(msg, build_error(msg.error)) end defp encode_fields(msg, error) do %{ data: msg.data, error: error, msg: msg, success: msg.status == :ok } |> serialize() |> Poison.encode_to_iodata!() end defp build_error(nil), do: nil defp build_error(%{code: nil}), do: nil defp build_error(%{code: code, description: description}) do ErrorHandler.build_error(code, description, nil) end defp build_error(%{code: code}), do: ErrorHandler.build_error(code, nil) defp build_error(code) when is_atom(code) do ErrorHandler.build_error(code, nil) end defp build_error(_), do: nil defp build_reason(nil), do: nil defp build_reason(reason) do ErrorHandler.build_error(:websocket_connect_error, reason, nil) end end
24.251656
74
0.637903
032418d7559b53455b12eb8e79372c54aca91bbb
1,299
ex
Elixir
web/schema.ex
gimc/joshua
bc77ed12b45f49879222231849e88e96198920d7
[ "MIT" ]
null
null
null
web/schema.ex
gimc/joshua
bc77ed12b45f49879222231849e88e96198920d7
[ "MIT" ]
null
null
null
web/schema.ex
gimc/joshua
bc77ed12b45f49879222231849e88e96198920d7
[ "MIT" ]
null
null
null
defmodule Joshua.Schema do use Absinthe.Schema import_types Absinthe.Type.Custom alias Joshua.Repo alias Joshua.Badge alias Joshua.Event alias Joshua.Progress object :badge do field :id, :id field :name, :string field :description, :string field :icon, :string field :count, :integer field :event_name, :string end object :progress do field :id, :id field :name, :string field :count, :integer field :required, :integer field :date_achieved, :naive_datetime end object :event do field :id, :id field :name, :string field :user_id, :integer end query do @desc "Get all badges" field :badges, list_of(:badge) do resolve fn _, _ -> {:ok, Repo.all(Badge)} end end @desc "Get all progress for user" field :all_progress, list_of(:progress) do arg :user_id, non_null(:integer) resolve fn %{user_id: user_id}, _ -> {:ok, Progress.by_user_id(user_id)} end end end mutation do @desc "Create an event" field :event, type: :event do arg :name, non_null(:string) arg :user_id, non_null(:integer) resolve fn args, _ -> %Event{} |> Event.changeset(args) |> Repo.insert() end end end end
19.984615
46
0.614319