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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
73b6064a73ce0fb6d0b5a198d8945052722b6bb0 | 494 | ex | Elixir | lib/garuda/view.ex | shankardevy/neem | b78b3da91e7fffb033be5c391d4ac1e1c05e8e22 | [
"MIT"
] | 44 | 2017-06-24T10:33:51.000Z | 2021-09-28T23:17:39.000Z | lib/garuda/view.ex | shankardevy/neem | b78b3da91e7fffb033be5c391d4ac1e1c05e8e22 | [
"MIT"
] | null | null | null | lib/garuda/view.ex | shankardevy/neem | b78b3da91e7fffb033be5c391d4ac1e1c05e8e22 | [
"MIT"
] | 7 | 2017-07-27T07:26:34.000Z | 2019-07-17T04:31:35.000Z | defmodule Garuda.View do
defmacro __using__(opts) do
path = Keyword.fetch!(opts, :path)
for template <- Path.wildcard(path <> "/*.eex") do
base_path = Path.basename(template, ".eex")
template_content = File.read!(template)
quote bind_quoted: [base_path: base_path,
template: template_content] do
def render(unquote(base_path), var!(assigns)) do
EEx.eval_string(unquote(template), var!(assigns))
end
end
end
end
end
| 30.875 | 59 | 0.637652 |
73b624beb74922c98bd36093a7d0439ad85665dc | 6,691 | exs | Elixir | test/crew/periods_test.exs | anamba/crew | c25f6a1d6ddbe0b58da9d556ff53a641c4d2a7b1 | [
"BSL-1.0"
] | null | null | null | test/crew/periods_test.exs | anamba/crew | c25f6a1d6ddbe0b58da9d556ff53a641c4d2a7b1 | [
"BSL-1.0"
] | 5 | 2020-07-20T01:49:01.000Z | 2021-09-08T00:17:04.000Z | test/crew/periods_test.exs | anamba/crew | c25f6a1d6ddbe0b58da9d556ff53a641c4d2a7b1 | [
"BSL-1.0"
] | null | null | null | defmodule Crew.PeriodsTest do
use Crew.DataCase
alias Crew.Periods
alias Crew.Sites
@valid_site_attrs %{name: "School Fair", slug: "fair", primary_domain: "fair.example.com"}
def site_fixture(attrs \\ %{}) do
{:ok, site} =
attrs
|> Enum.into(@valid_site_attrs)
|> Sites.create_site()
site
end
describe "periods" do
alias Crew.Periods.Period
@valid_attrs %{
name: "some name",
slug: "some slug",
description: "some description",
start_time: "2010-04-17T14:00:00Z",
end_time: "2010-04-17T15:00:00Z"
}
@update_attrs %{
name: "some updated name",
slug: "some updated slug",
description: "some updated description",
start_time: "2011-05-18T14:01:01Z",
end_time: "2011-05-18T15:01:01Z"
}
@invalid_attrs %{description: nil, end_time: nil, name: nil, slug: nil, start_time: nil}
def period_fixture(attrs \\ %{}, site_id) do
{:ok, period} =
attrs
|> Enum.into(@valid_attrs)
|> Periods.create_period(site_id)
period
end
test "list_periods/0 returns all periods" do
site_id = site_fixture().id
period = period_fixture(site_id)
assert Periods.list_periods(site_id) == [period]
end
test "get_period!/1 returns the period with given id" do
site_id = site_fixture().id
period = period_fixture(site_id)
assert Periods.get_period!(period.id) == period
end
test "create_period/1 with valid data creates a period" do
site_id = site_fixture().id
assert {:ok, %Period{} = period} = Periods.create_period(@valid_attrs, site_id)
assert period.name == "some name"
assert period.slug == "some slug"
assert period.description == "some description"
assert period.start_time == DateTime.from_naive!(~N[2010-04-17T14:00:00Z], "Etc/UTC")
assert period.end_time == DateTime.from_naive!(~N[2010-04-17T15:00:00Z], "Etc/UTC")
end
test "create_period/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Periods.create_period(@invalid_attrs)
end
test "update_period/2 with valid data updates the period" do
site_id = site_fixture().id
period = period_fixture(site_id)
assert {:ok, %Period{} = period} = Periods.update_period(period, @update_attrs)
assert period.name == "some updated name"
assert period.slug == "some updated slug"
assert period.description == "some updated description"
assert period.start_time == DateTime.from_naive!(~N[2011-05-18T14:01:01Z], "Etc/UTC")
assert period.end_time == DateTime.from_naive!(~N[2011-05-18T15:01:01Z], "Etc/UTC")
end
test "update_period/2 with invalid data returns error changeset" do
site_id = site_fixture().id
period = period_fixture(site_id)
assert {:error, %Ecto.Changeset{}} = Periods.update_period(period, @invalid_attrs)
assert period == Periods.get_period!(period.id)
end
test "delete_period/1 deletes the period" do
site_id = site_fixture().id
period = period_fixture(site_id)
assert {:ok, %Period{}} = Periods.delete_period(period)
assert_raise Ecto.NoResultsError, fn -> Periods.get_period!(period.id) end
end
test "change_period/1 returns a period changeset" do
site_id = site_fixture().id
period = period_fixture(site_id)
assert %Ecto.Changeset{} = Periods.change_period(period)
end
end
describe "period_groups" do
alias Crew.Periods.PeriodGroup
@valid_attrs %{
name: "some name",
slug: "some slug",
description: "some description",
event: true
}
@update_attrs %{
name: "some updated name",
slug: "some updated slug",
description: "some updated description",
event: false
}
@invalid_attrs %{description: nil, event: nil, name: nil, slug: nil}
def period_group_fixture(attrs \\ %{}, site_id) do
{:ok, period_group} =
attrs
|> Enum.into(@valid_attrs)
|> Periods.create_period_group(site_id)
period_group
end
test "list_period_groups/0 returns all period_groups" do
site_id = site_fixture().id
period_group = period_group_fixture(site_id)
assert Periods.list_period_groups(site_id) == [period_group]
end
test "get_period_group!/1 returns the period_group with given id" do
site_id = site_fixture().id
period_group = period_group_fixture(site_id)
assert Periods.get_period_group!(period_group.id) == period_group
end
test "create_period_group/1 with valid data creates a period_group" do
site_id = site_fixture().id
assert {:ok, %PeriodGroup{} = period_group} =
Periods.create_period_group(@valid_attrs, site_id)
assert period_group.name == "some name"
assert period_group.slug == "some slug"
assert period_group.description == "some description"
assert period_group.event == true
end
test "create_period_group/1 with invalid data returns error changeset" do
site_id = site_fixture().id
assert {:error, %Ecto.Changeset{}} = Periods.create_period_group(@invalid_attrs, site_id)
end
test "update_period_group/2 with valid data updates the period_group" do
site_id = site_fixture().id
period_group = period_group_fixture(site_id)
assert {:ok, %PeriodGroup{} = period_group} =
Periods.update_period_group(period_group, @update_attrs)
assert period_group.name == "some updated name"
assert period_group.slug == "some updated slug"
assert period_group.description == "some updated description"
assert period_group.event == false
end
test "update_period_group/2 with invalid data returns error changeset" do
site_id = site_fixture().id
period_group = period_group_fixture(site_id)
assert {:error, %Ecto.Changeset{}} =
Periods.update_period_group(period_group, @invalid_attrs)
assert period_group == Periods.get_period_group!(period_group.id)
end
test "delete_period_group/1 deletes the period_group" do
site_id = site_fixture().id
period_group = period_group_fixture(site_id)
assert {:ok, %PeriodGroup{}} = Periods.delete_period_group(period_group)
assert_raise Ecto.NoResultsError, fn -> Periods.get_period_group!(period_group.id) end
end
test "change_period_group/1 returns a period_group changeset" do
site_id = site_fixture().id
period_group = period_group_fixture(site_id)
assert %Ecto.Changeset{} = Periods.change_period_group(period_group)
end
end
end
| 34.137755 | 95 | 0.672545 |
73b661ce5847e99205d7e9f2842101c58dadb52a | 866 | exs | Elixir | config/config.exs | chengyin/json-to-elixir | 896cdc685aac7b0b0bdbdc730b5816f69b169bd5 | [
"BSD-3-Clause"
] | 1 | 2020-01-19T17:52:05.000Z | 2020-01-19T17:52:05.000Z | config/config.exs | chengyin/json-to-elixir | 896cdc685aac7b0b0bdbdc730b5816f69b169bd5 | [
"BSD-3-Clause"
] | null | null | null | config/config.exs | chengyin/json-to-elixir | 896cdc685aac7b0b0bdbdc730b5816f69b169bd5 | [
"BSD-3-Clause"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
# Configures the endpoint
config :json_to_elixir, JSONToElixirWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "JRxFOZnl8zT3HioE90VM3HwKMjILzfwjLcZ/eSS7FAMwvqSixYZUJvghz7EcPJCo",
render_errors: [view: JSONToElixirWeb.ErrorView, accepts: ~w(html json)],
pubsub: [name: JSONToElixir.PubSub, adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env()}.exs"
| 37.652174 | 86 | 0.775982 |
73b6790e1a80b6886f465ccf0a0b10584e9fc2f7 | 3,729 | exs | Elixir | test/smwc_web/controllers/user_confirmation_controller_test.exs | druu/smwcbot | 0c9e3530c470028c767b6a77be8a939481756438 | [
"MIT"
] | 2 | 2022-03-09T18:04:42.000Z | 2022-03-11T22:24:25.000Z | test/smwc_web/controllers/user_confirmation_controller_test.exs | druu/smwcbot | 0c9e3530c470028c767b6a77be8a939481756438 | [
"MIT"
] | null | null | null | test/smwc_web/controllers/user_confirmation_controller_test.exs | druu/smwcbot | 0c9e3530c470028c767b6a77be8a939481756438 | [
"MIT"
] | 2 | 2022-02-27T22:00:17.000Z | 2022-02-28T02:20:21.000Z | defmodule SMWCWeb.UserConfirmationControllerTest do
use SMWCWeb.ConnCase, async: true
import SMWC.AccountsFixtures
alias SMWC.Accounts
alias SMWC.Repo
setup do
%{user: user_fixture()}
end
describe "GET /users/confirm" do
test "renders the resend confirmation page", %{conn: conn} do
conn = get(conn, Routes.user_confirmation_path(conn, :new))
response = html_response(conn, 200)
assert response =~ "<h1>Resend confirmation instructions</h1>"
end
end
describe "POST /users/confirm" do
@tag :capture_log
test "sends a new confirmation token", %{conn: conn, user: user} do
conn =
post(conn, Routes.user_confirmation_path(conn, :create), %{
"user" => %{"email" => user.email}
})
assert redirected_to(conn) == "/"
assert get_flash(conn, :info) =~ "If your email is in our system"
assert Repo.get_by!(Accounts.UserToken, user_id: user.id).context == "confirm"
end
test "does not send confirmation token if User is confirmed", %{conn: conn, user: user} do
user
|> Accounts.User.confirm_changeset()
|> Repo.update!()
conn =
post(conn, Routes.user_confirmation_path(conn, :create), %{
"user" => %{"email" => user.email}
})
assert redirected_to(conn) == "/"
assert get_flash(conn, :info) =~ "If your email is in our system"
refute Repo.get_by(Accounts.UserToken, user_id: user.id)
end
test "does not send confirmation token if email is invalid", %{conn: conn} do
conn =
post(conn, Routes.user_confirmation_path(conn, :create), %{
"user" => %{"email" => "[email protected]"}
})
assert redirected_to(conn) == "/"
assert get_flash(conn, :info) =~ "If your email is in our system"
assert Repo.all(Accounts.UserToken) == []
end
end
describe "GET /users/confirm/:token" do
test "renders the confirmation page", %{conn: conn} do
conn = get(conn, Routes.user_confirmation_path(conn, :edit, "some-token"))
response = html_response(conn, 200)
assert response =~ "<h1>Confirm account</h1>"
form_action = Routes.user_confirmation_path(conn, :update, "some-token")
assert response =~ "action=\"#{form_action}\""
end
end
describe "POST /users/confirm/:token" do
test "confirms the given token once", %{conn: conn, user: user} do
token =
extract_user_token(fn url ->
Accounts.deliver_user_confirmation_instructions(user, url)
end)
conn = post(conn, Routes.user_confirmation_path(conn, :update, token))
assert redirected_to(conn) == "/"
assert get_flash(conn, :info) =~ "User confirmed successfully"
assert Accounts.get_user!(user.id).confirmed_at
refute get_session(conn, :user_token)
assert Repo.all(Accounts.UserToken) == []
# When not logged in
conn = post(conn, Routes.user_confirmation_path(conn, :update, token))
assert redirected_to(conn) == "/"
assert get_flash(conn, :error) =~ "User confirmation link is invalid or it has expired"
# When logged in
conn =
build_conn()
|> log_in_user(user)
|> post(Routes.user_confirmation_path(conn, :update, token))
assert redirected_to(conn) == "/"
refute get_flash(conn, :error)
end
test "does not confirm email with invalid token", %{conn: conn, user: user} do
conn = post(conn, Routes.user_confirmation_path(conn, :update, "oops"))
assert redirected_to(conn) == "/"
assert get_flash(conn, :error) =~ "User confirmation link is invalid or it has expired"
refute Accounts.get_user!(user.id).confirmed_at
end
end
end
| 34.527778 | 94 | 0.643604 |
73b68f43188cdcd7f0c08afc99e923cb4ac5f887 | 1,803 | ex | Elixir | test/support/conn_simulator.ex | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | 1 | 2019-05-07T15:03:54.000Z | 2019-05-07T15:03:54.000Z | test/support/conn_simulator.ex | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | null | null | null | test/support/conn_simulator.ex | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | null | null | null | defmodule MastaniServer.Test.ConnSimulator do
@moduledoc """
mock user_conn, owner_conn, guest_conn
"""
import MastaniServer.Support.Factory
import Phoenix.ConnTest, only: [build_conn: 0]
import Plug.Conn, only: [put_req_header: 3]
alias Helper.{Guardian, ORM}
alias MastaniServer.{Accounts, CMS}
def simu_conn(:guest) do
build_conn()
end
def simu_conn(:user) do
user_attr = mock_attrs(:user)
{:ok, user} = db_insert(:user, user_attr)
token = gen_jwt_token(id: user.id)
build_conn() |> put_req_header("authorization", token)
end
def simu_conn(:invalid_token) do
token = "invalid_token"
build_conn() |> put_req_header("authorization", token)
end
def simu_conn(:owner, content) do
token = gen_jwt_token(id: content.author.user.id)
build_conn() |> put_req_header("authorization", token)
end
def simu_conn(:user, %Accounts.User{} = user) do
token = gen_jwt_token(id: user.id)
build_conn() |> put_req_header("authorization", token)
end
def simu_conn(:user, cms: passport_rules) do
user_attr = mock_attrs(:user)
{:ok, user} = db_insert(:user, user_attr)
token = gen_jwt_token(id: user.id)
{:ok, _passport} = CMS.stamp_passport(passport_rules, %Accounts.User{id: user.id})
build_conn() |> put_req_header("authorization", token)
end
def simu_conn(:user, %Accounts.User{} = user, cms: passport_rules) do
token = gen_jwt_token(id: user.id)
{:ok, _passport} = CMS.stamp_passport(passport_rules, %Accounts.User{id: user.id})
build_conn() |> put_req_header("authorization", token)
end
defp gen_jwt_token(clauses) do
with {:ok, user} <- ORM.find_by(Accounts.User, clauses) do
{:ok, token, _info} = Guardian.jwt_encode(user)
"Bearer #{token}"
end
end
end
| 26.130435 | 86 | 0.686079 |
73b69096bc747c79d928b233508c724b461d32d2 | 1,395 | ex | Elixir | clients/sheets/lib/google_api/sheets/v4/model/batch_clear_values_request.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/sheets/lib/google_api/sheets/v4/model/batch_clear_values_request.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/sheets/lib/google_api/sheets/v4/model/batch_clear_values_request.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 "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Sheets.V4.Model.BatchClearValuesRequest do
@moduledoc """
The request for clearing more than one range of values in a spreadsheet.
## Attributes
- ranges (List[String]): The ranges to clear, in A1 notation. Defaults to: `null`.
"""
defstruct [
:"ranges"
]
end
defimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.BatchClearValuesRequest do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.BatchClearValuesRequest do
def encode(value, options) do
GoogleApi.Sheets.V4.Deserializer.serialize_non_nil(value, options)
end
end
| 30.326087 | 84 | 0.754122 |
73b69a4a6d6d6b0053ef28bc74fb1181014f7cc4 | 265 | ex | Elixir | lib/creek_dict_admin.ex | nativesintech/creek-dictionary-admin | 14bfd6c364010a1c905f97cd9388bad0a40589bc | [
"MIT"
] | null | null | null | lib/creek_dict_admin.ex | nativesintech/creek-dictionary-admin | 14bfd6c364010a1c905f97cd9388bad0a40589bc | [
"MIT"
] | 7 | 2019-09-20T02:00:23.000Z | 2019-10-07T04:22:51.000Z | lib/creek_dict_admin.ex | nativesintech/creek-dictionary-admin | 14bfd6c364010a1c905f97cd9388bad0a40589bc | [
"MIT"
] | null | null | null | defmodule CreekDictAdmin do
@moduledoc """
CreekDictAdmin keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
end
| 26.5 | 66 | 0.766038 |
73b6a7a96c83ab9fe9e88b1b60d0f46ad20d3932 | 1,047 | ex | Elixir | lib/exred_node_aws_iot_thingshadow_out.ex | exredorg/exred_node_aws_iot_thingshadow_out | 071fb2085fca560332bdb41ccb65242123fda7f5 | [
"MIT"
] | null | null | null | lib/exred_node_aws_iot_thingshadow_out.ex | exredorg/exred_node_aws_iot_thingshadow_out | 071fb2085fca560332bdb41ccb65242123fda7f5 | [
"MIT"
] | null | null | null | lib/exred_node_aws_iot_thingshadow_out.ex | exredorg/exred_node_aws_iot_thingshadow_out | 071fb2085fca560332bdb41ccb65242123fda7f5 | [
"MIT"
] | null | null | null | defmodule Exred.Node.AwsIotThingShadowOut do
@moduledoc """
Publishes messages to AWS IoT Cloud.
The incoming message needs to have a valid AWS topic in the topic field.
Incoming msg format:
```elixir
msg = %{
topic :: [binary] | binary
payload :: map,
qos :: integer, # quality of service
retain :: boolean # [GenMQTT doc](https://hexdocs.pm/gen_mqtt/GenMQTT.html#publish/5)
}
```
"""
@name "AWS Thing Shadow Out"
@category "output"
@info @moduledoc
@config %{
thing_name: %{type: "string", value: "myThing"},
name: %{value: @name, type: "string", attrs: %{max: 20}}
}
@ui_attributes %{fire_button: false, right_icon: "send"}
use Exred.NodePrototype
require Logger
@impl true
def handle_msg(msg, state) do
encoded_payload = Poison.encode!(msg.payload)
res =
AwsIotClient.publish(
msg.topic,
encoded_payload,
Map.get(msg, :qos, 0),
Map.get(msg, :retain, false)
)
{%{msg | payload: res}, state}
end
end
| 23.266667 | 96 | 0.617001 |
73b6b0f9ed23e735c807cc03b89ac1f6698fe1df | 35,678 | ex | Elixir | lib/teiserver/protocols/spring/spring_in.ex | marseel/teiserver | 7e085ae7853205d217183737d3eb69a4941bbe7e | [
"MIT"
] | null | null | null | lib/teiserver/protocols/spring/spring_in.ex | marseel/teiserver | 7e085ae7853205d217183737d3eb69a4941bbe7e | [
"MIT"
] | null | null | null | lib/teiserver/protocols/spring/spring_in.ex | marseel/teiserver | 7e085ae7853205d217183737d3eb69a4941bbe7e | [
"MIT"
] | null | null | null | defmodule Teiserver.Protocols.SpringIn do
@moduledoc """
In component of the Spring protocol
Protocol definition:
https://springrts.com/dl/LobbyProtocol/ProtocolDescription.html
"""
require Logger
alias Teiserver.Battle.Lobby
alias Teiserver.{Coordinator, Room, User, Client}
alias Phoenix.PubSub
import Central.Helpers.NumberHelper, only: [int_parse: 1]
import Central.Helpers.TimexHelper, only: [date_to_str: 2]
import Teiserver.Protocols.SpringOut, only: [reply: 4]
alias Teiserver.Protocols.{Spring, SpringOut}
alias Teiserver.Protocols.Spring.{MatchmakingIn, TelemetryIn, BattleIn}
alias Teiserver.{Account}
@spec data_in(String.t(), Map.t()) :: Map.t()
def data_in(data, state) do
if state.print_client_messages do
if String.contains?(data, "c.user.get_token") or String.contains?(data, "LOGIN") do
Logger.info("<-- #{state.username}: LOGIN/c.user.get_token")
else
Logger.info("<-- #{state.username}: #{Spring.format_log(data)}")
end
end
new_state =
if String.ends_with?(data, "\n") do
data = state.message_part <> data
data
|> String.split("\n")
|> Enum.reduce(state, fn data, acc ->
handle(data, acc)
end)
|> Map.put(:message_part, "")
else
%{state | message_part: state.message_part <> data}
end
new_state
end
# The main entry point for the module and the wrapper around
# parsing, processing and acting upon a player message
@spec handle(String.t(), map) :: map
def handle("", state), do: state
def handle("\r\n", state), do: state
def handle(data, state) do
tuple =
~r/^(#[0-9]+ )?([a-z_A-Z0-9\.]+)(.*)?$/
|> Regex.run(data)
|> _clean()
state =
case tuple do
{command, data, msg_id} ->
do_handle(command, data, msg_id, state)
nil ->
Logger.debug("Bad match on command: '#{data}'")
state
end
if state == nil do
throw("nil state returned while handling: #{data}")
end
%{state | last_msg: System.system_time(:second)}
end
defp _clean(nil), do: nil
defp _clean([_, msg_id, command, data]) do
{command, String.trim(data), String.trim(msg_id)}
end
defp do_handle("c.matchmaking." <> cmd, data, msg_id, state) do
MatchmakingIn.do_handle(cmd, data, msg_id, state)
end
defp do_handle("c.telemetry." <> cmd, data, msg_id, state) do
TelemetryIn.do_handle(cmd, data, msg_id, state)
end
defp do_handle("c.battle." <> cmd, data, msg_id, state) do
BattleIn.do_handle(cmd, data, msg_id, state)
end
defp do_handle("STARTTLS", _, msg_id, state) do
do_handle("STLS", nil, msg_id, state)
end
defp do_handle("LISTCOMPFLAGS", _, msg_id, state) do
reply(:compflags, nil, msg_id, state)
state
end
# https://ninenines.eu/docs/en/ranch/1.7/guide/transports/ - Upgrading a TCP socket to SSL
defp do_handle("STLS", _, msg_id, state) do
reply(:okay, "STLS", msg_id, state)
new_state = Teiserver.TcpServer.upgrade_connection(state)
reply(:welcome, nil, msg_id, new_state)
end
# Swap to the Tachyon protocol
defp do_handle("TACHYON", "", msg_id, state) do
reply(:okay, "TACHYON", msg_id, state)
{m_in, m_out} = Teiserver.Protocols.TachyonLib.get_modules()
%{state | protocol_in: m_in, protocol_out: m_out}
end
defp do_handle("TACHYON", "dev", msg_id, state) do
reply(:okay, "TACHYON", msg_id, state)
{m_in, m_out} = Teiserver.Protocols.TachyonLib.get_modules("dev")
%{state | protocol_in: m_in, protocol_out: m_out}
end
defp do_handle("TACHYON", "v" <> _ = version, msg_id, state) do
reply(:okay, "TACHYON", msg_id, state)
{m_in, m_out} = Teiserver.Protocols.TachyonLib.get_modules(version)
%{state | protocol_in: m_in, protocol_out: m_out}
end
# Use the Tachyon protocol for a single command
defp do_handle("TACHYON", data, _msg_id, state) do
{m_in, _m_out} = Teiserver.Protocols.TachyonLib.get_modules()
m_in.data_in("#{data}\n", state)
end
defp do_handle("c.battles.list_ids", _, msg_id, state) do
reply(:list_battles, Lobby.list_lobby_ids(), msg_id, state)
state
end
# Specific handlers for different commands
@spec do_handle(String.t(), String.t(), String.t(), map) :: map
defp do_handle("MYSTATUS", _data, msg_id, %{userid: nil} = state) do
reply(:servermsg, "You need to login before you can set your status", msg_id, state)
end
defp do_handle("MYSTATUS", data, msg_id, state) do
case Regex.run(~r/([0-9]+)/, data) do
[_, new_value] ->
new_status =
Spring.parse_client_status(new_value)
|> Map.take([:in_game, :away])
new_client =
(Client.get_client_by_id(state.userid) || %{})
|> Map.merge(new_status)
# This just accepts it and updates the client
Client.update(new_client, :client_updated_status)
nil ->
_no_match(state, "MYSTATUS", msg_id, data)
end
state
end
defp do_handle("c.user.get_token_by_email", _data, msg_id, %{transport: :ranch_tcp} = state) do
reply(
:no,
{"c.user.get_token_by_email", "cannot get token over insecure connection"},
msg_id,
state
)
end
defp do_handle("c.user.get_token_by_email", data, msg_id, state) do
case String.split(data, "\t") do
[email, plain_text_password] ->
user = Central.Account.get_user_by_email(email)
response =
if user do
Central.Account.User.verify_password(plain_text_password, user.password)
else
false
end
if response do
token = User.create_token(user)
reply(:user_token, {email, token}, msg_id, state)
else
reply(:no, {"c.user.get_token_by_email", "invalid credentials"}, msg_id, state)
end
_ ->
reply(:no, {"c.user.get_token_by_email", "bad format"}, msg_id, state)
end
end
defp do_handle("c.user.get_token_by_name", _data, msg_id, %{transport: :ranch_tcp} = state) do
reply(
:no,
{"c.user.get_token_by_name", "cannot get token over insecure connection"},
msg_id,
state
)
end
defp do_handle("c.user.get_token_by_name", data, msg_id, state) do
case String.split(data, "\t") do
[name, plain_text_password] ->
user = Central.Account.get_user_by_name(name)
response =
if user do
Central.Account.User.verify_password(plain_text_password, user.password)
else
false
end
if response do
token = User.create_token(user)
reply(:user_token, {name, token}, msg_id, state)
else
reply(:no, {"c.user.get_token_by_name", "invalid credentials"}, msg_id, state)
end
_ ->
reply(:no, {"c.user.get_token_by_name", "bad format"}, msg_id, state)
end
end
defp do_handle("c.user.login", data, msg_id, state) do
# Flags are optional hence the weird case statement
[token, lobby, lobby_hash, _flags] =
case String.split(data, "\t") do
[token, lobby, lobby_hash, flags] -> [token, lobby, lobby_hash, String.split(flags, " ")]
[token, lobby | _] -> [token, lobby, "", ""]
end
# Now try to login using a token
response = User.try_login(token, state.ip, lobby, lobby_hash)
case response do
{:error, "Unverified", userid} ->
reply(:agreement, nil, msg_id, state)
Map.put(state, :unverified_id, userid)
{:ok, user} ->
new_state = SpringOut.do_login_accepted(state, user)
# Do we have a clan?
if user.clan_id do
:timer.sleep(200)
clan = Teiserver.Clans.get_clan!(user.clan_id)
room_name = Room.clan_room_name(clan.tag)
SpringOut.do_join_room(new_state, room_name)
end
new_state
{:error, reason} ->
Logger.debug("[command:login] denied with reason #{reason}")
reply(:denied, reason, msg_id, state)
state
end
end
defp do_handle("LOGIN", data, msg_id, state) do
regex_result =
case Regex.run(~r/^(\S+) (\S+) (0) ([0-9\.\*]+) ([^\t]+)?\t?([^\t]+)?\t?([^\t]+)?/, data) do
nil -> nil
result -> result ++ ["", "", "", "", ""]
end
response =
case regex_result do
[_, username, password, _cpu, _ip, lobby, lobby_hash, _modes | _] ->
username = User.clean_name(username)
User.try_md5_login(username, password, state.ip, lobby, lobby_hash)
nil ->
_no_match(state, "LOGIN", msg_id, data)
{:error, "Invalid details format"}
end
case response do
{:error, "Unverified", userid} ->
reply(:agreement, nil, msg_id, state)
Map.put(state, :unverified_id, userid)
{:ok, user} ->
new_state = SpringOut.do_login_accepted(state, user)
# Do we have a clan?
if user.clan_id do
:timer.sleep(200)
clan = Teiserver.Clans.get_clan!(user.clan_id)
room_name = Room.clan_room_name(clan.tag)
SpringOut.do_join_room(new_state, room_name)
end
new_state
{:error, "Banned" <> _} ->
reply(:denied, "Banned, please see the discord channel #moderation-bot for more details", msg_id, state)
state
{:error, reason} ->
Logger.debug("[command:login] denied with reason #{reason}")
reply(:denied, reason, msg_id, state)
state
end
end
defp do_handle("REGISTER", data, msg_id, state) do
case Regex.run(~r/(\S+) (\S+) (\S+)/, data) do
[_, username, password_hash, email] ->
case User.register_user_with_md5(username, email, password_hash, state.ip) do
:success ->
reply(:registration_accepted, nil, msg_id, state)
{:error, reason} ->
reply(:registration_denied, reason, msg_id, state)
end
_ ->
_no_match(state, "REGISTER", msg_id, data)
end
state
end
defp do_handle("CONFIRMAGREEMENT", code, msg_id, %{unverified_id: userid} = state) do
case User.get_user_by_id(userid) do
nil ->
Logger.error("CONFIRMAGREEMENT - No user found for ID of '#{userid}'")
state
user ->
case code == to_string(user.verification_code) do
true ->
User.verify_user(user)
new_state = SpringOut.do_login_accepted(state, user)
new_state
false ->
reply(:denied, "Incorrect code", msg_id, state)
state
end
end
end
defp do_handle("CONFIRMAGREEMENT", _code, msg_id, state),
do:
reply(:servermsg, "You need to login before you can confirm the agreement.", msg_id, state)
defp do_handle("CREATEBOTACCOUNT", data, msg_id, state) do
case Regex.run(~r/(\S+) (\S+)/, data) do
[_, botname, _owner_name] ->
resp = User.register_bot(botname, state.userid)
case resp do
{:error, _reason} ->
deny(state, msg_id)
_ ->
reply(
:servermsg,
"A new bot account #{botname} has been created, with the same password as #{
state.username
}",
msg_id,
state
)
end
_ ->
_no_match(state, "CREATEBOTACCOUNT", msg_id, data)
end
state
end
defp do_handle("RENAMEACCOUNT", new_name, msg_id, state) do
case User.rename_user(state.userid, new_name) do
:success ->
:ok
{:error, reason} ->
reply(:servermsg, reason, msg_id, state)
end
state
end
defp do_handle("RESETPASSWORDREQUEST", _, msg_id, state) do
host = Application.get_env(:central, CentralWeb.Endpoint)[:url][:host]
url = "https://#{host}/password_reset"
reply(:okay, url, msg_id, state)
end
defp do_handle("CHANGEEMAILREQUEST", new_email, msg_id, state) do
new_user = User.request_email_change(state.user, new_email)
case new_user do
nil ->
reply(:change_email_request_denied, "no user", msg_id, state)
state
_ ->
reply(:change_email_request_accepted, nil, msg_id, state)
%{state | user: new_user}
end
end
defp do_handle("CHANGEEMAIL", data, msg_id, state) do
case Regex.run(~r/(\S+) (\S+)/, data) do
[_, new_email, supplied_code] ->
[correct_code, expected_email] = state.user.email_change_code
cond do
correct_code != supplied_code ->
reply(:change_email_denied, "bad code", msg_id, state)
state
new_email != expected_email ->
reply(:change_email_denied, "bad email", msg_id, state)
state
true ->
new_user = User.change_email(state.user, new_email)
reply(:change_email_accepted, nil, msg_id, state)
%{state | user: new_user}
end
_ ->
_no_match(state, "CHANGEEMAIL", msg_id, data)
end
end
defp do_handle("EXIT", _reason, _msg_id, state) do
Client.disconnect(state.userid, "Spring EXIT command")
send(self(), :terminate)
state
end
defp do_handle("GETUSERINFO", _, msg_id, state) do
ingame_hours = User.rank_time(state.userid)
[
"Registration date: #{date_to_str(state.user.inserted_at, format: :ymd_hms, tz: "UTC")}",
"Email address: #{state.user.email}",
"Ingame time: #{ingame_hours}"
]
|> Enum.each(fn msg ->
reply(:servermsg, msg, msg_id, state)
end)
state
end
defp do_handle("CHANGEPASSWORD", data, msg_id, state) do
case Regex.run(~r/(\S+) (\S+)/, data) do
[_, md5_old_password, md5_new_password] ->
case User.test_password(
md5_old_password,
state.user.password_hash
) do
false ->
reply(:servermsg, "Current password entered incorrectly", msg_id, state)
true ->
encrypted_new_password = User.encrypt_password(md5_new_password)
new_user = %{state.user | password_hash: encrypted_new_password}
User.update_user(new_user, persist: true)
reply(
:servermsg,
"Password changed, you will need to use it next time you login",
msg_id,
state
)
end
_ ->
_no_match(state, "CHANGEPASSWORD", msg_id, data)
end
state
end
# SLDB commands
defp do_handle("GETIP", username, msg_id, state) do
if User.allow?(state.userid, :bot) do
case Client.get_client_by_name(username) do
nil ->
reply(:no, "GETIP", msg_id, state)
client ->
reply(:user_ip, {username, client.ip}, msg_id, state)
end
else
state
end
end
defp do_handle("GETUSERID", data, msg_id, state) do
if User.allow?(state.userid, :bot) do
target = User.get_user_by_name(data)
hash = target.lobby_hash
reply(:user_id, {data, hash, target.springid}, msg_id, state)
else
state
end
end
# Friend list
defp do_handle("FRIENDLIST", _, msg_id, state),
do: reply(:friendlist, state.user, msg_id, state)
defp do_handle("FRIENDREQUESTLIST", _, msg_id, state),
do: reply(:friendlist_request, state.user, msg_id, state)
defp do_handle("UNFRIEND", data, msg_id, state) do
case String.split(data, "=") do
[_, username] ->
new_user = User.remove_friend(state.userid, User.get_userid(username))
%{state | user: new_user}
_ ->
_no_match(state, "UNFRIEND", msg_id, data)
end
end
defp do_handle("ACCEPTFRIENDREQUEST", data, msg_id, state) do
case String.split(data, "=") do
[_, username] ->
new_user = User.accept_friend_request(User.get_userid(username), state.userid)
%{state | user: new_user}
_ ->
_no_match(state, "ACCEPTFRIENDREQUEST", msg_id, data)
end
end
defp do_handle("DECLINEFRIENDREQUEST", data, msg_id, state) do
case String.split(data, "=") do
[_, username] ->
new_user = User.decline_friend_request(User.get_userid(username), state.userid)
%{state | user: new_user}
_ ->
_no_match(state, "DECLINEFRIENDREQUEST", msg_id, data)
end
end
defp do_handle("FRIENDREQUEST", data, msg_id, state) do
case String.split(data, "=") do
[_, username] ->
User.create_friend_request(state.userid, User.get_userid(username))
state
_ ->
_no_match(state, "FRIENDREQUEST", msg_id, data)
end
end
defp do_handle("IGNORE", data, _msg_id, state) do
[_, username] = String.split(data, "=")
User.ignore_user(state.userid, User.get_userid(username))
state
end
defp do_handle("UNIGNORE", data, _msg_id, state) do
[_, username] = String.split(data, "=")
User.unignore_user(state.userid, User.get_userid(username))
state
end
defp do_handle("IGNORELIST", _, msg_id, state),
do: reply(:ignorelist, state.user, msg_id, state)
defp do_handle("c.moderation.report_user", data, msg_id, state) do
case String.split(data, "\t") do
[target_name, location_type, location_id, reason] ->
if String.trim(reason) == "" or String.trim(reason) == "None Given" do
reply(:no, {"c.moderation.report_user", "no reason given"}, msg_id, state)
else
target = User.get_user_by_name(target_name) || %{id: nil}
location_id = if location_id == "nil", do: nil, else: location_id
result = Account.create_report(state.userid, target.id, location_type, location_id, reason)
case result do
{:ok, _} ->
reply(:okay, nil, msg_id, state)
{:error, reason} ->
reply(:no, {"c.moderation.report_user", reason}, msg_id, state)
end
end
_ ->
reply(:no, {"c.moderation.report_user", "bad command format"}, msg_id, state)
end
end
# Chat related
defp do_handle("JOIN", data, msg_id, state) do
regex_result = case Regex.run(~r/(\w+)(?:\t)?(\w+)?/, data) do
[_, room_name] ->
{room_name, ""}
[_, room_name, key] ->
{room_name, key}
_ ->
:nomatch
end
case regex_result do
:nomatch ->
_no_match(state, "JOIN", msg_id, data)
{room_name, _key} ->
case Room.can_join_room?(state.userid, room_name) do
true ->
SpringOut.do_join_room(state, room_name)
{false, reason} ->
reply(:join_failure, {room_name, reason}, msg_id, state)
end
end
if not state.exempt_from_cmd_throttle do
:timer.sleep(Application.get_env(:central, Teiserver)[:spring_post_state_change_delay])
end
state
end
defp do_handle("LEAVE", room_name, msg_id, state) do
PubSub.unsubscribe(Central.PubSub, "room:#{room_name}")
reply(:left_room, {state.username, room_name}, msg_id, state)
Room.remove_user_from_room(state.userid, room_name)
if not state.exempt_from_cmd_throttle do
:timer.sleep(Application.get_env(:central, Teiserver)[:spring_post_state_change_delay])
end
state
end
defp do_handle("CHANNELS", _, msg_id, state) do
reply(:list_channels, nil, msg_id, state)
end
defp do_handle("SAY", data, msg_id, state) do
case Regex.run(~r/(\w+) (.+)/, data) do
[_, room_name, msg] ->
Room.send_message(state.userid, room_name, msg)
_ ->
_no_match(state, "SAY", msg_id, data)
end
state
end
defp do_handle("SAYEX", data, msg_id, state) do
case Regex.run(~r/(\w+) (.+)/, data) do
[_, room_name, msg] ->
Room.send_message_ex(state.userid, room_name, msg)
_ ->
_no_match(state, "SAY", msg_id, data)
end
state
end
# This is meant get a chat history, we currently don't store a chat history
defp do_handle("GETCHANNELMESSAGES", _data, _msg_id, state) do
state
end
defp do_handle("SAYPRIVATE", data, msg_id, state) do
case Regex.run(~r/(\S+) (.+)/, data) do
[_, to_name, msg] ->
to_id = User.get_userid(to_name)
User.send_direct_message(state.userid, to_id, msg)
reply(:sent_direct_message, {to_id, msg}, msg_id, state)
_ ->
_no_match(state, "SAYPRIVATE", msg_id, data)
end
state
end
# Battles
# OPENBATTLE type natType password port maxPlayers gameHash rank mapHash {engineName} {engineVersion} {map} {title} {gameName}
defp do_handle("OPENBATTLE", data, msg_id, state) do
response =
case Regex.run(
~r/^(\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) ([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)\t(.+)$/,
data
) do
[
_,
type,
nattype,
password,
port,
max_players,
game_hash,
_rank,
map_hash,
engine_name,
engine_version,
map_name,
name,
game_name
] ->
nattype =
case nattype do
"0" -> "none"
"1" -> "holepunch"
"2" -> "fixed"
end
client = Client.get_client_by_id(state.userid)
password = if Enum.member?(["empty", "*"], password), do: nil, else: password
battle =
%{
founder_id: state.userid,
founder_name: state.username,
name: name,
type: if(type == "0", do: "normal", else: "replay"),
nattype: nattype,
port: port,
max_players: int_parse(max_players),
game_hash: game_hash,
map_hash: map_hash,
password: password,
rank: 0,
locked: false,
engine_name: engine_name,
engine_version: engine_version,
map_name: map_name,
game_name: game_name,
ip: client.ip
}
|> Lobby.create_battle()
|> Lobby.add_battle()
{:success, battle}
nil ->
_no_match(state, "OPENBATTLE", msg_id, data)
{:failure, "No match"}
end
case response do
{:success, battle} ->
reply(:battle_opened, battle.id, msg_id, state)
reply(:open_battle_success, battle.id, msg_id, state)
PubSub.unsubscribe(Central.PubSub, "legacy_battle_updates:#{battle.id}")
PubSub.subscribe(Central.PubSub, "legacy_battle_updates:#{battle.id}")
reply(:join_battle_success, battle, msg_id, state)
# Send information about the battle to them
reply(:add_script_tags, battle.tags, msg_id, state)
battle.start_rectangles
|> Enum.each(fn {team, r} ->
reply(:add_start_rectangle, {team, r}, msg_id, state)
end)
# They are offered the chance to give a battle status
reply(:request_battle_status, nil, msg_id, state)
# Update the client
Client.join_battle(state.userid, battle.id)
# Update local state to point to this battle and say
# we are the host
%{
state
| lobby_id: battle.id,
lobby_host: true,
known_battles: [battle.id | state.known_battles]
}
{:failure, reason} ->
reply(:open_battle_failure, reason, msg_id, state)
state
end
end
defp do_handle("JOINBATTLE", _data, msg_id, %{user: nil} = state) do
reply(:join_battle_failure, "No user detected", msg_id, state)
end
defp do_handle("JOINBATTLE", data, msg_id, state) do
# Double space is here as the hashcode isn't sent by Chobby
# Skylobby sends an * for empty so need to handle that
data = case Regex.run(~r/^(\S+) \*? (\S+)$/, data) do
[_, lobby_id, script_password] ->
"#{lobby_id} empty #{script_password}"
nil ->
data
end
response =
case Regex.run(~r/^(\S+) (\S+) (\S+)$/, data) do
[_, lobby_id, password, script_password] ->
Lobby.can_join?(state.userid, lobby_id, password, script_password)
nil ->
{:failure, "No match"}
end
if not state.exempt_from_cmd_throttle do
:timer.sleep(Application.get_env(:central, Teiserver)[:spring_post_state_change_delay])
end
case response do
{:waiting_on_host, script_password} ->
%{state | script_password: script_password}
{:failure, "No match"} ->
_no_match(state, "JOINBATTLE", msg_id, data)
{:failure, reason} ->
reply(:join_battle_failure, reason, msg_id, state)
end
end
defp do_handle("JOINBATTLEACCEPT", username, _msg_id, state) do
userid = User.get_userid(username)
Lobby.accept_join_request(userid, state.lobby_id)
state
end
defp do_handle("JOINBATTLEDENY", data, _msg_id, state) do
{username, reason} =
case String.split(data, " ", parts: 2) do
[username, reason] -> {username, reason}
[username] -> {username, "no reason given"}
end
userid = User.get_userid(username)
Lobby.deny_join_request(userid, state.lobby_id, reason)
state
end
defp do_handle("HANDICAP", data, msg_id, state) do
case Regex.run(~r/(\S+) (\d+)/, data) do
[_, username, value] ->
client_id = User.get_userid(username)
value = int_parse(value)
Lobby.force_change_client(state.userid, client_id, %{handicap: value})
_ ->
_no_match(state, "HANDICAP", msg_id, data)
end
state
end
defp do_handle("ADDSTARTRECT", data, msg_id, state) do
case Regex.run(~r/(\d+) (\d+) (\d+) (\d+) (\d+)/, data) do
[_, team, left, top, right, bottom] ->
if Lobby.allow?(state.userid, :addstartrect, state.lobby_id) do
Lobby.add_start_rectangle(state.lobby_id, [team, left, top, right, bottom])
end
_ ->
_no_match(state, "ADDSTARTRECT", msg_id, data)
end
state
end
defp do_handle("REMOVESTARTRECT", team, _msg_id, state) do
if Lobby.allow?(state.userid, :removestartrect, state.lobby_id) do
Lobby.remove_start_rectangle(state.lobby_id, team)
end
state
end
defp do_handle("SETSCRIPTTAGS", data, _msg_id, state) do
if Lobby.allow?(state.userid, :setscripttags, state.lobby_id) do
tags =
data
|> String.split("\t")
|> Enum.filter(fn t ->
flag = String.contains?(t, "=")
if flag != true, do: Logger.error("error in SETSCRIPTTAGS, = not found in tag: #{data}")
flag
end)
|> Map.new(fn t ->
[k, v] = String.split(t, "=")
{String.downcase(k), v}
end)
Lobby.set_script_tags(state.lobby_id, tags)
end
state
end
defp do_handle("REMOVESCRIPTTAGS", data, _msg_id, state) do
if Lobby.allow?(state.userid, :setscripttags, state.lobby_id) do
keys =
data
|> String.downcase()
|> String.split("\t")
Lobby.remove_script_tags(state.lobby_id, keys)
end
state
end
defp do_handle("KICKFROMBATTLE", username, _msg_id, state) do
if Lobby.allow?(state.userid, :kickfrombattle, state.lobby_id) do
userid = User.get_userid(username)
Lobby.kick_user_from_battle(userid, state.lobby_id)
end
state
end
defp do_handle("FORCETEAMNO", data, msg_id, state) do
case Regex.run(~r/(\S+) (\S+)/, data) do
[_, username, team_number] ->
client_id = User.get_userid(username)
value = int_parse(team_number)
Lobby.force_change_client(state.userid, client_id, %{team_number: value})
_ ->
_no_match(state, "FORCETEAMNO", msg_id, data)
end
state
end
defp do_handle("FORCEALLYNO", data, msg_id, state) do
case Regex.run(~r/(\S+) (\S+)/, data) do
[_, username, ally_team_number] ->
client_id = User.get_userid(username)
value = int_parse(ally_team_number)
Lobby.force_change_client(state.userid, client_id, %{ally_team_number: value})
_ ->
_no_match(state, "FORCEALLYNO", msg_id, data)
end
state
end
defp do_handle("FORCETEAMCOLOR", data, msg_id, state) do
case Regex.run(~r/(\S+) (\S+)/, data) do
[_, username, team_colour] ->
client_id = User.get_userid(username)
value = int_parse(team_colour)
Lobby.force_change_client(state.userid, client_id, %{team_colour: value})
_ ->
_no_match(state, "FORCETEAMCOLOR", msg_id, data)
end
state
end
defp do_handle("FORCESPECTATORMODE", username, _msg_id, state) do
client_id = User.get_userid(username)
Lobby.force_change_client(state.userid, client_id, %{player: false})
state
end
defp do_handle("DISABLEUNITS", data, _msg_id, state) do
if Lobby.allow?(state.userid, :disableunits, state.lobby_id) do
units = String.split(data, " ")
Lobby.disable_units(state.lobby_id, units)
end
state
end
defp do_handle("ENABLEUNITS", data, _msg_id, state) do
if Lobby.allow?(state.userid, :enableunits, state.lobby_id) do
units = String.split(data, " ")
Lobby.enable_units(state.lobby_id, units)
end
state
end
defp do_handle("ENABLEALLUNITS", _data, _msg_id, state) do
if Lobby.allow?(state.userid, :enableallunits, state.lobby_id) do
Lobby.enable_all_units(state.lobby_id)
end
state
end
defp do_handle("ADDBOT", data, msg_id, state) do
case Regex.run(~r/(\S+) (\d+) (\d+) (.+)/, data) do
[_, name, battlestatus, team_colour, ai_dll] ->
if Lobby.allow?(state.userid, :add_bot, state.lobby_id) do
bot_data =
Lobby.new_bot(
Map.merge(
%{
name: name,
owner_name: state.username,
owner_id: state.userid,
team_colour: team_colour,
ai_dll: ai_dll
},
Spring.parse_battle_status(battlestatus)
)
)
Lobby.add_bot_to_battle(
state.lobby_id,
bot_data
)
end
_ ->
_no_match(state, "ADDBOT", msg_id, data)
end
state
end
defp do_handle("UPDATEBOT", data, msg_id, state) do
case Regex.run(~r/(\S+) (\S+) (\S+)/, data) do
[_, botname, battlestatus, team_colour] ->
if Lobby.allow?(state.userid, {:update_bot, botname}, state.lobby_id) do
new_bot =
Map.merge(
%{
team_colour: team_colour
},
Spring.parse_battle_status(battlestatus)
)
Lobby.update_bot(state.lobby_id, botname, new_bot)
end
_ ->
_no_match(state, "UPDATEBOT", msg_id, data)
end
state
end
defp do_handle("REMOVEBOT", botname, _msg_id, state) do
if Lobby.allow?(state.userid, {:remove_bot, botname}, state.lobby_id) do
Lobby.remove_bot(state.lobby_id, botname)
end
state
end
defp do_handle("SAYBATTLE", msg, _msg_id, state) do
if Lobby.allow?(state.userid, :saybattle, state.lobby_id) do
Lobby.say(state.userid, msg, state.lobby_id)
end
state
end
defp do_handle("SAYBATTLEEX", msg, _msg_id, state) do
if Lobby.allow?(state.userid, :saybattleex, state.lobby_id) do
Lobby.sayex(state.userid, msg, state.lobby_id)
end
state
end
# SAYBATTLEPRIVATEEX username
defp do_handle("SAYBATTLEPRIVATEEX", data, msg_id, state) do
case Regex.run(~r/(\S+) (.+)/, data) do
[_, to_name, msg] ->
to_id = User.get_userid(to_name)
if Lobby.allow?(state.userid, :saybattleprivateex, state.lobby_id) do
Lobby.sayprivateex(state.userid, to_id, msg, state.lobby_id)
end
_ ->
_no_match(state, "SAYBATTLEPRIVATEEX", msg_id, data)
end
state
end
# https://springrts.com/dl/LobbyProtocol/ProtocolDescription.html#UPDATEBATTLEINFO:client
defp do_handle("UPDATEBATTLEINFO", data, msg_id, state) do
case Regex.run(~r/(\d+) (\d+) (\S+) (.+)$/, data) do
[_, spectator_count, locked, map_hash, map_name] ->
if Lobby.allow?(state.userid, :updatebattleinfo, state.lobby_id) do
battle = Lobby.get_battle(state.lobby_id)
new_battle = %{
battle
| spectator_count: int_parse(spectator_count),
locked: locked == "1",
map_hash: map_hash,
map_name: map_name
}
Lobby.update_battle(
new_battle,
{spectator_count, locked, map_hash, map_name},
:update_battle_info
)
end
_ ->
_no_match(state, "UPDATEBATTLEINFO", msg_id, data)
end
state
end
defp do_handle("LEAVEBATTLE", _, _msg_id, %{lobby_id: nil} = state) do
Lobby.remove_user_from_any_battle(state.userid)
|> Enum.each(fn b ->
PubSub.unsubscribe(Central.PubSub, "legacy_battle_updates:#{b}")
end)
if not state.exempt_from_cmd_throttle do
:timer.sleep(Application.get_env(:central, Teiserver)[:spring_post_state_change_delay])
end
%{state | lobby_host: false}
end
defp do_handle("LEAVEBATTLE", _, _msg_id, state) do
PubSub.unsubscribe(Central.PubSub, "legacy_battle_updates:#{state.lobby_id}")
Lobby.remove_user_from_battle(state.userid, state.lobby_id)
if not state.exempt_from_cmd_throttle do
:timer.sleep(Application.get_env(:central, Teiserver)[:spring_post_state_change_delay])
end
%{state | lobby_host: false}
end
defp do_handle("MYBATTLESTATUS", _, _, %{lobby_id: nil} = state), do: state
defp do_handle("MYBATTLESTATUS", data, msg_id, state) do
case Regex.run(~r/(\S+) (.+)/, data) do
[_, battlestatus, team_colour] ->
updates =
Spring.parse_battle_status(battlestatus)
|> Map.take([:ready, :team_number, :ally_team_number, :player, :sync, :side])
new_client =
(Client.get_client_by_id(state.userid) || %{})
|> Map.merge(updates)
|> Map.put(:team_colour, team_colour)
# This one needs a bit more nuance, for now we'll wrap it in this
# later it's possible we don't want players updating their status
if Lobby.allow?(state.userid, :mybattlestatus, state.lobby_id) do
case Coordinator.attempt_battlestatus_update(new_client, state.lobby_id) do
{true, allowed_client} ->
Client.update(allowed_client, :client_updated_battlestatus)
{false, _} ->
:ok
end
end
_ ->
_no_match(state, "MYBATTLESTATUS", msg_id, data)
end
state
end
# MISC
defp do_handle("PING", _, msg_id, state) do
reply(:pong, nil, msg_id, state)
state
end
defp do_handle("RING", username, _msg_id, state) do
userid = User.get_userid(username)
User.ring(userid, state.userid)
state
end
# Not handled catcher
defp do_handle(cmd, data, msg_id, state) do
_no_match(state, cmd, msg_id, data)
end
@spec _no_match(Map.t(), String.t(), String.t() | nil, Map.t()) :: Map.t()
def _no_match(state, cmd, msg_id, data) do
data =
data
|> String.replace("\t", "\\t")
msg = "No incomming match for #{cmd} with data '#{data}'. Userid #{state.userid}"
Logger.info(msg)
reply(:servermsg, msg, msg_id, state)
state
end
@spec deny(map(), String.t()) :: map()
defp deny(state, msg_id) do
reply(:servermsg, "You do not have permission to execute that command", msg_id, state)
state
end
end
| 29.316352 | 128 | 0.603453 |
73b6c3c47158df5f76b613d92f9265a473400cf9 | 147 | exs | Elixir | test/starling_ex_test.exs | shymega/starling_ex | 3ffbf93d2d1785ed91bd52f2881b5552092399ee | [
"Apache-2.0"
] | 1 | 2022-03-01T16:08:22.000Z | 2022-03-01T16:08:22.000Z | test/starling_ex_test.exs | shymega/starling_ex | 3ffbf93d2d1785ed91bd52f2881b5552092399ee | [
"Apache-2.0"
] | null | null | null | test/starling_ex_test.exs | shymega/starling_ex | 3ffbf93d2d1785ed91bd52f2881b5552092399ee | [
"Apache-2.0"
] | null | null | null | defmodule StarlingExTest do
use ExUnit.Case
doctest StarlingEx
test "greets the world" do
assert StarlingEx.hello() == :world
end
end
| 16.333333 | 39 | 0.727891 |
73b6c3de0f85cc26bb8c419c3126db6eb59236d2 | 1,355 | ex | Elixir | lib/metatags.ex | kidbombay/metatags | 6ac0ff9001b7e97557601132d170a4c9acb96b95 | [
"MIT"
] | 23 | 2018-06-17T18:33:25.000Z | 2022-01-19T17:20:51.000Z | lib/metatags.ex | kidbombay/metatags | 6ac0ff9001b7e97557601132d170a4c9acb96b95 | [
"MIT"
] | 69 | 2018-06-18T12:43:42.000Z | 2022-03-24T04:24:56.000Z | lib/metatags.ex | kidbombay/metatags | 6ac0ff9001b7e97557601132d170a4c9acb96b95 | [
"MIT"
] | 5 | 2019-10-02T08:40:36.000Z | 2021-12-11T14:00:07.000Z | defmodule Metatags do
@moduledoc """
Metatags is used to provide an easy API to print out context-specific
metatags.
"""
alias Metatags.HTML
alias Plug.Conn
@type metatag_value ::
String.t() | [String.t()] | {String.t(), Keyword.t()} | map() | nil
@doc """
Puts a key and a value in the on a %Conn{} struct
example:
```
iex> conn = %Conn{}
iex> Metatags.put(conn, "title", "Welcome!")
%Conn{private: %{metadata: %{"title" => "Welcome!"}}}
```
"""
@spec put(Conn.t(), atom, metatag_value()) :: struct
def put(conn, key, value) when is_atom(key) do
put(conn, Atom.to_string(key), value)
end
@spec put(Conn.t(), String.t(), metatag_value()) :: struct
def put(%Conn{private: %{metatags: metatags}} = conn, key, value) do
{_, metatags} =
Map.get_and_update(metatags, :metatags, fn metadata ->
{metadata, Map.put(metadata, key, value)}
end)
Conn.put_private(conn, :metatags, metatags)
end
@spec put(Conn.t(), String.t(), metatag_value, Keyword.t()) :: struct
def put(conn, key, value, extra_attributes) do
put(conn, key, {value, extra_attributes})
end
@doc """
Turns metadata information into HTML tags
"""
@spec print_tags(Conn.t()) :: Phoenix.HTML.safe()
def print_tags(%Conn{} = conn) do
HTML.from_conn(conn)
end
end
| 26.057692 | 77 | 0.616236 |
73b6dbcc1a7446d1c45138bfe98d4c3092ab4a77 | 2,569 | exs | Elixir | mix.exs | trarbr/nerves_system_rpi3 | a01e792e3c0c865d06e5ae3d3cd0ad98021abc10 | [
"Apache-2.0"
] | null | null | null | mix.exs | trarbr/nerves_system_rpi3 | a01e792e3c0c865d06e5ae3d3cd0ad98021abc10 | [
"Apache-2.0"
] | null | null | null | mix.exs | trarbr/nerves_system_rpi3 | a01e792e3c0c865d06e5ae3d3cd0ad98021abc10 | [
"Apache-2.0"
] | null | null | null | defmodule NervesSystemRpi3.MixProject do
use Mix.Project
@app :nerves_system_rpi3
@version Path.join(__DIR__, "VERSION")
|> File.read!()
|> String.trim()
def project do
[
app: @app,
version: @version,
elixir: "~> 1.6",
compilers: Mix.compilers() ++ [:nerves_package],
nerves_package: nerves_package(),
description: description(),
package: package(),
deps: deps(),
aliases: [loadconfig: [&bootstrap/1], docs: ["docs", ©_images/1]],
docs: [extras: ["README.md"], main: "readme"]
]
end
def application do
[]
end
defp bootstrap(args) do
set_target()
Application.start(:nerves_bootstrap)
Mix.Task.run("loadconfig", args)
end
defp nerves_package do
[
type: :system,
artifact_sites: [
{:github_releases, "nerves-project/#{@app}"}
],
build_runner_opts: build_runner_opts(),
platform: Nerves.System.BR,
platform_config: [
defconfig: "nerves_defconfig"
],
checksum: package_files()
]
end
defp deps do
[
{:nerves, "~> 1.5.0", runtime: false},
{:nerves_system_br, "1.9.5", runtime: false},
{:nerves_toolchain_arm_unknown_linux_gnueabihf, "1.2.0", runtime: false},
{:nerves_system_linter, "~> 0.3.0", runtime: false},
{:ex_doc, "~> 0.18", only: [:dev, :test], runtime: false}
]
end
defp description do
"""
Nerves System - Raspberry Pi 3 B / B+
"""
end
defp package do
[
files: package_files(),
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/nerves-project/#{@app}"}
]
end
defp package_files do
[
"fwup_include",
"rootfs_overlay",
"CHANGELOG.md",
"cmdline.txt",
"config.txt",
"fwup-revert.conf",
"fwup.conf",
"LICENSE",
"linux-4.19.defconfig",
"mix.exs",
"nerves_defconfig",
"post-build.sh",
"post-createfs.sh",
"ramoops.dts",
"README.md",
"VERSION"
]
end
# Copy the images referenced by docs, since ex_doc doesn't do this.
defp copy_images(_) do
File.cp_r("assets", "doc/assets")
end
defp build_runner_opts() do
if primary_site = System.get_env("BR2_PRIMARY_SITE") do
[make_args: ["BR2_PRIMARY_SITE=#{primary_site}"]]
else
[]
end
end
defp set_target() do
if function_exported?(Mix, :target, 1) do
apply(Mix, :target, [:target])
else
System.put_env("MIX_TARGET", "target")
end
end
end
| 22.33913 | 79 | 0.579603 |
73b6e4b66653c06764f733b16db026ed3f7d6301 | 2,045 | ex | Elixir | apps/buzzcms_web/lib/buzzcms_web/schemas/routes.ex | buzzcms/buzzcms | 8ca8e6dea381350f94cc4a666448b5dba6676520 | [
"Apache-2.0"
] | null | null | null | apps/buzzcms_web/lib/buzzcms_web/schemas/routes.ex | buzzcms/buzzcms | 8ca8e6dea381350f94cc4a666448b5dba6676520 | [
"Apache-2.0"
] | 41 | 2020-02-12T07:53:14.000Z | 2020-03-30T02:18:14.000Z | apps/buzzcms_web/lib/buzzcms_web/schemas/routes.ex | buzzcms/buzzcms | 8ca8e6dea381350f94cc4a666448b5dba6676520 | [
"Apache-2.0"
] | null | null | null | defmodule BuzzcmsWeb.Schema.Routes do
use Absinthe.Schema.Notation
use Absinthe.Relay.Schema.Notation, :modern
alias BuzzcmsWeb.RouteResolver
node object(:route) do
field :_id, non_null(:id), resolve: fn %{id: id}, _, _ -> {:ok, id} end
field :name, non_null(:string)
field :pattern, non_null(:string)
field :heading, :heading
field :seo, :seo
field :data, :json
end
input_object :route_filter_input do
field :name, :string_filter_input
end
connection(node_type: :route) do
field :count, non_null(:integer)
edge do
field :node, non_null(:route)
end
end
input_object :route_input do
field :name, :string
field :pattern, :string
field :heading, :heading_input
field :seo, :seo_input
field :data, :json
end
input_object :create_route_data_input do
field :name, non_null(:string)
field :pattern, non_null(:string)
field :heading, :heading_input
field :seo, :seo_input
field :data, :json
end
object :route_queries do
connection field :routes, node_type: :route do
arg(:filter, :route_filter_input)
arg(:order_by, list_of(non_null(:order_by_input)))
resolve(&RouteResolver.list/2)
end
end
object :route_mutations do
payload field :create_route do
input do
field :data, :create_route_data_input
end
output do
field :result, :route_edge
end
resolve(&RouteResolver.create/2)
end
payload field :edit_route do
input do
field :id, non_null(:id)
field :data, :route_input
end
output do
field :result, :route_edge
end
middleware(Absinthe.Relay.Node.ParseIDs, id: :route)
resolve(&RouteResolver.edit/2)
end
payload field :delete_route do
input do
field :id, non_null(:id)
end
output do
field :result, :route_edge
end
middleware(Absinthe.Relay.Node.ParseIDs, id: :route)
resolve(&RouteResolver.delete/2)
end
end
end
| 21.989247 | 75 | 0.6489 |
73b6ed3d646951a67d107b30a32386801a3e5eb5 | 446 | ex | Elixir | lib/elixir_adn/parser/meta_parser.ex | shaunc311/ElixirADN | 9d46329c47695eb04bed02fb9316b2090735141b | [
"0BSD"
] | 6 | 2015-02-08T01:22:31.000Z | 2015-09-24T01:24:18.000Z | lib/elixir_adn/parser/meta_parser.ex | shaunc311/ElixirADN | 9d46329c47695eb04bed02fb9316b2090735141b | [
"0BSD"
] | 23 | 2015-02-08T12:26:01.000Z | 2015-06-02T00:39:15.000Z | lib/elixir_adn/parser/meta_parser.ex | shaunc311/ElixirADN | 9d46329c47695eb04bed02fb9316b2090735141b | [
"0BSD"
] | null | null | null | defmodule ElixirADN.Parser.MetaParser do
@moduledoc ~S"""
Parse any meta data from the data object returned from ADN
"""
@doc ~S"""
Parse the document body for an error message
Examples:
iex> ElixirADN.Parser.MetaParser.parse_error "{\"meta\":{\"error_message\":\"hi\"}}"
"hi"
"""
def parse_error(body) when is_binary(body) do
Poison.decode!(body)
|> Map.get("meta")
|> Map.get("error_message")
end
end | 24.777778 | 88 | 0.652466 |
73b70300c7bc3a0e0c50275090dfbe868e99c59a | 610 | ex | Elixir | lib/discovery/handler/behaviour.ex | nerandell/discovery | 1bd40ad8a366d28e0f5848835135d989fcb49fdb | [
"MIT"
] | 227 | 2015-01-31T02:32:15.000Z | 2021-11-22T11:58:27.000Z | lib/discovery/handler/behaviour.ex | nerandell/discovery | 1bd40ad8a366d28e0f5848835135d989fcb49fdb | [
"MIT"
] | 9 | 2015-03-26T12:28:41.000Z | 2022-01-21T17:00:04.000Z | lib/discovery/handler/behaviour.ex | nerandell/discovery | 1bd40ad8a366d28e0f5848835135d989fcb49fdb | [
"MIT"
] | 20 | 2015-03-26T12:29:23.000Z | 2021-04-06T01:10:46.000Z | #
# The MIT License (MIT)
#
# Copyright (c) 2014-2015 Undead Labs, LLC
#
defmodule Discovery.Handler.Behaviour do
use Behaviour
defmacro __using__(_) do
quote do
@behaviour unquote(__MODULE__)
use GenEvent
#
# GenEvent callbacks
#
def handle_event({:services, services}, state) when is_list(services) do
handle_services(services, state)
end
def handle_event({:services, service}, state) do
handle_services([service], state)
end
end
end
defcallback handle_services(services :: [Discovery.Service.t], state :: term)
end
| 19.677419 | 79 | 0.655738 |
73b70dbfe970f6bfbf79fef040d1ffe2bcf5ef4a | 254 | ex | Elixir | examples/lwm 63 - Application Packaging/package_app/lib/package_app_cli.ex | Maultasche/LwmElixirProjects | 4b962230c9b5b3cf6cc8b34ef2161ca6fde4412c | [
"MIT"
] | 38 | 2018-12-31T10:51:42.000Z | 2022-03-25T18:18:10.000Z | examples/lwm 63 - Application Packaging/package_app/lib/package_app_cli.ex | Maultasche/LwmElixirProjects | 4b962230c9b5b3cf6cc8b34ef2161ca6fde4412c | [
"MIT"
] | null | null | null | examples/lwm 63 - Application Packaging/package_app/lib/package_app_cli.ex | Maultasche/LwmElixirProjects | 4b962230c9b5b3cf6cc8b34ef2161ca6fde4412c | [
"MIT"
] | 6 | 2019-08-19T03:21:36.000Z | 2021-07-16T09:34:49.000Z | defmodule PackageApp.CLI do
def main(argv) do
#Process the command line arguments and then call another method
#that will actually run something
IO.puts "Running PackageApp"
IO.puts "Command line arguments: #{inspect(argv)}"
end
end
| 25.4 | 68 | 0.728346 |
73b70e6c5e26e37f222afab8f6105eee7cefc0b3 | 715 | ex | Elixir | lib/color_wars_web/gettext.ex | kerlak/color_wars_server | a1f069eb110dcae3c519e4b85d64b5d13b9ffc4e | [
"MIT"
] | 1 | 2020-04-21T10:38:14.000Z | 2020-04-21T10:38:14.000Z | lib/color_wars_web/gettext.ex | kerlak/color_wars_server | a1f069eb110dcae3c519e4b85d64b5d13b9ffc4e | [
"MIT"
] | null | null | null | lib/color_wars_web/gettext.ex | kerlak/color_wars_server | a1f069eb110dcae3c519e4b85d64b5d13b9ffc4e | [
"MIT"
] | null | null | null | defmodule ColorWarsWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import ColorWarsWeb.Gettext
# Simple translation
gettext "Here is the string to translate"
# Plural translation
ngettext "Here is the string to translate",
"Here are the strings to translate",
3
# Domain-based translation
dgettext "errors", "Here is the error message to translate"
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :color_wars
end
| 28.6 | 72 | 0.683916 |
73b7231c0737d1a8ed8ff092be6aff7f05274802 | 193 | ex | Elixir | lib/generate/schedule_download_response.ex | smiyabe/cwmp_ex | 9db322497aa3208b5985ccf496ada5286cde3925 | [
"Artistic-2.0"
] | 3 | 2017-11-29T05:07:35.000Z | 2019-12-18T17:16:41.000Z | lib/generate/schedule_download_response.ex | smiyabe/cwmp_ex | 9db322497aa3208b5985ccf496ada5286cde3925 | [
"Artistic-2.0"
] | 1 | 2021-12-02T19:35:28.000Z | 2022-03-29T09:40:52.000Z | lib/generate/schedule_download_response.ex | smiyabe/cwmp_ex | 9db322497aa3208b5985ccf496ada5286cde3925 | [
"Artistic-2.0"
] | 2 | 2017-11-29T05:07:30.000Z | 2020-11-10T07:10:42.000Z | defimpl CWMP.Protocol.Generate, for: CWMP.Protocol.Messages.ScheduleDownloadResponse do
import XmlBuilder
def generate(_req) do
element("cwmp:ScheduleDownloadResponse", nil)
end
end
| 24.125 | 87 | 0.792746 |
73b730d0450193baa0109fcbcd4d910ca1ff32f8 | 718 | exs | Elixir | mix.exs | arghmeleg/algolia-elixir | dd70f242dcf50a1b3142800508b8792ec37b87b0 | [
"Apache-2.0"
] | null | null | null | mix.exs | arghmeleg/algolia-elixir | dd70f242dcf50a1b3142800508b8792ec37b87b0 | [
"Apache-2.0"
] | null | null | null | mix.exs | arghmeleg/algolia-elixir | dd70f242dcf50a1b3142800508b8792ec37b87b0 | [
"Apache-2.0"
] | null | null | null | defmodule Algolia.Mixfile do
use Mix.Project
def project do
[app: :algolia,
version: "0.6.5",
description: "Elixir implementation of Algolia Search API",
elixir: "~> 1.5",
package: package(),
deps: deps()]
end
def package do
[
maintainers: ["Sikan He"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/sikanhe/algolia-elixir"}
]
end
def application do
[applications: [:logger, :hackney]]
end
defp deps do
[{:hackney, "~> 1.9 or ~> 1.10"},
{:poison, "~> 2.2 or ~> 3.0"},
# Docs
{:ex_doc, "~> 0.15", only: :dev},
{:earmark, "~> 1.2", only: :dev},
{:inch_ex, ">= 0.0.0", only: :dev}]
end
end
| 21.117647 | 71 | 0.536212 |
73b7409f9fab8101be3d0d9ff41537c7343087ae | 758 | exs | Elixir | mix.exs | chun37/dqs | 143f8bf87d1b3022f3344ac5023797677f7a44a9 | [
"MIT"
] | 6 | 2021-03-17T13:38:27.000Z | 2021-05-09T04:01:08.000Z | mix.exs | chun37/dqs | 143f8bf87d1b3022f3344ac5023797677f7a44a9 | [
"MIT"
] | 12 | 2021-03-21T14:44:11.000Z | 2021-07-31T09:35:00.000Z | mix.exs | chun37/dqs | 143f8bf87d1b3022f3344ac5023797677f7a44a9 | [
"MIT"
] | 3 | 2021-04-11T11:08:59.000Z | 2021-11-02T15:36:04.000Z | defmodule Dqs.MixProject do
use Mix.Project
def project do
[
app: :dqs,
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, :cachex],
mod: {Dqs.Application, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
{:nostrum, git: "https://github.com/Kraigie/nostrum.git"},
{:ecto_sql, "~> 3.4"},
{:postgrex, ">= 0.0.0"},
{:cachex, "~> 3.3"}
]
end
end
| 22.294118 | 87 | 0.547493 |
73b752c2238443e584f245166db6fcb04f588823 | 532 | ex | Elixir | lib/course_planner_web/views/auth/layout_view.ex | digitalnatives/course_planner | 27b1c8067edc262685e9c4dcbfcf82633bc8b8dc | [
"MIT"
] | 38 | 2017-04-11T13:37:38.000Z | 2021-05-22T19:35:36.000Z | lib/course_planner_web/views/auth/layout_view.ex | digitalnatives/course_planner | 27b1c8067edc262685e9c4dcbfcf82633bc8b8dc | [
"MIT"
] | 226 | 2017-04-07T13:14:14.000Z | 2018-03-08T16:50:11.000Z | lib/course_planner_web/views/auth/layout_view.ex | digitalnatives/course_planner | 27b1c8067edc262685e9c4dcbfcf82633bc8b8dc | [
"MIT"
] | 7 | 2017-08-30T23:58:13.000Z | 2021-03-28T11:50:45.000Z | defmodule CoursePlannerWeb.Auth.LayoutView do
@moduledoc false
use CoursePlannerWeb, :view
def layout_title do
Application.get_env(:course_planner, :auth_email_title)
end
def error_tag(errors, field) when is_list(errors) and is_atom(field) do
case Keyword.fetch(errors, field) do
{:ok, message} ->
field_error_message = "#{humanize(field)} #{translate_error(message)}"
content_tag(:span, field_error_message, class: "login__error")
:error ->
html_escape("")
end
end
end
| 28 | 78 | 0.697368 |
73b7644960629c90f1c339fa93c3834dd67a59d8 | 956 | exs | Elixir | rojak-api/config/config.exs | pyk/rojak | 0dd69efedb58ee5d951e1a43cdfa65b60f8bb7c7 | [
"BSD-3-Clause"
] | 107 | 2016-10-02T05:54:42.000Z | 2021-08-05T00:20:51.000Z | rojak-api/config/config.exs | pyk/rojak | 0dd69efedb58ee5d951e1a43cdfa65b60f8bb7c7 | [
"BSD-3-Clause"
] | 134 | 2016-10-02T21:21:08.000Z | 2016-12-27T02:46:34.000Z | rojak-api/config/config.exs | pyk/rojak | 0dd69efedb58ee5d951e1a43cdfa65b60f8bb7c7 | [
"BSD-3-Clause"
] | 54 | 2016-10-02T08:47:56.000Z | 2020-03-08T00:56:03.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
# General application configuration
config :rojak_api,
namespace: RojakAPI,
ecto_repos: [RojakAPI.Repo]
# Configures the endpoint
config :rojak_api, RojakAPI.Endpoint,
url: [host: "localhost"],
secret_key_base: "B+moan4SjObwgpKmqQ1o8S70mGgoLL5SRE7cskrV7UIfCmTbeZa1cCqWEWxdUhl8",
render_errors: [view: RojakAPI.ErrorView, accepts: ~w(json)],
pubsub: [name: RojakAPI.PubSub,
adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
| 32.965517 | 86 | 0.763598 |
73b7698dc97879e3837fcaec643717c3ef5c6fca | 5,905 | ex | Elixir | lib/plug/adapters/test/conn.ex | jshmrtn/plug | fdfce10e6cf07414e55cb56ff843c45682c85d22 | [
"Apache-2.0"
] | 1 | 2021-02-24T13:06:18.000Z | 2021-02-24T13:06:18.000Z | lib/plug/adapters/test/conn.ex | jshmrtn/plug | fdfce10e6cf07414e55cb56ff843c45682c85d22 | [
"Apache-2.0"
] | null | null | null | lib/plug/adapters/test/conn.ex | jshmrtn/plug | fdfce10e6cf07414e55cb56ff843c45682c85d22 | [
"Apache-2.0"
] | 1 | 2020-11-16T05:08:58.000Z | 2020-11-16T05:08:58.000Z | defmodule Plug.Adapters.Test.Conn do
@behaviour Plug.Conn.Adapter
@moduledoc false
## Test helpers
def conn(conn, method, uri, body_or_params) do
maybe_flush()
uri = URI.parse(uri)
method = method |> to_string |> String.upcase()
query = uri.query || ""
owner = self()
{body, body_params, params, query, req_headers} =
body_or_params(body_or_params, query, conn.req_headers, method)
state = %{
method: method,
params: params,
req_body: body,
chunks: nil,
ref: make_ref(),
owner: owner,
http_protocol: get_from_adapter(conn, :get_http_protocol, :"HTTP/1.1"),
peer_data:
get_from_adapter(conn, :get_peer_data, %{
address: {127, 0, 0, 1},
port: 111_317,
ssl_cert: nil
})
}
%Plug.Conn{
conn
| adapter: {__MODULE__, state},
host: uri.host || conn.host || "www.example.com",
method: method,
owner: owner,
path_info: split_path(uri.path),
port: uri.port || 80,
remote_ip: conn.remote_ip || {127, 0, 0, 1},
req_headers: req_headers,
request_path: uri.path,
query_string: query,
body_params: body_params || %Plug.Conn.Unfetched{aspect: :body_params},
params: params || %Plug.Conn.Unfetched{aspect: :params},
scheme: (uri.scheme || "http") |> String.downcase() |> String.to_atom()
}
end
## Connection adapter
def send_resp(%{method: "HEAD"} = state, status, headers, _body) do
do_send(state, status, headers, "")
end
def send_resp(state, status, headers, body) do
do_send(state, status, headers, IO.iodata_to_binary(body))
end
def send_file(%{method: "HEAD"} = state, status, headers, _path, _offset, _length) do
do_send(state, status, headers, "")
end
def send_file(state, status, headers, path, offset, length) do
%File.Stat{type: :regular, size: size} = File.stat!(path)
length =
cond do
length == :all -> size
is_integer(length) -> length
end
{:ok, data} =
File.open!(path, [:read, :binary], fn device ->
:file.pread(device, offset, length)
end)
do_send(state, status, headers, data)
end
def send_chunked(state, _status, _headers), do: {:ok, "", %{state | chunks: ""}}
def chunk(%{method: "HEAD"} = state, _body), do: {:ok, "", state}
def chunk(%{chunks: chunks} = state, body) do
body = chunks <> IO.iodata_to_binary(body)
{:ok, body, %{state | chunks: body}}
end
defp do_send(%{owner: owner, ref: ref} = state, status, headers, body) do
send(owner, {ref, {status, headers, body}})
{:ok, body, state}
end
def read_req_body(%{req_body: body} = state, opts \\ []) do
size = min(byte_size(body), Keyword.get(opts, :length, 8_000_000))
data = :binary.part(body, 0, size)
rest = :binary.part(body, size, byte_size(body) - size)
tag =
case rest do
"" -> :ok
_ -> :more
end
{tag, data, %{state | req_body: rest}}
end
def inform(%{owner: owner, ref: ref}, status, headers) do
send(owner, {ref, :inform, {status, headers}})
:ok
end
def push(%{owner: owner, ref: ref}, path, headers) do
send(owner, {ref, :push, {path, headers}})
:ok
end
def get_peer_data(payload) do
Map.fetch!(payload, :peer_data)
end
def get_http_protocol(payload) do
Map.fetch!(payload, :http_protocol)
end
## Private helpers
defp get_from_adapter(conn, op, default) do
case conn.adapter do
{Plug.MissingAdapter, _} -> default
{adapter, payload} -> apply(adapter, op, [payload])
end
end
defp body_or_params(nil, query, headers, _method), do: {"", nil, nil, query, headers}
defp body_or_params(body, query, headers, _method) when is_binary(body) do
{body, nil, nil, query, headers}
end
defp body_or_params(params, query, headers, method) when is_list(params) do
body_or_params(Enum.into(params, %{}), query, headers, method)
end
defp body_or_params(params, query, headers, method)
when is_map(params) and method in ["GET", "HEAD"] do
params = stringify_params(params, &to_string/1)
query = Plug.Conn.Query.decode(query)
params = Map.merge(query, params)
query =
params
|> Map.merge(query)
|> Plug.Conn.Query.encode()
{"", nil, params, query, headers}
end
defp body_or_params(params, query, headers, _method) when is_map(params) do
content_type_header = {"content-type", "multipart/mixed; boundary=plug_conn_test"}
content_type = List.keyfind(headers, "content-type", 0, content_type_header)
headers = List.keystore(headers, "content-type", 0, content_type)
body_params = stringify_params(params, & &1)
params = Map.merge(Plug.Conn.Query.decode(query), body_params)
{"--plug_conn_test--", body_params, params, query, headers}
end
defp stringify_params([{_, _} | _] = params, value_fun),
do: Enum.into(params, %{}, &stringify_kv(&1, value_fun))
defp stringify_params([_ | _] = params, value_fun),
do: Enum.map(params, &stringify_params(&1, value_fun))
defp stringify_params(%{__struct__: mod} = struct, _value_fun) when is_atom(mod), do: struct
defp stringify_params(fun, _value_fun) when is_function(fun), do: fun
defp stringify_params(%{} = params, value_fun),
do: Enum.into(params, %{}, &stringify_kv(&1, value_fun))
defp stringify_params(other, value_fun), do: value_fun.(other)
defp stringify_kv({k, v}, value_fun), do: {to_string(k), stringify_params(v, value_fun)}
defp split_path(nil), do: []
defp split_path(path) do
segments = :binary.split(path, "/", [:global])
for segment <- segments, segment != "", do: segment
end
@already_sent {:plug_conn, :sent}
defp maybe_flush() do
receive do
@already_sent -> :ok
after
0 -> :ok
end
end
end
| 28.665049 | 94 | 0.630652 |
73b77a22f8150b651e6d455e99151e997829e137 | 7,563 | exs | Elixir | test/unit/parser/function_header_test.exs | wojtekmach/zigler | b2102744bff212351abfeb4f6d87e57dd1ab232c | [
"MIT"
] | 1 | 2021-02-26T00:00:34.000Z | 2021-02-26T00:00:34.000Z | test/unit/parser/function_header_test.exs | fhunleth/zigler | 037ff05087563d3255f58fb0abbaedeb12b97211 | [
"MIT"
] | null | null | null | test/unit/parser/function_header_test.exs | fhunleth/zigler | 037ff05087563d3255f58fb0abbaedeb12b97211 | [
"MIT"
] | null | null | null | defmodule ZiglerTest.Parser.FunctionHeaderTest do
# these tests make sure that the parser can correctly identify docstrings.
use ExUnit.Case, async: true
alias Zig.Parser
alias Zig.Parser.{Nif, Resource, ResourceCleanup}
@moduletag :parser
@moduletag :function
describe "the argument parser" do
test "correctly parses a basic identifier argument" do
assert {:ok, ["i64"], _, _, _, _} = Parser.parse_argument("foo: i64")
end
test "correctly parses a namespaced identifier argument" do
assert {:ok, ["beam.env"], _, _, _, _} = Parser.parse_argument("foo: beam.env")
end
test "correctly parses an ErlNifEnv identifier argument" do
assert {:ok, ["?*e.ErlNifEnv"], _, _, _, _} = Parser.parse_argument("foo: ?*e.ErlNifEnv")
end
end
describe "the argument list parser" do
test "correctly parses an empty argument list" do
assert {:ok, [], _, _, _, _} = Parser.parse_argument_list("")
end
test "correctly parses a argument list with space" do
assert {:ok, [], _, _, _, _} = Parser.parse_argument_list(" ")
end
test "correctly parses a argument list with a single def" do
assert {:ok, ["i64"], _, _, _, _} = Parser.parse_argument_list("foo: i64")
end
test "correctly parses a argument list with a multiple def" do
assert {:ok, ["i64", "f64"], _, _, _, _} = Parser.parse_argument_list("foo: i64, bar: f64")
end
end
describe "with a preloaded nif struct, the function header parser" do
test "correctly obtains the retval" do
assert {:ok, _, _, context, _, _} = Parser.parse_function_header("""
fn foo() i64 {
""", context: %{local: %Nif{name: :foo, arity: 0}})
assert %Parser{global: [function], local: nil} = context
assert %Nif{name: :foo, arity: 0, retval: "i64"} = function
end
test "correctly obtains zero arguments" do
assert {:ok, _, _, context, _, _} = Parser.parse_function_header("""
fn foo() i64 {
""", context: %{local: %Nif{name: :foo, arity: 0}})
assert %Parser{global: [function], local: nil} = context
assert %Nif{name: :foo, arity: 0, args: []} = function
end
test "correctly obtains one arguments" do
assert {:ok, _, _, context, _, _} = Parser.parse_function_header("""
fn foo(bar: i64) i64 {
""", context: %{local: %Nif{name: :foo, arity: 1}})
assert %Parser{global: [function], local: nil} = context
assert %Nif{name: :foo, arity: 1, args: ["i64"]} = function
end
test "raises compile error if the names mismatch" do
assert_raise SyntaxError, fn -> Parser.parse_function_header("""
fn bar() i64 {
""", context: %{local: %Nif{name: :foo, arity: 0}})
end
end
test "raises compile error if the arities mismatch" do
assert_raise SyntaxError, fn -> Parser.parse_function_header("""
fn foo() i64 {
""", context: %{local: %Nif{name: :foo, arity: 1}})
end
end
test "raises compile error if the arities mismatch, with a beam.env argument" do
assert_raise SyntaxError, fn -> Parser.parse_function_header("""
fn foo(env: beam.env) i64 {
""", context: %{local: %Nif{name: :foo, arity: 1}})
end
end
test "raises compile error if the arities mismatch, with a ErlNifEnv argument" do
assert_raise SyntaxError, fn -> Parser.parse_function_header("""
fn foo(env: ?*e.ErlNifEnv) i64 {
""", context: %{local: %Nif{name: :foo, arity: 1}})
end
end
test "raises compile error on an invalid return type" do
# but not if we don't have preloaded nif value
assert Parser.parse_function_header("""
fn foo() !i64 {
""")
assert_raise SyntaxError, fn -> Parser.parse_function_header("""
fn foo() !i64 {
""", context: %{local: %Nif{name: :foo, arity: 0}})
end
end
test "raises compile error on an invalid argument type" do
# but not if we don't have preloaded nif value
assert Parser.parse_function_header("""
fn foo(bar: strange.type) i64 {
""")
assert_raise SyntaxError, fn ->
Parser.parse_function_header("""
fn foo(bar: strange.type) i64 {
""", context: %{local: %Nif{name: :foo, arity: 1}})
end
end
end
describe "with a preloaded resource cleanup struct, the function header parser" do
test "correctly moves the resource cleanup struct to global context" do
assert {:ok, _, _, context, _, _} = Parser.parse_function_header("""
fn bar(env: beam.env, res: *foo) void {
""", context: %{local: %ResourceCleanup{for: :foo}})
assert %Parser{global: [cleanup], local: nil} = context
assert %ResourceCleanup{for: :foo, name: :bar} = cleanup
end
test "correctly moves the resource cleanup struct to global context when ?*e.ErlNifEnv is used" do
assert {:ok, _, _, context, _, _} = Parser.parse_function_header("""
fn bar(env: ?*e.ErlNifEnv, res: *foo) void {
""", context: %{local: %ResourceCleanup{for: :foo}})
assert %Parser{global: [cleanup], local: nil} = context
assert %ResourceCleanup{for: :foo, name: :bar} = cleanup
end
test "correctly moves the resource cleanup struct to global context even when there's a space in the pointer" do
assert {:ok, _, _, context, _, _} = Parser.parse_function_header("""
fn bar(env: beam.env, res: * foo) void {
""", context: %{local: %ResourceCleanup{for: :foo}})
assert %Parser{global: [cleanup], local: nil} = context
assert %ResourceCleanup{for: :foo, name: :bar} = cleanup
end
test "raises SyntaxError if the arguments don't match beam.env or e.ErlNifEnv" do
assert_raise SyntaxError, fn -> Parser.parse_function_header("""
fn bar(qqq: oddtype, res: *foo) void {
""", context: %{local: %ResourceCleanup{for: :foo}})
end
end
test "raises SyntaxError if the argument type doesn't match the resource type" do
assert_raise SyntaxError, fn -> Parser.parse_function_header("""
fn bar(env: beam.env, res: *bar) void {
""", context: %{local: %ResourceCleanup{for: :foo}})
end
end
test "raises SyntaxError if the argument type is the same as the original type without pointer" do
assert_raise SyntaxError, fn -> Parser.parse_function_header("""
fn bar(env: beam.env, res: bar) void {
""", context: %{local: %ResourceCleanup{for: :foo}})
end
end
test "raises SyntaxError if there are too many arguments" do
assert_raise SyntaxError, fn -> Parser.parse_function_header("""
fn bar(env: beam.env, res: *bar, extra: i64) void {
""", context: %{local: %ResourceCleanup{for: :foo}})
end
end
test "raises SyntaxError if you try to have a non-void retval" do
assert_raise SyntaxError, fn -> Parser.parse_function_header("""
fn bar(env: beam.env, res: *foo) i32 {
""", context: %{local: %ResourceCleanup{for: :foo}})
end
end
test "adds the cleanup struct into the actual resource if the resource definiton already exists" do
assert {:ok, _, _, context, _, _} = Parser.parse_function_header("""
fn bar(env: beam.env, res: *foo) void {
""", context: %{local: %ResourceCleanup{for: :foo}, global: [%Resource{name: :foo}]})
assert %Parser{global: [resource], local: nil} = context
assert %Resource{name: :foo, cleanup: :bar} = resource
end
end
end
| 38.19697 | 116 | 0.625545 |
73b79cd3a5bd3173df6f7162150f0b1306f2c41d | 596 | ex | Elixir | lib/ex_rlp/decode.ex | prihandi/ex_rlp | 064d0608c7fb70ba8605f36540a6dc7942d0e721 | [
"MIT"
] | null | null | null | lib/ex_rlp/decode.ex | prihandi/ex_rlp | 064d0608c7fb70ba8605f36540a6dc7942d0e721 | [
"MIT"
] | null | null | null | lib/ex_rlp/decode.ex | prihandi/ex_rlp | 064d0608c7fb70ba8605f36540a6dc7942d0e721 | [
"MIT"
] | null | null | null | defmodule ExRLP.Decode do
@moduledoc false
alias ExRLP.DecodeItem
@spec decode(binary(), keyword()) :: ExRLP.t()
def decode(""), do: raise(ExRLP.DecodeError)
def decode(item, options \\ []) when is_binary(item) do
item
|> unencode(Keyword.get(options, :encoding, :binary))
|> DecodeItem.decode_item()
end
@spec unencode(binary(), atom()) :: binary()
defp unencode(value, :binary), do: value
defp unencode(value, :hex), do: decode_hex(value)
@spec decode_hex(binary()) :: binary()
defp decode_hex(binary) do
Base.decode16!(binary, case: :lower)
end
end
| 25.913043 | 57 | 0.669463 |
73b7d02b9d90707453bd05ee33b179efc0708e09 | 3,624 | ex | Elixir | lib/ex_hl7/writer.ex | CaptChrisD/ex_hl7 | dc35edebba0c5b657aac31e4d18be7b0451f8ccd | [
"Apache-2.0"
] | 38 | 2015-06-21T17:44:44.000Z | 2021-10-03T08:46:08.000Z | lib/ex_hl7/writer.ex | CaptChrisD/ex_hl7 | dc35edebba0c5b657aac31e4d18be7b0451f8ccd | [
"Apache-2.0"
] | 2 | 2019-08-27T17:27:37.000Z | 2021-02-05T14:27:28.000Z | lib/ex_hl7/writer.ex | CaptChrisD/ex_hl7 | dc35edebba0c5b657aac31e4d18be7b0451f8ccd | [
"Apache-2.0"
] | 14 | 2016-02-04T15:11:55.000Z | 2021-11-13T20:28:19.000Z | defmodule HL7.Writer do
@moduledoc """
Writer for the HL7 protocol that converts a message into its wire format.
"""
defstruct state: :start,
separators: nil,
trim: true,
output_format: :wire,
buffer: [],
segment_builder: nil
alias HL7.{Codec, Segment, Type, Writer}
@type output_format :: :text | :wire
@type option ::
{:output_format, output_format()}
| {:segment_builder, module}
| {:separators, Type.separators()}
| {:trim, boolean}
@opaque state :: :start | :normal | :field_separator | :encoding_chars
@opaque t :: %Writer{
state: state,
separators: tuple,
trim: boolean,
output_format: output_format(),
buffer: iolist,
segment_builder: module
}
@spec new([option]) :: t
def new(options \\ []) do
%Writer{
state: :start,
separators: Keyword.get(options, :separators, Codec.separators()),
trim: Keyword.get(options, :trim, true),
output_format: Keyword.get(options, :output_format, :wire),
buffer: [],
segment_builder: Keyword.get(options, :segment_builder, Segment.Default.Builder)
}
end
@spec buffer(t) :: iodata
def buffer(%Writer{buffer: buffer}), do: Enum.reverse(buffer)
@spec builder(t) :: atom
def builder(%Writer{segment_builder: segment_builder}), do: segment_builder
@spec start_message(t) :: t
def start_message(writer), do: %Writer{writer | state: :normal, buffer: []}
@spec end_message(t) :: t
def end_message(writer), do: %Writer{writer | state: :normal}
@spec start_segment(t, Type.segment_id()) :: t
def start_segment(%Writer{buffer: buffer} = writer, segment_id = "MSH"),
do: %Writer{writer | state: :field_separator, buffer: [segment_id | buffer]}
def start_segment(%Writer{buffer: buffer} = writer, segment_id),
do: %Writer{writer | buffer: [segment_id | buffer]}
@spec end_segment(t, Type.segment_id()) :: t
def end_segment(
%Writer{buffer: buffer, separators: separators, trim: trim} = writer,
_segment_id
) do
eos = if writer.output_format === :text, do: ?\n, else: ?\r
%Writer{writer | buffer: [eos | maybe_trim_buffer(buffer, separators, trim)]}
end
@spec put_field(t, Type.field()) :: t
def put_field(%Writer{state: :normal, buffer: buffer, separators: separators} = writer, field) do
separator = Codec.separator(:field, separators)
buffer =
if field === "" do
# Avoid adding unnecessary empty fields
[separator | buffer]
else
case Codec.encode_field!(field, separators, writer.trim) do
[] -> [separator | buffer]
value -> [value, separator | buffer]
end
end
%Writer{writer | buffer: buffer}
end
def put_field(%Writer{state: :field_separator, buffer: buffer} = writer, <<separator>>) do
%Writer{writer | state: :encoding_chars, buffer: [separator | buffer]}
end
def put_field(%Writer{state: :encoding_chars, buffer: buffer} = writer, field) do
%Writer{writer | state: :normal, buffer: [field | buffer]}
end
defp maybe_trim_buffer(buffer, separators, true), do: trim_buffer(buffer, separators)
defp maybe_trim_buffer(buffer, _separators, false), do: buffer
defp trim_buffer([char | tail] = buffer, separators) when is_integer(char) do
case Codec.match_separator(char, separators) do
{:match, _item_type} -> trim_buffer(tail, separators)
:nomatch -> buffer
end
end
defp trim_buffer(buffer, _separators) do
buffer
end
end
| 32.945455 | 99 | 0.638245 |
73b7ec9f1e3158e89a56f9e5e15d1689b3267e83 | 1,851 | ex | Elixir | lib/daily_meals_web.ex | vinolivae/daily_meals | 8f375cbb7eaf54abfa6b683705bb8075067f9078 | [
"MIT"
] | null | null | null | lib/daily_meals_web.ex | vinolivae/daily_meals | 8f375cbb7eaf54abfa6b683705bb8075067f9078 | [
"MIT"
] | null | null | null | lib/daily_meals_web.ex | vinolivae/daily_meals | 8f375cbb7eaf54abfa6b683705bb8075067f9078 | [
"MIT"
] | null | null | null | defmodule DailyMealsWeb do
@moduledoc """
The entrypoint for defining your web interface, such
as controllers, views, channels and so on.
This can be used in your application as:
use DailyMealsWeb, :controller
use DailyMealsWeb, :view
The definitions below will be executed for every view,
controller, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below. Instead, define any helper function in modules
and import those modules here.
"""
def controller do
quote do
use Phoenix.Controller, namespace: DailyMealsWeb
import Plug.Conn
import DailyMealsWeb.Gettext
alias DailyMealsWeb.Router.Helpers, as: Routes
end
end
def view do
quote do
use Phoenix.View,
root: "lib/daily_meals_web/templates",
namespace: DailyMealsWeb
# Import convenience functions from controllers
import Phoenix.Controller,
only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1]
# Include shared imports and aliases for views
unquote(view_helpers())
end
end
def router do
quote do
use Phoenix.Router
import Plug.Conn
import Phoenix.Controller
end
end
def channel do
quote do
use Phoenix.Channel
import DailyMealsWeb.Gettext
end
end
defp view_helpers do
quote do
# Import basic rendering functionality (render, render_layout, etc)
import Phoenix.View
import DailyMealsWeb.ErrorHelpers
import DailyMealsWeb.Gettext
alias DailyMealsWeb.Router.Helpers, as: Routes
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
| 23.43038 | 76 | 0.694219 |
73b8231c57b477099b5091f5d3243f19673e1586 | 1,108 | exs | Elixir | test/format_test.exs | aleandros/whatsupwith | ccbd70e4dab795a7771ef3ffa66649aa347a23d1 | [
"MIT"
] | null | null | null | test/format_test.exs | aleandros/whatsupwith | ccbd70e4dab795a7771ef3ffa66649aa347a23d1 | [
"MIT"
] | null | null | null | test/format_test.exs | aleandros/whatsupwith | ccbd70e4dab795a7771ef3ffa66649aa347a23d1 | [
"MIT"
] | null | null | null | defmodule FormatTest do
use ExUnit.Case
alias Whatsupwith.{Format, Program}
test "returns and empty string for no program data" do
assert Format.tabular_format([]) == ""
end
test "separates every column by at least one space" do
prog = %Program{name: "a", path: "/bin/a"}
assert Format.tabular_format([prog]) == "a /bin/a"
end
test "rows are separated by new lines" do
progs = [%Program{name: "a", path: "/bin/a"},
%Program{name: "a", path: "/bin/a"}]
expected = """
a /bin/a
a /bin/a
"""
assert prepare(Format.tabular_format(progs)) == expected
end
test "column width is defined by the longest element" do
progs = [%Program{name: "a", path: "/bin/a"},
%Program{name: "a2", path: "/bin/a2"}]
expected = """
a /bin/a
a2 /bin/a2
"""
assert prepare(Format.tabular_format(progs)) == expected
end
defp prepare(txt) do
"#{txt}\n"
|> String.split("\n")
|> Enum.map(&String.trim_trailing/1)
|> Enum.join("\n")
end
end
| 27.02439 | 60 | 0.558664 |
73b8324d465ec5f6faea4e17d6e51f49797e54e2 | 699 | ex | Elixir | lib/exp_web/gettext.ex | karloescota/exp | 77267b80febf6d738b3ac6b6203795feef01e666 | [
"MIT"
] | null | null | null | lib/exp_web/gettext.ex | karloescota/exp | 77267b80febf6d738b3ac6b6203795feef01e666 | [
"MIT"
] | null | null | null | lib/exp_web/gettext.ex | karloescota/exp | 77267b80febf6d738b3ac6b6203795feef01e666 | [
"MIT"
] | null | null | null | defmodule ExpWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import ExpWeb.Gettext
# Simple translation
gettext("Here is the string to translate")
# Plural translation
ngettext("Here is the string to translate",
"Here are the strings to translate",
3)
# Domain-based translation
dgettext("errors", "Here is the error message to translate")
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :exp
end
| 27.96 | 72 | 0.672389 |
73b83ed3c997cf7268a85c41c0f083f80c54ecc2 | 1,561 | ex | Elixir | lib/project1.ex | sanketachari/Bitcoin_Miner | 3dabebad93fd9ca6f2244b0cb6205c220a576e50 | [
"MIT"
] | null | null | null | lib/project1.ex | sanketachari/Bitcoin_Miner | 3dabebad93fd9ca6f2244b0cb6205c220a576e50 | [
"MIT"
] | null | null | null | lib/project1.ex | sanketachari/Bitcoin_Miner | 3dabebad93fd9ca6f2244b0cb6205c220a576e50 | [
"MIT"
] | 1 | 2018-11-18T05:05:57.000Z | 2018-11-18T05:05:57.000Z | defmodule Project1 do
use GenServer
def main(args \\ []) do
leadingZeros = ""
{_, input, _} = OptionParser.parse(args, switches: [])
if length(input) === 1 do
k = List.to_string(input)
if String.contains? k, "." do
IO.puts "This is client. Calling server"
MiningManager.getWork(k)
else
IO.puts "Calling Miners"
{:ok, ifs} = :inet.getif()
ips = Enum.map(ifs, fn {ip, _broadaddr, _mask} -> ip end)
[localIP | ip2] = Enum.map(ips, fn x -> to_string(:inet.ntoa(x)) end)
# Extract ip of local machine
case localIP do
"127.0.0.1" -> localIP = to_string(ip2)
_ ->
end
node = String.to_atom("w213@" <> localIP)
case Node.start(node) do
{:ok, _} -> Node.set_cookie(Node.self, :"foo")
{:error, _} -> IO.puts "Unable to start node locally"
end
leadingZeros = String.duplicate("0", String.to_integer(k))
:ets.new(:user_lookup, [:set, :public, :named_table])
:ets.insert(:user_lookup, {"leadingZeros", leadingZeros})
:ets.insert(:user_lookup, {"server", self()})
:ets.insert(:user_lookup, {"processorCount", System.schedulers_online()})
MiningManager.startMining(leadingZeros)
end
else
IO.puts "Invalid Arguments. Enter valid k"
IO.puts "Use one of the following:"
IO.puts "\t ./project1 {number}"
IO.puts "\t ./project1 {HostName/IP address of the remote master miner}"
end
end
end
| 31.22 | 81 | 0.57271 |
73b844eaf5c254051308e9a9a87a32364fcdfef1 | 179 | exs | Elixir | priv/repo/migrations/20190324155606_add_password_hash_to_users.exs | wvffle/analytics | 2c0fd55bc67f74af1fe1e2641678d44e9fee61d5 | [
"MIT"
] | 984 | 2019-09-02T11:36:41.000Z | 2020-06-08T06:25:48.000Z | priv/repo/migrations/20190324155606_add_password_hash_to_users.exs | wvffle/analytics | 2c0fd55bc67f74af1fe1e2641678d44e9fee61d5 | [
"MIT"
] | 24 | 2019-09-10T09:53:17.000Z | 2020-06-08T07:35:26.000Z | priv/repo/migrations/20190324155606_add_password_hash_to_users.exs | wvffle/analytics | 2c0fd55bc67f74af1fe1e2641678d44e9fee61d5 | [
"MIT"
] | 51 | 2019-09-03T10:48:10.000Z | 2020-06-07T00:23:34.000Z | defmodule Plausible.Repo.Migrations.AddPasswordHashToUsers do
use Ecto.Migration
def change do
alter table(:users) do
add :password_hash, :string
end
end
end
| 17.9 | 61 | 0.731844 |
73b879d8f0a3f1613ad7f21def4c21614c475ac7 | 5,302 | ex | Elixir | lib/google_api/pub_sub/v1/model/policy.ex | balena/elixir-google-api-pubsub | 40a089e324effd7e17dac21279e4dd1bd3f8fe19 | [
"Apache-2.0"
] | null | null | null | lib/google_api/pub_sub/v1/model/policy.ex | balena/elixir-google-api-pubsub | 40a089e324effd7e17dac21279e4dd1bd3f8fe19 | [
"Apache-2.0"
] | null | null | null | lib/google_api/pub_sub/v1/model/policy.ex | balena/elixir-google-api-pubsub | 40a089e324effd7e17dac21279e4dd1bd3f8fe19 | [
"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.PubSub.V1.Model.Policy do
@moduledoc """
Defines an Identity and Access Management (IAM) policy. It is used to
specify access control policies for Cloud Platform resources.
A `Policy` is a collection of `bindings`. A `binding` binds one or more
`members` to a single `role`. Members can be user accounts, service accounts,
Google groups, and domains (such as G Suite). A `role` is a named list of
permissions (defined by IAM or configured by users). A `binding` can
optionally specify a `condition`, which is a logic expression that further
constrains the role binding based on attributes about the request and/or
target resource.
**JSON Example**
{
"bindings": [
{
"role": "roles/resourcemanager.organizationAdmin",
"members": [
"user:[email protected]",
"group:[email protected]",
"domain:google.com",
"serviceAccount:[email protected]"
]
},
{
"role": "roles/resourcemanager.organizationViewer",
"members": ["user:[email protected]"],
"condition": {
"title": "expirable access",
"description": "Does not grant access after Sep 2020",
"expression": "request.time <
timestamp('2020-10-01T00:00:00.000Z')",
}
}
]
}
**YAML Example**
bindings:
- members:
- user:[email protected]
- group:[email protected]
- domain:google.com
- serviceAccount:[email protected]
role: roles/resourcemanager.organizationAdmin
- members:
- user:[email protected]
role: roles/resourcemanager.organizationViewer
condition:
title: expirable access
description: Does not grant access after Sep 2020
expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
For a description of IAM and its features, see the
[IAM developer's guide](https://cloud.google.com/iam/docs).
## Attributes
* `bindings` (*type:* `list(GoogleApi.PubSub.V1.Model.Binding.t)`, *default:* `nil`) - Associates a list of `members` to a `role`. Optionally may specify a
`condition` that determines when binding is in effect.
`bindings` with no members will result in an error.
* `etag` (*type:* `String.t`, *default:* `nil`) - `etag` is used for optimistic concurrency control as a way to help
prevent simultaneous updates of a policy from overwriting each other.
It is strongly suggested that systems make use of the `etag` in the
read-modify-write cycle to perform policy updates in order to avoid race
conditions: An `etag` is returned in the response to `getIamPolicy`, and
systems are expected to put that etag in the request to `setIamPolicy` to
ensure that their change will be applied to the same version of the policy.
If no `etag` is provided in the call to `setIamPolicy`, then the existing
policy is overwritten. Due to blind-set semantics of an etag-less policy,
'setIamPolicy' will not fail even if either of incoming or stored policy
does not meet the version requirements.
* `version` (*type:* `integer()`, *default:* `nil`) - Specifies the format of the policy.
Valid values are 0, 1, and 3. Requests specifying an invalid value will be
rejected.
Operations affecting conditional bindings must specify version 3. This can
be either setting a conditional policy, modifying a conditional binding,
or removing a conditional binding from the stored conditional policy.
Operations on non-conditional policies may specify any valid value or
leave the field unset.
If no etag is provided in the call to `setIamPolicy`, any version
compliance checks on the incoming and/or stored policy is skipped.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:bindings => list(GoogleApi.PubSub.V1.Model.Binding.t()),
:etag => String.t(),
:version => integer()
}
field(:bindings, as: GoogleApi.PubSub.V1.Model.Binding, type: :list)
field(:etag)
field(:version)
end
defimpl Poison.Decoder, for: GoogleApi.PubSub.V1.Model.Policy do
def decode(value, options) do
GoogleApi.PubSub.V1.Model.Policy.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.PubSub.V1.Model.Policy do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.567164 | 159 | 0.675594 |
73b8a595f96d56bfbe2300f2cafda05b1fecf0ee | 8,812 | ex | Elixir | lib/taglet.ex | ringofhealth/ex_tag | a0aa0a3c8f57311867e33d2290a944a46351d0e2 | [
"Apache-2.0"
] | null | null | null | lib/taglet.ex | ringofhealth/ex_tag | a0aa0a3c8f57311867e33d2290a944a46351d0e2 | [
"Apache-2.0"
] | null | null | null | lib/taglet.ex | ringofhealth/ex_tag | a0aa0a3c8f57311867e33d2290a944a46351d0e2 | [
"Apache-2.0"
] | null | null | null | defmodule Taglet do
alias Taglet.{Tagging, Tag, TagletQuery}
import Taglet.RepoClient
@moduledoc """
Documentation for Taglet.
Taglet allows you to manage tags associated to your records.
Please read README.md to get more info about how to use that
package.
"""
@type taggable :: module | struct
@type tags :: String.t() | list
@type tag :: String.t()
@type context :: String.t()
@type tag_list :: list
@type opts :: list
@doc """
Get a persisted struct and inserts a new tag associated to this
struct for a specific context.
You can pass a tag or a list of tags.
In case the tag would be duplicated nothing will happen.
It returns the struct with a new entry for the given context.
"""
@spec add(struct, tags, context, opts) :: struct
def add(struct, tags, context \\ "tags", opts \\ [])
def add(struct, nil, _context, _opts), do: struct
def add(struct, tag, context, opts) when is_bitstring(tag),
do: add(struct, [tag], context, opts)
def add(struct, tags, context, _opts) when is_list(context),
do: add(struct, tags, "tags", context)
def add(struct, tags, context, opts) when is_bitstring(context) do
tag_list = tag_list(struct, context, opts)
new_tags = tags -- tag_list
add_new_tags(struct, context, new_tags, tag_list, opts)
end
defp add_new_tags(struct, context, [], tag_list, _opts), do: put_tags(struct, context, tag_list)
defp add_new_tags(struct, context, new_tags, tag_list, opts) do
taggings =
Enum.map(new_tags, fn tag ->
generate_tagging(struct, tag, context, opts)
end)
repo().insert_all(Tagging, taggings, opts)
put_tags(struct, context, tag_list ++ new_tags)
end
defp generate_tagging(struct, tag, context, opts) do
tag_resource = get_or_create(tag, opts)
%{
taggable_id: struct.id,
taggable_type: struct.__struct__ |> taggable_type,
context: context,
tag_id: tag_resource.id,
inserted_at: NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
}
end
@doc """
Get a persisted struct and removes the tag association for
a specific context.
In case the association doesn't exist nothing will happen.
In the same way that add/3 it returns a struct
"""
@spec remove(struct, tag, context, opts) :: struct
def remove(struct, tag, context \\ "tags", opts \\ [])
def remove(struct, tag, context, opts) when is_list(context),
do: remove(struct, tag, "tags", opts)
def remove(struct, tag, context, opts) do
tag_list = tag_list(struct, context, opts)
case tag in tag_list do
true ->
struct
|> TagletQuery.get_tags_association(get_or_create(tag, opts), context)
|> repo().delete_all(opts)
remove_from_tag_if_unused(tag, opts)
put_tags(struct, context, List.delete(tag_list, tag))
false ->
put_tags(struct, context, tag_list)
end
end
# Remove tag from Tag table if it's unused
defp remove_from_tag_if_unused(nil, _opts), do: nil
defp remove_from_tag_if_unused(tag, opts) do
tag = repo().get_by(Tag, [name: tag], opts)
if tag do
TagletQuery.count_tagging_by_tag_id(tag.id)
|> repo().one(opts)
|> case do
0 -> repo().delete(tag, opts)
_ -> nil
end
end
end
defp get_or_create(tag, opts) do
case repo().get_by(Tag, [name: tag], opts) do
nil -> repo().insert!(%Tag{name: tag}, opts)
tag_resource -> tag_resource
end
end
defp put_tags(struct, context, tags) do
Map.put(struct, String.to_atom(context), tags)
end
@doc """
Rename the tag name by a new one. This actions has effect only
in the context specificied.
If the old_tag does not exist return nil.
"""
@spec rename(struct, tag, tag, context, opts) :: nil | struct
def rename(struct, old_tag_name, new_tag_name, context, opts \\ []) do
case repo().get_by(Tag, [name: old_tag_name], opts) do
nil -> nil
tag -> rename_tag(struct, tag, new_tag_name, context, opts)
end
end
defp rename_tag(struct, old_tag, new_tag_name, context, opts) do
case taggings_by_tag_id(old_tag.id, opts) do
0 ->
# If the old tag is NOT in Tagging we have only to rename its `name`
# in Tag table.
Tag.changeset(old_tag, %{name: new_tag_name})
|> repo().update(opts)
_ ->
# In this case we have to get or create a new Tag, and uptade all relations
# context - taggable_type with the new_tag.id
new_tag = get_or_create(new_tag_name, opts)
TagletQuery.get_tags_association(struct, old_tag, context)
|> repo().update_all([set: [tag_id: new_tag.id]], opts)
if taggings_by_tag_id(old_tag.id, opts) == 0 do
repo().delete(old_tag, opts)
end
end
end
# Return the number of entries in Tagging with the tag_id passed as param.
defp taggings_by_tag_id(tag_id, opts) do
TagletQuery.count_tagging_by_tag_id(tag_id)
|> repo().one(opts)
end
@doc """
It searchs the associated tags for a specific
context.
You can pass as first argument an struct or a module (phoenix model)
- With a struct: it returns the list of tags associated to that struct and context.
- With a module: it returns all the tags associated to one module and context.
"""
@spec tag_list(taggable, context, opts) :: tag_list
def tag_list(taggable, context \\ "tags", opts \\ []) do
taggable
|> tag_list_queryable(context)
|> repo().all(opts)
end
@doc """
It works exactly like tag_list but return a queryable
You can pass as first argument an struct or a module (phoenix model)
- With a struct: it returns the list of tags associated to that struct and context.
- With a module: it returns all the tags associated to one module and context.
"""
@spec tag_list_queryable(taggable, context) :: Ecto.Queryable.t()
def tag_list_queryable(taggable, context \\ "tags")
def tag_list_queryable(struct, context) when is_map(struct) do
id = struct.id
type = struct.__struct__ |> taggable_type
TagletQuery.search_tags(context, type, id)
end
def tag_list_queryable(model, context) do
TagletQuery.search_tags(context, taggable_type(model))
end
@doc """
Given a tag, module and context ('tag' by default), will find
all the module resources associated to the given tag.
You can pass a simple tag or a list of tags.
"""
@spec tagged_with(tags, module, context, opts) :: list
def tagged_with(tags, model, context \\ "tags", opts \\ [])
def tagged_with(tag, model, context, opts) when is_bitstring(tag),
do: tagged_with([tag], model, context, opts)
def tagged_with(tag, model, context, _opts) when is_list(context),
do: tagged_with(tag, model, "tags", context)
def tagged_with(tags, model, context, opts) do
do_tags_search(model, tags, context) |> repo().all(opts)
end
@spec tagged_with_any(tags, module, context, opts) :: list
def tagged_with_any(tags, model, context \\ "tags", opts \\ [])
def tagged_with_any(tag, model, context, opts) when is_bitstring(tag),
do: tagged_with([tag], model, context, opts)
def tagged_with_any(tag, model, context, _opts) when is_list(context),
do: tagged_with_any(tag, model, "tags", context)
def tagged_with_any(tags, model, context, opts) do
do_tags_search_any(model, tags, context) |> repo().all(opts)
end
@doc """
The same than tagged_with/3 but returns the query instead of db results.
The purpose of this function is allow you to include it in your filter flow
or perform actions like paginate the results.
"""
def tagged_with_query(query, tags, context \\ "tags")
def tagged_with_query(query, tag, context) when is_bitstring(tag),
do: tagged_with_query(query, [tag], context)
def tagged_with_query(query, tags, context) do
do_tags_search(query, tags, context)
end
def tagged_with_any_query(query, tags, context \\ "tags")
def tagged_with_any_query(query, tag, context) when is_bitstring(tag),
do: tagged_with_query(query, [tag], context)
def tagged_with_any_query(query, tags, context) do
do_tags_search_any(query, tags, context)
end
defp do_tags_search(queryable, tags, context) do
%Ecto.Query{from: %Ecto.Query.FromExpr{source: {_source, schema}}} =
Ecto.Queryable.to_query(queryable)
queryable
|> TagletQuery.search_tagged_with(tags, context, taggable_type(schema))
end
defp do_tags_search_any(queryable, tags, context) do
%Ecto.Query{from: %Ecto.Query.FromExpr{source: {_source, schema}}} =
Ecto.Queryable.to_query(queryable)
queryable
|> TagletQuery.search_tagged_with_any(tags, context, taggable_type(schema))
end
defp taggable_type(module), do: module |> Module.split() |> List.last()
end
| 30.919298 | 98 | 0.684181 |
73b8d6b7ee3479fde03cee4008f0efb8a1ecbeee | 973 | exs | Elixir | apps/omg_child_chain/test/test_helper.exs | boolafish/elixir-omg | 46b568404972f6e4b4da3195d42d4fb622edb934 | [
"Apache-2.0"
] | null | null | null | apps/omg_child_chain/test/test_helper.exs | boolafish/elixir-omg | 46b568404972f6e4b4da3195d42d4fb622edb934 | [
"Apache-2.0"
] | null | null | null | apps/omg_child_chain/test/test_helper.exs | 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.
ExUnit.configure(exclude: [common: true, integration: true, property: true, wrappers: true])
ExUnitFixtures.start()
# loading all fixture files from the whole umbrella project
ExUnitFixtures.load_fixture_files()
ExUnit.start()
{:ok, _} = Application.ensure_all_started(:briefly)
{:ok, _} = Application.ensure_all_started(:erlexec)
{:ok, _} = Application.ensure_all_started(:fake_server)
| 40.541667 | 92 | 0.769784 |
73b8e121a1be7c6caeee6f47e83bbd99f799a93f | 1,103 | exs | Elixir | apps/wechat_base/test/wechat_base/api/endpoint/body_type/form_test.exs | secretworry/exwechat | 2d3a8bf03135eebd58452122c2f7b3718b5f5b3d | [
"Apache-2.0"
] | null | null | null | apps/wechat_base/test/wechat_base/api/endpoint/body_type/form_test.exs | secretworry/exwechat | 2d3a8bf03135eebd58452122c2f7b3718b5f5b3d | [
"Apache-2.0"
] | null | null | null | apps/wechat_base/test/wechat_base/api/endpoint/body_type/form_test.exs | secretworry/exwechat | 2d3a8bf03135eebd58452122c2f7b3718b5f5b3d | [
"Apache-2.0"
] | null | null | null | defmodule WechatBase.Api.Endpoint.BodyType.FormTest do
use WechatBase.Api.Endpoint.BodyType.Case
alias WechatBase.Api.Endpoint.BodyType.Form
alias Maxwell.Conn
test "should embed a valid body" do
opts = Form.init([
{:string, "string", %{}},
{:integer, "integer", %{}},
{:float, "float", %{}},
{:file, "media", %{}}
])
path = fixture_path("test.txt")
body = %{
"string" => "test",
"integer" => 42,
"float" => 4.2,
"media" => path
}
{:ok, conn} = Form.embed(Conn.new("http://example.com"), body, opts)
assert conn.req_body
== {:multipart,
[{"string", "test"},
{"integer", 42},
{"float", 4.2},
{:file, path,
{"form-data", [{"name", "media"}, {"filename", "test.txt"}]}, []}]}
end
test "should reject a invalid body" do
opts = Form.init([
{:string, "string", %{required?: true}}
])
assert_body_errors Form.embed(Conn.new("http://example.com"), %{}, opts),
[{"string", {"is required", []}}]
end
end | 28.282051 | 81 | 0.511333 |
73b903286af21679c82f10ff96bbfe1682481d09 | 435 | ex | Elixir | lib/rocketpay_web/views/users_view.ex | mCodex/nlw4-elixir | e1e281d1790c4638cec5b6a4380d9bc6b7ef9472 | [
"MIT"
] | null | null | null | lib/rocketpay_web/views/users_view.ex | mCodex/nlw4-elixir | e1e281d1790c4638cec5b6a4380d9bc6b7ef9472 | [
"MIT"
] | null | null | null | lib/rocketpay_web/views/users_view.ex | mCodex/nlw4-elixir | e1e281d1790c4638cec5b6a4380d9bc6b7ef9472 | [
"MIT"
] | null | null | null | defmodule RocketpayWeb.UsersView do
alias Rocketpay.{Account, User}
def render("create.json", %{user: %User{id: id, name: name, nickname: nickname, account: %Account{id: account_id, balance: balance}}}) do
%{
message: "User created",
user: %{
id: id,
name: name,
nickname: nickname,
account: %{
id: account_id,
balance: balance
}
}
}
end
end
| 22.894737 | 139 | 0.558621 |
73b9319250abadd55e8296651f0094d742b121bb | 4,990 | ex | Elixir | lib/surface/catalogue/components/component_api.ex | kevinschweikert/surface_catalogue | 692cd58352e79b4ebe185c8e7f34a0ed354a6762 | [
"MIT"
] | 132 | 2021-02-02T04:03:17.000Z | 2022-03-24T07:02:00.000Z | lib/surface/catalogue/components/component_api.ex | kevinschweikert/surface_catalogue | 692cd58352e79b4ebe185c8e7f34a0ed354a6762 | [
"MIT"
] | 30 | 2021-02-16T13:18:43.000Z | 2022-03-20T20:25:47.000Z | lib/surface/catalogue/components/component_api.ex | kevinschweikert/surface_catalogue | 692cd58352e79b4ebe185c8e7f34a0ed354a6762 | [
"MIT"
] | 17 | 2021-03-20T16:23:13.000Z | 2022-03-15T16:21:08.000Z | defmodule Surface.Catalogue.Components.ComponentAPI do
@moduledoc false
use Surface.Component
alias Surface.Catalogue.Components.Tabs
alias Surface.Catalogue.Components.Tabs.TabItem
alias Surface.Catalogue.Components.Table
alias Surface.Catalogue.Components.Table.Column
alias Surface.Catalogue.Markdown
@doc "The component's module"
prop module, :module, required: true
data has_api?, :boolean
data props, :list
data events, :list
data slots, :list
data functions, :list
def update(assigns) do
%{
props: props,
events: events,
slots: slots,
functions: functions
} = fetch_info(assigns.module)
has_api? = props != [] || events != [] || slots != [] || functions != []
assigns
|> assign(:props, props)
|> assign(:events, events)
|> assign(:slots, slots)
|> assign(:functions, functions)
|> assign(:has_api?, has_api?)
end
def render(assigns) do
assigns = update(assigns)
~F"""
<div class="ComponentAPI">
<div :if={!@has_api?}>No public API defined.</div>
<Tabs id={"component-info-tabs-#{@module}"} :if={@has_api?}>
<TabItem label="Properties" visible={@props != []}>
<Table data={prop <- @props}>
<Column label="Name">
<code>{prop.name}</code>
</Column>
<Column label="Description">
{format_required(prop)} {prop.doc |> format_desc() |> Markdown.to_html(strip: true)}
</Column>
<Column label="Type">
<code>{inspect(prop.type)}</code>
</Column>
<Column label="Values">
{format_values(prop.opts[:values])}
</Column>
<Column label="Default">
{format_default(prop.opts)}
</Column>
</Table>
</TabItem>
<TabItem label="Slots" visible={@slots != []}>
<Table data={slot <- @slots}>
<Column label="Name">
<code>{slot.name}</code>
</Column>
<Column label="Description">
{format_required(slot)} {slot.doc |> format_desc() |> Markdown.to_html(strip: true)}
</Column>
</Table>
</TabItem>
<TabItem label="Events" visible={@events != []}>
<Table data={event <- @events}>
<Column label="Name">
<code>{event.name}</code>
</Column>
<Column label="Description">
{event.doc |> format_desc() |> Markdown.to_html()}
</Column>
</Table>
</TabItem>
<TabItem label="Functions" visible={@functions != []}>
<Table data={func <- @functions}>
<Column label="Name">
<code>{func.signature}</code>
</Column>
<Column label="Description">
{func.doc |> format_desc() |> Markdown.to_html()}
</Column>
</Table>
</TabItem>
</Tabs>
</div>
"""
end
defp format_required(prop) do
if prop.opts[:required] do
{:safe, "<strong>Required</strong>. "}
else
""
end
end
defp format_desc(doc) do
if doc in [nil, ""] do
""
else
doc
|> String.trim()
|> String.trim_trailing(".")
|> Kernel.<>(".")
end
end
defp format_values(values) when values in [nil, []] do
"—"
end
defp format_values(values) do
values
|> Enum.map(fn value -> raw(["<code>", format_value(value), "</code>"]) end)
|> Enum.intersperse(", ")
end
defp format_value(value) when is_binary(value) do
value
end
defp format_value(value) do
inspect(value)
end
defp format_default(opts) do
if Keyword.has_key?(opts, :default) do
raw(["<code>", inspect(opts[:default]), "</code>"])
else
"—"
end
end
defp fetch_info(module) do
functions = fetch_functions(module)
initial = %{
props: [],
events: [],
slots: module.__slots__(),
functions: functions
}
props = Enum.reverse(module.__props__())
Enum.reduce(props, initial, fn
%{type: :event} = prop, acc ->
%{acc | events: [prop | acc.events]}
prop, acc ->
%{acc | props: [prop | acc.props]}
end)
end
defp fetch_functions(module) do
callbacks =
for {:behaviour, [mod]} <- module.module_info()[:attributes],
callback <- mod.behaviour_info(:callbacks) do
callback
end
case Code.fetch_docs(module) do
{:docs_v1, _line, _beam_language, "text/markdown", _moduledoc, _metadata, docs} ->
for {{:function, func, arity}, _line, [sig | _], doc, _} <- docs,
text = extract_doc_text(doc),
{func, arity} not in callbacks do
%{signature: sig, doc: text}
end
_ ->
[]
end
end
defp extract_doc_text(%{"en" => doc}), do: doc
defp extract_doc_text(:none), do: ""
defp extract_doc_text(_), do: nil
end
| 26.402116 | 98 | 0.547094 |
73b93b897341ee67a929471bd1d5052c3578b65f | 2,004 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/service_attachments_scoped_list.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/compute/lib/google_api/compute/v1/model/service_attachments_scoped_list.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/compute/lib/google_api/compute/v1/model/service_attachments_scoped_list.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Compute.V1.Model.ServiceAttachmentsScopedList do
@moduledoc """
## Attributes
* `serviceAttachments` (*type:* `list(GoogleApi.Compute.V1.Model.ServiceAttachment.t)`, *default:* `nil`) - A list of ServiceAttachments contained in this scope.
* `warning` (*type:* `GoogleApi.Compute.V1.Model.ServiceAttachmentsScopedListWarning.t`, *default:* `nil`) - Informational warning which replaces the list of service attachments when the list is empty.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:serviceAttachments => list(GoogleApi.Compute.V1.Model.ServiceAttachment.t()) | nil,
:warning => GoogleApi.Compute.V1.Model.ServiceAttachmentsScopedListWarning.t() | nil
}
field(:serviceAttachments, as: GoogleApi.Compute.V1.Model.ServiceAttachment, type: :list)
field(:warning, as: GoogleApi.Compute.V1.Model.ServiceAttachmentsScopedListWarning)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.ServiceAttachmentsScopedList do
def decode(value, options) do
GoogleApi.Compute.V1.Model.ServiceAttachmentsScopedList.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.ServiceAttachmentsScopedList do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.08 | 205 | 0.759481 |
73b97a30fe2bf3d58fd300c556595762ae565abf | 1,115 | exs | Elixir | config/config.exs | mirego/sigaws | d16d6bc72859ef9664f3892dad001e628e6263e3 | [
"MIT"
] | 8 | 2017-04-18T05:28:21.000Z | 2022-01-20T16:32:35.000Z | config/config.exs | mirego/sigaws | d16d6bc72859ef9664f3892dad001e628e6263e3 | [
"MIT"
] | 11 | 2017-04-09T18:51:33.000Z | 2021-11-11T00:10:17.000Z | config/config.exs | mirego/sigaws | d16d6bc72859ef9664f3892dad001e628e6263e3 | [
"MIT"
] | 14 | 2017-08-06T22:11:46.000Z | 2022-03-17T18:24:49.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 :sigaws, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:sigaws, :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"
| 35.967742 | 73 | 0.750673 |
73b9b5bb26a38b095ec4cae1e3b0bd54ceea998e | 326 | ex | Elixir | lib/graphql/types/role.ex | isshindev/accent | ae4c13139b0a0dfd64ff536b94c940a4e2862150 | [
"BSD-3-Clause"
] | 806 | 2018-04-07T20:40:33.000Z | 2022-03-30T01:39:57.000Z | lib/graphql/types/role.ex | isshindev/accent | ae4c13139b0a0dfd64ff536b94c940a4e2862150 | [
"BSD-3-Clause"
] | 194 | 2018-04-07T13:49:37.000Z | 2022-03-30T19:58:45.000Z | lib/graphql/types/role.ex | doc-ai/accent | e337e16f3658cc0728364f952c0d9c13710ebb06 | [
"BSD-3-Clause"
] | 89 | 2018-04-09T13:55:49.000Z | 2022-03-24T07:09:31.000Z | defmodule Accent.GraphQL.Types.Role do
use Absinthe.Schema.Notation
enum :role do
value(:bot, as: "bot")
value(:owner, as: "owner")
value(:admin, as: "admin")
value(:developer, as: "developer")
value(:reviewer, as: "reviewer")
end
object :role_item do
field(:slug, non_null(:role))
end
end
| 20.375 | 38 | 0.644172 |
73b9bb5a7c040bed7f7dad24ceefa71d594a73c4 | 40,309 | ex | Elixir | clients/composer/lib/google_api/composer/v1beta1/api/projects.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/composer/lib/google_api/composer/v1beta1/api/projects.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/composer/lib/google_api/composer/v1beta1/api/projects.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Composer.V1beta1.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.Composer.V1beta1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Create a new environment.
## Parameters
* `connection` (*type:* `GoogleApi.Composer.V1beta1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The parent must be of the form
"projects/{projectId}/locations/{locationId}".
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.Composer.V1beta1.Model.Environment.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Composer.V1beta1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec composer_projects_locations_environments_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Composer.V1beta1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def composer_projects_locations_environments_create(
connection,
projects_id,
locations_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1beta1/projects/{projectsId}/locations/{locationsId}/environments", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Composer.V1beta1.Model.Operation{}])
end
@doc """
Delete an environment.
## Parameters
* `connection` (*type:* `GoogleApi.Composer.V1beta1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The environment to delete, in the form:
"projects/{projectId}/locations/{locationId}/environments/{environmentId}"
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `environments_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Composer.V1beta1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec composer_projects_locations_environments_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Composer.V1beta1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def composer_projects_locations_environments_delete(
connection,
projects_id,
locations_id,
environments_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1beta1/projects/{projectsId}/locations/{locationsId}/environments/{environmentsId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"environmentsId" => URI.encode(environments_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.Composer.V1beta1.Model.Operation{}])
end
@doc """
Get an existing environment.
## Parameters
* `connection` (*type:* `GoogleApi.Composer.V1beta1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The resource name of the environment to get, in the form:
"projects/{projectId}/locations/{locationId}/environments/{environmentId}"
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `environments_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Composer.V1beta1.Model.Environment{}}` on success
* `{:error, info}` on failure
"""
@spec composer_projects_locations_environments_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Composer.V1beta1.Model.Environment.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def composer_projects_locations_environments_get(
connection,
projects_id,
locations_id,
environments_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1beta1/projects/{projectsId}/locations/{locationsId}/environments/{environmentsId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"environmentsId" => URI.encode(environments_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.Composer.V1beta1.Model.Environment{}])
end
@doc """
List environments.
## Parameters
* `connection` (*type:* `GoogleApi.Composer.V1beta1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. List environments in the given project and location, in the form:
"projects/{projectId}/locations/{locationId}"
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - The maximum number of environments to return.
* `:pageToken` (*type:* `String.t`) - The next_page_token value returned from a previous List request, if any.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Composer.V1beta1.Model.ListEnvironmentsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec composer_projects_locations_environments_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Composer.V1beta1.Model.ListEnvironmentsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def composer_projects_locations_environments_list(
connection,
projects_id,
locations_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1beta1/projects/{projectsId}/locations/{locationsId}/environments", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Composer.V1beta1.Model.ListEnvironmentsResponse{}]
)
end
@doc """
Update an environment.
## Parameters
* `connection` (*type:* `GoogleApi.Composer.V1beta1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The relative resource name of the environment to update, in the form:
"projects/{projectId}/locations/{locationId}/environments/{environmentId}"
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `environments_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:updateMask` (*type:* `String.t`) - Required. A comma-separated list of paths, relative to `Environment`, of
fields to update.
For example, to set the version of scikit-learn to install in the
environment to 0.19.0 and to remove an existing installation of
argparse, the `updateMask` parameter would include the following two
`paths` values: "config.softwareConfig.pypiPackages.scikit-learn" and
"config.softwareConfig.pypiPackages.argparse". The included patch
environment would specify the scikit-learn version as follows:
{
"config":{
"softwareConfig":{
"pypiPackages":{
"scikit-learn":"==0.19.0"
}
}
}
}
Note that in the above example, any existing PyPI packages
other than scikit-learn and argparse will be unaffected.
Only one update type may be included in a single request's `updateMask`.
For example, one cannot update both the PyPI packages and
labels in the same request. However, it is possible to update multiple
members of a map field simultaneously in the same request. For example,
to set the labels "label1" and "label2" while clearing "label3" (assuming
it already exists), one can
provide the paths "labels.label1", "labels.label2", and "labels.label3"
and populate the patch environment as follows:
{
"labels":{
"label1":"new-label1-value"
"label2":"new-label2-value"
}
}
Note that in the above example, any existing labels that are not
included in the `updateMask` will be unaffected.
It is also possible to replace an entire map field by providing the
map field's path in the `updateMask`. The new value of the field will
be that which is provided in the patch environment. For example, to
delete all pre-existing user-specified PyPI packages and
install botocore at version 1.7.14, the `updateMask` would contain
the path "config.softwareConfig.pypiPackages", and
the patch environment would be the following:
{
"config":{
"softwareConfig":{
"pypiPackages":{
"botocore":"==1.7.14"
}
}
}
}
<strong>Note:</strong> Only the following fields can be updated:
<table>
<tbody>
<tr>
<td><strong>Mask</strong></td>
<td><strong>Purpose</strong></td>
</tr>
<tr>
<td>config.softwareConfig.pypiPackages
</td>
<td>Replace all custom custom PyPI packages. If a replacement
package map is not included in `environment`, all custom
PyPI packages are cleared. It is an error to provide both this mask and a
mask specifying an individual package.</td>
</tr>
<tr>
<td>config.softwareConfig.pypiPackages.<var>packagename</var></td>
<td>Update the custom PyPI package <var>packagename</var>,
preserving other packages. To delete the package, include it in
`updateMask`, and omit the mapping for it in
`environment.config.softwareConfig.pypiPackages`. It is an error
to provide both a mask of this form and the
"config.softwareConfig.pypiPackages" mask.</td>
</tr>
<tr>
<td>labels</td>
<td>Replace all environment labels. If a replacement labels map is not
included in `environment`, all labels are cleared. It is an error to
provide both this mask and a mask specifying one or more individual
labels.</td>
</tr>
<tr>
<td>labels.<var>labelName</var></td>
<td>Set the label named <var>labelName</var>, while preserving other
labels. To delete the label, include it in `updateMask` and omit its
mapping in `environment.labels`. It is an error to provide both a
mask of this form and the "labels" mask.</td>
</tr>
<tr>
<td>config.nodeCount</td>
<td>Horizontally scale the number of nodes in the environment. An integer
greater than or equal to 3 must be provided in the `config.nodeCount`
field.
</td>
</tr>
<tr>
<td>config.softwareConfig.airflowConfigOverrides</td>
<td>Replace all Apache Airflow config overrides. If a replacement config
overrides map is not included in `environment`, all config overrides
are cleared.
It is an error to provide both this mask and a mask specifying one or
more individual config overrides.</td>
</tr>
<tr>
<td>config.softwareConfig.airflowConfigOverrides.<var>section</var>-<var>name
</var></td>
<td>Override the Apache Airflow config property <var>name</var> in the
section named <var>section</var>, preserving other properties. To delete
the property override, include it in `updateMask` and omit its mapping
in `environment.config.softwareConfig.airflowConfigOverrides`.
It is an error to provide both a mask of this form and the
"config.softwareConfig.airflowConfigOverrides" mask.</td>
</tr>
<tr>
<td>config.softwareConfig.envVariables</td>
<td>Replace all environment variables. If a replacement environment
variable map is not included in `environment`, all custom environment
variables are cleared.
It is an error to provide both this mask and a mask specifying one or
more individual environment variables.</td>
</tr>
<tr>
<td>config.softwareConfig.imageVersion</td>
<td>Upgrade the version of the environment in-place. Refer to
`SoftwareConfig.image_version` for information on how to format the new
image version. Additionally, the new image version cannot effect a version
downgrade and must match the current image version's Composer major
version and Airflow major and minor versions. Consult the
<a href="/composer/docs/concepts/versioning/composer-versions">Cloud
Composer Version List</a> for valid values.</td>
</tr>
</tbody>
</table>
* `:body` (*type:* `GoogleApi.Composer.V1beta1.Model.Environment.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Composer.V1beta1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec composer_projects_locations_environments_patch(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Composer.V1beta1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def composer_projects_locations_environments_patch(
connection,
projects_id,
locations_id,
environments_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url(
"/v1beta1/projects/{projectsId}/locations/{locationsId}/environments/{environmentsId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"environmentsId" => URI.encode(environments_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.Composer.V1beta1.Model.Operation{}])
end
@doc """
List ImageVersions for provided location.
## Parameters
* `connection` (*type:* `GoogleApi.Composer.V1beta1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. List ImageVersions in the given project and location, in the form:
"projects/{projectId}/locations/{locationId}"
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - The maximum number of image_versions to return.
* `:pageToken` (*type:* `String.t`) - The next_page_token value returned from a previous List request, if any.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Composer.V1beta1.Model.ListImageVersionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec composer_projects_locations_image_versions_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Composer.V1beta1.Model.ListImageVersionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def composer_projects_locations_image_versions_list(
connection,
projects_id,
locations_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1beta1/projects/{projectsId}/locations/{locationsId}/imageVersions", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Composer.V1beta1.Model.ListImageVersionsResponse{}]
)
end
@doc """
Deletes a long-running operation. This method indicates that the client is
no longer interested in the operation result. It does not cancel the
operation. If the server doesn't support this method, it returns
`google.rpc.Code.UNIMPLEMENTED`.
## Parameters
* `connection` (*type:* `GoogleApi.Composer.V1beta1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the operation resource to be deleted.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `operations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Composer.V1beta1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec composer_projects_locations_operations_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Composer.V1beta1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def composer_projects_locations_operations_delete(
connection,
projects_id,
locations_id,
operations_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1beta1/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"operationsId" => URI.encode(operations_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.Composer.V1beta1.Model.Empty{}])
end
@doc """
Gets the latest state of a long-running operation. Clients can use this
method to poll the operation result at intervals as recommended by the API
service.
## Parameters
* `connection` (*type:* `GoogleApi.Composer.V1beta1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the operation resource.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `operations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Composer.V1beta1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec composer_projects_locations_operations_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Composer.V1beta1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def composer_projects_locations_operations_get(
connection,
projects_id,
locations_id,
operations_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1beta1/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"operationsId" => URI.encode(operations_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.Composer.V1beta1.Model.Operation{}])
end
@doc """
Lists operations that match the specified filter in the request. If the
server doesn't support this method, it returns `UNIMPLEMENTED`.
NOTE: the `name` binding allows API services to override the binding
to use different resource name schemes, such as `users/*/operations`. To
override the binding, API services can add a binding such as
`"/v1/{name=users/*}/operations"` to their service configuration.
For backwards compatibility, the default name includes the operations
collection id, however overriding users must ensure the name binding
is the parent resource, without the operations collection id.
## Parameters
* `connection` (*type:* `GoogleApi.Composer.V1beta1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the operation's parent resource.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - The standard list filter.
* `:pageSize` (*type:* `integer()`) - The standard list page size.
* `:pageToken` (*type:* `String.t`) - The standard list page token.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Composer.V1beta1.Model.ListOperationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec composer_projects_locations_operations_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Composer.V1beta1.Model.ListOperationsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def composer_projects_locations_operations_list(
connection,
projects_id,
locations_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1beta1/projects/{projectsId}/locations/{locationsId}/operations", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Composer.V1beta1.Model.ListOperationsResponse{}]
)
end
end
| 44.393172 | 196 | 0.611402 |
73ba0d446b9188bdfafc95d8bef12799087e52db | 182 | ex | Elixir | lib/pdf_party/reader/xref/stream.ex | luisgabrielroldan/pdf_party | f26fd69a05a9050a1a8faaa226c0c3ad5ba1c6db | [
"MIT"
] | 4 | 2018-10-26T02:11:14.000Z | 2019-04-25T20:59:52.000Z | lib/pdf_party/reader/xref/stream.ex | luisgabrielroldan/pdf_party | f26fd69a05a9050a1a8faaa226c0c3ad5ba1c6db | [
"MIT"
] | 1 | 2018-10-26T21:20:40.000Z | 2018-10-26T21:20:40.000Z | lib/pdf_party/reader/xref/stream.ex | luisgabrielroldan/pdf_party | f26fd69a05a9050a1a8faaa226c0c3ad5ba1c6db | [
"MIT"
] | 1 | 2018-10-26T02:11:17.000Z | 2018-10-26T02:11:17.000Z | defmodule PDFParty.Reader.XRef.StreamParser do
@moduledoc """
XRef Stream parser
"""
def parse(_io_device, _stream_offset),
do: {:error, :xref_stream_not_supported}
end
| 20.222222 | 46 | 0.730769 |
73ba871d0b2bed0560af75cf8fd82ecb34548560 | 10,885 | ex | Elixir | apps/admin_api/lib/admin_api/v1/router.ex | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 322 | 2018-02-28T07:38:44.000Z | 2020-05-27T23:09:55.000Z | apps/admin_api/lib/admin_api/v1/router.ex | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 643 | 2018-02-28T12:05:20.000Z | 2020-05-22T08:34:38.000Z | apps/admin_api/lib/admin_api/v1/router.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 AdminAPI.V1.Router do
@moduledoc """
Routes for the Admin API endpoints.
"""
use AdminAPI, :router
alias AdminAPI.V1.AdminAPIAuthPlug
# Pipeline for plugs to apply for all endpoints
pipeline :api do
plug(:accepts, ["json"])
end
# Pipeline for endpoints that require user authentication or provider
# authentication
pipeline :admin_api do
plug(AdminAPIAuthPlug)
end
# Authenticated endpoints
scope "/", AdminAPI.V1 do
pipe_through([:api, :admin_api])
post("/auth_token.switch_account", AdminAuthController, :switch_account)
# Exports
post("/export.all", ExportController, :all)
post("/export.get", ExportController, :get)
post("/export.download", ExportController, :download)
# Exchange pair endpoints
post("/exchange_pair.all", ExchangePairController, :all)
post("/exchange_pair.get", ExchangePairController, :get)
post("/exchange_pair.create", ExchangePairController, :create)
post("/exchange_pair.update", ExchangePairController, :update)
post("/exchange_pair.delete", ExchangePairController, :delete)
# Token endpoints
post("/token.all", TokenController, :all)
post("/token.get", TokenController, :get)
post("/token.create", TokenController, :create)
post("/token.update", TokenController, :update)
post("/token.enable_or_disable", TokenController, :enable_or_disable)
post("/token.stats", TokenController, :stats)
post("/token.get_mints", MintController, :all_for_token)
post("/token.mint", MintController, :mint)
post("/token.upload_avatar", TokenController, :upload_avatar)
# Transaction endpoints
post("/transaction.all", TransactionController, :all)
post("/transaction.export", TransactionController, :export)
post("/transaction.get", TransactionController, :get)
post("/transaction.create", TransactionController, :create)
post("/transaction.calculate", TransactionCalculationController, :calculate)
post("/transaction_request.all", TransactionRequestController, :all)
post("/transaction_request.create", TransactionRequestController, :create)
post("/transaction_request.get", TransactionRequestController, :get)
post("/transaction_request.consume", TransactionConsumptionController, :consume)
post("/transaction_request.cancel", TransactionRequestController, :cancel)
post(
"/transaction_request.get_transaction_consumptions",
TransactionConsumptionController,
:all_for_transaction_request
)
post("/transaction_consumption.all", TransactionConsumptionController, :all)
post("/transaction_consumption.get", TransactionConsumptionController, :get)
post("/transaction_consumption.approve", TransactionConsumptionController, :approve)
post("/transaction_consumption.reject", TransactionConsumptionController, :reject)
post("/transaction_consumption.cancel", TransactionConsumptionController, :cancel)
# Category endpoints
post("/category.all", CategoryController, :all)
post("/category.get", CategoryController, :get)
post("/category.create", CategoryController, :create)
post("/category.update", CategoryController, :update)
post("/category.delete", CategoryController, :delete)
# Account endpoints
post("/account.all", AccountController, :all)
post("/account.get", AccountController, :get)
post("/account.create", AccountController, :create)
post("/account.update", AccountController, :update)
post("/account.upload_avatar", AccountController, :upload_avatar)
post(
"/account.get_wallets_and_user_wallets",
AccountWalletController,
:all_for_account_and_users
)
post("/account.get_wallets", AccountWalletController, :all_for_account)
post("/account.get_users", UserController, :all_for_account)
post("/account.get_descendants", AccountController, :descendants_for_account)
post("/account.get_transactions", TransactionController, :all_for_account)
post("/account.get_transaction_requests", TransactionRequestController, :all_for_account)
post(
"/account.get_transaction_consumptions",
TransactionConsumptionController,
:all_for_account
)
# Account membership endpoints
post("/account.assign_user", AccountMembershipController, :assign_user)
post("/account.unassign_user", AccountMembershipController, :unassign_user)
post("/account.assign_key", AccountMembershipController, :assign_key)
post("/account.unassign_key", AccountMembershipController, :unassign_key)
post(
"/account.get_admin_user_memberships",
AccountMembershipController,
:all_admin_memberships_for_account
)
post(
"/account.get_key_memberships",
AccountMembershipController,
:all_key_memberships_for_account
)
# deprecated
post(
"/account.get_members",
AccountMembershipDeprecatedController,
:all_admin_for_account
)
# User endpoints
post("/user.all", UserController, :all)
post("/user.get", UserController, :get)
post("/user.login", UserAuthController, :login)
post("/user.logout", UserAuthController, :logout)
post("/user.create", UserController, :create)
post("/user.update", UserController, :update)
post("/user.get_wallets", WalletController, :all_for_user)
post("/user.get_transactions", TransactionController, :all_for_user)
post("/user.get_transaction_consumptions", TransactionConsumptionController, :all_for_user)
post("/user.enable_or_disable", UserController, :enable_or_disable)
# Wallet endpoints
post("/wallet.all", WalletController, :all)
post("/wallet.get_balances", BalanceController, :all_for_wallet)
post("/wallet.get", WalletController, :get)
post("/wallet.create", WalletController, :create)
post("/wallet.enable_or_disable", WalletController, :enable_or_disable)
post(
"/wallet.get_transaction_consumptions",
TransactionConsumptionController,
:all_for_wallet
)
# Blockchain wallet endpoints
post("/blockchain_wallet.get_balances", BlockchainWalletController, :all_for_wallet)
post("/blockchain_wallet.get", BlockchainWalletController, :get)
post("/blockchain_wallet.all", BlockchainWalletController, :all)
# Admin endpoints
post("/admin.all", AdminUserController, :all)
post("/admin.get", AdminUserController, :get)
post("/admin.create", AdminUserController, :create)
post("/admin.update", AdminUserController, :update)
post("/admin.enable_or_disable", AdminUserController, :enable_or_disable)
post(
"/admin.get_account_memberships",
AccountMembershipController,
:all_account_memberships_for_admin
)
# Role endpoints
# deprecated
post("/role.all", RoleController, :all)
# deprecated
post("/role.get", RoleController, :get)
# deprecated
post("/role.create", RoleController, :create)
# deprecated
post("/role.update", RoleController, :update)
# deprecated
post("/role.delete", RoleController, :delete)
# Permission endpoints
post("/permission.all", PermissionController, :all)
# API Access endpoints
post("/access_key.all", KeyController, :all)
post("/access_key.get", KeyController, :get)
post("/access_key.create", KeyController, :create)
post("/access_key.enable_or_disable", KeyController, :enable_or_disable)
post("/access_key.delete", KeyController, :delete)
post("/access_key.update", KeyController, :update)
post(
"/access_key.get_account_memberships",
AccountMembershipController,
:all_account_memberships_for_key
)
# API Key endpoints
post("/api_key.all", APIKeyController, :all)
post("/api_key.create", APIKeyController, :create)
post("/api_key.get", APIKeyController, :get)
post("/api_key.enable_or_disable", APIKeyController, :enable_or_disable)
post("/api_key.delete", APIKeyController, :delete)
# Deprecated in PR #535
post("/api_key.update", APIKeyController, :update)
# Settings endpoint
post("/settings.all", SettingsController, :get_settings)
# Configuration endpoint
post("/configuration.all", ConfigurationController, :all)
post("/configuration.update", ConfigurationController, :update)
# Activity logs endpoint
post("/activity_log.all", ActivityLogController, :all)
# 2FA endpoints
post("/me.create_backup_codes", TwoFactorAuthController, :create_backup_codes)
post("/me.create_secret_code", TwoFactorAuthController, :create_secret_code)
post("/me.enable_2fa", TwoFactorAuthController, :enable)
post("/me.disable_2fa", TwoFactorAuthController, :disable)
# Self endpoints (operations on the currently authenticated user)
post("/me.get", SelfController, :get)
post("/me.get_accounts", SelfController, :get_accounts)
post("/me.get_account", SelfController, :get_account)
post("/me.update", SelfController, :update)
post("/me.update_password", SelfController, :update_password)
post("/me.update_email", SelfController, :update_email)
post("/me.upload_avatar", SelfController, :upload_avatar)
post("/me.logout", AdminAuthController, :logout)
# Simulate a server error. Useful for testing the internal server error response
# and error reporting. Locked behind authentication to prevent spamming.
post("/status.server_error", StatusController, :server_error)
end
# Public endpoints and Fallback endpoints.
# Handles all remaining routes
# that are not handled by the scopes above.
scope "/", AdminAPI.V1 do
pipe_through([:api])
post("/admin.login", AdminAuthController, :login)
post("/admin.login_2fa", TwoFactorAuthController, :login)
post("/invite.accept", InviteController, :accept)
# Forget Password endpoints
post("/admin.reset_password", ResetPasswordController, :reset)
post("/admin.update_password", ResetPasswordController, :update)
# Verifying email update request is unauthenticated, because the user
# may be opening and verifying the email from a different device.
post("/admin.verify_email_update", SelfController, :verify_email)
post("/status", StatusController, :index)
match(:*, "/*path", FallbackController, :not_found)
end
end
| 38.736655 | 95 | 0.729995 |
73ba8bf964599487ca98ceb5d47af8f27aeefb80 | 3,031 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/interconnect_diagnostics_link_status.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/interconnect_diagnostics_link_status.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/interconnect_diagnostics_link_status.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Compute.V1.Model.InterconnectDiagnosticsLinkStatus do
@moduledoc """
## Attributes
- arpCaches ([InterconnectDiagnosticsArpEntry]): A list of InterconnectDiagnostics.ARPEntry objects, describing the ARP neighbor entries seen on this link. This will be empty if the link is bundled Defaults to: `null`.
- circuitId (String.t): The unique ID for this link assigned during turn up by Google. Defaults to: `null`.
- googleDemarc (String.t): The Demarc address assigned by Google and provided in the LoA. Defaults to: `null`.
- lacpStatus (InterconnectDiagnosticsLinkLacpStatus): Defaults to: `null`.
- receivingOpticalPower (InterconnectDiagnosticsLinkOpticalPower): Defaults to: `null`.
- transmittingOpticalPower (InterconnectDiagnosticsLinkOpticalPower): Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:arpCaches => list(GoogleApi.Compute.V1.Model.InterconnectDiagnosticsArpEntry.t()),
:circuitId => any(),
:googleDemarc => any(),
:lacpStatus => GoogleApi.Compute.V1.Model.InterconnectDiagnosticsLinkLacpStatus.t(),
:receivingOpticalPower =>
GoogleApi.Compute.V1.Model.InterconnectDiagnosticsLinkOpticalPower.t(),
:transmittingOpticalPower =>
GoogleApi.Compute.V1.Model.InterconnectDiagnosticsLinkOpticalPower.t()
}
field(:arpCaches, as: GoogleApi.Compute.V1.Model.InterconnectDiagnosticsArpEntry, type: :list)
field(:circuitId)
field(:googleDemarc)
field(:lacpStatus, as: GoogleApi.Compute.V1.Model.InterconnectDiagnosticsLinkLacpStatus)
field(
:receivingOpticalPower,
as: GoogleApi.Compute.V1.Model.InterconnectDiagnosticsLinkOpticalPower
)
field(
:transmittingOpticalPower,
as: GoogleApi.Compute.V1.Model.InterconnectDiagnosticsLinkOpticalPower
)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.InterconnectDiagnosticsLinkStatus do
def decode(value, options) do
GoogleApi.Compute.V1.Model.InterconnectDiagnosticsLinkStatus.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.InterconnectDiagnosticsLinkStatus do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.520548 | 220 | 0.758825 |
73ba8e643d54e212b71bb0e5160189716e550b6b | 651 | ex | Elixir | lib/bankapi_web/views/client_view.ex | t00lmaker/elixir-bank | 41897d8fa87bb2fedbe3ef6f8f5cd78b756e24f0 | [
"MIT"
] | 4 | 2020-05-05T18:37:28.000Z | 2022-01-05T00:56:19.000Z | lib/bankapi_web/views/client_view.ex | t00lmaker/elixir-bank | 41897d8fa87bb2fedbe3ef6f8f5cd78b756e24f0 | [
"MIT"
] | 21 | 2019-12-01T15:32:02.000Z | 2019-12-19T13:10:36.000Z | lib/bankapi_web/views/client_view.ex | t00lmaker/elixir-bank | 41897d8fa87bb2fedbe3ef6f8f5cd78b756e24f0 | [
"MIT"
] | 2 | 2020-09-12T16:07:11.000Z | 2020-12-11T06:46:45.000Z | defmodule BankWeb.ClientView do
use BankWeb, :view
alias BankWeb.ClientView
alias BankWeb.UserView
def render("index.json", %{clients: clients}) do
%{data: render_many(clients, ClientView, "client.json")}
end
def render("show.json", %{client: client}) do
%{data: render_one(client, ClientView, "client.json")}
end
def render("client.json", %{client: client}) do
%{
id: client.id,
name: client.name,
social_id: client.social_id,
birth_date: client.birth_date,
is_active: client.is_active,
email: client.email,
user: render_one(client.user, UserView, "user.json")
}
end
end
| 25.038462 | 60 | 0.660522 |
73baab291f79a9eaad5f7f6015be89ef7822ec6e | 312 | exs | Elixir | config/test.exs | crosscloudci/ci_status_repository | 335e8b89bbf59e6cf63e49541ce3ea6b60167e52 | [
"Apache-2.0"
] | 2 | 2019-03-05T16:29:10.000Z | 2020-01-17T14:11:48.000Z | config/test.exs | crosscloudci/ci_status_repository | 335e8b89bbf59e6cf63e49541ce3ea6b60167e52 | [
"Apache-2.0"
] | 3 | 2019-03-18T20:26:48.000Z | 2020-06-25T14:31:13.000Z | config/test.exs | crosscloudci/ci_status_repository | 335e8b89bbf59e6cf63e49541ce3ea6b60167e52 | [
"Apache-2.0"
] | 1 | 2018-06-16T15:32:25.000Z | 2018-06-16T15:32:25.000Z | use Mix.Config
import_config "test.secret.exs"
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :cncf_dashboard_api, CncfDashboardApi.Endpoint,
http: [port: 4001],
server: false
# Print only warnings and errors during test
config :logger, level: :info
| 24 | 56 | 0.766026 |
73babc97abb42161283247631a203ef4e82ebbaa | 1,670 | ex | Elixir | debian/manpage.1.ex | alibenD/design_pattern_example_code | f78b2c2ac2ff3ce73cd404ea0e16d345d17b217f | [
"MIT"
] | null | null | null | debian/manpage.1.ex | alibenD/design_pattern_example_code | f78b2c2ac2ff3ce73cd404ea0e16d345d17b217f | [
"MIT"
] | null | null | null | debian/manpage.1.ex | alibenD/design_pattern_example_code | f78b2c2ac2ff3ce73cd404ea0e16d345d17b217f | [
"MIT"
] | null | null | null | .\" Hey, EMACS: -*- nroff -*-
.\" (C) Copyright 2020 Aliben <[email protected]>,
.\"
.\" First parameter, NAME, should be all caps
.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
.\" other parameters are allowed: see man(7), man(1)
.TH Design-pattern SECTION "February 7 2020"
.\" Please adjust this date whenever revising the manpage.
.\"
.\" Some roff macros, for reference:
.\" .nh disable hyphenation
.\" .hy enable hyphenation
.\" .ad l left justify
.\" .ad b justify to both left and right margins
.\" .nf disable filling
.\" .fi enable filling
.\" .br insert line break
.\" .sp <n> insert n+1 empty lines
.\" for manpage-specific macros, see man(7)
.SH NAME
design-pattern \- program to do something
.SH SYNOPSIS
.B design-pattern
.RI [ options ] " files" ...
.br
.B bar
.RI [ options ] " files" ...
.SH DESCRIPTION
This manual page documents briefly the
.B design-pattern
and
.B bar
commands.
.PP
.\" TeX users may be more comfortable with the \fB<whatever>\fP and
.\" \fI<whatever>\fP escape sequences to invode bold face and italics,
.\" respectively.
\fBdesign-pattern\fP is a program that...
.SH OPTIONS
These programs follow the usual GNU command line syntax, with long
options starting with two dashes (`-').
A summary of options is included below.
For a complete description, see the Info files.
.TP
.B \-h, \-\-help
Show summary of options.
.TP
.B \-v, \-\-version
Show version of program.
.SH SEE ALSO
.BR bar (1),
.BR baz (1).
.br
The programs are documented fully by
.IR "The Rise and Fall of a Fooish Bar" ,
available via the Info system.
| 29.298246 | 70 | 0.667066 |
73babcfef1de55ba9b8e27be9ef707dcf79d5b2b | 1,015 | ex | Elixir | clients/digital_asset_links/lib/google_api/digital_asset_links/v1/connection.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/digital_asset_links/lib/google_api/digital_asset_links/v1/connection.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/digital_asset_links/lib/google_api/digital_asset_links/v1/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.DigitalAssetLinks.V1.Connection do
@moduledoc """
Handle Tesla connections for GoogleApi.DigitalAssetLinks.V1.
"""
@type t :: Tesla.Env.client()
use GoogleApi.Gax.Connection,
scopes: [],
otp_app: :google_api_digital_asset_links,
base_url: "https://digitalassetlinks.googleapis.com/"
end
| 33.833333 | 74 | 0.753695 |
73bae7aabf60489d4b0eed9a22bfa55533d471d2 | 837 | ex | Elixir | lib/policr_mini/ecto_enums.ex | uxh/policr-mini | bad33834a9bd6405afb241b74000cec2cb78ef21 | [
"MIT"
] | 487 | 2020-06-08T03:04:21.000Z | 2022-03-31T14:51:36.000Z | lib/policr_mini/ecto_enums.ex | uxh/policr-mini | bad33834a9bd6405afb241b74000cec2cb78ef21 | [
"MIT"
] | 141 | 2020-06-11T01:03:29.000Z | 2022-03-30T20:23:32.000Z | lib/policr_mini/ecto_enums.ex | uxh/policr-mini | bad33834a9bd6405afb241b74000cec2cb78ef21 | [
"MIT"
] | 61 | 2020-06-10T05:25:03.000Z | 2022-03-23T15:54:26.000Z | defmodule PolicrMini.EctoEnums do
@moduledoc """
枚举类型定义。
"""
import EctoEnum
defenum ChatType,
private: "private",
group: "group",
supergroup: "supergroup",
channel: "channel"
defenum VerificationModeEnum, image: 0, custom: 1, arithmetic: 2, initiative: 3
defenum VerificationStatusEnum, waiting: 0, passed: 1, timeout: 2, wronged: 3, expired: 4
defenum VerificationEntranceEnum, unity: 0, independent: 1
defenum VerificationOccasionEnum, private: 0, public: 1
defenum KillingMethodEnum, ban: 0, kick: 1
defenum OperationActionEnum, kick: 0, ban: 1
defenum OperationRoleEnum, system: 0, admin: 1
defenum StatVerificationStatus, passed: 0, timeout: 1, wronged: 2, other: 3
defenum MentionText, user_id: 0, full_name: 1, mosaic_full_name: 2
defenum ServiceMessage, joined: 0, lefted: 1
end
| 33.48 | 91 | 0.729988 |
73bb1ab668756f521eb89f585f508fda055fe58a | 1,939 | ex | Elixir | lib/aql/update.ex | elbow-jason/durango | a31b5636789ef275f19963343eda03d10ebc3ca0 | [
"MIT"
] | 7 | 2018-03-04T14:33:46.000Z | 2020-10-26T17:32:23.000Z | lib/aql/update.ex | elbow-jason/durango | a31b5636789ef275f19963343eda03d10ebc3ca0 | [
"MIT"
] | 5 | 2018-08-01T07:29:02.000Z | 2018-12-31T12:59:16.000Z | lib/aql/update.ex | elbow-jason/durango | a31b5636789ef275f19963343eda03d10ebc3ca0 | [
"MIT"
] | null | null | null | defmodule Durango.AQL.Update do
alias Durango.Query
defmacro inject_parser() do
quote do
alias Durango.Query
alias Durango.Dsl
@in_keys [:in, :into]
def parse_query(%Query{} = q, [{:update, update_expr}, {:with, with_expr}, {in_key, in_expr} | rest ]) when in_key in @in_keys do
in_token = case in_key do
:in -> "IN"
:into -> "INTO"
end
q
|> Query.put_local_var(:OLD)
|> Query.put_local_var(:NEW)
|> Query.append_tokens("UPDATE")
|> Dsl.parse_expr(update_expr)
|> Query.append_tokens("WITH")
|> Dsl.parse_expr(with_expr)
|> Query.append_tokens(in_token)
|> Dsl.parse_collection_name(in_expr)
|> Dsl.parse_query(rest)
end
def parse_query(%Query{} = q, [{:update, update_expr}, {:with, with_expr} | rest ]) do
q
|> Query.put_local_var(:OLD)
|> Query.put_local_var(:NEW)
|> Query.append_tokens("UPDATE")
|> Dsl.parse_expr(update_expr)
|> Query.append_tokens("WITH")
|> Dsl.parse_expr(with_expr)
|> Dsl.parse_query(rest)
end
def parse_query(%Query{} = q, [{:update, {:in, _, [update_expr, in_expr]}} | rest ]) do
q
|> Query.put_local_var(:OLD)
|> Query.put_local_var(:NEW)
|> Query.append_tokens("UPDATE")
|> Dsl.parse_expr(update_expr)
|> Query.append_tokens("IN")
|> Dsl.parse_collection_name(in_expr)
|> Dsl.parse_query(rest)
end
def parse_query(%Query{} = q, [{:update, update_expr}, {:in, in_expr} | rest]) do
q
|> Query.put_local_var(:OLD)
|> Query.put_local_var(:NEW)
|> Query.append_tokens("UPDATE")
|> Dsl.parse_expr(update_expr)
|> Query.append_tokens("IN")
|> Dsl.parse_collection_name(in_expr)
|> Dsl.parse_query(rest)
end
end
end
end
| 30.777778 | 135 | 0.570913 |
73bb44f8a5a37d0d0205b6b29133d353401ed565 | 597 | exs | Elixir | elixir/elixir-sips/samples/digraph_maps/mix.exs | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | 2 | 2015-12-09T02:16:51.000Z | 2021-07-26T22:53:43.000Z | elixir/elixir-sips/samples/digraph_maps/mix.exs | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | null | null | null | elixir/elixir-sips/samples/digraph_maps/mix.exs | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | 1 | 2016-05-08T18:40:31.000Z | 2016-05-08T18:40:31.000Z | defmodule DigraphMaps.Mixfile do
use Mix.Project
def project do
[app: :digraph_maps,
version: "0.0.1",
elixir: "~> 1.0",
deps: deps]
end
# Configuration for the OTP application
#
# Type `mix help compile.app` for more information
def application do
[applications: [:logger]]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# Type `mix help deps` for more examples and options
defp deps do
[]
end
end
| 19.258065 | 77 | 0.613065 |
73bb4aa52de0167caa73ca97e023e9f5fd827208 | 2,072 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/order_documents_list_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/order_documents_list_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/order_documents_list_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.DFAReporting.V33.Model.OrderDocumentsListResponse do
@moduledoc """
Order document List Response
## Attributes
* `kind` (*type:* `String.t`, *default:* `dfareporting#orderDocumentsListResponse`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#orderDocumentsListResponse".
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Pagination token to be used for the next list operation.
* `orderDocuments` (*type:* `list(GoogleApi.DFAReporting.V33.Model.OrderDocument.t)`, *default:* `nil`) - Order document collection
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => String.t(),
:nextPageToken => String.t(),
:orderDocuments => list(GoogleApi.DFAReporting.V33.Model.OrderDocument.t())
}
field(:kind)
field(:nextPageToken)
field(:orderDocuments, as: GoogleApi.DFAReporting.V33.Model.OrderDocument, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.OrderDocumentsListResponse do
def decode(value, options) do
GoogleApi.DFAReporting.V33.Model.OrderDocumentsListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.OrderDocumentsListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.09434 | 198 | 0.742761 |
73bb5bf07226b0c725e40c440c5a10da321d9f50 | 2,422 | exs | Elixir | test/absinthe/phase/document/validation/variables_of_correct_type_test.exs | podium/absinthe | 7d14fab0282a3987e124f4d5dc3009bc94eb884c | [
"MIT"
] | null | null | null | test/absinthe/phase/document/validation/variables_of_correct_type_test.exs | podium/absinthe | 7d14fab0282a3987e124f4d5dc3009bc94eb884c | [
"MIT"
] | null | null | null | test/absinthe/phase/document/validation/variables_of_correct_type_test.exs | podium/absinthe | 7d14fab0282a3987e124f4d5dc3009bc94eb884c | [
"MIT"
] | null | null | null | defmodule Absinthe.Phase.Document.Validation.VariablesOfCorrectTypeTest do
@phase Absinthe.Phase.Document.Arguments.VariableTypesMatch
import ExUnit.CaptureLog
use Absinthe.ValidationPhaseCase, async: true, phase: @phase
test "types of variables does not match types of arguments" do
fun = fn ->
Absinthe.run(
"""
query test($intArg: Int!) {
complicatedArgs {
stringArgField(stringArg: $intArg)
}
}
""",
Absinthe.Fixtures.PetsSchema,
variables: %{"intArg" => 5}
)
end
assert capture_log([level: :warn], fun) =~
"In operation `test, variable `$intArg` of type `Int` found as input to argument of type `String`."
end
test "variable type check handles non existent type" do
{:ok, %{errors: errors}} =
Absinthe.run(
"""
query test($intArg: DoesNotExist!) {
complicatedArgs {
stringArgField(stringArg: $intArg)
}
}
""",
Absinthe.Fixtures.PetsSchema,
variables: %{"intArg" => 5}
)
expected_error_msg = "Argument \"stringArg\" has invalid value $intArg."
assert expected_error_msg in (errors |> Enum.map(& &1.message))
end
test "types of variables does not match types of arguments even when the value is null" do
fun = fn ->
Absinthe.run(
"""
query test($intArg: Int) {
complicatedArgs {
stringArgField(stringArg: $intArg)
}
}
""",
Absinthe.Fixtures.PetsSchema,
variables: %{"intArg" => nil}
)
end
assert capture_log([level: :warn], fun) =~
"In operation `test, variable `$intArg` of type `Int` found as input to argument of type `String`."
end
test "types of variables does not match types of arguments in named fragments" do
fun = fn ->
Absinthe.run(
"""
query test($intArg: Int) {
complicatedArgs {
...Fragment
}
}
fragment Fragment on ComplicatedArgs {
stringArgField(stringArg: $intArg)
}
""",
Absinthe.Fixtures.PetsSchema,
variables: %{"intArg" => 5}
)
end
assert capture_log([level: :warn], fun) =~
"In operation `test, variable `$intArg` of type `Int` found as input to argument of type `String`."
end
end
| 27.83908 | 112 | 0.576383 |
73bb7001086d62b013b5515f77770bb2d7123d46 | 1,838 | exs | Elixir | config/config.exs | mammenj/elixir-auction | 94941bb820a221e3917014919d97571784ac9388 | [
"Apache-2.0"
] | null | null | null | config/config.exs | mammenj/elixir-auction | 94941bb820a221e3917014919d97571784ac9388 | [
"Apache-2.0"
] | null | null | null | config/config.exs | mammenj/elixir-auction | 94941bb820a221e3917014919d97571784ac9388 | [
"Apache-2.0"
] | null | null | null | # This file is responsible for configuring your umbrella
# and **all applications** and their dependencies with the
# help of the Config module.
#
# Note that all applications in your umbrella share the
# same configuration and dependencies, which is why they
# all use the same configuration file. If you want different
# configurations or dependencies per app, it is best to
# move said applications out of the umbrella.
import Config
config :auction_web,
generators: [context_app: false]
# Configures the endpoint
config :auction_web, AuctionWeb.Endpoint,
url: [host: "localhost"],
render_errors: [view: AuctionWeb.ErrorView, accepts: ~w(html json), layout: false],
pubsub_server: AuctionWeb.PubSub,
live_view: [signing_salt: "yOhkBLek"]
# Configure esbuild (the version is required)
config :esbuild,
version: "0.12.18",
default: [
args:
~w(js/app.js --bundle --target=es2016 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*),
cd: Path.expand("../apps/auction_web/assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]
# Sample configuration:
#
# config :logger, :console,
# level: :info,
# format: "$date $time [$level] $metadata$message\n",
# metadata: [:user_id]
#
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
config :auction, ecto_repos: [Auction.Repo]
config :auction, Auction.Repo,
database: "auction",
username: "postgres",
password: "root",
hostname: "localhost",
port: "5432"
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{config_env()}.exs"
| 30.633333 | 117 | 0.711643 |
73bb70ff51b3b4f8582178b00743cabaa715d80a | 1,027 | ex | Elixir | apps/robby_web/web/models/user.ex | jeffweiss/openrobby | 9fed2024e6ce87a6fe27ef3af85558f3116aca2a | [
"Apache-2.0"
] | null | null | null | apps/robby_web/web/models/user.ex | jeffweiss/openrobby | 9fed2024e6ce87a6fe27ef3af85558f3116aca2a | [
"Apache-2.0"
] | null | null | null | apps/robby_web/web/models/user.ex | jeffweiss/openrobby | 9fed2024e6ce87a6fe27ef3af85558f3116aca2a | [
"Apache-2.0"
] | null | null | null | defmodule RobbyWeb.User do
use RobbyWeb.Web, :model
schema "users" do
field :dn, :string
field :username, :string
field :salt, :string
field :email, :string
timestamps()
end
@required_fields ~w(dn username salt email)a
@optional_fields ~w()
@doc """
Creates a changeset based on the `model` and `params`.
If no params are provided, an invalid changeset is returned
with no validation performed.
"""
def changeset(model, params \\ %{}) do
model
|> cast(params, List.flatten(@required_fields, @optional_fields))
|> validate_required(@required_fields)
end
def changeset_from_ldap(nil) do
%RobbyWeb.User{}
|> changeset
end
def changeset_from_ldap(ldap_user) do
%RobbyWeb.User{}
|> changeset(%{
:dn => ldap_user.dn,
:username => ldap_user.uid,
:salt => generate_new_salt(),
:email => ldap_user.mail
})
end
def generate_new_salt do
:crypto.strong_rand_bytes(48) |> Base.encode64
end
end
| 22.326087 | 69 | 0.644596 |
73bb884c312fa4e55700c1bb294b2422d3683e84 | 1,974 | ex | Elixir | clients/app_engine/lib/google_api/app_engine/v1/model/endpoints_api_service.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/app_engine/lib/google_api/app_engine/v1/model/endpoints_api_service.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/app_engine/lib/google_api/app_engine/v1/model/endpoints_api_service.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 "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.AppEngine.V1.Model.EndpointsApiService do
@moduledoc """
Cloud Endpoints (https://cloud.google.com/endpoints) configuration. The Endpoints API Service provides tooling for serving Open API and gRPC endpoints via an NGINX proxy.The fields here refer to the name and configuration id of a \"service\" resource in the Service Management API (https://cloud.google.com/service-management/overview).
## Attributes
- configId (String): Endpoints service configuration id as specified by the Service Management API. For example \"2016-09-19r1\" Defaults to: `null`.
- name (String): Endpoints service name which is the name of the \"service\" resource in the Service Management API. For example \"myapi.endpoints.myproject.cloud.goog\" Defaults to: `null`.
"""
defstruct [
:"configId",
:"name"
]
end
defimpl Poison.Decoder, for: GoogleApi.AppEngine.V1.Model.EndpointsApiService do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.AppEngine.V1.Model.EndpointsApiService do
def encode(value, options) do
GoogleApi.AppEngine.V1.Deserializer.serialize_non_nil(value, options)
end
end
| 41.125 | 348 | 0.762411 |
73bbba32dd5ed42b8aaeab013e9fd935a2b49790 | 1,194 | ex | Elixir | test/support/helpers.ex | RichMorin/earmark | e65fcf67345c84c23d237c732e5c174246662c68 | [
"Apache-1.1"
] | null | null | null | test/support/helpers.ex | RichMorin/earmark | e65fcf67345c84c23d237c732e5c174246662c68 | [
"Apache-1.1"
] | null | null | null | test/support/helpers.ex | RichMorin/earmark | e65fcf67345c84c23d237c732e5c174246662c68 | [
"Apache-1.1"
] | null | null | null | defmodule Support.Helpers do
alias Earmark.Block.IdDef
alias Earmark.Context
alias Earmark.Inline
###############
# Helpers.... #
###############
def context do
%Earmark.Context{}
end
def as_html(markdown, options \\ []) do
Earmark.as_html(markdown, struct(Earmark.Options, options))
end
def as_html!(markdown, options \\ []) do
Earmark.as_html!(markdown, struct(Earmark.Options, options))
end
def test_links do
[
{"id1", %IdDef{url: "url 1", title: "title 1"}},
{"id2", %IdDef{url: "url 2"}},
{"img1", %IdDef{url: "img 1", title: "image 1"}},
{"img2", %IdDef{url: "img 2"}},
]
|> Enum.into(Map.new)
end
def pedantic_context do
ctx = put_in(context().options.gfm, false)
ctx = put_in(ctx.options.pedantic, true)
ctx = put_in(ctx.links, test_links())
Context.update_context(ctx)
end
def gfm_context do
Context.update_context(context())
end
def convert_pedantic(string, lnb \\ 0) do
Inline.convert(string, lnb, pedantic_context()).value
end
def convert_gfm(string, lnb \\ 0) do
Inline.convert(string, lnb, gfm_context())
end
end
# SPDX-License-Identifier: Apache-2.0
| 21.321429 | 64 | 0.627303 |
73bbbcfdc5c551694ed5a9cff096780f06688b75 | 3,402 | exs | Elixir | mix.exs | fmarczin/custom-rpi0 | e92197165ae683865937d681282773caaeee080f | [
"Apache-2.0"
] | null | null | null | mix.exs | fmarczin/custom-rpi0 | e92197165ae683865937d681282773caaeee080f | [
"Apache-2.0"
] | null | null | null | mix.exs | fmarczin/custom-rpi0 | e92197165ae683865937d681282773caaeee080f | [
"Apache-2.0"
] | null | null | null | defmodule NervesSystemRpi0.MixProject do
use Mix.Project
@github_organization "nerves-project"
@app :nerves_system_rpi0
@source_url "https://github.com/#{@github_organization}/#{@app}"
@version Path.join(__DIR__, "VERSION")
|> File.read!()
|> String.trim()
def project do
[
app: @app,
version: @version,
elixir: "~> 1.6",
compilers: Mix.compilers() ++ [:nerves_package],
nerves_package: nerves_package(),
description: description(),
package: package(),
deps: deps(),
aliases: [loadconfig: [&bootstrap/1], docs: ["docs", ©_images/1]],
docs: docs(),
preferred_cli_env: %{
docs: :docs,
"hex.build": :docs,
"hex.publish": :docs
}
]
end
def application do
[]
end
defp bootstrap(args) do
set_target()
Application.start(:nerves_bootstrap)
Mix.Task.run("loadconfig", args)
end
defp nerves_package do
[
type: :system,
artifact_sites: [
{:github_releases, "#{@github_organization}/#{@app}"}
],
build_runner_opts: build_runner_opts(),
platform: Nerves.System.BR,
platform_config: [
defconfig: "nerves_defconfig"
],
# The :env key is an optional experimental feature for adding environment
# variables to the crosscompile environment. These are intended for
# llvm-based tooling that may need more precise processor information.
env: [
{"TARGET_ARCH", "arm"},
{"TARGET_CPU", "arm1176jzf_s"},
{"TARGET_OS", "linux"},
{"TARGET_ABI", "gnueabihf"}
],
checksum: package_files()
]
end
defp deps do
[
{:nerves, "~> 1.5.4 or ~> 1.6.0 or ~> 1.7.3", runtime: false},
{:nerves_system_br, "1.14.4", runtime: false},
{:nerves_toolchain_armv6_nerves_linux_gnueabihf, "~> 1.4.1", runtime: false},
{:nerves_system_linter, "~> 0.4", only: [:dev, :test], runtime: false},
{:ex_doc, "~> 0.22", only: :docs, runtime: false}
]
end
defp description do
"""
Nerves System - Raspberry Pi Zero and Zero W
"""
end
defp docs do
[
extras: ["README.md", "CHANGELOG.md"],
main: "readme",
source_ref: "v#{@version}",
source_url: @source_url,
skip_undefined_reference_warnings_on: ["CHANGELOG.md"]
]
end
defp package do
[
files: package_files(),
licenses: ["Apache 2.0"],
links: %{"GitHub" => @source_url}
]
end
defp package_files do
[
"fwup_include",
"rootfs_overlay",
"CHANGELOG.md",
"cmdline.txt",
"config.txt",
"fwup-revert.conf",
"fwup.conf",
"LICENSE",
"linux-5.4.defconfig",
"mix.exs",
"nerves_defconfig",
"post-build.sh",
"post-createfs.sh",
"ramoops.dts",
"README.md",
"VERSION"
]
end
# Copy the images referenced by docs, since ex_doc doesn't do this.
defp copy_images(_) do
File.cp_r("assets", "doc/assets")
end
defp build_runner_opts() do
case System.get_env("BR2_PRIMARY_SITE") do
nil -> []
primary_site -> [make_args: ["BR2_PRIMARY_SITE=#{primary_site}"]]
end
end
defp set_target() do
if function_exported?(Mix, :target, 1) do
apply(Mix, :target, [:target])
else
System.put_env("MIX_TARGET", "target")
end
end
end
| 24.3 | 83 | 0.585244 |
73bbbcfe36c1a92b69f6013277c881f0c49b68e6 | 1,919 | ex | Elixir | lib/entitiex/formatter.ex | undr/entitiex | c6666909290b4077b47659ce11891659226e3b88 | [
"MIT"
] | null | null | null | lib/entitiex/formatter.ex | undr/entitiex | c6666909290b4077b47659ce11891659226e3b88 | [
"MIT"
] | null | null | null | lib/entitiex/formatter.ex | undr/entitiex | c6666909290b4077b47659ce11891659226e3b88 | [
"MIT"
] | null | null | null | defmodule Entitiex.Formatter do
alias Entitiex.Types
@spec to_s(any() | [any()]) :: String.t()
def to_s(value) when is_list(value),
do: Enum.map(value, &to_s/1)
def to_s(value),
do: to_string(value)
@spec to_atom(any() | [any()]) :: atom()
def to_atom(value) when is_list(value),
do: Enum.map(value, &to_atom/1)
def to_atom(value),
do: to_string(value) |> String.to_atom
@spec camelize(any() | [any()]) :: String.t()
def camelize(value) when is_list(value),
do: Enum.map(value, &camelize/1)
def camelize(value) when is_atom(value),
do: to_string(value) |> camelize
def camelize(value),
do: Macro.camelize(value)
@spec lcamelize(any() | [any()]) :: String.t()
def lcamelize(value) when is_list(value),
do: Enum.map(value, &lcamelize/1)
def lcamelize(value) when is_atom(value),
do: to_string(value) |> lcamelize
def lcamelize(value) do
camelized = Macro.camelize(value)
first = String.first(camelized)
String.replace_prefix(camelized, first, String.downcase(first))
end
@spec upcase(any() | [any()]) :: String.t
def upcase(value) when is_list(value),
do: Enum.map(value, &upcase/1)
def upcase(value),
do: to_string(value) |> String.upcase
@spec downcase(any() | [any()]) :: String.t
def downcase(value) when is_list(value),
do: Enum.map(value, &downcase/1)
def downcase(value),
do: to_string(value) |> String.downcase
@spec format(Types.normal_funcs(), any()) :: {:ok, any()} | :error
def format(formatter, value) when is_function(formatter),
do: format([formatter], value)
def format(formatters, value) do
formatters
|> Enum.reject(&is_nil/1)
|> Enum.reduce(value, fn func, acc -> func.(acc) end)
end
@spec normalize(Types.funcs(), module()) :: Types.normal_funcs()
def normalize(formatters, entity),
do: Entitiex.Normalizer.normalize(:formatter, formatters, entity)
end
| 31.983333 | 69 | 0.662845 |
73bbd5097fecec9c4eebe6c98cc0f914a4f1c4c0 | 192 | exs | Elixir | priv/repo/migrations/20171213115525_add_contract_block_number_to_icos.exs | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | 81 | 2017-11-20T01:20:22.000Z | 2022-03-05T12:04:25.000Z | priv/repo/migrations/20171213115525_add_contract_block_number_to_icos.exs | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 359 | 2017-10-15T14:40:53.000Z | 2022-01-25T13:34:20.000Z | priv/repo/migrations/20171213115525_add_contract_block_number_to_icos.exs | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | 16 | 2017-11-19T13:57:40.000Z | 2022-02-07T08:13:02.000Z | defmodule Sanbase.Repo.Migrations.AddContractBlockNumberToIcos do
use Ecto.Migration
def change do
alter table(:icos) do
add(:contract_block_number, :integer)
end
end
end
| 19.2 | 65 | 0.744792 |
73bbdb24b1d53b931deae23bd2f30a8fcd59e567 | 591 | exs | Elixir | mix.exs | Spock1992/Simple-chat-in-elixir | 513b8b1d428840d7ebd15c0341be27795605fc29 | [
"MIT"
] | null | null | null | mix.exs | Spock1992/Simple-chat-in-elixir | 513b8b1d428840d7ebd15c0341be27795605fc29 | [
"MIT"
] | null | null | null | mix.exs | Spock1992/Simple-chat-in-elixir | 513b8b1d428840d7ebd15c0341be27795605fc29 | [
"MIT"
] | null | null | null | defmodule Chat.MixProject do
use Mix.Project
def project do
[
app: :chat,
version: "0.1.0",
elixir: "~> 1.6",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {Chat, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
]
end
end
| 19.7 | 88 | 0.558376 |
73bbe82d698c78d0a6aa283606903bb614a0e0c6 | 1,117 | ex | Elixir | lib/Base/Client_handler/client_handler_AfterAuth.ex | ServusGameServer/Servus_Protobuf | cb870b7dccb6676e71045e231fd31547d63efa74 | [
"Apache-2.0"
] | 2 | 2018-10-19T06:14:08.000Z | 2018-11-23T00:56:09.000Z | lib/Base/Client_handler/client_handler_AfterAuth.ex | ServusGameServer/Servus_Protobuf | cb870b7dccb6676e71045e231fd31547d63efa74 | [
"Apache-2.0"
] | null | null | null | lib/Base/Client_handler/client_handler_AfterAuth.ex | ServusGameServer/Servus_Protobuf | cb870b7dccb6676e71045e231fd31547d63efa74 | [
"Apache-2.0"
] | null | null | null | defmodule Servus.ClientHandler_AfterAuth do
@moduledoc """
Handles the socket connection of a client (player). All messages are
received via tcp and interpreted as JSON.
"""
alias Servus.Serverutils
require Logger
def run(clientHandle, decodedProtobuf) do
if Map.has_key?(clientHandle, :auth) do
case decodedProtobuf.modul do
:DIRECTGAME ->
Servus.ClientHandler_Game.run(clientHandle, decodedProtobuf)
clientHandle
:QUEUE ->
Servus.ClientHandler_Queue.run(clientHandle, decodedProtobuf)
_ ->
Servus.ClientHandler_Modul.run(clientHandle, decodedProtobuf)
end
else
# not Logged in --> ERROR
sendback = %LoadedProtobuf.ServusMessage{} |> Map.merge(decodedProtobuf)
sendback = %{sendback | value: nil}
sendback = %{sendback | error: true}
sendback = %{sendback | errorMessage: nil}
sendback = %{sendback | errorType: :ERROR_NO_AUTH}
Logger.warn("Call from Module but No Auth performed")
Serverutils.send(clientHandle.socket, sendback)
clientHandle
end
end
end
| 31.914286 | 78 | 0.679499 |
73bbf620c369289eae7df5fe1dff582a73a7c82d | 315 | ex | Elixir | lib/api/fake.ex | m3ta4a/amplitude_ex | 0fbd2ac7cbdaec4d8c0070b8f5fa6cd38eb7cb84 | [
"BSD-3-Clause"
] | null | null | null | lib/api/fake.ex | m3ta4a/amplitude_ex | 0fbd2ac7cbdaec4d8c0070b8f5fa6cd38eb7cb84 | [
"BSD-3-Clause"
] | null | null | null | lib/api/fake.ex | m3ta4a/amplitude_ex | 0fbd2ac7cbdaec4d8c0070b8f5fa6cd38eb7cb84 | [
"BSD-3-Clause"
] | null | null | null | defmodule Amplitude.API.Fake do
defp priv(path) do
priv =
:code.priv_dir(:amplitude)
|> to_string
priv <> "/mock" <> path
end
defp load(path) do
with {:ok, content} <- File.read(priv(path)),
do: Jason.decode(content)
end
def api_track(_), do: load("/track/response.txt")
end
| 19.6875 | 51 | 0.615873 |
73bc1d4eb4615d816dd9532ac1dce75cb5167280 | 10,348 | ex | Elixir | lib/shitty_linq_ex.ex | uduDudu/shitty_linq_ex | 8e9e93afd2aeb2a93b936755e14fd80edf0b5f03 | [
"Unlicense"
] | null | null | null | lib/shitty_linq_ex.ex | uduDudu/shitty_linq_ex | 8e9e93afd2aeb2a93b936755e14fd80edf0b5f03 | [
"Unlicense"
] | null | null | null | lib/shitty_linq_ex.ex | uduDudu/shitty_linq_ex | 8e9e93afd2aeb2a93b936755e14fd80edf0b5f03 | [
"Unlicense"
] | null | null | null | defmodule ShittyLinqEx do
@moduledoc """
Documentation for `ShittyLinqEx`.
"""
@doc """
Applies an accumulator function over a sequence. The specified seed value is used as the initial
accumulator value, and the specified function is used to select the result value.
## Parameters
- `source`: an enumerable to aggregate over.
- `seed`: the initial accumulator value.
- `func`: an accumulator function to be invoked on each element.
- `resultSelector`: a function to transform the final accumulator value into the result value.
## Returns
The transformed final accumulator value.
## Examples
iex> import ShittyLinqEx, only: [aggregate: 4]
iex> fruits = ["apple", "mango", "orange", "passionfruit", "grape"]
iex> aggregate(
...> fruits,
...> "banana",
...> fn next, longest ->
...> if String.length(next) > String.length(longest) do
...> next
...> else
...> longest
...> end
...> end,
...> &String.upcase/1)
"PASSIONFRUIT"
"""
def aggregate(source, seed, func, resultSelector)
when is_list(source) and is_function(func, 2) and is_function(resultSelector, 1) do
:lists.foldl(func, seed, source)
|> resultSelector.()
end
def aggregate(first..last, seed, func, resultSelector)
when is_function(func, 2) and is_function(resultSelector, 1) do
if first <= last do
aggregate_range_inc(first, last, seed, func)
else
aggregate_range_dec(first, last, seed, func)
end
|> resultSelector.()
end
def aggregate(%{} = source, seed, func, resultSelector)
when is_function(func, 2) and is_function(resultSelector, 1) do
:maps.fold(
fn key, value, accumulator -> func.({key, value}, accumulator) end,
seed,
source
)
|> resultSelector.()
end
def aggregate(source, seed, func, resultSelector)
when is_list(source) and is_function(func, 2) and is_function(resultSelector, 1) do
:lists.foldl(func, seed, source)
|> resultSelector.()
end
def aggregate(first..last, seed, func, resultSelector)
when is_function(func, 2) and is_function(resultSelector, 1) do
if first <= last do
aggregate_range_inc(first, last, seed, func)
else
aggregate_range_dec(first, last, seed, func)
end
|> resultSelector.()
end
@doc """
Applies an accumulator function over a sequence.
The specified seed value is used as the initial accumulator value.
## Parameters
- `source`: an enumerable to aggregate over.
- `seed`: the initial accumulator value.
- `func`: an accumulator function to be invoked on each element.
## Returns
The final accumulator value.
## Examples
iex> import ShittyLinqEx, only: [aggregate: 3]
iex> ints = [4, 8, 8, 3, 9, 0, 7, 8, 2]
iex> aggregate(
...> ints,
...> 0,
...> fn next, total ->
...> if rem(next, 2) == 0 do
...> total + 1
...> else
...> total
...> end
...> end)
6
iex> import ShittyLinqEx, only: [aggregate: 3]
iex> aggregate(4..1, 1, &*/2)
24
iex> import ShittyLinqEx, only: [aggregate: 3]
iex> aggregate(1..3, 1, &+/2)
7
iex> import ShittyLinqEx, only: [aggregate: 3]
iex> letters_to_numbers = %{a: 1, b: 2, c: 3}
iex> aggregate(
...> letters_to_numbers,
...> [],
...> fn {key, _value}, keys -> [key | keys] end)
[:c, :b, :a]
"""
def aggregate(source, seed, func)
when is_list(source) and is_function(func, 2) do
:lists.foldl(func, seed, source)
end
def aggregate(first..last, seed, func)
when is_function(func, 2) do
if first <= last do
aggregate_range_inc(first, last, seed, func)
else
aggregate_range_dec(first, last, seed, func)
end
end
def aggregate(%{} = source, seed, func)
when is_function(func, 2) do
:maps.fold(
fn key, value, acc -> func.({key, value}, acc) end,
seed,
source
)
end
@doc """
Applies an accumulator function over a sequence.
## Parameters
- `source`: an enumerable to aggregate over.
- `func`: an accumulator function to be invoked on each element.
## Returns
The final accumulator value.
## Examples
iex> import ShittyLinqEx, only: [aggregate: 2]
iex> sentence = "the quick brown fox jumps over the lazy dog"
iex> words = String.split(sentence)
iex> aggregate(
...> words,
...> fn word, workingSentence -> word <> " " <> workingSentence end)
"dog lazy the over jumps fox brown quick the"
"""
def aggregate([head | tail], func)
when is_function(func, 2) do
aggregate(tail, head, func)
end
@doc """
Determines whether all elements of a sequence satisfy a condition.
##Parameters
- `list`: A list that contains the elements to apply the predicate to.
- `funciton`: A function to test each element for a condition.
##Returns
true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.
##Examples
iex> import ShittyLinqEx, only: [all: 2]
iex> all(
...> ["Barley", "Boots", "Whiskers"],
...> fn pet -> String.first(pet) == "B" end)
false
iex> import ShittyLinqEx, only: [all: 2]
iex> all(
...> [1, 3, 5, 7, 9],
...> fn number -> rem(number,2) == 1 end)
true
"""
@spec all(list, fun) :: bool
def all(list, predicate) when is_list(list) and is_function(predicate,1), do: do_all(list, predicate)
defp do_all([], _predicate), do: true
defp do_all([head | tail], predicate), do: predicate.(head) && do_all(tail, predicate)
@doc """
Inverts the order of the elements in a sequence.
## Parameters
- `list`: A sequence of values to reverse.
## Returns
A sequence whose elements correspond to those of the input sequence in reverse order.
## Examples
iex> import ShittyLinqEx, only: [reverse: 1]
iex> reverse(["A", "B", "C"])
["C", "B", "A"]
iex> import ShittyLinqEx, only: [reverse: 1]
iex> reverse([42, "orange", ":atom"])
[":atom", "orange", 42]
"""
@spec reverse(list) :: list
def reverse(list) when is_list(list), do: reverse(list, [])
def reverse([head | tail], acc), do: reverse(tail, [head | acc])
def reverse([], acc), do: acc
@doc """
Returns the first element of a sequence.
## Parameters
- `list`: A sequence of values of which the first element should be returned.
- `predicate`: A function to check for each element
- `value`: A value which will be checked in the predicate function
## Returns
First value of the input sequence.
## Examples
iex> import ShittyLinqEx, only: [first: 1]
iex> first(["A", "B", "C"])
"A"
iex> import ShittyLinqEx, only: [first: 1]
iex> first([42, "orange", ":atom"])
42
iex> import ShittyLinqEx, only: [first: 3]
iex> first([4, 2, 3], &>/2, 1)
4
"""
def first(list) when is_list(list), do: List.first(list)
def first([]), do: nil
def first(nil), do: nil
def first([head | tail], func, value) when is_list(tail) and is_function(func, 2) do
case func.(head, value) do
true -> head
false -> first(tail, func, value)
end
end
def first([], _func, _value), do: nil
@doc """
Returns a specified number of contiguous elements from the start of a sequence.
## Parameters
- `source`: A sequence of values to take.
- `count`: The number of elements to return.
## Returns
A sequence that contains the specified number of elements from the start of the input sequence.
## Examples
iex> import ShittyLinqEx, only: [take: 2]
iex> take(["A", "B", "C"], 2)
["A", "B"]
iex> import ShittyLinqEx, only: [take: 2]
iex> take([42, "orange", ":atom"], 7)
[42, "orange", ":atom"]
iex> import ShittyLinqEx, only: [take: 2]
iex> take([1, 2, 3], 0)
[]
iex> import ShittyLinqEx, only: [take: 2]
iex> take(nil, 5)
nil
"""
def take(_source, 0), do: []
def take(_souce, count) when is_integer(count) and count < 0, do: []
def take(nil, _count), do: nil
def take([], _count), do: []
def take(source, count)
when is_list(source) and is_integer(count) and count > 0 do
take_list(source, count)
end
@doc """
Filters a sequence of values based on a predicate.
## Parameters
- `source`: an enumerable to filter.
- `predicate`: a function to test each element for a condition.
## Returns
An enumerable that contains elements from the input sequence that satisfy the condition.
## Examples
iex> import ShittyLinqEx, only: [where: 2]
iex> where(
...> ["apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry"],
...> fn fruit -> String.length(fruit) < 6 end)
["apple", "mango", "grape"]
iex> import ShittyLinqEx, only: [where: 2]
iex> where(
...> [0, 30, 20, 15, 90, 85, 40, 75],
...> fn number, index -> number <= index * 10 end)
[0, 20, 15, 40]
"""
def where(source, predicate) when is_list(source) and is_function(predicate, 1) do
where_list(source, predicate)
end
def where(source, predicate) when is_list(source) and is_function(predicate, 2) do
where_list(source, predicate, 0)
end
defp aggregate_range_inc(first, first, seed, func) do
func.(first, seed)
end
defp aggregate_range_inc(first, last, seed, func) do
aggregate_range_inc(first + 1, last, func.(first, seed), func)
end
defp aggregate_range_dec(first, first, seed, func) do
func.(first, seed)
end
defp aggregate_range_dec(first, last, seed, func) do
aggregate_range_dec(first - 1, last, func.(first, seed), func)
end
defp take_list([head | _], 1), do: [head]
defp take_list([head | tail], counter), do: [head | take_list(tail, counter - 1)]
defp take_list([], _counter), do: []
defp where_list([head | tail], fun) do
case fun.(head) do
true -> [head | where_list(tail, fun)]
_ -> where_list(tail, fun)
end
end
defp where_list([], _fun) do
[]
end
defp where_list([head | tail], fun, index) do
case fun.(head, index) do
true -> [head | where_list(tail, fun, index + 1)]
_ -> where_list(tail, fun, index + 1)
end
end
defp where_list([], _fun, _index) do
[]
end
end
| 26 | 137 | 0.622632 |
73bc211a27b0fcf75cbcdea05ae3deafffe0e8cc | 1,435 | exs | Elixir | test/gateways/stripe_test.exs | aashishsingh2803/gringotts | cf39d54d27e9a13cce97f9787f7bec606b82b83d | [
"MIT"
] | 4 | 2018-03-23T13:02:37.000Z | 2018-08-14T15:55:24.000Z | test/gateways/stripe_test.exs | Siriusdark/gringotts | cf39d54d27e9a13cce97f9787f7bec606b82b83d | [
"MIT"
] | null | null | null | test/gateways/stripe_test.exs | Siriusdark/gringotts | cf39d54d27e9a13cce97f9787f7bec606b82b83d | [
"MIT"
] | null | null | null | defmodule Gringotts.Gateways.StripeTest do
use ExUnit.Case
alias Gringotts.Gateways.Stripe
alias Gringotts.{
CreditCard,
Address
}
@card %CreditCard{
first_name: "John",
last_name: "Smith",
number: "4242424242424242",
year: "2017",
month: "12",
verification_code: "123"
}
@address %Address{
street1: "123 Main",
street2: "Suite 100",
city: "New York",
region: "NY",
country: "US",
postal_code: "11111"
}
@required_opts [config: [api_key: "sk_test_vIX41hayC0BKrPWQerLuOMld"], currency: "usd"]
@optional_opts [address: @address]
describe "authorize/3" do
# test "should authorize wth card and required opts attrs" do
# amount = 5
# response = Stripe.authorize(amount, @card, @required_opts ++ @optional_opts)
# assert Map.has_key?(response, "id")
# assert response["amount"] == 500
# assert response["captured"] == false
# assert response["currency"] == "usd"
# end
# test "should not authorize if card is not passed" do
# amount = 5
# response = Stripe.authorize(amount, %{}, @required_opts ++ @optional_opts)
# assert Map.has_key?(response, "error")
# end
# test "should not authorize if required opts not present" do
# amount = 5
# response = Stripe.authorize(amount, @card, @optional_opts)
# assert Map.has_key?(response, "error")
# end
end
end
| 24.322034 | 89 | 0.629965 |
73bcb3023db7e8cc59df2031c46d9256a263cc8f | 741 | exs | Elixir | mix.exs | demarius/slacker | d31566c260486e61af8da2bca1edbdd4af5bd274 | [
"MIT"
] | 1 | 2016-08-10T17:46:51.000Z | 2016-08-10T17:46:51.000Z | mix.exs | demarius/slacker | d31566c260486e61af8da2bca1edbdd4af5bd274 | [
"MIT"
] | null | null | null | mix.exs | demarius/slacker | d31566c260486e61af8da2bca1edbdd4af5bd274 | [
"MIT"
] | null | null | null | defmodule Slacker.Mixfile do
use Mix.Project
def project do
[app: :slacker,
version: "0.0.1",
elixir: "~> 1.3",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps()]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
[applications: [
:logger, :slack
], mod: {Slacker, []}]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# Type "mix help deps" for more examples and options
defp deps do
[
{:slack, "~> 0.7.0"}
]
end
end
| 20.027027 | 77 | 0.578947 |
73bcd97904099d1d362934f2a833e2436f049412 | 2,734 | exs | Elixir | config/prod.exs | colbydehart/MartaWhistle | 852d1aaecb1fe5705fdcaab30283870613f6a66f | [
"MIT"
] | null | null | null | config/prod.exs | colbydehart/MartaWhistle | 852d1aaecb1fe5705fdcaab30283870613f6a66f | [
"MIT"
] | null | null | null | config/prod.exs | colbydehart/MartaWhistle | 852d1aaecb1fe5705fdcaab30283870613f6a66f | [
"MIT"
] | null | null | null | use Mix.Config
# For production, we configure the host to read the PORT
# from the system environment. Therefore, you will need
# to set PORT=80 before running your server.
#
# You should also configure the url host to something
# meaningful, we use this information when generating URLs.
#
# Finally, we also include the path to a manifest
# containing the digested version of static files. This
# manifest is generated by the mix phoenix.digest task
# which you typically run after static files are built.
config :train_whistle, TrainWhistle.Endpoint,
http: [port: {:system, "PORT"}],
url: [scheme: "http", host: "transitwhistle.com", port: 80],
cache_static_manifest: "priv/static/manifest.json",
secret_key_base: System.get_env("SECRET_KEY_BASE")
config :train_whistle, TrainWhistle.Repo,
adapter: Ecto.Adapters.Postgres,
username: System.get_env("DATABASE_USER"),
password: System.get_env("DATABASE_PASSWORD"),
database: System.get_env("DATABASE_NAME"),
url: System.get_env("DATABASE_URL"),
pool_size: System.get_env("POOL_SIZE")
# Do not print debug messages in production
config :logger, level: :info
# Configure ExTwilio
config :ex_twilio,
account_sid: System.get_env("TWILIO_ACCOUNT_SID"),
auth_token: System.get_env("TWILIO_AUTH_TOKEN"),
twilio_number: System.get_env("TWILIO_NUMBER")
config :quantum, cron: [
"* * * * *": {Mix.Tasks.TrainWhistle.Poller, :poll}
]
config :guardian, Guardian,
secret_key: System.get_env("GUARDIAN_KEY")
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :train_whistle, TrainWhistle.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables return an absolute path to
# the key and cert in disk or a relative path inside priv,
# for example "priv/ssl/server.key".
#
# We also recommend setting `force_ssl`, ensuring no data is
# ever sent via http, always redirecting to https:
#
# config :train_whistle, TrainWhistle.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#
# config :phoenix, :serve_endpoints, true
#
# Alternatively, you can configure exactly which server to
# start per endpoint:
#
# config :train_whistle, TrainWhistle.Endpoint, server: true
#
# Finally import the config/prod.secret.exs
# which should be versioned separately.
| 32.939759 | 67 | 0.724214 |
73bce609ababb36f059f727d453c05c926d18a19 | 143 | exs | Elixir | test/organizing_a_project_3/issues_test.exs | mikan/elixir-practice | 624525605eb2324e0c55a4ddcb68388c0d2ecefc | [
"Apache-2.0"
] | null | null | null | test/organizing_a_project_3/issues_test.exs | mikan/elixir-practice | 624525605eb2324e0c55a4ddcb68388c0d2ecefc | [
"Apache-2.0"
] | 1 | 2020-01-28T00:19:53.000Z | 2020-01-28T00:19:53.000Z | test/organizing_a_project_3/issues_test.exs | mikan/elixir-practice | 624525605eb2324e0c55a4ddcb68388c0d2ecefc | [
"Apache-2.0"
] | null | null | null | defmodule Issues3Test do
use ExUnit.Case
doctest ElixirPractice.OrganizingAProject3
test "the truth" do
assert 1 + 1 == 2
end
end
| 15.888889 | 44 | 0.727273 |
73bd03d6aa92e6a32c9dc6db997d6edfa561cc9e | 957 | exs | Elixir | config/config.exs | Frylock13/PhoenixChat | 05f9a14df49a981ce1c9ebf41740577ccb2aae81 | [
"MIT"
] | 1 | 2016-02-24T01:45:57.000Z | 2016-02-24T01:45:57.000Z | config/config.exs | Frylock13/PhoenixChat | 05f9a14df49a981ce1c9ebf41740577ccb2aae81 | [
"MIT"
] | null | null | null | config/config.exs | Frylock13/PhoenixChat | 05f9a14df49a981ce1c9ebf41740577ccb2aae81 | [
"MIT"
] | 1 | 2016-02-24T01:47:02.000Z | 2016-02-24T01:47:02.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
# Configures the endpoint
config :chat_demo, ChatDemo.Endpoint,
url: [host: "localhost"],
root: Path.dirname(__DIR__),
secret_key_base: "GGbMxoPXDU0p/+Za3GmHzZoVOHf9Y199sHP5MTMesLobhvTLvSap97+NGDxGG914",
render_errors: [accepts: ~w(html json)],
pubsub: [name: ChatDemo.PubSub,
adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
# Configure phoenix generators
config :phoenix, :generators,
migration: true,
binary_id: false
| 31.9 | 86 | 0.756531 |
73bd05f885e1bbd626bc76178ed4cc572143bfc5 | 2,555 | exs | Elixir | test/honeybadger/plug_data_test.exs | blitzstudios/honeybadger-elixir | 81ec81c8e7303847de784c2fb7a189b8521c296c | [
"MIT"
] | 175 | 2015-07-04T16:01:53.000Z | 2022-03-30T10:18:03.000Z | test/honeybadger/plug_data_test.exs | blitzstudios/honeybadger-elixir | 81ec81c8e7303847de784c2fb7a189b8521c296c | [
"MIT"
] | 225 | 2015-07-03T22:08:58.000Z | 2022-02-03T14:16:20.000Z | test/honeybadger/plug_data_test.exs | blitzstudios/honeybadger-elixir | 81ec81c8e7303847de784c2fb7a189b8521c296c | [
"MIT"
] | 69 | 2015-09-17T13:56:28.000Z | 2022-03-20T17:49:17.000Z | defmodule Honeybadger.PlugDataTest do
use Honeybadger.Case, async: true
use Plug.Test
alias Honeybadger.PlugData
describe "build_plug_env/2" do
test "building outside of a phoenix app" do
conn = conn(:get, "/bang?foo=bar")
assert match?(
%{component: "PlugApp", params: %{"foo" => "bar"}, url: "/bang"},
PlugData.build_plug_env(conn, PlugApp)
)
end
test "building inside of a phoenix app" do
conn =
:get
|> conn("/bang")
|> put_private(:phoenix_controller, DanController)
|> put_private(:phoenix_action, :fight)
assert match?(
%{action: "fight", component: "DanController"},
PlugData.build_plug_env(conn, PlugApp)
)
end
end
describe "build_cgi_data/1" do
test "general CGI data is extracted" do
conn = conn(:get, "/bang")
%{port: remote_port} = get_peer_data(conn)
cgi_data = %{
"CONTENT_LENGTH" => [],
"ORIGINAL_FULLPATH" => "/bang",
"PATH_INFO" => "bang",
"QUERY_STRING" => "",
"REMOTE_ADDR" => "127.0.0.1",
"REMOTE_PORT" => remote_port,
"REQUEST_METHOD" => "GET",
"SCRIPT_NAME" => "",
"SERVER_ADDR" => "127.0.0.1",
"SERVER_NAME" => Application.get_env(:honeybadger, :hostname),
"SERVER_PORT" => 80
}
assert cgi_data == PlugData.build_cgi_data(conn)
end
test "formatted headers are included" do
headers = [
{"content-type", "application/json"},
{"origin", "somewhere"}
]
conn = %{conn(:get, "/bang") | req_headers: headers}
assert match?(
%{"HTTP_CONTENT_TYPE" => "application/json", "HTTP_ORIGIN" => "somewhere"},
PlugData.build_cgi_data(conn)
)
end
test "handles invalid remote ip" do
conn = %{conn(:get, "/bang") | remote_ip: nil}
%{port: remote_port} = get_peer_data(conn)
assert PlugData.build_cgi_data(conn) == %{
"CONTENT_LENGTH" => [],
"ORIGINAL_FULLPATH" => "/bang",
"PATH_INFO" => "bang",
"QUERY_STRING" => "",
"REMOTE_ADDR" => "",
"REMOTE_PORT" => remote_port,
"REQUEST_METHOD" => "GET",
"SCRIPT_NAME" => "",
"SERVER_ADDR" => "127.0.0.1",
"SERVER_NAME" => Application.get_env(:honeybadger, :hostname),
"SERVER_PORT" => 80
}
end
end
end
| 29.367816 | 90 | 0.52955 |
73bd3c6a3f74956bce365abca8d2bd7f0786d08e | 156 | ex | Elixir | lib/chapter_2_exercise_1.ex | danpker/elixir-otp-guidebook | 9c04f498207d6f397ecaa02d1dfba0861e425728 | [
"MIT"
] | null | null | null | lib/chapter_2_exercise_1.ex | danpker/elixir-otp-guidebook | 9c04f498207d6f397ecaa02d1dfba0861e425728 | [
"MIT"
] | null | null | null | lib/chapter_2_exercise_1.ex | danpker/elixir-otp-guidebook | 9c04f498207d6f397ecaa02d1dfba0861e425728 | [
"MIT"
] | null | null | null | defmodule Chapter2.Exercise1 do
def sum([]) do
0
end
def sum([head | tail]) do
head + sum(tail)
end
def sum(head) do
head
end
end
| 11.142857 | 31 | 0.589744 |
73bd46659a3085faaab0ea55ad95b77ea5931601 | 3,296 | ex | Elixir | lib/new_relic/harvest/collector/harvest_cycle.ex | trustvox/elixir_agent | 391c83c82336c96fd78a03c8ee316d48de2eea4f | [
"Apache-2.0"
] | null | null | null | lib/new_relic/harvest/collector/harvest_cycle.ex | trustvox/elixir_agent | 391c83c82336c96fd78a03c8ee316d48de2eea4f | [
"Apache-2.0"
] | null | null | null | lib/new_relic/harvest/collector/harvest_cycle.ex | trustvox/elixir_agent | 391c83c82336c96fd78a03c8ee316d48de2eea4f | [
"Apache-2.0"
] | null | null | null | defmodule NewRelic.Harvest.Collector.HarvestCycle do
use GenServer
# Manages the harvest cycle for a given harvester.
@moduledoc false
alias NewRelic.Harvest.Collector
def start_link(config) do
GenServer.start_link(__MODULE__, config, name: config[:name])
end
def init(
name: name,
harvest_cycle_key: harvest_cycle_key,
supervisor: supervisor
) do
if NewRelic.Config.enabled?(), do: send(self(), :harvest_cycle)
{:ok,
%{
name: name,
harvest_cycle_key: harvest_cycle_key,
supervisor: supervisor,
harvester: nil,
timer: nil
}}
end
# API
def current_harvester(name), do: Collector.HarvesterStore.current(name)
def manual_shutdown(name) do
harvester = current_harvester(name)
Process.monitor(harvester)
GenServer.call(name, :pause)
receive do
{:DOWN, _ref, _, ^harvester, _reason} ->
NewRelic.log(:warn, "Completed shutdown #{inspect(name)}")
end
end
# Server
def handle_call(:restart, _from, %{timer: timer} = state) do
stop_harvest_cycle(timer)
harvester = swap_harvester(state)
timer = trigger_harvest_cycle(state)
{:reply, :ok, %{state | harvester: harvester, timer: timer}}
end
def handle_call(:pause, _from, %{timer: old_timer} = state) do
stop_harvester(state)
stop_harvest_cycle(old_timer)
{:reply, :ok, %{state | harvester: nil, timer: nil}}
end
def handle_info(:harvest_cycle, state) do
harvester = swap_harvester(state)
timer = trigger_harvest_cycle(state)
{:noreply, %{state | harvester: harvester, timer: timer}}
end
def handle_info(
{:DOWN, _ref, _, pid, _reason},
%{harvester: crashed_harvester, timer: old_timer} = state
)
when pid == crashed_harvester do
stop_harvest_cycle(old_timer)
harvester = swap_harvester(state)
timer = trigger_harvest_cycle(state)
{:noreply, %{state | harvester: harvester, timer: timer}}
end
def handle_info({:DOWN, _ref, _, _pid, _reason}, state) do
{:noreply, state}
end
def handle_info(_msg, state) do
{:noreply, state}
end
# Helpers
defp swap_harvester(%{supervisor: supervisor, name: name, harvester: harvester}) do
{:ok, next} = Supervisor.start_child(supervisor, [])
Process.monitor(next)
Collector.HarvesterStore.update(name, next)
send_harvest(supervisor, harvester)
next
end
defp stop_harvester(%{supervisor: supervisor, name: name, harvester: harvester}) do
Collector.HarvesterStore.update(name, nil)
send_harvest(supervisor, harvester)
end
def send_harvest(_supervisor, nil), do: :no_harvester
@harvest_timeout 15_000
def send_harvest(supervisor, harvester) do
Task.Supervisor.start_child(
Collector.TaskSupervisor,
fn ->
GenServer.call(harvester, :send_harvest, @harvest_timeout)
Supervisor.terminate_child(supervisor, harvester)
end,
shutdown: @harvest_timeout
)
end
defp stop_harvest_cycle(timer), do: timer && Process.cancel_timer(timer)
defp trigger_harvest_cycle(%{harvest_cycle_key: harvest_cycle_key}) do
harvest_cycle = Collector.AgentRun.lookup(harvest_cycle_key) || 60_000
Process.send_after(self(), :harvest_cycle, harvest_cycle)
end
end
| 27.016393 | 85 | 0.689017 |
73bd8616c37b9ac8e80bce14330c8a360d11fe37 | 272 | exs | Elixir | fizzbuzz.exs | PragTob/fizzbuzz | 13a362f0ad88ee202164ea3aadbbfce185c7ce57 | [
"MIT"
] | 2 | 2018-01-02T13:47:40.000Z | 2018-01-28T20:08:28.000Z | fizzbuzz.exs | PragTob/fizzbuzz | 13a362f0ad88ee202164ea3aadbbfce185c7ce57 | [
"MIT"
] | null | null | null | fizzbuzz.exs | PragTob/fizzbuzz | 13a362f0ad88ee202164ea3aadbbfce185c7ce57 | [
"MIT"
] | null | null | null | defmodule FizzBuzz do
def fizzbuzz(n) when rem(n, 15) == 0, do: "FizzBuzz"
def fizzbuzz(n) when rem(n, 5) == 0, do: "Buzz"
def fizzbuzz(n) when rem(n, 3) == 0, do: "Fizz"
def fizzbuzz(n), do: n
end
Enum.each(1..100, fn i -> i |> FizzBuzz.fizzbuzz |> IO.puts end)
| 30.222222 | 64 | 0.613971 |
73bd8a0f2c9abd6f0079791f9541e7f9d1dd087f | 14,876 | ex | Elixir | lib/config_cat.ex | kianmeng/elixir-sdk | 89fb73f6249f82ac8415246519c17ad4ade54760 | [
"MIT"
] | 14 | 2020-10-15T09:15:12.000Z | 2022-03-18T19:42:28.000Z | lib/config_cat.ex | kianmeng/elixir-sdk | 89fb73f6249f82ac8415246519c17ad4ade54760 | [
"MIT"
] | 54 | 2020-10-14T05:08:21.000Z | 2021-05-28T13:00:22.000Z | lib/config_cat.ex | kianmeng/elixir-sdk | 89fb73f6249f82ac8415246519c17ad4ade54760 | [
"MIT"
] | 5 | 2020-10-13T10:24:17.000Z | 2021-11-30T17:47:11.000Z | defmodule ConfigCat do
@moduledoc """
The ConfigCat Elixir SDK.
`ConfigCat` provides a `Supervisor` that must be added to your applications
supervision tree and an API for accessing your ConfigCat settings.
## Add ConfigCat to Your Supervision Tree
Your application's supervision tree might need to be different, but the most
basic approach is to add `ConfigCat` as a child of your top-most supervisor.
```elixir
# lib/my_app/application.ex
def start(_type, _args) do
children = [
# ... other children ...
{ConfigCat, [sdk_key: "YOUR SDK KEY"]}
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
```
If you need to run more than one instance of `ConfigCat`, you can add multiple
`ConfigCat` children. You will need to give `ConfigCat` a unique `name` option
for each, as well as using `Supervisor.child_spec/2` to provide a unique `id`
for each instance.
```elixir
# lib/my_app/application.ex
def start(_type, _args) do
children = [
# ... other children ...
Supervisor.child_spec({ConfigCat, [sdk_key: "sdk_key_1", name: :first]}, id: :config_cat_1),
Supervisor.child_spec({ConfigCat, [sdk_key: "sdk_key_2", name: :second]}, id: :config_cat_2),
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
```
### Options
`ConfigCat` takes a number of other keyword arguments:
- `sdk_key`: **REQUIRED** The SDK key for accessing your ConfigCat settings.
Go to the [Connect your application](https://app.configcat.com/sdkkey) tab
to get your SDK key.
```elixir
{ConfigCat, [sdk_key: "YOUR SDK KEY"]}
```
- `base_url`: **OPTIONAL** Allows you to specify a custom URL for fetching
your ConfigCat settings.
```elixir
{ConfigCat, [sdk_key: "YOUR SDK KEY", base_url: "https://my-cdn.example.com"]}
```
- `cache`: **OPTIONAL** Custom cache implementation. By default, `ConfigCat`
uses its own in-memory cache, but you can also provide the name of a module
that implements the `ConfigCat.ConfigCache` behaviour if you want to provide
your own cache (e.g. based on Redis). If your cache implementation requires
supervision, it is your application's responsibility to provide that.
```elixir
{ConfigCat, [sdk_key: "YOUR SDK KEY", cache: MyCustomCacheModule]}
```
- `cache_policy`: **OPTIONAL** Specifies the [polling
mode](https://configcat.com/docs/sdk-reference/elixir#polling-modes) used by
`ConfigCat`. Defaults to auto-polling mode with a 60 second poll interval.
You can specify a different polling mode or polling interval using
`ConfigCat.CachePolicy.auto/1`, `ConfigCat.CachePolicy.lazy/1`, or
`ConfigCat.CachePolicy.manual/0`.
```elixir
{ConfigCat, [sdk_key: "YOUR SDK KEY", cache_policy: ConfigCat.CachePolicy.manual()]}
```
- `data_governance`: **OPTIONAL** Describes the location of your feature flag
and setting data within the ConfigCat CDN. This parameter needs to be in
sync with your Data Governance preferences. Defaults to `:global`. [More
about Data Governance](https://configcat.com/docs/advanced/data-governance).
```elixir
{ConfigCat, [sdk_key: "YOUR SDK KEY", data_governance: :eu_only]}
```
- `http_proxy`: **OPTIONAL** Specify this option if you need to use a proxy
server to access your ConfigCat settings. You can provide a simple URL, like
`https://my_proxy.example.com` or include authentication information, like
`https://user:password@my_proxy.example.com/`.
```elixir
{ConfigCat, [sdk_key: "YOUR SDK KEY", http_proxy: "https://my_proxy.example.com"]}
```
- `name`: **OPTIONAL** A unique identifier for this instance of `ConfigCat`.
Defaults to `ConfigCat`. Must be provided if you need to run more than one
instance of `ConfigCat` in the same application. If you provide a `name`,
you must then pass that name to all of the API functions using the `client`
option.
```elixir
{ConfigCat, [sdk_key: "YOUR SDK KEY", name: :unique_name]}
```
```elixir
ConfigCat.get_value("setting", "default", client: :unique_name)
```
## Use the API
Once `ConfigCat` has been started as part of your application's supervision
tree, you can use its API to access your settings.
```elixir
ConfigCat.get_value("isMyAwesomeFeatureEnabled", false)
```
By default, all of the public API functions will communicate with the default
instance of the `ConfigCat` application.
If you are running multiple instances of `ConfigCat`, you must provide the
`client` option to the functions, passing along the unique name you specified
above.
```elixir
ConfigCat.get_value("isMyAwesomeFeatureEnabled", false, client: :second)
```
"""
use Supervisor
alias ConfigCat.{
CacheControlConfigFetcher,
CachePolicy,
Client,
Config,
Constants,
InMemoryCache,
User
}
require Constants
@typedoc "Options that can be passed to all API functions."
@type api_option :: {:client, instance_id()}
@typedoc """
Data Governance mode
[More about Data Governance](https://configcat.com/docs/advanced/data-governance)
"""
@type data_governance :: :eu_only | :global
@typedoc "Identifier of a specific instance of `ConfigCat`."
@type instance_id :: atom()
@typedoc "The name of a configuration setting."
@type key :: Config.key()
@typedoc "An option that can be provided when starting `ConfigCat`."
@type option ::
{:base_url, String.t()}
| {:cache, module()}
| {:cache_policy, CachePolicy.t()}
| {:data_governance, data_governance()}
| {:http_proxy, String.t()}
| {:name, instance_id()}
| {:sdk_key, String.t()}
@type options :: [option()]
@typedoc "The return value of the `force_refresh/1` function."
@type refresh_result :: :ok | {:error, term()}
@typedoc "The actual value of a configuration setting."
@type value :: Config.value()
@typedoc "The name of a variation being tested."
@type variation_id :: Config.variation_id()
@default_cache InMemoryCache
@doc """
Starts an instance of `ConfigCat`.
Normally not called directly by your code. Instead, it will be
called by your application's Supervisor once you add `ConfigCat`
to its supervision tree.
"""
@spec start_link(options()) :: Supervisor.on_start()
def start_link(options) when is_list(options) do
sdk_key = options[:sdk_key]
validate_sdk_key(sdk_key)
options =
default_options()
|> Keyword.merge(options)
|> generate_cache_key(sdk_key)
name = Keyword.fetch!(options, :name)
Supervisor.start_link(__MODULE__, options, name: name)
end
defp validate_sdk_key(nil), do: raise(ArgumentError, "SDK Key is required")
defp validate_sdk_key(""), do: raise(ArgumentError, "SDK Key is required")
defp validate_sdk_key(sdk_key) when is_binary(sdk_key), do: :ok
defp default_options,
do: [
cache: @default_cache,
cache_policy: CachePolicy.auto(),
name: __MODULE__
]
@impl Supervisor
def init(options) do
fetcher_options = fetcher_options(options)
policy_options =
options
|> Keyword.put(:fetcher_id, fetcher_options[:name])
|> cache_policy_options()
client_options =
options
|> Keyword.put(:cache_policy_id, policy_options[:name])
|> client_options()
children =
[
{CacheControlConfigFetcher, fetcher_options},
{CachePolicy, policy_options},
{Client, client_options}
]
|> add_default_cache(options)
Supervisor.init(children, strategy: :one_for_one)
end
defp add_default_cache(children, options) do
case Keyword.get(options, :cache) do
@default_cache -> [{@default_cache, cache_options(options)} | children]
_ -> children
end
end
@doc """
Queries all settings keys in your configuration.
### Options
- `client`: If you are running multiple instances of `ConfigCat`,
provide the `client: :unique_name` option, specifying the name you
configured for the instance you want to access.
"""
@spec get_all_keys([api_option()]) :: [key()]
def get_all_keys(options \\ []) do
name = Keyword.get(options, :client, __MODULE__)
Client.get_all_keys(client_name(name))
end
@doc "See `get_value/4`."
@spec get_value(key(), value(), User.t() | [api_option()]) :: value()
def get_value(key, default_value, user_or_options \\ []) do
if Keyword.keyword?(user_or_options) do
get_value(key, default_value, nil, user_or_options)
else
get_value(key, default_value, user_or_options, [])
end
end
@doc """
Retrieves a setting value from your configuration.
Retrieves the setting named `key` from your configuration. To use ConfigCat's
[targeting](https://configcat.com/docs/advanced/targeting) feature, provide a
`ConfigCat.User` struct containing the information used by the targeting
rules.
Returns the value of the setting, or `default_value` if an error occurs.
### Options
- `client`: If you are running multiple instances of `ConfigCat`, provide the
`client: :unique_name` option, specifying the name you configured for the
instance you want to access.
"""
@spec get_value(key(), value(), User.t() | nil, [api_option()]) :: value()
def get_value(key, default_value, user, options) do
name = Keyword.get(options, :client, __MODULE__)
Client.get_value(client_name(name), key, default_value, user)
end
@doc "See `get_variation_id/4`."
@spec get_variation_id(key(), variation_id(), User.t() | [api_option()]) :: variation_id()
def get_variation_id(key, default_variation_id, user_or_options \\ []) do
if Keyword.keyword?(user_or_options) do
get_variation_id(key, default_variation_id, nil, user_or_options)
else
get_variation_id(key, default_variation_id, user_or_options, [])
end
end
@doc """
Retrieves the variation id for a setting from your configuration.
Retrieves the setting named `key` from your configuration. To use ConfigCat's
[targeting](https://configcat.com/docs/advanced/targeting) feature, provide a
`ConfigCat.User` struct containing the information used by the targeting
rules.
Returns the variation id of the setting, or `default_variation_id` if an error
occurs.
### Options
- `client`: If you are running multiple instances of `ConfigCat`, provide the
`client: :unique_name` option, specifying the name you configured for the
instance you want to access.
"""
@spec get_variation_id(key(), variation_id(), User.t() | nil, [api_option()]) :: variation_id()
def get_variation_id(key, default_variation_id, user, options) do
name = Keyword.get(options, :client, __MODULE__)
Client.get_variation_id(client_name(name), key, default_variation_id, user)
end
@doc "See `get_all_variation_ids/2`."
@spec get_all_variation_ids(User.t() | [api_option()]) :: [variation_id()]
def get_all_variation_ids(user_or_options \\ []) do
if Keyword.keyword?(user_or_options) do
get_all_variation_ids(nil, user_or_options)
else
get_all_variation_ids(user_or_options, [])
end
end
@doc """
Retrieves a list of all variation ids from your configuration.
To use ConfigCat's [targeting](https://configcat.com/docs/advanced/targeting)
feature, provide a `ConfigCat.User` struct containing the information used by
the targeting rules.
Returns a list of all variation ids.
### Options
- `client`: If you are running multiple instances of `ConfigCat`, provide the
`client: :unique_name` option, specifying the name you configured for the
instance you want to access.
"""
@spec get_all_variation_ids(User.t() | nil, [api_option()]) :: [variation_id()]
def get_all_variation_ids(user, options) do
name = Keyword.get(options, :client, __MODULE__)
Client.get_all_variation_ids(client_name(name), user)
end
@doc """
Fetches the name and value of the setting corresponding to a variation id.
Returns a tuple containing the setting name and value, or `nil` if an error
occurs.
### Options
- `client`: If you are running multiple instances of `ConfigCat`, provide the
`client: :unique_name` option, specifying the name you configured for the
instance you want to access.
"""
@spec get_key_and_value(variation_id(), [api_option()]) :: {key(), value()} | nil
def get_key_and_value(variation_id, options \\ []) do
name = Keyword.get(options, :client, __MODULE__)
Client.get_key_and_value(client_name(name), variation_id)
end
@doc """
Force a refresh of the configuration from ConfigCat's CDN.
Depending on the polling mode you're using, `ConfigCat` may automatically
fetch your configuration during normal operation. Call this function to
force a manual refresh when you want one.
If you are using manual polling mode (`ConfigCat.CachePolicy.manual/0`),
this is the only way to fetch your configuration.
Returns `:ok`.
### Options
- `client`: If you are running multiple instances of `ConfigCat`, provide the
`client: :unique_name` option, specifying the name you configured for the
instance you want to access.
"""
@spec force_refresh([api_option()]) :: refresh_result()
def force_refresh(options \\ []) do
name = Keyword.get(options, :client, __MODULE__)
Client.force_refresh(client_name(name))
end
defp cache_policy_name(name), do: :"#{name}.CachePolicy"
defp client_name(name), do: :"#{name}.Client"
defp fetcher_name(name), do: :"#{name}.ConfigFetcher"
defp generate_cache_key(options, sdk_key) do
prefix =
case Keyword.get(options, :cache) do
@default_cache -> options[:name]
_ -> "elixir_"
end
cache_key =
:crypto.hash(:sha, "#{prefix}_#{ConfigCat.Constants.config_filename()}_#{sdk_key}")
|> Base.encode16()
Keyword.put(options, :cache_key, cache_key)
end
defp cache_options(options) do
Keyword.take(options, [:cache_key])
end
defp cache_policy_options(options) do
options
|> Keyword.update!(:name, &cache_policy_name/1)
|> Keyword.take([:cache, :cache_key, :cache_policy, :fetcher_id, :name])
end
defp client_options(options) do
options
|> Keyword.update!(:name, &client_name/1)
|> Keyword.update!(:cache_policy, &CachePolicy.policy_name/1)
|> Keyword.take([
:cache_policy,
:cache_policy_id,
:name
])
end
defp fetcher_options(options) do
options
|> Keyword.update!(:name, &fetcher_name/1)
|> Keyword.put(:mode, options[:cache_policy].mode)
|> Keyword.take([:base_url, :http_proxy, :data_governance, :mode, :name, :sdk_key])
end
end
| 32.76652 | 99 | 0.693399 |
73bdbd9e548aa8673e7bcbe9f9bb32bc5a3f5827 | 13,768 | ex | Elixir | test/event_store/support/subscription_test_case.ex | mquickform/commanded | 260b1ec28c2fb3c1fcbb61b8c4abacabd7dc7ed2 | [
"MIT"
] | null | null | null | test/event_store/support/subscription_test_case.ex | mquickform/commanded | 260b1ec28c2fb3c1fcbb61b8c4abacabd7dc7ed2 | [
"MIT"
] | 1 | 2018-12-05T18:17:08.000Z | 2018-12-05T18:17:08.000Z | test/event_store/support/subscription_test_case.ex | mquickform/commanded | 260b1ec28c2fb3c1fcbb61b8c4abacabd7dc7ed2 | [
"MIT"
] | 1 | 2018-12-05T18:15:03.000Z | 2018-12-05T18:15:03.000Z | defmodule Commanded.EventStore.SubscriptionTestCase do
import Commanded.SharedTestCase
define_tests do
alias Commanded.EventStore
alias Commanded.EventStore.{EventData, Subscriber}
alias Commanded.Helpers.ProcessHelper
defmodule BankAccountOpened do
defstruct [:account_number, :initial_balance]
end
describe "transient subscription to single stream" do
test "should receive events appended to the stream" do
stream_uuid = UUID.uuid4()
assert :ok = EventStore.subscribe(stream_uuid)
:ok = EventStore.append_to_stream(stream_uuid, 0, build_events(1))
received_events = assert_receive_events(1, from: 1)
assert Enum.map(received_events, & &1.stream_id) == [stream_uuid]
assert Enum.map(received_events, & &1.stream_version) == [1]
:ok = EventStore.append_to_stream(stream_uuid, 1, build_events(2))
received_events = assert_receive_events(2, from: 2)
assert Enum.map(received_events, & &1.stream_id) == [stream_uuid, stream_uuid]
assert Enum.map(received_events, & &1.stream_version) == [2, 3]
:ok = EventStore.append_to_stream(stream_uuid, 3, build_events(3))
received_events = assert_receive_events(3, from: 4)
assert Enum.map(received_events, & &1.stream_id) == [
stream_uuid,
stream_uuid,
stream_uuid
]
assert Enum.map(received_events, & &1.stream_version) == [4, 5, 6]
refute_receive {:events, _received_events}
end
test "should not receive events appended to another stream" do
stream_uuid = UUID.uuid4()
another_stream_uuid = UUID.uuid4()
assert :ok = EventStore.subscribe(stream_uuid)
:ok = EventStore.append_to_stream(another_stream_uuid, 0, build_events(1))
:ok = EventStore.append_to_stream(another_stream_uuid, 1, build_events(2))
refute_receive {:events, _received_events}
end
end
describe "transient subscription to all streams" do
test "should receive events appended to any stream" do
assert :ok = EventStore.subscribe(:all)
:ok = EventStore.append_to_stream("stream1", 0, build_events(1))
received_events = assert_receive_events(1, from: 1)
assert Enum.map(received_events, & &1.stream_id) == ["stream1"]
assert Enum.map(received_events, & &1.stream_version) == [1]
:ok = EventStore.append_to_stream("stream2", 0, build_events(2))
received_events = assert_receive_events(2, from: 2)
assert Enum.map(received_events, & &1.stream_id) == ["stream2", "stream2"]
assert Enum.map(received_events, & &1.stream_version) == [1, 2]
:ok = EventStore.append_to_stream("stream3", 0, build_events(3))
received_events = assert_receive_events(3, from: 4)
assert Enum.map(received_events, & &1.stream_id) == ["stream3", "stream3", "stream3"]
assert Enum.map(received_events, & &1.stream_version) == [1, 2, 3]
:ok = EventStore.append_to_stream("stream1", 1, build_events(2))
received_events = assert_receive_events(2, from: 7)
assert Enum.map(received_events, & &1.stream_id) == ["stream1", "stream1"]
assert Enum.map(received_events, & &1.stream_version) == [2, 3]
refute_receive {:events, _received_events}
end
end
describe "subscribe to single stream" do
test "should receive `:subscribed` message once subscribed" do
{:ok, subscription} = EventStore.subscribe_to("stream1", "subscriber", self(), :origin)
assert_receive {:subscribed, ^subscription}
end
test "should receive events appended to stream" do
{:ok, subscription} = EventStore.subscribe_to("stream1", "subscriber", self(), :origin)
assert_receive {:subscribed, ^subscription}
:ok = EventStore.append_to_stream("stream1", 0, build_events(1))
:ok = EventStore.append_to_stream("stream1", 1, build_events(2))
:ok = EventStore.append_to_stream("stream1", 3, build_events(3))
assert_receive_events(subscription, 1, from: 1)
assert_receive_events(subscription, 2, from: 2)
assert_receive_events(subscription, 3, from: 4)
refute_receive {:events, _received_events}
end
test "should not receive events appended to another stream" do
{:ok, subscription} = EventStore.subscribe_to("stream1", "subscriber", self(), :origin)
:ok = EventStore.append_to_stream("stream1", 0, build_events(1))
:ok = EventStore.append_to_stream("stream2", 0, build_events(2))
:ok = EventStore.append_to_stream("stream3", 0, build_events(3))
assert_receive_events(subscription, 1, from: 1)
refute_receive {:events, _received_events}
end
test "should skip existing events when subscribing from current position" do
:ok = EventStore.append_to_stream("stream1", 0, build_events(1))
:ok = EventStore.append_to_stream("stream1", 1, build_events(2))
wait_for_event_store()
{:ok, subscription} = EventStore.subscribe_to("stream1", "subscriber", self(), :current)
assert_receive {:subscribed, ^subscription}
refute_receive {:events, _events}
:ok = EventStore.append_to_stream("stream1", 3, build_events(3))
:ok = EventStore.append_to_stream("stream2", 0, build_events(3))
:ok = EventStore.append_to_stream("stream3", 0, build_events(3))
assert_receive_events(subscription, 3, from: 4)
refute_receive {:events, _events}
end
test "should receive events already apended to stream" do
:ok = EventStore.append_to_stream("stream1", 0, build_events(1))
:ok = EventStore.append_to_stream("stream2", 0, build_events(2))
:ok = EventStore.append_to_stream("stream3", 0, build_events(3))
{:ok, subscription} = EventStore.subscribe_to("stream3", "subscriber", self(), :origin)
assert_receive {:subscribed, ^subscription}
assert_receive_events(subscription, 3, from: 1)
:ok = EventStore.append_to_stream("stream3", 3, build_events(1))
:ok = EventStore.append_to_stream("stream3", 4, build_events(1))
assert_receive_events(subscription, 2, from: 4)
refute_receive {:events, _received_events}
end
test "should prevent duplicate subscriptions" do
{:ok, _subscription} = EventStore.subscribe_to("stream1", "subscriber", self(), :origin)
assert {:error, :subscription_already_exists} ==
EventStore.subscribe_to("stream1", "subscriber", self(), :origin)
end
end
describe "subscribe to all streams" do
test "should receive `:subscribed` message once subscribed" do
{:ok, subscription} = EventStore.subscribe_to(:all, "subscriber", self(), :origin)
assert_receive {:subscribed, ^subscription}
end
test "should receive events appended to any stream" do
{:ok, subscription} = EventStore.subscribe_to(:all, "subscriber", self(), :origin)
assert_receive {:subscribed, ^subscription}
:ok = EventStore.append_to_stream("stream1", 0, build_events(1))
:ok = EventStore.append_to_stream("stream2", 0, build_events(2))
:ok = EventStore.append_to_stream("stream3", 0, build_events(3))
assert_receive_events(subscription, 1, from: 1)
assert_receive_events(subscription, 2, from: 2)
assert_receive_events(subscription, 3, from: 4)
refute_receive {:events, _received_events}
end
test "should receive events already appended to any stream" do
:ok = EventStore.append_to_stream("stream1", 0, build_events(1))
:ok = EventStore.append_to_stream("stream2", 0, build_events(2))
wait_for_event_store()
{:ok, subscription} = EventStore.subscribe_to(:all, "subscriber", self(), :origin)
assert_receive {:subscribed, ^subscription}
assert_receive_events(subscription, 1, from: 1)
assert_receive_events(subscription, 2, from: 2)
:ok = EventStore.append_to_stream("stream3", 0, build_events(3))
assert_receive_events(subscription, 3, from: 4)
refute_receive {:events, _received_events}
end
test "should skip existing events when subscribing from current position" do
:ok = EventStore.append_to_stream("stream1", 0, build_events(1))
:ok = EventStore.append_to_stream("stream2", 0, build_events(2))
wait_for_event_store()
{:ok, subscription} = EventStore.subscribe_to(:all, "subscriber", self(), :current)
assert_receive {:subscribed, ^subscription}
refute_receive {:events, _received_events}
:ok = EventStore.append_to_stream("stream3", 0, build_events(3))
assert_receive_events(subscription, 3, from: 4)
refute_receive {:events, _received_events}
end
test "should prevent duplicate subscriptions" do
{:ok, _subscription} = EventStore.subscribe_to(:all, "subscriber", self(), :origin)
assert {:error, :subscription_already_exists} ==
EventStore.subscribe_to(:all, "subscriber", self(), :origin)
end
end
describe "unsubscribe from all streams" do
test "should not receive further events appended to any stream" do
{:ok, subscription} = EventStore.subscribe_to(:all, "subscriber", self(), :origin)
assert_receive {:subscribed, ^subscription}
:ok = EventStore.append_to_stream("stream1", 0, build_events(1))
assert_receive_events(subscription, 1, from: 1)
:ok = EventStore.unsubscribe(subscription)
:ok = EventStore.append_to_stream("stream2", 0, build_events(2))
:ok = EventStore.append_to_stream("stream3", 0, build_events(3))
refute_receive {:events, _received_events}
end
end
describe "resume subscription" do
test "should remember last seen event number when subscription resumes" do
:ok = EventStore.append_to_stream("stream1", 0, build_events(1))
:ok = EventStore.append_to_stream("stream2", 0, build_events(1))
{:ok, subscriber} = Subscriber.start_link(self())
assert_receive {:subscribed, _subscription}
assert_receive {:events, received_events}
assert length(received_events) == 1
assert Enum.map(received_events, & &1.stream_id) == ["stream1"]
assert_receive {:events, received_events}
assert length(received_events) == 1
assert Enum.map(received_events, & &1.stream_id) == ["stream2"]
stop_subscriber(subscriber)
{:ok, _subscriber} = Subscriber.start_link(self())
assert_receive {:subscribed, _subscription}
:ok = EventStore.append_to_stream("stream3", 0, build_events(1))
assert_receive {:events, received_events}
assert length(received_events) == 1
assert Enum.map(received_events, & &1.stream_id) == ["stream3"]
refute_receive {:events, _received_events}
end
end
describe "subscription process" do
test "should not stop subscriber process when subscription down" do
{:ok, subscriber} = Subscriber.start_link(self())
ref = Process.monitor(subscriber)
assert_receive {:subscribed, subscription}
ProcessHelper.shutdown(subscription)
refute Process.alive?(subscription)
refute_receive {:DOWN, ^ref, :process, ^subscriber, _reason}
end
test "should stop subscription process when subscriber down" do
{:ok, subscriber} = Subscriber.start_link(self())
assert_receive {:subscribed, subscription}
ref = Process.monitor(subscription)
stop_subscriber(subscriber)
assert_receive {:DOWN, ^ref, :process, ^subscription, _reason}
end
end
defp stop_subscriber(subscriber) do
ProcessHelper.shutdown(subscriber)
wait_for_event_store()
end
defp wait_for_event_store do
case event_store_wait() do
nil -> :ok
wait -> :timer.sleep(wait)
end
end
defp assert_receive_events(subscription, expected_count, opts) do
assert_receive_events(expected_count, Keyword.put(opts, :subscription, subscription))
end
defp assert_receive_events(expected_count, opts) do
from_event_number = Keyword.get(opts, :from, 1)
assert_receive {:events, received_events}
received_events
|> Enum.with_index(from_event_number)
|> Enum.each(fn {received_event, expected_event_number} ->
assert received_event.event_number == expected_event_number
end)
case Keyword.get(opts, :subscription) do
nil -> :ok
subscription -> EventStore.ack_event(subscription, List.last(received_events))
end
case expected_count - length(received_events) do
0 ->
received_events
remaining when remaining > 0 ->
received_events ++
assert_receive_events(
remaining,
Keyword.put(opts, :from, from_event_number + length(received_events))
)
remaining when remaining < 0 ->
flunk("Received #{abs(remaining)} more event(s) than expected")
end
end
defp build_event(account_number) do
%EventData{
causation_id: UUID.uuid4(),
correlation_id: UUID.uuid4(),
event_type: "#{__MODULE__}.BankAccountOpened",
data: %BankAccountOpened{account_number: account_number, initial_balance: 1_000},
metadata: %{"user_id" => "test"}
}
end
defp build_events(count) do
for account_number <- 1..count, do: build_event(account_number)
end
end
end
| 36.231579 | 96 | 0.664149 |
73bdcdec1322964626d9bace65eece5ae42c94ea | 345 | ex | Elixir | lib/options_tracker_web/live/components_live/radio_button_component.ex | mgwidmann/options_tracker | 5520f88a9a5873842a63a23d4bcc5da82a51feba | [
"MIT"
] | 12 | 2020-06-25T17:25:15.000Z | 2021-09-30T20:13:33.000Z | lib/options_tracker_web/live/components_live/radio_button_component.ex | mgwidmann/options_tracker | 5520f88a9a5873842a63a23d4bcc5da82a51feba | [
"MIT"
] | 5 | 2020-08-05T03:12:31.000Z | 2021-07-15T04:59:03.000Z | lib/options_tracker_web/live/components_live/radio_button_component.ex | mgwidmann/options_tracker | 5520f88a9a5873842a63a23d4bcc5da82a51feba | [
"MIT"
] | 2 | 2021-07-03T17:20:15.000Z | 2021-09-01T15:38:58.000Z | defmodule OptionsTrackerWeb.Components.RadioButtonComponent do
use OptionsTrackerWeb, :live_component
def is_button_on?(%{params: params, data: data}, name) do
value = params[name] || params[to_string(name)] || Map.get(data, name)
if is_binary(value) do
value != "" && value != "false"
else
value
end
end
end
| 24.642857 | 74 | 0.672464 |
73be3d32a34af63f14de6dfad2e36c6a5b9a7188 | 2,582 | exs | Elixir | test/board_test.exs | marc-costello/elixirConnect4 | e4a0b879cdcbddb9a112d806a7b66c92790e35f9 | [
"MIT"
] | null | null | null | test/board_test.exs | marc-costello/elixirConnect4 | e4a0b879cdcbddb9a112d806a7b66c92790e35f9 | [
"MIT"
] | null | null | null | test/board_test.exs | marc-costello/elixirConnect4 | e4a0b879cdcbddb9a112d806a7b66c92790e35f9 | [
"MIT"
] | null | null | null | defmodule BoardTests do
use ExUnit.Case
alias GameSettings, as: GS
test "a connect4 board should have 7 columns" do
board = Board.create_new()
columnCount = length board
assert columnCount == GS.no_columns
end
test "a connect4 board should have 6 rows" do
board = Board.create_new()
rowCount =
board
|> List.first
|> length
assert rowCount == GS.no_rows
end
test "a board should be initialised full of :empty" do
board = Board.create_new()
allEmpties =
board
|> List.flatten
|> Enum.all? &(&1 == :empty)
assert allEmpties
end
test "a given board empty/blank" do
board = Board.create_new()
assert Board.is_blank?(board) == true
end
test "drop a coin on a given column using the players colour" do
board = Board.create_new()
player = %Player{type: :human, colour: :red}
{:ok, _updatedBoard, player_used, _coords} = Board.drop_coin 2, board, player
assert player_used.colour == player.colour
end
test "given a board and a valid column number, can a coin be dropped? should return ok" do
board = Board.create_new()
{status, _index} = Board.can_drop_coin?(board, 1)
assert status == :ok
end
test "given a board and a valid column number, can drop coin should return the index of the first empty row" do
board = Board.create_new()
{:ok, index} = Board.can_drop_coin?(board, 1)
assert index == 0
end
test "given a board and an invalid column number, can a coin be dropped should return false" do
board = Board.create_new()
assert Board.can_drop_coin?(board, 99) == false
end
test "given a board with a full column, can a coin be dropped should return false" do
board = Board.create_new()
columnIndex = 0
fullColumn = for _ <- 1..GS.no_columns, do: :red
updatedBoard = board |> List.replace_at(columnIndex, fullColumn)
assert Board.can_drop_coin?(updatedBoard, columnIndex) == false
end
test "format board into horizontal lists for diffing" do
board = for _ <- 1..GS.no_columns, do: [:red, :empty, :empty, :empty, :empty, :empty]
correct_assertion_board = for n <- 1..GS.no_rows do
if n == 1 do
for _ <- 1..GS.no_columns, do: :red
else
for _ <- 1..GS.no_columns, do: :empty
end
end
horizontal_board = Board.convert(board, :horizontal)
assert horizontal_board == correct_assertion_board
end
end
| 31.876543 | 114 | 0.631294 |
73be409cf8dda42a679dc2cf54478d120327b876 | 17,826 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v35/api/targeting_templates.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v35/api/targeting_templates.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v35/api/targeting_templates.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.DFAReporting.V35.Api.TargetingTemplates do
@moduledoc """
API calls for all endpoints tagged `TargetingTemplates`.
"""
alias GoogleApi.DFAReporting.V35.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets one targeting template by ID.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V35.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `id` (*type:* `String.t`) - Targeting template ID.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V35.Model.TargetingTemplate{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_targeting_templates_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V35.Model.TargetingTemplate.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def dfareporting_targeting_templates_get(
connection,
profile_id,
id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/dfareporting/v3.5/userprofiles/{profileId}/targetingTemplates/{id}", %{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1),
"id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V35.Model.TargetingTemplate{}])
end
@doc """
Inserts a new targeting template.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V35.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").
* `:body` (*type:* `GoogleApi.DFAReporting.V35.Model.TargetingTemplate.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V35.Model.TargetingTemplate{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_targeting_templates_insert(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V35.Model.TargetingTemplate.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def dfareporting_targeting_templates_insert(
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,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/dfareporting/v3.5/userprofiles/{profileId}/targetingTemplates", %{
"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.V35.Model.TargetingTemplate{}])
end
@doc """
Retrieves a list of targeting templates, optionally filtered. This method supports paging.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V35.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").
* `:advertiserId` (*type:* `String.t`) - Select only targeting templates with this advertiser ID.
* `:ids` (*type:* `list(String.t)`) - Select only targeting templates with these IDs.
* `:maxResults` (*type:* `integer()`) - Maximum number of results to return.
* `:pageToken` (*type:* `String.t`) - Value of the nextPageToken from the previous result page.
* `:searchString` (*type:* `String.t`) - Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "template*2015" will return objects with names like "template June 2015", "template April 2015", or simply "template 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "template" will match objects with name "my template", "template 2015", or simply "template".
* `:sortField` (*type:* `String.t`) - Field by which to sort the list.
* `:sortOrder` (*type:* `String.t`) - Order of sorted results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V35.Model.TargetingTemplatesListResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_targeting_templates_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V35.Model.TargetingTemplatesListResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def dfareporting_targeting_templates_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,
:advertiserId => :query,
:ids => :query,
:maxResults => :query,
:pageToken => :query,
:searchString => :query,
:sortField => :query,
:sortOrder => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/dfareporting/v3.5/userprofiles/{profileId}/targetingTemplates", %{
"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.V35.Model.TargetingTemplatesListResponse{}]
)
end
@doc """
Updates an existing targeting template. This method supports patch semantics.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V35.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `id` (*type:* `String.t`) - TargetingTemplate ID.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.DFAReporting.V35.Model.TargetingTemplate.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V35.Model.TargetingTemplate{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_targeting_templates_patch(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V35.Model.TargetingTemplate.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def dfareporting_targeting_templates_patch(
connection,
profile_id,
id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/dfareporting/v3.5/userprofiles/{profileId}/targetingTemplates", %{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1)
})
|> Request.add_param(:query, :id, id)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V35.Model.TargetingTemplate{}])
end
@doc """
Updates an existing targeting template.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V35.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").
* `:body` (*type:* `GoogleApi.DFAReporting.V35.Model.TargetingTemplate.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V35.Model.TargetingTemplate{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_targeting_templates_update(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V35.Model.TargetingTemplate.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def dfareporting_targeting_templates_update(
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,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/dfareporting/v3.5/userprofiles/{profileId}/targetingTemplates", %{
"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.V35.Model.TargetingTemplate{}])
end
end
| 43.691176 | 480 | 0.614888 |
73be6bce1b873c602b173dffbe31b23259a4e5bc | 705 | ex | Elixir | lib/cotoami_web/gettext.ex | reallinfo/cotoami | faaee71710019fa55a8215ea60d1d3bafc30d506 | [
"Apache-2.0"
] | 337 | 2016-11-28T15:46:58.000Z | 2022-03-01T06:21:25.000Z | lib/cotoami_web/gettext.ex | reallinfo/cotoami | faaee71710019fa55a8215ea60d1d3bafc30d506 | [
"Apache-2.0"
] | 79 | 2017-02-27T05:44:36.000Z | 2021-12-09T00:28:11.000Z | lib/cotoami_web/gettext.ex | reallinfo/cotoami | faaee71710019fa55a8215ea60d1d3bafc30d506 | [
"Apache-2.0"
] | 47 | 2018-02-03T01:32:13.000Z | 2021-11-08T07:54:43.000Z | defmodule CotoamiWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import Cotoami.Gettext
# Simple translation
gettext "Here is the string to translate"
# Plural translation
ngettext "Here is the string to translate",
"Here are the strings to translate",
3
# Domain-based translation
dgettext "errors", "Here is the error message to translate"
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :cotoami
end
| 28.2 | 72 | 0.679433 |
73be6e467ece8363cd0aab5b18c3607277dc2cf5 | 884 | ex | Elixir | clients/app_engine/lib/google_api/app_engine/v1/metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/app_engine/lib/google_api/app_engine/v1/metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/app_engine/lib/google_api/app_engine/v1/metadata.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.AppEngine.V1 do
@moduledoc """
API client metadata for GoogleApi.AppEngine.V1.
"""
@discovery_revision "20211016"
def discovery_revision(), do: @discovery_revision
end
| 32.740741 | 74 | 0.75905 |
73be70e5159d9ff23057808c0265eb325b4292df | 1,402 | ex | Elixir | apps/ello_events/lib/sidekiq.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 16 | 2017-06-21T21:31:20.000Z | 2021-05-09T03:23:26.000Z | apps/ello_events/lib/sidekiq.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 25 | 2017-06-07T12:18:28.000Z | 2018-06-08T13:27:43.000Z | apps/ello_events/lib/sidekiq.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 3 | 2018-06-14T15:34:07.000Z | 2022-02-28T21:06:13.000Z | defmodule Ello.Events.Sidekiq do
@doc "Sidekiq queue to enqueue in"
@callback queue() :: String.t
@doc "Sidekiq worker to process the event"
@callback worker() :: String.t
@doc "List of arguments to pass into Sidekiq"
@callback args(opts :: struct) :: [any()]
defmacro __using__(_) do
quote do
@behaviour Ello.Events
@behaviour Ello.Events.Sidekiq
def handler, do: Ello.Events.Sidekiq
def queue, do: "default"
def worker, do: List.last(Module.split(__MODULE__))
defoverridable [queue: 0, worker: 0, handler: 0]
end
end
def publish(module, struct) do
Task.async fn ->
payload = module
|> build_job(struct)
|> Jason.encode!()
redis(["LPUSH", "sidekiq:queue:#{module.queue()}", payload])
end
end
@max_retries 10
defp build_job(module, struct) do
%{
queue: module.queue,
retry: @max_retries,
class: module.worker,
args: module.args(struct),
jid: UUID.uuid4,
enqueued_at: unix_now_float(),
}
end
defp unix_now_float do
DateTime.to_unix(DateTime.utc_now(), :microsecond) / 1_000_000
end
defp redis(args) do
case Application.get_env(:ello_events, :redis, {Ello.Core.Redis, :command}) do
{mod, fun} -> apply(mod, fun, [args])
fun when is_function(fun, 1) -> fun.(args)
end
end
end
| 23.366667 | 82 | 0.615549 |
73beb5de50ce41702b18dd06081b5d5e83d15520 | 1,142 | exs | Elixir | mix.exs | secoint/faker | 36d0a1a38fd4dc5a53e732e16223e64eb54ff305 | [
"MIT"
] | null | null | null | mix.exs | secoint/faker | 36d0a1a38fd4dc5a53e732e16223e64eb54ff305 | [
"MIT"
] | null | null | null | mix.exs | secoint/faker | 36d0a1a38fd4dc5a53e732e16223e64eb54ff305 | [
"MIT"
] | null | null | null | defmodule Faker.Mixfile do
use Mix.Project
@version "0.12.0"
def project do
[
app: :faker,
version: @version,
elixir: "~> 1.4",
description: "Faker is a pure Elixir library for generating fake data.",
package: package(),
name: "Faker",
source_url: "https://github.com/igas/faker",
deps: deps(),
dialyzer: [
flags: [
:error_handling,
:race_conditions,
:underspecs
]
]
]
end
def application do
[
applications: [:crypto],
env: env()
]
end
defp env do
[
locale: :en,
country: nil,
random_module: Faker.Random.Elixir
]
end
defp deps do
[
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false},
{:earmark, ">= 0.0.0", only: :dev, runtime: false},
{:credo, ">= 0.0.0", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 0.5", only: [:dev], runtime: false}
]
end
defp package do
%{
files: ["lib", "mix.exs", "mix.lock"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/igas/faker"}
}
end
end
| 19.689655 | 78 | 0.510508 |
73bec19886624032102dffd6d0b79b8360492927 | 836 | ex | Elixir | lib/grizzly/zwave/commands/thermostat_mode_supported_get.ex | smartrent/grizzly | 65a397ea7bfedb5518fe63a3f058a0b6af473e39 | [
"Apache-2.0"
] | 76 | 2019-09-04T16:56:58.000Z | 2022-03-29T06:54:36.000Z | lib/grizzly/zwave/commands/thermostat_mode_supported_get.ex | smartrent/grizzly | 65a397ea7bfedb5518fe63a3f058a0b6af473e39 | [
"Apache-2.0"
] | 124 | 2019-09-05T14:01:24.000Z | 2022-02-28T22:58:14.000Z | lib/grizzly/zwave/commands/thermostat_mode_supported_get.ex | smartrent/grizzly | 65a397ea7bfedb5518fe63a3f058a0b6af473e39 | [
"Apache-2.0"
] | 10 | 2019-10-23T19:25:45.000Z | 2021-11-17T13:21:20.000Z | defmodule Grizzly.ZWave.Commands.ThermostatModeSupportedGet do
@moduledoc """
This module implements command THERMOSTAT_MODE_SUPPORTED_GET of the
COMMAND_CLASS_THERMOSTAT_MODE command class.
This command is used to query the thermostat's supported modes.
"""
@behaviour Grizzly.ZWave.Command
alias Grizzly.ZWave.Command
alias Grizzly.ZWave.CommandClasses.ThermostatMode
@impl Grizzly.ZWave.Command
@spec new([]) :: {:ok, Command.t()}
def new(_opts \\ []) do
command = %Command{
name: :thermostat_mode_supported_get,
command_byte: 0x04,
command_class: ThermostatMode,
impl: __MODULE__
}
{:ok, command}
end
@impl Grizzly.ZWave.Command
def encode_params(_command) do
<<>>
end
@impl Grizzly.ZWave.Command
def decode_params(_binary) do
{:ok, []}
end
end
| 22.594595 | 69 | 0.710526 |
73bec33983fb9ac9b050f0b2e08ef5b47efb2fba | 1,339 | ex | Elixir | lib/phone/nanp/us.ex | net/phone | 18e1356d2f8d32fe3f95638c3c44bceab0164fb2 | [
"Apache-2.0"
] | null | null | null | lib/phone/nanp/us.ex | net/phone | 18e1356d2f8d32fe3f95638c3c44bceab0164fb2 | [
"Apache-2.0"
] | null | null | null | lib/phone/nanp/us.ex | net/phone | 18e1356d2f8d32fe3f95638c3c44bceab0164fb2 | [
"Apache-2.0"
] | null | null | null | defmodule Phone.NANP.US do
@moduledoc false
use Helper.Country
def country, do: "United States"
def a2, do: "US"
def a3, do: "USA"
matcher :modules, [Phone.NANP.US.AK, Phone.NANP.US.AL, Phone.NANP.US.AR, Phone.NANP.US.AZ,
Phone.NANP.US.CA, Phone.NANP.US.CO, Phone.NANP.US.CT, Phone.NANP.US.DC,
Phone.NANP.US.DE, Phone.NANP.US.FL, Phone.NANP.US.GA, Phone.NANP.US.HI,
Phone.NANP.US.IA, Phone.NANP.US.ID, Phone.NANP.US.IL, Phone.NANP.US.IN,
Phone.NANP.US.KS, Phone.NANP.US.KY, Phone.NANP.US.LA, Phone.NANP.US.MA,
Phone.NANP.US.MD, Phone.NANP.US.ME, Phone.NANP.US.MI, Phone.NANP.US.MN,
Phone.NANP.US.MO, Phone.NANP.US.MS, Phone.NANP.US.MT, Phone.NANP.US.NC,
Phone.NANP.US.ND, Phone.NANP.US.NE, Phone.NANP.US.NH, Phone.NANP.US.NJ,
Phone.NANP.US.NM, Phone.NANP.US.NV, Phone.NANP.US.NY, Phone.NANP.US.OH,
Phone.NANP.US.OK, Phone.NANP.US.OR, Phone.NANP.US.PA, Phone.NANP.US.RI,
Phone.NANP.US.SC, Phone.NANP.US.SD, Phone.NANP.US.TN, Phone.NANP.US.TX,
Phone.NANP.US.UT, Phone.NANP.US.VT, Phone.NANP.US.VA, Phone.NANP.US.WA,
Phone.NANP.US.WI, Phone.NANP.US.WV, Phone.NANP.US.WY]
end
| 55.791667 | 92 | 0.57879 |
73bede1e97a90ec01185cc1e8a59a11828289e69 | 2,055 | exs | Elixir | test/jwt/algorithm/hmac_test.exs | tzumby/elixir-jwt | 1e44bef4d1f706062050fedad79bdd9b3b4d81a5 | [
"MIT"
] | 13 | 2017-05-15T13:37:11.000Z | 2021-07-29T23:06:23.000Z | test/jwt/algorithm/hmac_test.exs | tzumby/elixir-jwt | 1e44bef4d1f706062050fedad79bdd9b3b4d81a5 | [
"MIT"
] | 7 | 2019-01-26T12:42:24.000Z | 2021-03-16T23:01:00.000Z | test/jwt/algorithm/hmac_test.exs | tzumby/elixir-jwt | 1e44bef4d1f706062050fedad79bdd9b3b4d81a5 | [
"MIT"
] | 3 | 2019-07-26T06:03:48.000Z | 2020-01-14T20:42:55.000Z | defmodule JWT.Algorithm.HmacTest do
use ExUnit.Case
alias JWT.Algorithm.Hmac
doctest Hmac
@hs256_key "gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9C"
@hs384_key "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS"
@hs512_key "ysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hc"
@signing_input_0 "{\"iss\":\"joe\",\"exp\":1300819380,\"http://example.com/is_root\":true}"
@signing_input_1 "{\"iss\":\"mike\",\"exp\":1300819380,\"http://example.com/is_root\":false}"
defp detect_changed_input_or_mac(sha_bits, key) do
mac_0 = Hmac.sign(sha_bits, key, @signing_input_0)
assert Hmac.verify?(mac_0, sha_bits, key, @signing_input_0)
refute Hmac.verify?(mac_0, sha_bits, key, @signing_input_1)
mac_1 = Hmac.sign(sha_bits, key, @signing_input_1)
refute Hmac.verify?(mac_1, sha_bits, key, @signing_input_0)
assert Hmac.verify?(mac_1, sha_bits, key, @signing_input_1)
end
test "HS256 sign/3 and verify?/4", do: detect_changed_input_or_mac(:sha256, @hs256_key)
test "HS384 sign/3 and verify?/4", do: detect_changed_input_or_mac(:sha384, @hs384_key)
test "HS512 sign/3 and verify?/4", do: detect_changed_input_or_mac(:sha512, @hs512_key)
test "changed key returns verify?/4 false" do
sha_bits = :sha256
key_1 = "gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9Z"
mac = Hmac.sign(sha_bits, @hs256_key, @signing_input_0)
assert Hmac.verify?(mac, sha_bits, @hs256_key, @signing_input_0)
refute Hmac.verify?(mac, sha_bits, key_1, @signing_input_0)
end
# param validation
test "sign/3 w unrecognized sha_bits raises" do
assert_raise FunctionClauseError, fn ->
Hmac.sign(:sha257, @hs256_key, @signing_input_0)
end
end
test "sign/3 w :sha256 w key length (31) < MAC length (32) raises" do
assert_raise JWT.SecurityError, fn ->
Hmac.sign(:sha256, "gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9", @signing_input_0)
end
end
test "sign/3 w :sha256 w key length == MAC length (32)" do
mac = Hmac.sign(:sha256, @hs256_key, @signing_input_0)
assert byte_size(mac) == 32
end
end
| 36.052632 | 95 | 0.724574 |
73bedf84020152576c8ef04961de3f6e2e94e182 | 2,621 | ex | Elixir | lib/option.ex | kianmeng/artificery | 6322217f8c028d77254a4cefc8a06c8a0864c736 | [
"Apache-2.0"
] | null | null | null | lib/option.ex | kianmeng/artificery | 6322217f8c028d77254a4cefc8a06c8a0864c736 | [
"Apache-2.0"
] | null | null | null | lib/option.ex | kianmeng/artificery | 6322217f8c028d77254a4cefc8a06c8a0864c736 | [
"Apache-2.0"
] | null | null | null | defmodule Artificery.Option do
@moduledoc false
defstruct name: nil,
type: :string,
help: nil,
flags: %{}
# These mimic those accepted by OptionParser
@type option_type :: :boolean
| :integer
| :float
| :string
| :count
| :keep
@type t :: %__MODULE__{
name: atom,
type: option_type,
help: nil | String.t,
flags: map
}
@valid_flags [
:required,
:default,
:alias,
:transform,
:hidden,
:accumulate
]
@doc """
Creates a new Option struct
"""
@spec new(atom, map) :: t
def new(name, flags) when is_atom(name) and is_map(flags) do
type = Map.get(flags, :type) || :string
help = Map.get(flags, :help)
{_, flags} = Map.split(flags, [:type, :help])
%__MODULE__{
name: name,
type: type,
help: help,
flags: flags
}
end
@doc """
Validates the Option struct, raising an error if invalid
"""
@spec validate!(t, [caller: module]) :: :ok | no_return
def validate!(%__MODULE__{flags: flags}, caller: caller) do
validate_flags!(caller, flags)
end
defp validate_flags!(caller, flags) when is_map(flags) do
do_validate_flags!(caller, Map.to_list(flags))
end
defp do_validate_flags!(_caller, []), do: :ok
defp do_validate_flags!(caller, [{:transform, transform} | rest]) do
case transform do
nil ->
:ok
f when is_function(f, 1) ->
:ok
a when is_atom(a) ->
:ok
{m, f, a} when is_atom(m) and is_atom(f) and is_list(a) ->
arity = length(a) + 1
if function_exported?(m, f, arity) do
:ok
else
raise "Invalid transform: #{m}.#{f}/#{arity} is either undefined or not exported!"
end
end
do_validate_flags!(caller, rest)
end
defp do_validate_flags!(caller, [{bool_flag, v} | rest]) when bool_flag in [:required, :hidden] do
if is_boolean(v) do
:ok
else
raise "Invalid value for '#{inspect bool_flag}' - should be true or false, got: #{inspect v}"
end
do_validate_flags!(caller, rest)
end
defp do_validate_flags!(caller, [{flag, _} | rest]) when is_atom(flag) do
if flag in @valid_flags do
:ok
else
invalid_flag = Atom.to_string(flag)
closest =
@valid_flags
|> Enum.map(&Atom.to_string/1)
|> Enum.max_by(fn f -> String.jaro_distance(invalid_flag, f) end)
raise "Invalid option flag '#{invalid_flag}', did you mean '#{closest}'?"
end
do_validate_flags!(caller, rest)
end
end
| 25.950495 | 100 | 0.581076 |
73bedf9eb5e814e2e280015fe06dd6876e0b3cb2 | 325 | exs | Elixir | priv/repo/migrations/20170406200237_create_awesome_list_section.exs | sprql/awesome_elixir | ae1a372bf3060142a546aaf6cb28ffda491d9fa0 | [
"MIT"
] | 1 | 2017-04-13T05:37:08.000Z | 2017-04-13T05:37:08.000Z | priv/repo/migrations/20170406200237_create_awesome_list_section.exs | sprql/awesome_elixir | ae1a372bf3060142a546aaf6cb28ffda491d9fa0 | [
"MIT"
] | null | null | null | priv/repo/migrations/20170406200237_create_awesome_list_section.exs | sprql/awesome_elixir | ae1a372bf3060142a546aaf6cb28ffda491d9fa0 | [
"MIT"
] | null | null | null | defmodule AwesomeElixir.Repo.Migrations.CreateAwesomeElixir.AwesomeList.Section do
use Ecto.Migration
def change do
create table(:awesome_list_sections) do
add :name, :string
add :description, :string
timestamps()
end
create index(:awesome_list_sections, [:name], unique: true)
end
end
| 21.666667 | 82 | 0.72 |
73bef68ffe293a20e5e8bfd27a6256721bb6987b | 1,542 | exs | Elixir | mix.exs | appcues/jorb | 4aad0ae440b18374ff1d37cb4780e812f48b704e | [
"MIT"
] | null | null | null | mix.exs | appcues/jorb | 4aad0ae440b18374ff1d37cb4780e812f48b704e | [
"MIT"
] | 7 | 2018-02-08T21:48:39.000Z | 2019-10-16T19:53:18.000Z | mix.exs | appcues/jorb | 4aad0ae440b18374ff1d37cb4780e812f48b704e | [
"MIT"
] | null | null | null | defmodule Jorb.Mixfile do
use Mix.Project
def project do
[
app: :jorb,
version: "0.4.1",
elixir: "~> 1.5",
start_permanent: Mix.env() == :prod,
deps: deps(),
name: "Jorb",
source_url: "https://github.com/appcues/jorb",
homepage_url: "http://hexdocs.pm/jorb",
description: "A simple job publisher/processor for Elixir",
docs: [main: "Jorb", extras: ["README.md"]],
files: ~w(mix.exs lib LICENSE.md README.md CHANGELOG.md),
package: [
maintainers: ["Andy LeClair"],
licenses: ["MIT"],
links: %{
"GitHub" => "https://github.com/appcues/jorb"
}
],
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
]
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {Jorb.Application, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:ex_aws, "~> 2.0"},
{:ex_aws_sqs, "~> 3.0"},
{:hackney, "~> 1.9"},
{:sweet_xml, "~> 0.6"},
{:poison, "~> 1.0"},
{:jason, "~> 1.0"},
{:uuid, "~> 1.1"},
{:ets_lock, "~> 0.2.1"},
{:ex_doc, "~> 0.19", only: :dev, runtime: false},
{:dialyxir, "~> 0.5", only: [:dev, :test], runtime: false},
{:excoveralls, "~> 0.11", only: :test}
]
end
end
| 26.135593 | 65 | 0.51751 |
73bef96752dc5af8fd258a1f56ef7f7205a70354 | 2,601 | ex | Elixir | lib/mix/tasks/ecto.drop.ex | larryweya/ecto | d0d1fd43f0f97856a119184163167a7e79574923 | [
"Apache-2.0"
] | 1 | 2019-05-03T08:51:16.000Z | 2019-05-03T08:51:16.000Z | lib/mix/tasks/ecto.drop.ex | larryweya/ecto | d0d1fd43f0f97856a119184163167a7e79574923 | [
"Apache-2.0"
] | 1 | 2020-07-17T10:07:44.000Z | 2020-07-17T10:07:44.000Z | lib/mix/tasks/ecto.drop.ex | larryweya/ecto | d0d1fd43f0f97856a119184163167a7e79574923 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Ecto.Drop do
use Mix.Task
import Mix.Ecto
@shortdoc "Drops the repository storage"
@default_opts [force: false]
@aliases [
f: :force,
q: :quiet,
r: :repo
]
@switches [
force: :boolean,
quiet: :boolean,
repo: [:keep, :string],
no_compile: :boolean,
no_deps_check: :boolean,
]
@moduledoc """
Drop the storage for the given repository.
The repositories to drop are the ones specified under the
`:ecto_repos` option in the current app configuration. However,
if the `-r` option is given, it replaces the `:ecto_repos` config.
Since Ecto tasks can only be executed once, if you need to drop
multiple repositories, set `:ecto_repos` accordingly or pass the `-r`
flag multiple times.
## Examples
mix ecto.drop
mix ecto.drop -r Custom.Repo
## Command line options
* `-r`, `--repo` - the repo to drop
* `-q`, `--quiet` - run the command quietly
* `-f`, `--force` - do not ask for confirmation when dropping the database.
Configuration is asked only when `:start_permanent` is set to true
(typically in production)
* `--no-compile` - do not compile before dropping
* `--no-deps-check` - do not compile before dropping
"""
@doc false
def run(args) do
repos = parse_repo(args)
{opts, _} = OptionParser.parse! args, strict: @switches, aliases: @aliases
opts = Keyword.merge(@default_opts, opts)
Enum.each repos, fn repo ->
ensure_repo(repo, args)
ensure_implements(repo.__adapter__, Ecto.Adapter.Storage,
"drop storage for #{inspect repo}")
if skip_safety_warnings?() or
opts[:force] or
Mix.shell.yes?("Are you sure you want to drop the database for repo #{inspect repo}?") do
drop_database(repo, opts)
end
end
end
defp skip_safety_warnings? do
Mix.Project.config[:start_permanent] != true
end
defp drop_database(repo, opts) do
case repo.__adapter__.storage_down(repo.config) do
:ok ->
unless opts[:quiet] do
Mix.shell.info "The database for #{inspect repo} has been dropped"
end
{:error, :already_down} ->
unless opts[:quiet] do
Mix.shell.info "The database for #{inspect repo} has already been dropped"
end
{:error, term} when is_binary(term) ->
Mix.raise "The database for #{inspect repo} couldn't be dropped: #{term}"
{:error, term} ->
Mix.raise "The database for #{inspect repo} couldn't be dropped: #{inspect term}"
end
end
end
| 28.9 | 98 | 0.635525 |
73bf05ec9f731c69328bb1872e207ede6d3ba5db | 884 | ex | Elixir | chapter2/challenges/exflight/lib/bookings/report.ex | mCodex/rocketseat-ignite-elixir | bdb48db778c36b2325c75a41b4d6f7ef77b03cf5 | [
"MIT"
] | 1 | 2021-07-23T19:48:27.000Z | 2021-07-23T19:48:27.000Z | chapter2/challenges/exflight/lib/bookings/report.ex | mCodex/rocketseat-ignite-elixir | bdb48db778c36b2325c75a41b4d6f7ef77b03cf5 | [
"MIT"
] | null | null | null | chapter2/challenges/exflight/lib/bookings/report.ex | mCodex/rocketseat-ignite-elixir | bdb48db778c36b2325c75a41b4d6f7ef77b03cf5 | [
"MIT"
] | null | null | null | defmodule Exflight.Bookings.Report do
alias Exflight.Bookings.Agent, as: BookingAgent
alias Exflight.Bookings.Booking
def generate_report(from_date, to_date, filename \\ "report.csv") do
bookings = BookingAgent.get_by_interval(from_date, to_date)
bookings_strings = parse_bookings_result(bookings)
generate_file(bookings_strings, filename)
end
defp parse_bookings_result(bookings) do
bookings
|> Enum.map(&booking_to_string/1)
end
defp booking_to_string(%Booking{
id: id,
id_usuario: id_usuario,
data_completa: data_completa,
cidade_origem: cidade_origem,
cidade_destino: cidade_destino
}) do
"#{id}, #{id_usuario}, #{data_completa}, #{cidade_origem}, #{cidade_destino}\n"
end
defp generate_file(bookings_string, filename) do
filename
|> File.write(bookings_string)
end
end
| 26.787879 | 83 | 0.713801 |
73bf1834c9c17da9ddf92596887092e575bd6a14 | 77 | exs | Elixir | config/test.exs | phpcitizen/rstwitter | 2d7d2d139a75cb590dcf67b66fff2341ec15dd4f | [
"MIT"
] | 2 | 2018-08-21T03:52:51.000Z | 2020-09-26T23:00:37.000Z | config/test.exs | phpcitizen/rstwitter | 2d7d2d139a75cb590dcf67b66fff2341ec15dd4f | [
"MIT"
] | 1 | 2019-06-17T09:58:23.000Z | 2019-06-17T09:58:23.000Z | config/test.exs | phpcitizen/rstwitter | 2d7d2d139a75cb590dcf67b66fff2341ec15dd4f | [
"MIT"
] | 2 | 2019-06-15T20:27:35.000Z | 2020-08-24T19:48:50.000Z | use Mix.Config
config :rs_twitter,
http_client: RsTwitter.Http.ClientMock
| 15.4 | 40 | 0.805195 |
73bf26c4bd78ef9b8250f8255879e4a01e265876 | 3,078 | ex | Elixir | lib/cforum_web/views/users/user_view.ex | MatthiasApsel/cforum_ex | 52c621a583182d82692b74694b0b2792ac23b8ff | [
"MIT"
] | null | null | null | lib/cforum_web/views/users/user_view.ex | MatthiasApsel/cforum_ex | 52c621a583182d82692b74694b0b2792ac23b8ff | [
"MIT"
] | null | null | null | lib/cforum_web/views/users/user_view.ex | MatthiasApsel/cforum_ex | 52c621a583182d82692b74694b0b2792ac23b8ff | [
"MIT"
] | null | null | null | defmodule CforumWeb.Users.UserView do
use CforumWeb, :view
alias Cforum.Tags.Tag
alias Cforum.ConfigManager
alias CforumWeb.Paginator
alias CforumWeb.Sortable
alias Cforum.Abilities
alias Cforum.ConfigManager
alias Cforum.Helpers
alias CforumWeb.Views.ViewHelpers
alias CforumWeb.Views.ViewHelpers.Path
def page_title(:index, _), do: gettext("Users")
def page_title(:show, assigns), do: gettext("User %{username}", username: assigns[:user].username)
def page_title(:show_messages, assigns),
do: gettext("All messages for user %{username}", username: assigns[:user].username)
def page_title(:show_scores, assigns),
do: gettext("All scores for user %{username}", username: assigns[:user].username)
def page_title(:show_votes, assigns), do: gettext("All votes for user %{username}", username: assigns[:user].username)
def page_title(:confirm_delete, assigns), do: gettext("Delete user %{username}", username: assigns[:user].username)
def page_title(:update, assigns), do: gettext("Edit profile: %{username}", username: assigns[:user].username)
def page_title(:edit, assigns), do: page_title(:update, assigns)
def page_heading(:index, _), do: gettext("Users")
def page_heading(:show, assigns), do: gettext("User %{username}", username: assigns[:user].username)
def page_heading(:show_messages, assigns),
do: gettext("All messages for user %{username}", username: assigns[:user].username)
def page_heading(:show_scores, assigns),
do: gettext("All scores for user %{username}", username: assigns[:user].username)
def page_heading(:show_votes, assigns),
do: gettext("All votes for user %{username}", username: assigns[:user].username)
def page_heading(:confirm_delete, assigns), do: gettext("Delete user %{username}", username: assigns[:user].username)
def page_heading(:update, assigns), do: page_title(:update, assigns)
def page_heading(:edit, assigns), do: page_heading(:update, assigns)
def body_id(:index, _), do: "users-index"
def body_id(:show, _), do: "users-show"
def body_id(:show_messages, _), do: "users-messages"
def body_id(:show_scores, _), do: "users-scores"
def body_id(:show_votes, _), do: "users-votes"
def body_id(:confirm_delete, _), do: "users-destroy"
def body_id(:update, _), do: "users-edit"
def body_id(:edit, conn), do: body_id(:update, conn)
def body_classes(:index, _), do: "users"
def body_classes(:show, _), do: "users show"
def body_classes(:show_messages, _), do: "users messages"
def body_classes(:show_scores, _), do: "users scores"
def body_classes(:show_votes, _), do: "users votes"
def body_classes(:confirm_delete, _), do: "users destroy"
def body_classes(:update, _), do: "users edit"
def body_classes(:edit, conn), do: body_classes(:update, conn)
def merge_default_config(setting, options) do
Enum.reduce(ConfigManager.user_config_keys(), options, fn key, opts ->
if Map.has_key?(opts, key),
do: opts,
else: Map.put(opts, String.to_atom(key), ConfigManager.conf(setting, key))
end)
end
end
| 42.164384 | 120 | 0.715075 |
73bf6daa56a0650f08890596ff0837a2fb7db977 | 144 | exs | Elixir | test/test_helper.exs | esl/sphinx | 2b514a713035512d80ab5d63f6945b1e11357b28 | [
"Apache-2.0"
] | 1 | 2021-03-11T23:23:34.000Z | 2021-03-11T23:23:34.000Z | test/test_helper.exs | filipevarjao/sphinx | ef9e3296ed134a6dbc448654541facf5d0792574 | [
"Apache-2.0"
] | 6 | 2019-12-04T19:42:33.000Z | 2019-12-19T16:27:15.000Z | test/test_helper.exs | esl/sphinx | 2b514a713035512d80ab5d63f6945b1e11357b28 | [
"Apache-2.0"
] | 2 | 2021-03-11T23:27:14.000Z | 2022-03-06T10:20:41.000Z | Application.ensure_all_started(:sphinx)
ExUnit.configure(exclude: :pending)
ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(Sphinx.Repo, :manual)
| 28.8 | 52 | 0.8125 |
73bf773a549a83276c3f90320530137a84b5e656 | 904 | ex | Elixir | clients/big_query_reservation/lib/google_api/big_query_reservation/v1/metadata.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/big_query_reservation/lib/google_api/big_query_reservation/v1/metadata.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/big_query_reservation/lib/google_api/big_query_reservation/v1/metadata.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.BigQueryReservation.V1 do
@moduledoc """
API client metadata for GoogleApi.BigQueryReservation.V1.
"""
@discovery_revision "20200516"
def discovery_revision(), do: @discovery_revision
end
| 33.481481 | 74 | 0.764381 |
73bfb95378aeafa885ad97f1e43527aaac1f1f4a | 1,102 | exs | Elixir | config/config.exs | web2solutions/inventory_management | 5ade39c983e344caa53db5fe4eb0684ba08b5dd1 | [
"MIT"
] | null | null | null | config/config.exs | web2solutions/inventory_management | 5ade39c983e344caa53db5fe4eb0684ba08b5dd1 | [
"MIT"
] | null | null | null | config/config.exs | web2solutions/inventory_management | 5ade39c983e344caa53db5fe4eb0684ba08b5dd1 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
# General application configuration
use Mix.Config
config :inventory_management,
ecto_repos: [InventoryManagement.Repo]
# Configures the endpoint
config :inventory_management, InventoryManagementWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "Aj8a+Lf7KR7+1Rf94z+Q01rA/rBIu134ts6IG5JO9CD4sNwqfGEtNMjq4kCTaQSe",
render_errors: [view: InventoryManagementWeb.ErrorView, accepts: ~w(json), layout: false],
pubsub_server: InventoryManagement.PubSub,
live_view: [signing_salt: "UyQ9xVaO"]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env()}.exs"
| 34.4375 | 92 | 0.783122 |
73bfba9971f72840283c7b0b56734a6058b390cb | 863 | ex | Elixir | apps/core/test/support/ops_factories/medication_dispense_factory.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 8 | 2019-06-14T11:34:49.000Z | 2021-08-05T19:14:24.000Z | apps/core/test/support/ops_factories/medication_dispense_factory.ex | edenlabllc/ehealth.api.public | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 1 | 2019-07-08T15:20:22.000Z | 2019-07-08T15:20:22.000Z | apps/core/test/support/ops_factories/medication_dispense_factory.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 6 | 2018-05-11T13:59:32.000Z | 2022-01-19T20:15:22.000Z | defmodule Core.OPSFactories.MedicationDispenseFactory do
@moduledoc false
alias Ecto.UUID
defmacro __using__(_opts) do
quote do
def medication_dispense_factory do
%{
id: UUID.generate(),
status: "NEW",
inserted_by: UUID.generate(),
updated_by: UUID.generate(),
is_active: true,
dispensed_at: to_string(Date.utc_today()),
party_id: UUID.generate(),
legal_entity_id: UUID.generate(),
payment_id: UUID.generate(),
payment_amount: 20.5,
division_id: UUID.generate(),
medical_program_id: UUID.generate(),
medication_request: nil,
medication_request_id: UUID.generate(),
inserted_at: NaiveDateTime.utc_now(),
updated_at: NaiveDateTime.utc_now()
}
end
end
end
end
| 27.83871 | 56 | 0.606025 |
73bfce69a31d1f1548b5ee98fc0354b683b9edc8 | 11,051 | ex | Elixir | lib/mapper/greek.ex | nikneroz/exconv | 31a9f424462f88024af3afb32d2cb80160f07ebf | [
"MIT"
] | null | null | null | lib/mapper/greek.ex | nikneroz/exconv | 31a9f424462f88024af3afb32d2cb80160f07ebf | [
"MIT"
] | 1 | 2020-07-16T09:38:33.000Z | 2020-07-16T09:38:33.000Z | lib/mapper/greek.ex | nikneroz/exconv | 31a9f424462f88024af3afb32d2cb80160f07ebf | [
"MIT"
] | null | null | null | defmodule Exconv.Mapper.Greek do
def to_unicode(255), do: 173 # <<194, 173>> | ""
def to_unicode(254), do: 944 # <<206, 176>> | "ΰ"
def to_unicode(253), do: 912 # <<206, 144>> | "ΐ"
def to_unicode(252), do: 971 # <<207, 139>> | "ϋ"
def to_unicode(251), do: 970 # <<207, 138>> | "ϊ"
def to_unicode(250), do: 950 # <<206, 182>> | "ζ"
def to_unicode(249), do: 965 # <<207, 133>> | "υ"
def to_unicode(248), do: 967 # <<207, 135>> | "χ"
def to_unicode(247), do: 962 # <<207, 130>> | "ς"
def to_unicode(246), do: 969 # <<207, 137>> | "ω"
def to_unicode(245), do: 952 # <<206, 184>> | "θ"
def to_unicode(244), do: 964 # <<207, 132>> | "τ"
def to_unicode(243), do: 963 # <<207, 131>> | "σ"
def to_unicode(242), do: 961 # <<207, 129>> | "ρ"
def to_unicode(241), do: 974 # <<207, 142>> | "ώ"
def to_unicode(240), do: 960 # <<207, 128>> | "π"
def to_unicode(239), do: 959 # <<206, 191>> | "ο"
def to_unicode(238), do: 957 # <<206, 189>> | "ν"
def to_unicode(237), do: 956 # <<206, 188>> | "μ"
def to_unicode(236), do: 955 # <<206, 187>> | "λ"
def to_unicode(235), do: 954 # <<206, 186>> | "κ"
def to_unicode(234), do: 958 # <<206, 190>> | "ξ"
def to_unicode(233), do: 953 # <<206, 185>> | "ι"
def to_unicode(232), do: 951 # <<206, 183>> | "η"
def to_unicode(231), do: 947 # <<206, 179>> | "γ"
def to_unicode(230), do: 966 # <<207, 134>> | "φ"
def to_unicode(229), do: 949 # <<206, 181>> | "ε"
def to_unicode(228), do: 948 # <<206, 180>> | "δ"
def to_unicode(227), do: 968 # <<207, 136>> | "ψ"
def to_unicode(226), do: 946 # <<206, 178>> | "β"
def to_unicode(225), do: 945 # <<206, 177>> | "α"
def to_unicode(224), do: 973 # <<207, 141>> | "ύ"
def to_unicode(223), do: 911 # <<206, 143>> | "Ώ"
def to_unicode(222), do: 972 # <<207, 140>> | "ό"
def to_unicode(221), do: 943 # <<206, 175>> | "ί"
def to_unicode(220), do: 942 # <<206, 174>> | "ή"
def to_unicode(219), do: 941 # <<206, 173>> | "έ"
def to_unicode(218), do: 910 # <<206, 142>> | "Ύ"
def to_unicode(217), do: 908 # <<206, 140>> | "Ό"
def to_unicode(216), do: 906 # <<206, 138>> | "Ί"
def to_unicode(215), do: 905 # <<206, 137>> | "Ή"
def to_unicode(214), do: 247 # <<195, 183>> | "÷"
def to_unicode(213), do: 8217 # <<226, 128, 153>> | "’"
def to_unicode(212), do: 8216 # <<226, 128, 152>> | "‘"
def to_unicode(211), do: 8221 # <<226, 128, 157>> | "”"
def to_unicode(210), do: 8220 # <<226, 128, 156>> | "“"
def to_unicode(209), do: 8213 # <<226, 128, 149>> | "―"
def to_unicode(208), do: 8211 # <<226, 128, 147>> | "–"
def to_unicode(207), do: 339 # <<197, 147>> | "œ"
def to_unicode(206), do: 904 # <<206, 136>> | "Έ"
def to_unicode(205), do: 902 # <<206, 134>> | "Ά"
def to_unicode(204), do: 935 # <<206, 167>> | "Χ"
def to_unicode(203), do: 933 # <<206, 165>> | "Υ"
def to_unicode(202), do: 160 # <<194, 160>> | " "
def to_unicode(201), do: 8230 # <<226, 128, 166>> | "…"
def to_unicode(200), do: 187 # <<194, 187>> | "»"
def to_unicode(199), do: 171 # <<194, 171>> | "«"
def to_unicode(198), do: 932 # <<206, 164>> | "Τ"
def to_unicode(197), do: 8776 # <<226, 137, 136>> | "≈"
def to_unicode(196), do: 929 # <<206, 161>> | "Ρ"
def to_unicode(195), do: 927 # <<206, 159>> | "Ο"
def to_unicode(194), do: 172 # <<194, 172>> | "¬"
def to_unicode(193), do: 925 # <<206, 157>> | "Ν"
def to_unicode(192), do: 940 # <<206, 172>> | "ά"
def to_unicode(191), do: 937 # <<206, 169>> | "Ω"
def to_unicode(190), do: 936 # <<206, 168>> | "Ψ"
def to_unicode(189), do: 939 # <<206, 171>> | "Ϋ"
def to_unicode(188), do: 934 # <<206, 166>> | "Φ"
def to_unicode(187), do: 924 # <<206, 156>> | "Μ"
def to_unicode(186), do: 922 # <<206, 154>> | "Κ"
def to_unicode(185), do: 921 # <<206, 153>> | "Ι"
def to_unicode(184), do: 919 # <<206, 151>> | "Η"
def to_unicode(183), do: 918 # <<206, 150>> | "Ζ"
def to_unicode(182), do: 917 # <<206, 149>> | "Ε"
def to_unicode(181), do: 914 # <<206, 146>> | "Β"
def to_unicode(180), do: 165 # <<194, 165>> | "¥"
def to_unicode(179), do: 8805 # <<226, 137, 165>> | "≥"
def to_unicode(178), do: 8804 # <<226, 137, 164>> | "≤"
def to_unicode(177), do: 177 # <<194, 177>> | "±"
def to_unicode(176), do: 913 # <<206, 145>> | "Α"
def to_unicode(175), do: 183 # <<194, 183>> | "·"
def to_unicode(174), do: 176 # <<194, 176>> | "°"
def to_unicode(173), do: 8800 # <<226, 137, 160>> | "≠"
def to_unicode(172), do: 167 # <<194, 167>> | "§"
def to_unicode(171), do: 938 # <<206, 170>> | "Ϊ"
def to_unicode(170), do: 931 # <<206, 163>> | "Σ"
def to_unicode(169), do: 169 # <<194, 169>> | "©"
def to_unicode(168), do: 174 # <<194, 174>> | "®"
def to_unicode(167), do: 223 # <<195, 159>> | "ß"
def to_unicode(166), do: 928 # <<206, 160>> | "Π"
def to_unicode(165), do: 926 # <<206, 158>> | "Ξ"
def to_unicode(164), do: 923 # <<206, 155>> | "Λ"
def to_unicode(163), do: 920 # <<206, 152>> | "Θ"
def to_unicode(162), do: 916 # <<206, 148>> | "Δ"
def to_unicode(161), do: 915 # <<206, 147>> | "Γ"
def to_unicode(160), do: 8224 # <<226, 128, 160>> | "†"
def to_unicode(159), do: 252 # <<195, 188>> | "ü"
def to_unicode(158), do: 251 # <<195, 187>> | "û"
def to_unicode(157), do: 249 # <<195, 185>> | "ù"
def to_unicode(156), do: 8364 # <<226, 130, 172>> | "€"
def to_unicode(155), do: 166 # <<194, 166>> | "¦"
def to_unicode(154), do: 246 # <<195, 182>> | "ö"
def to_unicode(153), do: 244 # <<195, 180>> | "ô"
def to_unicode(152), do: 8240 # <<226, 128, 176>> | "‰"
def to_unicode(151), do: 189 # <<194, 189>> | "½"
def to_unicode(150), do: 8226 # <<226, 128, 162>> | "•"
def to_unicode(149), do: 239 # <<195, 175>> | "ï"
def to_unicode(148), do: 238 # <<195, 174>> | "î"
def to_unicode(147), do: 8482 # <<226, 132, 162>> | "™"
def to_unicode(146), do: 163 # <<194, 163>> | "£"
def to_unicode(145), do: 235 # <<195, 171>> | "ë"
def to_unicode(144), do: 234 # <<195, 170>> | "ê"
def to_unicode(143), do: 232 # <<195, 168>> | "è"
def to_unicode(142), do: 233 # <<195, 169>> | "é"
def to_unicode(141), do: 231 # <<195, 167>> | "ç"
def to_unicode(140), do: 168 # <<194, 168>> | "¨"
def to_unicode(139), do: 900 # <<206, 132>> | "΄"
def to_unicode(138), do: 228 # <<195, 164>> | "ä"
def to_unicode(137), do: 226 # <<195, 162>> | "â"
def to_unicode(136), do: 224 # <<195, 160>> | "à"
def to_unicode(135), do: 901 # <<206, 133>> | "΅"
def to_unicode(134), do: 220 # <<195, 156>> | "Ü"
def to_unicode(133), do: 214 # <<195, 150>> | "Ö"
def to_unicode(132), do: 179 # <<194, 179>> | "³"
def to_unicode(131), do: 201 # <<195, 137>> | "É"
def to_unicode(130), do: 178 # <<194, 178>> | "²"
def to_unicode(129), do: 185 # <<194, 185>> | "¹"
def to_unicode(128), do: 196 # <<195, 132>> | "Ä"
def to_unicode(126), do: 126 # <<126>> | "~"
def to_unicode(125), do: 125 # <<125>> | "}"
def to_unicode(124), do: 124 # <<124>> | "|"
def to_unicode(123), do: 123 # <<123>> | "{"
def to_unicode(122), do: 122 # <<122>> | "z"
def to_unicode(121), do: 121 # <<121>> | "y"
def to_unicode(120), do: 120 # <<120>> | "x"
def to_unicode(119), do: 119 # <<119>> | "w"
def to_unicode(118), do: 118 # <<118>> | "v"
def to_unicode(117), do: 117 # <<117>> | "u"
def to_unicode(116), do: 116 # <<116>> | "t"
def to_unicode(115), do: 115 # <<115>> | "s"
def to_unicode(114), do: 114 # <<114>> | "r"
def to_unicode(113), do: 113 # <<113>> | "q"
def to_unicode(112), do: 112 # <<112>> | "p"
def to_unicode(111), do: 111 # <<111>> | "o"
def to_unicode(110), do: 110 # <<110>> | "n"
def to_unicode(109), do: 109 # <<109>> | "m"
def to_unicode(108), do: 108 # <<108>> | "l"
def to_unicode(107), do: 107 # <<107>> | "k"
def to_unicode(106), do: 106 # <<106>> | "j"
def to_unicode(105), do: 105 # <<105>> | "i"
def to_unicode(104), do: 104 # <<104>> | "h"
def to_unicode(103), do: 103 # <<103>> | "g"
def to_unicode(102), do: 102 # <<102>> | "f"
def to_unicode(101), do: 101 # <<101>> | "e"
def to_unicode(100), do: 100 # <<100>> | "d"
def to_unicode(99), do: 99 # <<99>> | "c"
def to_unicode(98), do: 98 # <<98>> | "b"
def to_unicode(97), do: 97 # <<97>> | "a"
def to_unicode(96), do: 96 # <<96>> | "`"
def to_unicode(95), do: 95 # <<95>> | "_"
def to_unicode(94), do: 94 # <<94>> | "^"
def to_unicode(93), do: 93 # <<93>> | "]"
def to_unicode(92), do: 92 # <<92>> | "\\"
def to_unicode(91), do: 91 # <<91>> | "["
def to_unicode(90), do: 90 # <<90>> | "Z"
def to_unicode(89), do: 89 # <<89>> | "Y"
def to_unicode(88), do: 88 # <<88>> | "X"
def to_unicode(87), do: 87 # <<87>> | "W"
def to_unicode(86), do: 86 # <<86>> | "V"
def to_unicode(85), do: 85 # <<85>> | "U"
def to_unicode(84), do: 84 # <<84>> | "T"
def to_unicode(83), do: 83 # <<83>> | "S"
def to_unicode(82), do: 82 # <<82>> | "R"
def to_unicode(81), do: 81 # <<81>> | "Q"
def to_unicode(80), do: 80 # <<80>> | "P"
def to_unicode(79), do: 79 # <<79>> | "O"
def to_unicode(78), do: 78 # <<78>> | "N"
def to_unicode(77), do: 77 # <<77>> | "M"
def to_unicode(76), do: 76 # <<76>> | "L"
def to_unicode(75), do: 75 # <<75>> | "K"
def to_unicode(74), do: 74 # <<74>> | "J"
def to_unicode(73), do: 73 # <<73>> | "I"
def to_unicode(72), do: 72 # <<72>> | "H"
def to_unicode(71), do: 71 # <<71>> | "G"
def to_unicode(70), do: 70 # <<70>> | "F"
def to_unicode(69), do: 69 # <<69>> | "E"
def to_unicode(68), do: 68 # <<68>> | "D"
def to_unicode(67), do: 67 # <<67>> | "C"
def to_unicode(66), do: 66 # <<66>> | "B"
def to_unicode(65), do: 65 # <<65>> | "A"
def to_unicode(64), do: 64 # <<64>> | "@"
def to_unicode(63), do: 63 # <<63>> | "?"
def to_unicode(62), do: 62 # <<62>> | ">"
def to_unicode(61), do: 61 # <<61>> | "="
def to_unicode(60), do: 60 # <<60>> | "<"
def to_unicode(59), do: 59 # <<59>> | ";"
def to_unicode(58), do: 58 # <<58>> | ":"
def to_unicode(57), do: 57 # <<57>> | "9"
def to_unicode(56), do: 56 # <<56>> | "8"
def to_unicode(55), do: 55 # <<55>> | "7"
def to_unicode(54), do: 54 # <<54>> | "6"
def to_unicode(53), do: 53 # <<53>> | "5"
def to_unicode(52), do: 52 # <<52>> | "4"
def to_unicode(51), do: 51 # <<51>> | "3"
def to_unicode(50), do: 50 # <<50>> | "2"
def to_unicode(49), do: 49 # <<49>> | "1"
def to_unicode(48), do: 48 # <<48>> | "0"
def to_unicode(47), do: 47 # <<47>> | "/"
def to_unicode(46), do: 46 # <<46>> | "."
def to_unicode(45), do: 45 # <<45>> | "-"
def to_unicode(44), do: 44 # <<44>> | ","
def to_unicode(43), do: 43 # <<43>> | "+"
def to_unicode(42), do: 42 # <<42>> | "*"
def to_unicode(41), do: 41 # <<41>> | ")"
def to_unicode(40), do: 40 # <<40>> | "("
def to_unicode(39), do: 39 # <<39>> | "'"
def to_unicode(38), do: 38 # <<38>> | "&"
def to_unicode(37), do: 37 # <<37>> | "%"
def to_unicode(36), do: 36 # <<36>> | "$"
def to_unicode(35), do: 35 # <<35>> | "#"
def to_unicode(34), do: 34 # <<34>> | "\""
def to_unicode(33), do: 33 # <<33>> | "!"
def to_unicode(32), do: 32 # <<32>> | " "
end | 49.115556 | 57 | 0.523392 |
73bfd0a47eb302e31663f8842c241dd22c5e71dc | 1,460 | ex | Elixir | lib/google_api/translate/v3beta1/model/gcs_source.ex | dungkvy/google_api_translate | 3c49bb93b921d4ca2a542fb3ca93bffe9dd0c51a | [
"Apache-2.0"
] | null | null | null | lib/google_api/translate/v3beta1/model/gcs_source.ex | dungkvy/google_api_translate | 3c49bb93b921d4ca2a542fb3ca93bffe9dd0c51a | [
"Apache-2.0"
] | null | null | null | lib/google_api/translate/v3beta1/model/gcs_source.ex | dungkvy/google_api_translate | 3c49bb93b921d4ca2a542fb3ca93bffe9dd0c51a | [
"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.Translate.V3beta1.Model.GcsSource do
@moduledoc """
The Google Cloud Storage location for the input content.
## Attributes
* `inputUri` (*type:* `String.t`, *default:* `nil`) - Required. Source data URI. For example, `gs://my_bucket/my_object`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:"inputUri" => String.t,
}
field(:"inputUri")
end
defimpl Poison.Decoder, for: GoogleApi.Translate.V3beta1.Model.GcsSource do
def decode(value, options) do
GoogleApi.Translate.V3beta1.Model.GcsSource.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Translate.V3beta1.Model.GcsSource do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 29.795918 | 125 | 0.732192 |
73bfd82260c73f0beb7addf4a35c9a8cc72476ea | 2,126 | exs | Elixir | test/queutils/blocking_producer_test.exs | Cantido/queutils | 5f5bade636eb54431502b7c11990ed72d7fdabf5 | [
"MIT"
] | 3 | 2020-05-27T11:19:29.000Z | 2021-03-24T20:03:01.000Z | test/queutils/blocking_producer_test.exs | Cantido/queutils | 5f5bade636eb54431502b7c11990ed72d7fdabf5 | [
"MIT"
] | 2 | 2020-11-06T04:33:01.000Z | 2022-02-24T11:05:36.000Z | test/queutils/blocking_producer_test.exs | Cantido/queutils | 5f5bade636eb54431502b7c11990ed72d7fdabf5 | [
"MIT"
] | null | null | null | defmodule Queutils.BlockingProducerTest do
use ExUnit.Case
alias Queutils.BlockingProducer
doctest Queutils.BlockingProducer
test "pushing with zero demand adds to the queue" do
pushed_item = make_ref()
state = %{
queue: [],
waiting: [],
demand: 0,
max_length: 1_000,
pushed_count: 0,
popped_count: 0
}
{:reply, :ok, [], new_state} =
BlockingProducer.handle_call({:push, pushed_item}, nil, state)
assert new_state.queue == [pushed_item]
assert new_state.pushed_count == 1
assert new_state.popped_count == 0
end
test "pushing with greather-than-zero demand emits the item immediately" do
pushed_item = make_ref()
state = %{
queue: [],
waiting: [],
demand: 1,
max_length: 1_000,
pushed_count: 0,
popped_count: 0
}
{:reply, :ok, [^pushed_item], new_state} =
BlockingProducer.handle_call({:push, pushed_item}, nil, state)
assert new_state.queue == []
assert new_state.pushed_count == 1
assert new_state.popped_count == 1
end
test "pushing with no demand and a full queue stores a ref to the caller" do
pushed_item = make_ref()
waiter = make_ref()
state = %{
queue: [],
waiting: [],
demand: 0,
max_length: 0,
pushed_count: 0,
popped_count: 0
}
{:noreply, [], new_state} =
BlockingProducer.handle_call({:push, pushed_item}, waiter, state)
assert new_state.waiting == [{waiter, pushed_item}]
assert new_state.pushed_count == 0
assert new_state.popped_count == 0
end
test "pushing onto a zero-length queue with demand emits the event immediately" do
pushed_item = make_ref()
state = %{
queue: [],
waiting: [],
demand: 1,
max_length: 0,
pushed_count: 0,
popped_count: 0
}
{:reply, :ok, [^pushed_item], new_state} =
BlockingProducer.handle_call({:push, pushed_item}, nil, state)
assert new_state.waiting == []
assert new_state.queue == []
assert new_state.pushed_count == 1
assert new_state.popped_count == 1
end
end
| 26.246914 | 84 | 0.631703 |
73bfdf304614ea84733268e6c10de8e99a178844 | 2,188 | ex | Elixir | clients/document_ai/lib/google_api/document_ai/v1/model/google_cloud_documentai_v1beta2_document_text_anchor.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | clients/document_ai/lib/google_api/document_ai/v1/model/google_cloud_documentai_v1beta2_document_text_anchor.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | clients/document_ai/lib/google_api/document_ai/v1/model/google_cloud_documentai_v1beta2_document_text_anchor.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1beta2DocumentTextAnchor do
@moduledoc """
Text reference indexing into the Document.text.
## Attributes
* `content` (*type:* `String.t`, *default:* `nil`) - Contains the content of the text span so that users do not have to look it up in the text_segments. It is always populated for formFields.
* `textSegments` (*type:* `list(GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1beta2DocumentTextAnchorTextSegment.t)`, *default:* `nil`) - The text segments from the Document.text.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:content => String.t() | nil,
:textSegments =>
list(
GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1beta2DocumentTextAnchorTextSegment.t()
)
| nil
}
field(:content)
field(:textSegments,
as: GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1beta2DocumentTextAnchorTextSegment,
type: :list
)
end
defimpl Poison.Decoder,
for: GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1beta2DocumentTextAnchor do
def decode(value, options) do
GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1beta2DocumentTextAnchor.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1beta2DocumentTextAnchor do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.730159 | 195 | 0.738117 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.