code
stringlengths 114
1.05M
| path
stringlengths 3
312
| quality_prob
float64 0.5
0.99
| learning_prob
float64 0.2
1
| filename
stringlengths 3
168
| kind
stringclasses 1
value |
---|---|---|---|---|---|
defmodule RallyApi.Rallyties do
@moduledoc """
This module contains shared functions for making things Rallyfied
"""
@createable_types [
allowed_attribute_value: "allowedattributevalue", attachment: "attachment",
attachment_content: "attachmentcontent", attribute_definition: "attributedefinition",
build: "build", build_definition: "builddefinition", change: "change", changeset: "changeset",
conversation_post: "conversationpost", defect: "defect", defect_suite: "defectsuite",
hierarchical_requirement: "hierarchicalrequirement", iteration: "iteration", milestone: "milestone",
feature: "portfolioitem/feature", initiative: "portfolioitem/initiative",
preference: "preference", preliminary_estimate: "preliminaryestimate", project: "project",
project_permission: "projectpermission", release: "release", scm_repository: "scmrepository",
state: "state", story: "hierarchicalrequirement", tag: "tag", task: "task",
test_case: "testcase", test_case_result: "testcaseresult", test_case_step: "testcasestep",
test_folder: "testfolder", test_set: "testset", time_entry_item: "timeentryitem",
time_entry_value: "timeentryvalue", type_definition: "typedefinition", user: "user",
user_iteration_capacity: "useriterationcapacity", web_link_definition: "weblinkdefinition",
workspace: "workspace", workspace_permission: "workspacepermission",
]
@doc """
Maps a snake_case `Atom` to the Rally Type for all _Createable_ objects in the Rally API
## Examples:
iex> RallyApi.Rallyties.createable_types[:feature]
"portfolioitem/feature"
iex> RallyApi.Rallyties.createable_types[:defect_suite]
"defectsuite"
"""
def createable_types, do: @createable_types
@deleteable_types [
allowed_attribute_value: "allowedattributevalue", attachment: "attachment",
attachment_content: "attachmentcontent", build: "build", build_definition: "builddefinition",
change: "change", changeset: "changeset", conversation_post: "conversationpost",
defect: "defect", defect_suite: "defectsuite", hierarchical_requirement: "hierarchicalrequirement",
iteration: "iteration", milestone: "milestone", feature: "portfolioitem/feature",
initiative: "portfolioitem/initiative", preference: "preference",
preliminary_estimate: "preliminaryestimate", project_permission: "projectpermission",
recycle_bin_entry: "recyclebinentry", release: "release", scm_repository: "scmrepository",
state: "state", story: "hierarchicalrequirement", task: "task", test_case: "testcase",
test_case_result: "testcaseresult", test_case_step: "testcasestep", test_folder: "testfolder",
test_set: "testset", time_entry_value: "timeentryvalue", time_entry_item: "timeentryitem",
type_definition: "typedefinition", user: "user", user_iteration_capacity: "useriterationcapacity",
workspace_permission: "workspacepermission",
]
@doc """
Maps a snake_case `Atom` to the Rally Type for all _Deleteable_ objects in the Rally API
## Examples:
iex> RallyApi.Rallyties.deleteable_types[:feature]
"portfolioitem/feature"
iex> RallyApi.Rallyties.deleteable_types[:defect_suite]
"defectsuite"
iex> RallyApi.Rallyties.deleteable_types[:workspace]
nil
"""
def deleteable_types, do: @deleteable_types
@queryable_types [
artifact: "artifact", artifact_notification: "artifactnotification", attachment: "attachment",
blocker: "blocker", build: "build", build_definition: "builddefinition",
change: "change", changeset: "changeset", conversation_post: "conversationpost",
defect: "defect", defect_suite: "defectsuite", hierarchical_requirement: "hierarchicalrequirement",
iteration: "iteration", iteration_cumulative_flow_data: "iterationcumulativeflowdata",
milestone: "milestone", portfolio_item: "portfolioitem", feature: "portfolioitem/feature",
initiative: "portfolioitem/initiative", preference: "preference",
preliminary_estimate: "preliminaryestimate", project: "project", project_permission: "projectpermission",
recycle_bin_entry: "recyclebinentry", release: "release",
release_cumulative_flow_data: "releasecumulativeflowdata", requirement: "requirement", revision: "revision",
schedulable_artifact: "schedulableartifact", scm_repository: "scmrepository", state: "state",
story: "hierarchicalrequirement", subscription: "subscription", tag: "tag",
task: "task", test_case: "testcase", test_case_result: "testcaseresult",
test_case_step: "testcasestep", test_folder: "testfolder", test_set: "testset",
time_entry_item: "timeentryitem", time_entry_value: "timeentryvalue", type_definition: "typedefinition",
user: "user", user_iteration_capacity: "useriterationcapacity", user_permission: "userpermission",
user_profile: "userprofile", workspace: "workspace", workspace_configuration: "workspaceconfiguration",
workspace_permission: "workspacepermission",
]
@doc """
Maps a snake_case `Atom` to the Rally Type for all _Queryable_ objects in the Rally API
## Examples:
iex> RallyApi.Rallyties.queryable_types[:story]
"hierarchicalrequirement"
iex> RallyApi.Rallyties.queryable_types[:defect_suite]
"defectsuite"
"""
def queryable_types, do: @queryable_types
@collectable_types [
allowed_query_operator: "AllowedQueryOperators", allowed_query_operators: "AllowedQueryOperators",
allowed_value: "AllowedValues", allowed_values: "AllowedValues",
artifact: "Artifacts", artifacts: "Artifacts",
attachment: "Attachments", attachments: "Attachments",
attribute: "Attributes", attributes: "Attributes",
build: "Builds", builds: "Builds",
build_definition: "BuildDefinitions", build_definitions: "BuildDefinitions",
change: "Changes", changes: "Changes",
changeset: "Changesets", changesets: "Changesets",
children: "Children",
collaborator: "Collaborators", collaborators: "Collaborators",
defect: "Defects", defects: "Defects",
defect_suite: "DefectSuites", defect_suites: "DefectSuites",
discussion: "Discussion", discussions: "Discussion",
duplicate: "Duplicates", duplicates: "Duplicates",
editor: "Editors", editors: "Editors",
iteration: "Iterations", iterations: "Iterations",
milestone: "Milestones", milestones: "Milestones",
predecessor: "Predecessors", predecessors: "Predecessors",
project: "Projects", projects: "Projects",
release: "Releases", releases: "Releases",
result: "Results", results: "Results",
revision: "Revisions", revisions: "Revisions",
step: "Steps", steps: "Steps",
successor: "Successors", successors: "Successors",
tag: "Tags", tags: "Tags",
task: "Tasks", tasks: "Tasks",
team_member: "TeamMembers", team_members: "TeamMembers",
team_membership: "TeamMemberships", team_memberships: "TeamMemberships",
test_case: "TestCases", test_cases: "TestCases",
test_set: "TestSets", test_sets: "TestSets",
type_definition: "TypeDefinitions", type_definitions: "TypeDefinitions",
user_iteration_capacity: "UserIterationCapacities", user_iteration_capacities: "UserIterationCapacities",
user_permission: "UserPermissions", user_permissions: "UserPermissions",
user_story: "UserStories", user_stories: "UserStories",
value: "Values", values: "Values",
workspace: "Workspaces", workspaces: "Workspaces",
]
@doc """
Maps a snake_case `Atom` to the Rally Type for all _Collection_ objects in the Rally API.
The map includes both singular and plural mappings.
## Examples:
iex> RallyApi.Rallyties.collectable_types[:release]
"Releases"
iex> RallyApi.Rallyties.collectable_types[:releases]
"Releases"
"""
def collectable_types, do: @collectable_types
@doc """
Rally uses the `_ref` value frequently when making reference to a REST Resource in the API.
The `get_ref` function finds the `_ref` key from the given `Map`.
"""
def get_ref(%{"_ref" => ref}), do: ref
def get_ref(object) when is_map(object) do
object
|> Map.values
|> List.first
|> get_ref
end
@doc """
Rally expects the body JSON to have the Object Type as the root attibute.
This function takes a `Map` and prepends the Object Type if it is not
already the root attribute.
## Examples:
iex> RallyApi.Rallyties.wrap_attributes_with_rally_type(:defect, %{"Name" => "A Defect"})
%{"Defect" => %{"Name" => "A Defect"}}
iex> RallyApi.Rallyties.wrap_attributes_with_rally_type(:defect, %{"Defect" => %{"Name" => "A Defect"}})
%{"Defect" => %{"Name" => "A Defect"}}
iex> RallyApi.Rallyties.wrap_attributes_with_rally_type(:conversation_post, %{"Artifact" => "path/to/artifact"})
%{"ConversationPost" => %{"Artifact" => "path/to/artifact"}}
"""
def wrap_attributes_with_rally_type(type, attrs) when is_map(attrs) do
root = type
|> Atom.to_string
|> Macro.camelize
case attrs do
%{^root => _} -> attrs
_ -> %{root => attrs}
end
end
end
|
lib/rally_api/rallyties.ex
| 0.864382 | 0.612049 |
rallyties.ex
|
starcoder
|
defmodule Okta.Apps do
@moduledoc """
The `Okta.Apps` module provides access methods to the [Okta Apps API](https://developer.okta.com/docs/reference/api/apps/).
All methods require a Tesla Client struct created with `Okta.client(base_url, api_key)`.
## Examples
```
client = Okta.Client("https://dev-000000.okta.com", "<PASSWORD>")
{:ok, result, _env} = Okta.Groups.list_applications(client)
```
"""
@apps_url "/api/v1/apps"
@doc """
Adds a new application to your organization.
The `app` parameter is a map containing the app specific `name`, `signOnMode` and `settings`.
The API documentation has examples of different types of apps and the required parameters.
## Examples
```
client = Okta.Client("https://dev-000000.okta.com", "<PASSWORD>")
{:ok, result, _env} = Okta.Apps.add_application(client, %{
name: "bookmark", label: "Sample bookmark App", signOnMode: "BOOKMARK", settings: %{ app: %{ requestIntegration: false, url: "https://example.com/bookmark.htm"}}
})
```
https://developer.okta.com/docs/reference/api/apps/#add-application
"""
@spec add_application(Okta.client(), map(), boolean) :: Okta.result()
def add_application(client, app, activate \\ true) do
Tesla.post(client, @apps_url, app, query: [activate: activate]) |> Okta.result()
end
@doc """
Adds a new OAuth2 application to your organization.
The `label` parameter is a string readablle label for the applicatio, while `client_credentials` and `settings` are the configured of the application.
None of the values of `client_credentials` are required but `client_settings` have different requirements depending on what is set for `grant_types` (which is required) in `settings`
## Examples
```
Okta.Apps.add_oauth2_application(client,
"Label",
%{},
%{grant_types: ["implicit"],
redirect_uris: ["http://localhost:3000/implicit/callback"],
response_types: ["id_token", "token"],
application_type: "browser"})
```
The API documentation has examples of different types of apps and the required parameters.
https://developer.okta.com/docs/reference/api/apps/#add-oauth-2-0-client-application
"""
@spec add_oauth2_application(Okta.client(), String.t(), map(), map(), boolean()) ::
Okta.result()
def add_oauth2_application(client, label, client_credentials, client_settings, activate \\ true) do
add_application(
client,
%{
name: "oidc_client",
signOnMode: "OPENID_CONNECT",
label: label,
credentials: %{oauthClient: client_credentials},
settings: %{oauthClient: client_settings}
},
activate
)
end
@doc """
Fetches an application from your Okta organization by `application_id`.
https://developer.okta.com/docs/reference/api/apps/#get-application
"""
@spec get_application(Okta.client(), String.t()) :: Okta.result()
def get_application(client, application_id) do
Tesla.get(client, @apps_url <> "/#{application_id}") |> Okta.result()
end
@doc """
Enumerates apps added to your organization with pagination. A subset of apps can be returned that match a supported filter expression or query.
See API documentation for valid optional parameters
https://developer.okta.com/docs/reference/api/apps/#list-applications
"""
@spec list_applications(Okta.client(), keyword()) :: Okta.result()
def list_applications(client, opts \\ []) do
Tesla.get(client, @apps_url, query: opts) |> Okta.result()
end
@doc """
Enumerates apps added to your organization with pagination given a specific filter expression
https://developer.okta.com/docs/reference/api/apps/#list-applications
"""
@spec filter_applications(Okta.client(), String.t(), keyword()) :: Okta.result()
def filter_applications(client, filter, opts \\ []) do
list_applications(client, Keyword.merge(opts, filter: filter))
end
@doc """
Enumerates all applications assigned to a user and optionally embeds their Application User in a single response.
https://developer.okta.com/docs/reference/api/apps/#list-applications-assigned-to-user
"""
@spec list_applications_for_user(Okta.client(), String.t(), boolean, keyword()) :: Okta.result()
def list_applications_for_user(client, user_id, expand \\ false, opts \\ []) do
filter =
case expand do
true -> "user.id+eq+\"#{user_id}\"&expand=user/#{user_id}"
false -> "user.id+eq+\"#{user_id}\""
end
filter_applications(client, filter, opts)
end
@doc """
Enumerates all applications assigned to a group
https://developer.okta.com/docs/reference/api/apps/#list-applications-assigned-to-group
"""
@spec list_applications_for_group(Okta.client(), String.t(), keyword()) :: Okta.result()
def list_applications_for_group(client, group_id, opts \\ []) do
filter = "group.id+eq+\"#{group_id}\""
filter_applications(client, filter, opts)
end
@doc """
Enumerates all applications using a key.
https://developer.okta.com/docs/reference/api/apps/#list-applications-using-a-key
"""
@spec list_applications_for_key(Okta.client(), String.t(), keyword()) :: Okta.result()
def list_applications_for_key(client, key, opts \\ []) do
filter = "credentials.signing.kid+eq+\"#{key}\""
filter_applications(client, filter, opts)
end
@doc """
Updates an application in your organization.
https://developer.okta.com/docs/reference/api/apps/#update-application
"""
@spec update_application(Okta.client(), String.t(), map()) :: Okta.result()
def update_application(client, app_id, app) do
Tesla.put(client, @apps_url <> "/#{app_id}", app) |> Okta.result()
end
@doc """
Removes an inactive application.
https://developer.okta.com/docs/reference/api/apps/#delete-application
"""
@spec delete_application(Okta.client(), String.t()) :: Okta.result()
def delete_application(client, app_id) do
Tesla.delete(client, @apps_url <> "/#{app_id}") |> Okta.result()
end
@doc """
Activates an inactive application.
https://developer.okta.com/docs/reference/api/apps/#activate-application
"""
@spec activate_application(Okta.client(), String.t()) :: Okta.result()
def activate_application(client, app_id) do
Tesla.post(client, @apps_url <> "/#{app_id}" <> "/lifecycle/activate", %{}) |> Okta.result()
end
@doc """
Deactivates an active application.
https://developer.okta.com/docs/reference/api/apps/#deactivate-application
"""
@spec deactivate_application(Okta.client(), String.t()) :: Okta.result()
def deactivate_application(client, app_id) do
Tesla.post(client, @apps_url <> "/#{app_id}" <> "/lifecycle/deactivate", %{}) |> Okta.result()
end
@doc """
Assign a user to an application which can be done with and wihout application specific credentials and profile for SSO and provisioning
https://developer.okta.com/docs/reference/api/apps/#application-user-operations
"""
@spec assign_user_to_application(Okta.client(), String.t(), String.t(), map(), map()) ::
Okta.result()
def assign_user_to_application(client, app_id, user_id, credentials \\ %{}, profile \\ %{}) do
Tesla.post(client, @apps_url <> "/#{app_id}" <> "/users", %{
id: user_id,
scope: "USER",
credentials: credentials,
profile: profile
})
|> Okta.result()
end
@doc """
Fetches a specific user assignment for an application by id.
https://developer.okta.com/docs/reference/api/apps/#get-assigned-user-for-application
"""
@spec get_user_for_application(Okta.client(), String.t(), String.t()) :: Okta.result()
def get_user_for_application(client, application_id, user_id) do
Tesla.get(client, @apps_url <> "/#{application_id}" <> "/users/#{user_id}") |> Okta.result()
end
@doc """
Enumerates all assigned application users for an application.
https://developer.okta.com/docs/reference/api/apps/#list-users-assigned-to-application
"""
@spec list_users_for_application(Okta.client(), String.t(), keyword()) :: Okta.result()
def list_users_for_application(client, application_id, opts \\ []) do
Tesla.get(client, @apps_url <> "/#{application_id}" <> "/users", query: opts) |> Okta.result()
end
@doc """
Update a user for an application, either a profile, credentials or both can be provided.
https://developer.okta.com/docs/reference/api/apps/#update-application-credentials-for-assigned-user
"""
@spec update_user_for_application(
Okta.client(),
String.t(),
String.t(),
map() | nil,
map() | nil
) :: Okta.result()
def update_user_for_application(client, app_id, user_id, nil, profile),
do: update_user_for_applicationp(client, app_id, user_id, %{profile: profile})
def update_user_for_application(client, app_id, user_id, credentials, nil),
do: update_user_for_applicationp(client, app_id, user_id, %{credentials: credentials})
def update_user_for_application(client, app_id, user_id, credentials, profile),
do:
update_user_for_applicationp(client, app_id, user_id, %{
credentials: credentials,
profile: profile
})
defp update_user_for_applicationp(client, app_id, user_id, body) do
Tesla.post(client, @apps_url <> "/#{app_id}" <> "/users/#{user_id}", body) |> Okta.result()
end
@doc """
Removes an assignment for a user from an application.
https://developer.okta.com/docs/reference/api/apps/#remove-user-from-application
"""
@spec remove_user_from_application(Okta.client(), String.t(), String.t()) :: Okta.result()
def remove_user_from_application(client, app_id, user_id) do
Tesla.delete(client, @apps_url <> "/#{app_id}" <> "/users/#{user_id}") |> Okta.result()
end
@doc """
Assigns a group to an application
https://developer.okta.com/docs/reference/api/apps/#application-group-operations
"""
@spec assign_group_to_application(Okta.client(), String.t(), String.t(), map()) :: Okta.result()
def assign_group_to_application(client, app_id, group_id, app_group \\ %{}) do
Tesla.put(client, @apps_url <> "/#{app_id}" <> "/groups/#{group_id}", app_group)
|> Okta.result()
end
@doc """
Fetches an application group assignment
https://developer.okta.com/docs/reference/api/apps/#get-assigned-group-for-application
"""
@spec get_group_for_application(Okta.client(), String.t(), String.t()) :: Okta.result()
def get_group_for_application(client, application_id, group_id) do
Tesla.get(client, @apps_url <> "/#{application_id}" <> "/groups/#{group_id}") |> Okta.result()
end
@doc """
Enumerates group assignments for an application
https://developer.okta.com/docs/reference/api/apps/#list-groups-assigned-to-application
"""
@spec list_groups_for_application(Okta.client(), String.t(), keyword()) :: Okta.result()
def list_groups_for_application(client, application_id, opts \\ []) do
Tesla.get(client, @apps_url <> "/#{application_id}" <> "/groups", query: opts)
|> Okta.result()
end
@doc """
Removes a group assignment from an application.
https://developer.okta.com/docs/reference/api/apps/#remove-group-from-application
"""
@spec remove_group_from_application(Okta.client(), String.t(), String.t()) :: Okta.result()
def remove_group_from_application(client, app_id, group_id) do
Tesla.delete(client, @apps_url <> "/#{app_id}" <> "/groups/#{group_id}") |> Okta.result()
end
end
|
lib/okta/apps.ex
| 0.894487 | 0.705303 |
apps.ex
|
starcoder
|
defmodule Annex.Layer.Dense do
@moduledoc """
`rows` are the number outputs and `columns` are the number of inputs.
"""
use Annex.Debug, debug: true
alias Annex.{
Data,
Data.DMatrix,
Data.List1D,
Layer.Backprop,
Layer.Dense,
LayerConfig,
Shape,
Utils
}
require Data
use Annex.Layer
@type data :: Data.data()
@type t :: %__MODULE__{
data_type: Data.type(),
weights: data(),
biases: data(),
rows: pos_integer(),
columns: pos_integer(),
input: data() | nil,
output: data() | nil
}
defp default_data_type do
:annex
|> Application.get_env(__MODULE__, [])
|> Keyword.get(:data_type, DMatrix)
end
defstruct weights: nil,
biases: nil,
rows: nil,
columns: nil,
input: nil,
output: nil,
data_type: nil
@impl Layer
@spec init_layer(LayerConfig.t(Dense)) :: t() | no_return()
def init_layer(%LayerConfig{} = cfg) do
with(
{:ok, :data_type, data_type} <- build_data_type(cfg),
{:ok, :rows, rows} <- build_rows(cfg),
{:ok, :columns, columns} <- build_columns(cfg),
{:ok, :weights, weights} <- build_weights(cfg, data_type, rows, columns),
{:ok, :biases, biases} <- build_biases(cfg, data_type, rows)
) do
%Dense{
biases: biases,
weights: weights,
rows: rows,
columns: columns,
data_type: data_type
}
else
{:error, _field, error} ->
raise error
end
end
defp build_rows(cfg) do
with(
{:ok, :rows, rows} <- LayerConfig.fetch(cfg, :rows),
:ok <-
validate :rows, "must be a positive integer" do
is_int? = is_integer(rows)
is_positive? = rows > 0
is_int? && is_positive?
end
) do
{:ok, :rows, rows}
end
end
defp build_columns(cfg) do
with(
{:ok, :columns, columns} <- LayerConfig.fetch(cfg, :columns),
:ok <-
validate :columns, "must be a positive integer" do
is_int? = is_integer(columns)
is_positive? = columns > 0
is_int? && is_positive?
end
) do
{:ok, :columns, columns}
end
end
defp build_data_type(cfg) do
with(
{:ok, :data_type, data_type} <-
LayerConfig.fetch_lazy(cfg, :data_type, fn ->
default_data_type()
end),
:ok <-
validate :data_type, "must be a module" do
Utils.is_module?(data_type)
end
) do
{:ok, :data_type, data_type}
end
end
defp build_weights(cfg, data_type, rows, columns) do
with(
{:ok, :weights, weights} <-
LayerConfig.fetch_lazy(cfg, :weights, fn ->
List1D.new_random(rows * columns)
end),
:ok <-
validate :weights, "must be an Annex.Data" do
type = Data.infer_type(weights)
Data.is_type?(type, weights)
end,
:ok <-
validate :weights, "data size must be the same as the layer" do
[weights_rows, weights_columns] =
case Data.shape(weights) do
[w_rows] -> [w_rows, 1]
[w_rows, w_cols] -> [w_rows, w_cols]
end
weights_size = weights_rows * weights_columns
layer_size = rows * columns
weights_size == layer_size
end,
casted_weights <- Data.cast(data_type, weights, [rows, columns])
) do
{:ok, :weights, casted_weights}
end
end
defp build_biases(cfg, data_type, rows) do
with(
{:ok, :biases, biases} <-
LayerConfig.fetch_lazy(cfg, :biases, fn ->
List1D.ones(rows)
end),
:ok <-
validate :biases, "must be an Annex.Data" do
type = Data.infer_type(biases)
Data.is_type?(type, biases)
end,
:ok <-
validate :biases, "data size must match rows" do
[biases_rows, biases_columns] =
case Data.shape(biases) do
[b_rows] -> [b_rows, 1]
[b_rows, b_cols] -> [b_rows, b_cols]
end
biases_rows * biases_columns == rows
end,
casted_biases <- Data.cast(data_type, biases, [rows, 1])
) do
{:ok, :biases, casted_biases}
end
end
defp get_output(%Dense{output: o}), do: o
defp get_weights(%Dense{weights: weights}), do: weights
defp get_biases(%Dense{biases: biases}), do: biases
defp get_input(%Dense{input: input}), do: input
@spec rows(t()) :: pos_integer()
def rows(%Dense{rows: n}), do: n
@spec columns(t()) :: pos_integer()
def columns(%Dense{columns: n}), do: n
@impl Layer
@spec feedforward(t(), Data.data()) :: {t(), Data.data()}
def feedforward(%Dense{} = dense, inputs) do
debug_assert "Dense.feedforward/2 input must be dottable with the weights" do
weights = get_weights(dense)
[_, dense_columns] = Data.shape(weights)
[inputs_rows, _] = Data.shape(inputs)
dense_columns == inputs_rows
end
biases = get_biases(dense)
output =
dense
|> get_weights()
|> Data.apply_op(:dot, [inputs])
|> Data.apply_op(:add, [biases])
updated_dense = %Dense{
dense
| input: inputs,
output: output
}
{updated_dense, output}
end
@impl Layer
@spec backprop(t(), Data.data(), Backprop.t()) :: {t(), Data.data(), Backprop.t()}
def backprop(%Dense{} = dense, error, props) do
learning_rate = Backprop.get_learning_rate(props)
derivative = Backprop.get_derivative(props)
output = get_output(dense)
debug_assert "backprop error must have the same shape as output" do
output_shape = Data.shape(output)
error_shape = Data.shape(error)
output_shape == error_shape
end
weights = get_weights(dense)
input = get_input(dense)
biases = get_biases(dense)
gradients =
output
|> Data.apply_op(:map, [derivative])
|> Data.apply_op(:multiply, [error])
|> Data.apply_op(:multiply, [learning_rate])
input_t = Data.apply_op(input, :transpose, [])
debug_assert "gradients must be dottable with input_T" do
[_, gradients_cols] = Data.shape(gradients)
[input_rows, _] = Data.shape(input_t)
gradients_cols == input_rows
end
weight_deltas = Data.apply_op(gradients, :dot, [input_t])
updated_weights = Data.apply_op(weights, :subtract, [weight_deltas])
updated_biases = Data.apply_op(biases, :subtract, [gradients])
next_error =
weights
|> Data.apply_op(:transpose, [])
|> Data.apply_op(:dot, [error])
updated_dense = %Dense{
dense
| input: nil,
output: nil,
weights: updated_weights,
biases: updated_biases
}
{updated_dense, next_error, props}
end
@impl Layer
@spec data_type(t()) :: Data.type()
def data_type(%Dense{data_type: data_type}), do: data_type
@impl Layer
@spec shapes(t()) :: {Shape.t(), Shape.t()}
def shapes(%Dense{} = dense) do
rows = rows(dense)
columns = columns(dense)
{[rows, columns], [columns, rows]}
end
defimpl Inspect do
def inspect(dense, _) do
shapes =
dense
|> Dense.shapes()
|> Kernel.inspect()
data_type =
dense
|> Dense.data_type()
|> inspect()
"#Dense<[#{data_type}, #{shapes}]>"
end
end
end
|
lib/annex/layer/dense.ex
| 0.916794 | 0.64058 |
dense.ex
|
starcoder
|
defmodule Trans.Translator do
@moduledoc """
Provides easy access to struct translations.
Although translations are stored in regular fields of an struct and can be accessed directly, **it
is recommended to access translations using the functions provided by this module** instead. This
functions present additional behaviours such as:
* Checking that the given struct uses `Trans`
* Automatically inferring the [translation container](Trans.html#module-translation-container)
when needed.
* Falling back to the default value or raising if a translation does not exist.
* Translating entire structs.
All examples in this module assume the following article, based on the schema defined in
[Structured translations](Trans.html#module-structured-translations)
article = %MyApp.Article{
title: "How to Write a Spelling Corrector",
body: "A wonderful article by <NAME>",
translations: %MyApp.Article.Translations{
es: %MyApp.Article.Translation{
title: "Cómo escribir un corrector ortográfico",
body: "Un artículo maravilloso de <NAME>"
},
fr: %MyApp.Article.Translation{
title: "Comment écrire un correcteur orthographique",
body: "Un merveilleux article de <NAME>"
}
}
}
"""
defguardp is_locale(locale) when is_binary(locale) or is_atom(locale)
@doc """
Translate a whole struct into the given locale.
Translates the whole struct with all translatable values and translatable associations into the
given locale. Similar to `translate/3` but returns the whole struct.
## Examples
Assuming the example article in this module, we can translate the entire struct into Spanish:
# Translate the entire article into Spanish
article_es = Trans.Translator.translate(article, :es)
article_es.title #=> "Cómo escribir un corrector ortográfico"
article_es.body #=> "Un artículo maravilloso de <NAME>"
Just like `translate/3`, falls back to the default locale if the translation does not exist:
# The Deutsch translation does not exist
article_de = Trans.Translator.translate(article, :de)
article_de.title #=> "How to Write a Spelling Corrector"
article_de.body #=> "A wonderful article by <NAME>"
"""
@doc since: "2.3.0"
@spec translate(Trans.translatable(), Trans.locale()) :: Trans.translatable()
def translate(%{__struct__: module} = translatable, locale) when is_locale(locale) do
if Keyword.has_key?(module.__info__(:functions), :__trans__) do
translatable
|> translate_fields(locale)
|> translate_assocs(locale)
else
translatable
end
end
@doc """
Translate a single field into the given locale.
Translates the field into the given locale or falls back to the default value if there is no
translation available.
## Examples
Assuming the example article in this module:
# We can get the Spanish title:
Trans.Translator.translate(article, :title, :es)
"Cómo escribir un corrector ortográfico"
# If the requested locale is not available, the default value will be returned:
Trans.Translator.translate(article, :title, :de)
"How to Write a Spelling Corrector"
# If we request a translation for an invalid field, we will receive an error:
Trans.Translator.translate(article, :fake_attr, :es)
** (RuntimeError) 'Article' module must declare 'fake_attr' as translatable
"""
@spec translate(Trans.translatable(), atom, Trans.locale()) :: any
def translate(%{__struct__: module} = translatable, field, locale)
when is_locale(locale) and is_atom(field) do
unless Trans.translatable?(translatable, field) do
raise "'#{inspect(module)}' module must declare '#{inspect(field)}' as translatable"
end
# Return the translation or fall back to the default value
case translate_field(translatable, locale, field) do
:error -> Map.fetch!(translatable, field)
nil -> Map.fetch!(translatable, field)
translation -> translation
end
end
@doc """
Translate a single field into the given locale or raise if there is no translation.
Just like `translate/3` gets a translated field into the given locale. Raises if there is no
translation availabe.
## Examples
Assuming the example article in this module:
Trans.Translator.translate!(article, :title, :de)
** (RuntimeError) translation doesn't exist for field ':title' in language 'de'
"""
@doc since: "2.3.0"
@spec translate!(Trans.translatable(), atom, Trans.locale()) :: any
def translate!(%{__struct__: module} = translatable, field, locale)
when is_locale(locale) and is_atom(field) do
unless Trans.translatable?(translatable, field) do
raise "'#{inspect(module)}' module must declare '#{inspect(field)}' as translatable"
end
# Return the translation or fall back to the default value
case translate_field(translatable, locale, field) do
:error ->
raise "translation doesn't exist for field '#{inspect(field)}' in language '#{locale}'"
translation ->
translation
end
end
defp translate_field(%{__struct__: module} = struct, locale, field) do
with {:ok, all_translations} <- Map.fetch(struct, module.__trans__(:container)),
{:ok, translations_for_locale} <- get_translations_for_locale(all_translations, locale),
{:ok, translated_field} <- get_translated_field(translations_for_locale, field) do
translated_field
end
end
defp translate_fields(%{__struct__: module} = struct, locale) do
fields = module.__trans__(:fields)
Enum.reduce(fields, struct, fn field, struct ->
case translate_field(struct, locale, field) do
:error -> struct
translation -> Map.put(struct, field, translation)
end
end)
end
defp translate_assocs(%{__struct__: module} = struct, locale) do
associations = module.__schema__(:associations)
embeds = module.__schema__(:embeds)
Enum.reduce(associations ++ embeds, struct, fn assoc_name, struct ->
Map.update(struct, assoc_name, nil, fn
%Ecto.Association.NotLoaded{} = item ->
item
items when is_list(items) ->
Enum.map(items, &translate(&1, locale))
%{} = item ->
translate(item, locale)
item ->
item
end)
end)
end
# check if struct (means it's using ecto embeds); if so, make sure 'locale' is also atom
defp get_translations_for_locale(%{__struct__: _} = all_translations, locale)
when is_binary(locale) do
get_translations_for_locale(all_translations, String.to_existing_atom(locale))
end
defp get_translations_for_locale(%{__struct__: _} = all_translations, locale)
when is_atom(locale) do
Map.fetch(all_translations, locale)
end
# fallback to default behaviour
defp get_translations_for_locale(all_translations, locale) do
Map.fetch(all_translations, to_string(locale))
end
# there are no translations for this locale embed
defp get_translated_field(nil, _field), do: nil
# check if struct (means it's using ecto embeds); if so, make sure 'field' is also atom
defp get_translated_field(%{__struct__: _} = translations_for_locale, field)
when is_binary(field) do
get_translated_field(translations_for_locale, String.to_existing_atom(field))
end
defp get_translated_field(%{__struct__: _} = translations_for_locale, field)
when is_atom(field) do
Map.fetch(translations_for_locale, field)
end
# fallback to default behaviour
defp get_translated_field(translations_for_locale, field) do
Map.fetch(translations_for_locale, to_string(field))
end
end
|
lib/trans/translator.ex
| 0.868813 | 0.498779 |
translator.ex
|
starcoder
|
defmodule Txpost.Parsers.CBOR do
@moduledoc """
A `Plug.Parsers` module for parsing CBOR request bodies.
CBOR documents that dont decode to maps are parsed into a `"_cbor"` key to
allow param merging. An empty request body is parsed as an empty map.
## Options
All options supported by `Plug.Conn.read_body/2` are also supported here. They
are repeated here for convenience:
* `:length` - sets the maximum number of bytes to read from the request, defaults to 8_000_000 bytes
* `:read_length` - sets the amount of bytes to read at one time from the underlying socket to fill the chunk, defaults to 1_000_000 bytes
* `:read_timeout` - sets the timeout for each socket read, defaults to 15_000ms
## Example
Add the parser your app's list of parsers.
plug Plug.Parsers,
parsers: [
:json,
Txpost.Parsers.CBOR
]
"""
import Txpost.Utils.Tags
@behaviour Plug.Parsers
@impl true
def init(opts) do
{body_reader, opts} = Keyword.pop(opts, :body_reader, {Plug.Conn, :read_body, []})
{decoder, opts} = Keyword.pop(opts, :cbor_decoder, {CBOR, :decode, []})
{body_reader, decoder, opts}
end
@impl true
def parse(conn, "application", subtype, _params, {{mod, fun, args}, decoder, opts}) do
if subtype == "cbor" or String.ends_with?(subtype, "+cbor") do
apply(mod, fun, [conn, opts | args]) |> decode(decoder)
else
{:next, conn}
end
end
def parse(conn, _type, _subtype, _params, _opts) do
{:next, conn}
end
defp decode({:ok, "", conn}, _decoder) do
{:ok, %{}, conn}
end
defp decode({:ok, body, conn}, {module, fun, args}) do
case apply(module, fun, [body | args]) do
{:ok, terms, _rest} when is_map(terms) ->
{:ok, detag(terms), conn}
{:ok, terms, _rest} ->
{:ok, %{"_cbor" => detag(terms)}, conn}
{:error, reason} ->
raise Plug.Parsers.ParseError, exception: reason
end
end
defp decode({:more, _, conn}, _decoder) do
{:error, :too_large, conn}
end
defp decode({:error, :timeout}, _decoder) do
raise Plug.TimeoutError
end
defp decode({:error, _}, _decoder) do
raise Plug.BadRequestError
end
end
|
lib/txpost/parsers/cbor.ex
| 0.798972 | 0.458106 |
cbor.ex
|
starcoder
|
defmodule XtbClient.Connection do
use GenServer
alias XtbClient.{MainSocket, StreamingSocket, StreamingMessage}
alias XtbClient.Messages.{
Candles,
ChartLast,
ChartRange,
DateRange,
ProfitCalculation,
Quotations,
SymbolInfo,
SymbolVolume,
TickPrices,
TradeInfos,
Trades,
TradeTransaction,
TradeTransactionStatus,
TradingHours
}
require Logger
@type client :: atom | pid | {atom, any} | {:via, atom, any}
@moduledoc """
`GenServer` which handles all commands and queries issued to XTB platform.
Acts as a proxy process between the client and the underlying main and streaming socket.
After successful initialization the process should hold references to both `XtbClient.MainSocket` and `XtbClient.StreamingSocket` processes,
so it can mediate all commands and queries from the caller to the connected socket.
For the synchronous operations clients should expect to get results as the function returned value.
## Example of synchronous call
```
params = %{app_name: "XtbClient", type: :demo, url: "wss://ws.xtb.com", user: "<<USER_ID>>", password: "<<PASSWORD>>"}
{:ok, pid} = XtbClient.Connection.start_link(params)
version = XtbClient.Connection.get_version(pid)
# expect to see the actual version of the backend server
```
Asynchronous operations, mainly `subscribe_` functions, returns immediately and stores the `pid` of the subscriber, so later it can send the message there.
Note that each `subscribe_` function expects the `subscriber` as an argument, so `XtbClient.Connection` could serve different types
of events to different subscribers. Only limitation is that each `subscribe_` function handles only one subscriber.
## Example of asynchronous call
```
defmodule StreamListener do
use GenServer
def start_link(args) do
name = Map.get(args, "name") |> String.to_atom()
GenServer.start_link(__MODULE__, args, name: name)
end
@impl true
def init(state) do
{:ok, state}
end
@impl true
def handle_info(message, state) do
IO.inspect({self(), message}, label: "Listener handle info")
{:noreply, state}
end
end
params = %{app_name: "XtbClient", type: :demo, url: "wss://ws.xtb.com", user: "<<USER_ID>>", password: "<<PASSWORD>>"}
{:ok, cpid} = XtbClient.Connection.start_link(params)
args = %{symbol: "LITECOIN"}
query = XtbClient.Messages.Quotations.Query.new(args)
{:ok, lpid} = StreamListener.start_link(%{"name" => args.symbol})
XtbClient.Connection.subscribe_get_tick_prices(cpid, lpid, query)
# expect to see logs from StreamListener process with tick pricess logged
```
"""
@doc """
Starts a `XtbClient.Connection` process linked to the calling process.
"""
@spec start_link(map) :: GenServer.on_start()
def start_link(args) do
state =
args
|> Map.put(:clients, %{})
|> Map.put(:subscribers, %{})
options = Map.get(args, :options, [])
GenServer.start_link(__MODULE__, state, options)
end
@impl true
def init(state) do
{:ok, mpid} = MainSocket.start_link(state)
Process.sleep(1_000)
MainSocket.stream_session_id(mpid, self())
Process.flag(:trap_exit, true)
state =
state
|> Map.put(:mpid, mpid)
|> Map.delete(:user)
|> Map.delete(:password)
{:ok, state}
end
@doc """
Returns array of all symbols available for the user.
"""
@spec get_all_symbols(client()) :: XtbClient.Messages.SymbolInfos.t()
def get_all_symbols(pid) do
GenServer.call(pid, {"getAllSymbols"})
end
@doc """
Returns calendar with market events.
"""
@spec get_calendar(client()) :: XtbClient.Messages.CalendarInfos.t()
def get_calendar(pid) do
GenServer.call(pid, {"getCalendar"})
end
@doc """
Returns chart info from start date to the current time.
If the chosen period of `XtbClient.Messages.ChartLast.Query` is greater than 1 minute, the last candle returned by the API can change until the end of the period (the candle is being automatically updated every minute).
Limitations: there are limitations in charts data availability. Detailed ranges for charts data, what can be accessed with specific period, are as follows:
- PERIOD_M1 --- <0-1) month, i.e. one month time
- PERIOD_M30 --- <1-7) month, six months time
- PERIOD_H4 --- <7-13) month, six months time
- PERIOD_D1 --- 13 month, and earlier on
Note, that specific PERIOD_ is the lowest (i.e. the most detailed) period, accessible in listed range. For instance, in months range <1-7) you can access periods: PERIOD_M30, PERIOD_H1, PERIOD_H4, PERIOD_D1, PERIOD_W1, PERIOD_MN1.
Specific data ranges availability is guaranteed, however those ranges may be wider, e.g.: PERIOD_M1 may be accessible for 1.5 months back from now, where 1.0 months is guaranteed.
## Example scenario:
* request charts of 5 minutes period, for 3 months time span, back from now;
* response: you are guaranteed to get 1 month of 5 minutes charts; because, 5 minutes period charts are not accessible 2 months and 3 months back from now
**Please note that this function can be usually replaced by its streaming equivalent `subscribe_get_candles/3` which is the preferred way of retrieving current candle data.**
"""
@spec get_chart_last(
client(),
XtbClient.Messages.ChartLast.Query.t()
) :: XtbClient.Messages.RateInfos.t()
def get_chart_last(pid, %ChartLast.Query{} = params) do
GenServer.call(pid, {"getChartLastRequest", %{info: params}})
end
@doc """
Returns chart info with data between given start and end dates.
Limitations: there are limitations in charts data availability. Detailed ranges for charts data, what can be accessed with specific period, are as follows:
- PERIOD_M1 --- <0-1) month, i.e. one month time
- PERIOD_M30 --- <1-7) month, six months time
- PERIOD_H4 --- <7-13) month, six months time
- PERIOD_D1 --- 13 month, and earlier on
Note, that specific PERIOD_ is the lowest (i.e. the most detailed) period, accessible in listed range. For instance, in months range <1-7) you can access periods: PERIOD_M30, PERIOD_H1, PERIOD_H4, PERIOD_D1, PERIOD_W1, PERIOD_MN1.
Specific data ranges availability is guaranteed, however those ranges may be wider, e.g.: PERIOD_M1 may be accessible for 1.5 months back from now, where 1.0 months is guaranteed.
**Please note that this function can be usually replaced by its streaming equivalent `subscribe_get_candles/3` which is the preferred way of retrieving current candle data.**
"""
@spec get_chart_range(client(), XtbClient.Messages.ChartRange.Query.t()) ::
XtbClient.Messages.RateInfos.t()
def get_chart_range(pid, %ChartRange.Query{} = params) do
GenServer.call(pid, {"getChartRangeRequest", %{info: params}})
end
@doc """
Returns calculation of commission and rate of exchange.
The value is calculated as expected value and therefore might not be perfectly accurate.
"""
@spec get_commission_def(client(), XtbClient.Messages.SymbolVolume.t()) ::
XtbClient.Messages.CommissionDefinition.t()
def get_commission_def(pid, %SymbolVolume{} = params) do
GenServer.call(pid, {"getCommissionDef", params})
end
@doc """
Returns information about account currency and account leverage.
"""
@spec get_current_user_data(client()) :: XtbClient.Messages.UserInfo.t()
def get_current_user_data(pid) do
GenServer.call(pid, {"getCurrentUserData"})
end
@doc """
Returns IBs data from the given time range.
"""
@spec get_ibs_history(client(), XtbClient.Messages.DateRange.t()) :: any()
def get_ibs_history(pid, %DateRange{} = params) do
GenServer.call(pid, {"getIbsHistory", params})
end
@doc """
Returns various account indicators.
**Please note that this function can be usually replaced by its streaming equivalent `subscribe_get_balance/2` which is the preferred way of retrieving current account indicators.**
"""
@spec get_margin_level(client()) :: XtbClient.Messages.BalanceInfo.t()
def get_margin_level(pid) do
GenServer.call(pid, {"getMarginLevel"})
end
@doc """
Returns expected margin for given instrument and volume.
The value is calculated as expected margin value and therefore might not be perfectly accurate.
"""
@spec get_margin_trade(client(), XtbClient.Messages.SymbolVolume.t()) ::
XtbClient.Messages.MarginTrade.t()
def get_margin_trade(pid, %SymbolVolume{} = params) do
GenServer.call(pid, {"getMarginTrade", params})
end
@doc """
Returns news from trading server which were sent within specified period of time.
**Please note that this function can be usually replaced by its streaming equivalent `subscribe_get_news/2` which is the preferred way of retrieving news data.**
"""
@spec get_news(client(), XtbClient.Messages.DateRange.t()) :: XtbClient.Messages.NewsInfos.t()
def get_news(pid, %DateRange{} = params) do
GenServer.call(pid, {"getNews", params})
end
@doc """
Calculates estimated profit for given deal data.
Should be used for calculator-like apps only.
Profit for opened transactions should be taken from server, due to higher precision of server calculation.
"""
@spec get_profit_calculation(client(), XtbClient.Messages.ProfitCalculation.Query.t()) ::
XtbClient.Messages.ProfitCalculation.t()
def get_profit_calculation(pid, %ProfitCalculation.Query{} = params) do
GenServer.call(pid, {"getProfitCalculation", params})
end
@doc """
Returns current time on trading server.
"""
@spec get_server_time(client()) :: XtbClient.Messages.ServerTime.t()
def get_server_time(pid) do
GenServer.call(pid, {"getServerTime"})
end
@doc """
Returns a list of step rules for DMAs.
"""
@spec get_step_rules(client()) :: XtbClient.Messages.StepRules.t()
def get_step_rules(pid) do
GenServer.call(pid, {"getStepRules"})
end
@doc """
Returns information about symbol available for the user.
"""
@spec get_symbol(client(), XtbClient.Messages.SymbolInfo.Query.t()) ::
XtbClient.Messages.SymbolInfo.t()
def get_symbol(pid, %SymbolInfo.Query{} = params) do
GenServer.call(pid, {"getSymbol", params})
end
@doc """
Returns array of current quotations for given symbols, only quotations that changed from given timestamp are returned.
New timestamp obtained from output will be used as an argument of the next call of this command.
**Please note that this function can be usually replaced by its streaming equivalent `subscribe_get_tick_prices/3` which is the preferred way of retrieving ticks data.**
"""
@spec get_tick_prices(client(), XtbClient.Messages.TickPrices.Query.t()) ::
XtbClient.Messages.TickPrices.t()
def get_tick_prices(pid, %TickPrices.Query{} = params) do
GenServer.call(pid, {"getTickPrices", params})
end
@doc """
Returns array of trades listed in orders query.
"""
@spec get_trade_records(client(), XtbClient.Messages.TradeInfos.Query.t()) ::
XtbClient.Messages.TradeInfos.t()
def get_trade_records(pid, %TradeInfos.Query{} = params) do
GenServer.call(pid, {"getTradeRecords", params})
end
@doc """
Returns array of user's trades.
**Please note that this function can be usually replaced by its streaming equivalent `subscribe_get_trades/2` which is the preferred way of retrieving trades data.**
"""
@spec get_trades(client(), XtbClient.Messages.Trades.Query.t()) ::
XtbClient.Messages.TradeInfos.t()
def get_trades(pid, %Trades.Query{} = params) do
GenServer.call(pid, {"getTrades", params})
end
@doc """
Returns array of user's trades which were closed within specified period of time.
"""
@spec get_trades_history(client(), XtbClient.Messages.DateRange.t()) ::
XtbClient.Messages.TradeInfos.t()
def get_trades_history(pid, %DateRange{} = params) do
GenServer.call(pid, {"getTradesHistory", params})
end
@doc """
Returns quotes and trading times.
"""
@spec get_trading_hours(client(), XtbClient.Messages.TradingHours.Query.t()) ::
XtbClient.Messages.TradingHours.t()
def get_trading_hours(pid, %TradingHours.Query{} = params) do
GenServer.call(pid, {"getTradingHours", params})
end
@doc """
Returns the current API version.
"""
@spec get_version(client()) :: XtbClient.Messages.Version.t()
def get_version(pid) do
GenServer.call(pid, {"getVersion"})
end
@doc """
Starts trade transaction.
`trade_transaction/2` sends main transaction information to the server.
## How to verify that the trade request was accepted?
The status field set to 'true' does not imply that the transaction was accepted. It only means, that the server acquired your request and began to process it.
To analyse the status of the transaction (for example to verify if it was accepted or rejected) use the `trade_transaction_status/2` command with the order number that came back with the response of the `trade_transaction/2` command.
"""
@spec trade_transaction(client(), XtbClient.Messages.TradeTransaction.Command.t()) ::
XtbClient.Messages.TradeTransaction.t()
def trade_transaction(pid, %TradeTransaction.Command{} = params) do
GenServer.call(pid, {"tradeTransaction", %{tradeTransInfo: params}})
end
@doc """
Returns current transaction status.
At any time of transaction processing client might check the status of transaction on server side.
In order to do that client must provide unique order taken from `trade_transaction/2` invocation.
"""
@spec trade_transaction_status(client(), XtbClient.Messages.TradeTransactionStatus.Query.t()) ::
XtbClient.Messages.TradeTransactionStatus.t()
def trade_transaction_status(pid, %TradeTransactionStatus.Query{} = params) do
GenServer.call(pid, {"tradeTransactionStatus", params})
end
@doc """
Allows to get actual account indicators values in real-time, as soon as they are available in the system.
Operation is asynchronous, so the immediate response is an `:ok` atom.
When the new data are available, the `XtbClient.Messages.BalanceInfo` struct is sent to the `subscriber` process.
"""
@spec subscribe_get_balance(client(), client()) :: :ok
def subscribe_get_balance(pid, subscriber) do
GenServer.cast(pid, {:subscribe, {subscriber, StreamingMessage.new("getBalance", "balance")}})
end
@doc """
Subscribes for API chart candles.
The interval of every candle is 1 minute. A new candle arrives every minute.
Operation is asynchronous, so the immediate response is an `:ok` atom.
When the new data are available, the `XtbClient.Messages.Candle` struct is sent to the `subscriber` process.
"""
@spec subscribe_get_candles(client(), client(), XtbClient.Messages.Candles.Query.t()) :: :ok
def subscribe_get_candles(pid, subscriber, %Candles.Query{} = params) do
GenServer.cast(
pid,
{:subscribe, {subscriber, StreamingMessage.new("getCandles", "candle", params)}}
)
end
@doc """
Subscribes for 'keep alive' messages.
A new 'keep alive' message is sent by the API every 3 seconds.
Operation is asynchronous, so the immediate response is an `:ok` atom.
When the new data are available, the `XtbClient.Messages.KeepAlive` struct is sent to the `subscriber` process.
"""
@spec subscribe_keep_alive(client(), client()) :: :ok
def subscribe_keep_alive(pid, subscriber) do
GenServer.cast(
pid,
{:subscribe, {subscriber, StreamingMessage.new("getKeepAlive", "keepAlive")}}
)
end
@doc """
Subscribes for news.
Operation is asynchronous, so the immediate response is an `:ok` atom.
When the new data are available, the `XtbClient.Messages.NewsInfo` struct is sent to the `subscriber` process.
"""
@spec subscribe_get_news(client(), client()) :: :ok
def subscribe_get_news(pid, subscriber) do
GenServer.cast(pid, {:subscribe, {subscriber, StreamingMessage.new("getNews", "news")}})
end
@doc """
Subscribes for profits.
Operation is asynchronous, so the immediate response is an `:ok` atom.
When the new data are available, the `XtbClient.Messages.ProfitInfo` struct is sent to the `subscriber` process.
"""
@spec subscribe_get_profits(client(), client()) :: :ok
def subscribe_get_profits(pid, subscriber) do
GenServer.cast(pid, {:subscribe, {subscriber, StreamingMessage.new("getProfits", "profit")}})
end
@doc """
Establishes subscription for quotations and allows to obtain the relevant information in real-time, as soon as it is available in the system.
The `subscribe_get_tick_prices/3` command can be invoked many times for the same symbol, but only one subscription for a given symbol will be created.
Please beware that when multiple records are available, the order in which they are received is not guaranteed.
Operation is asynchronous, so the immediate response is an `:ok` atom.
When the new data are available, the `XtbClient.Messages.TickPrice` struct is sent to the `subscriber` process.
"""
@spec subscribe_get_tick_prices(client(), client(), XtbClient.Messages.Quotations.Query.t()) ::
:ok
def subscribe_get_tick_prices(pid, subscriber, %Quotations.Query{} = params) do
GenServer.cast(
pid,
{:subscribe, {subscriber, StreamingMessage.new("getTickPrices", "tickPrices", params)}}
)
end
@doc """
Establishes subscription for user trade status data and allows to obtain the relevant information in real-time, as soon as it is available in the system.
Please beware that when multiple records are available, the order in which they are received is not guaranteed.
Operation is asynchronous, so the immediate response is an `:ok` atom.
When the new data are available, the `XtbClient.Messages.TradeInfo` struct is sent to the `subscriber` process.
"""
@spec subscribe_get_trades(client(), client()) :: :ok
def subscribe_get_trades(pid, subscriber) do
GenServer.cast(pid, {:subscribe, {subscriber, StreamingMessage.new("getTrades", "trade")}})
end
@doc """
Allows to get status for sent trade requests in real-time, as soon as it is available in the system.
Please beware that when multiple records are available, the order in which they are received is not guaranteed.
Operation is asynchronous, so the immediate response is an `:ok` atom.
When the new data are available, the `XtbClient.Messages.TradeStatus` struct is sent to the `subscriber` process.
"""
@spec subscribe_get_trade_status(client(), client()) :: :ok
def subscribe_get_trade_status(pid, subscriber) do
GenServer.cast(
pid,
{:subscribe, {subscriber, StreamingMessage.new("getTradeStatus", "tradeStatus")}}
)
end
@impl true
def handle_call({method}, {_pid, ref} = from, %{mpid: mpid, clients: clients} = state) do
ref_string = inspect(ref)
MainSocket.query(mpid, self(), ref_string, method)
clients = Map.put(clients, ref_string, from)
state = %{state | clients: clients}
{:noreply, state}
end
@impl true
def handle_call({method, params}, {_pid, ref} = from, %{mpid: mpid, clients: clients} = state) do
ref_string = inspect(ref)
MainSocket.query(mpid, self(), ref_string, method, params)
clients = Map.put(clients, ref_string, from)
state = %{state | clients: clients}
{:noreply, state}
end
@impl true
def handle_cast({:response, ref, resp} = _message, %{clients: clients} = state) do
{client, clients} = Map.pop!(clients, ref)
GenServer.reply(client, resp)
state = %{state | clients: clients}
{:noreply, state}
end
@impl true
def handle_cast({:stream_session_id, session_id} = _message, state) do
args = Map.put(state, :stream_session_id, session_id)
{:ok, spid} = StreamingSocket.start_link(args)
state = Map.put(state, :spid, spid)
{:noreply, state}
end
@impl true
def handle_cast(
{:subscribe, {subscriber, %StreamingMessage{} = streaming_message}} = _message,
%{spid: spid, subscribers: subscribers} = state
) do
StreamingSocket.subscribe(spid, self(), streaming_message)
token = StreamingMessage.encode_token(streaming_message)
subscribers = Map.put(subscribers, token, subscriber)
state = %{state | subscribers: subscribers}
{:noreply, state}
end
@impl true
def handle_cast(
{:stream_result, {token, result}} = _message,
%{subscribers: subscribers} = state
) do
subscriber = Map.get(subscribers, token)
send(subscriber, {:ok, result})
{:noreply, state}
end
@impl true
def handle_info({:EXIT, pid, reason}, state) do
Logger.error(
"Module handled exit message from #{inspect(pid)} with reason #{inspect(reason)}."
)
{:stop, :shutdown, state}
end
end
|
lib/xtb_client/connection.ex
| 0.872917 | 0.69999 |
connection.ex
|
starcoder
|
defmodule Operate.Cell do
@moduledoc """
Module for working with Operate tape cells.
A cell represents a single atomic procedure call. A `t:Operate.Cell.t/0`
contains the Op script and parameters. When the cell is executed it returns a
result.
## Examples
iex> %Operate.Cell{op: "return function(state, a, b) return state + a + b end", params: [3, 5]}
...> |> Operate.Cell.exec(Operate.VM.init, state: 1)
{:ok, 9}
"""
alias Operate.{BPU, VM}
@typedoc "Operate Cell"
@type t :: %__MODULE__{
ref: String.t,
params: list,
op: String.t,
index: integer,
data_index: integer
}
defstruct ref: nil,
params: [],
op: nil,
index: nil,
data_index: nil
@doc """
Converts the given `t:Operate.BPU.Cell.t/0` into a `t:Operate.Cell.t/0`. Returns
the result in an `:ok` / `:error` tuple pair.
"""
@spec from_bpu(BPU.Cell.t) ::
{:ok, __MODULE__.t} |
{:error, String.t}
def from_bpu(%BPU.Cell{cell: [head | tail], i: index}) do
head = case Enum.all?(head, fn({k, _}) -> is_atom(k) end) do
true -> head
false ->
for {key, val} <- head, into: %{}, do: {String.to_atom(key), val}
end
with {:ok, str} <- Base.decode64(head.b),
params when is_list(params) <- Enum.map(tail, &normalize_param/1)
do
# TODO - in future use h attribute of BOB2
ref = case byte_size(str) do
s when s == 4 or s == 32 -> Base.encode16(str, case: :lower)
_ -> str
end
cell = struct(__MODULE__, [
ref: ref,
params: params,
index: index,
data_index: head.ii
])
{:ok, cell}
else
error -> error
end
end
@doc """
As `from_bpu/1`, but returns the result or raises an exception.
"""
@spec from_bpu!(BPU.Cell.t) :: __MODULE__.t
def from_bpu!(%BPU.Cell{} = cell) do
case from_bpu(cell) do
{:ok, cell} -> cell
{:error, err} -> raise err
end
end
@doc """
Executes the given cell in the given VM state.
## Options
The accepted options are:
* `:state` - Specifiy the state which is always the first parameter in the executed function. Defaults to `nil`.
## Examples
iex> %Operate.Cell{op: "return function(state) return state..' world' end", params: []}
...> |> Operate.Cell.exec(Operate.VM.init, state: "hello")
{:ok, "hello world"}
"""
@spec exec(__MODULE__.t, VM.t, keyword) ::
{:ok, VM.lua_output} |
{:error, String.t}
def exec(%__MODULE__{} = cell, vm, options \\ []) do
state = Keyword.get(options, :state, nil)
vm = vm
|> VM.set!("ctx.cell_index", cell.index)
|> VM.set!("ctx.data_index", cell.data_index)
|> VM.set!("ctx.global_index", cell.data_index) # TODO - remove global_index in v 0.1.0
case VM.eval(vm, cell.op) do
{:ok, function} -> VM.exec_function(function, [state | cell.params])
err -> err
end
end
@doc """
As `exec/3`, but returns the result or raises an exception.
## Options
The accepted options are:
* `:state` - Specifiy the state which is always the first parameter in the executed function. Defaults to `nil`.
"""
@spec exec!(__MODULE__.t, VM.t, keyword) :: VM.lua_output
def exec!(%__MODULE__{} = cell, vm, options \\ []) do
case exec(cell, vm, options) do
{:ok, result} -> result
{:error, err} -> raise err
end
end
@doc """
Validates the given cell. Returns true if the cell has a reference and script.
## Examples
iex> %Operate.Cell{ref: "abc", op: "return 123"}
...> |> Operate.Cell.valid?
true
iex> %Operate.Cell{}
...> |> Operate.Cell.valid?
false
"""
@spec valid?(__MODULE__.t) :: boolean
def valid?(%__MODULE__{} = cell) do
[:ref, :op]
|> Enum.all?(& Map.get(cell, &1) |> validate_presence)
end
# Private: Normalizes the cell param
defp normalize_param(%{b: b}), do: Base.decode64!(b)
defp normalize_param(%{"b" => b}), do: Base.decode64!(b)
defp normalize_param(_), do: nil
# Private: Checks the given value is not nil or empty
defp validate_presence(val) do
case val do
v when is_binary(v) -> String.trim(v) != ""
nil -> false
_ -> true
end
end
end
|
lib/operate/cell.ex
| 0.721449 | 0.680135 |
cell.ex
|
starcoder
|
defmodule Nebulex.Adapters.Multilevel do
@moduledoc """
Adapter module for Multi-level Cache.
This is just a simple layer on top of local or distributed cache
implementations that enables to have a cache hierarchy by levels.
Multi-level caches generally operate by checking the fastest,
level 1 (L1) cache first; if it hits, the adapter proceeds at
high speed. If that first cache misses, the next fastest cache
(level 2, L2) is checked, and so on, before accessing external
memory (that can be handled by a `:fallback` function).
For write functions, the "Write Through" policy is applied by default;
this policy ensures that the data is stored safely as it is written
throughout the hierarchy. However, it is possible to force the write
operation in a specific level (although it is not recommended) via
`level` option, where the value is a positive integer greater than 0.
## Options
These options can be set through the config file:
* `:cache_model` - Specifies the cache model: `:inclusive` or `:exclusive`;
defaults to `:inclusive`. In an inclusive cache, the same data can be
present in all caches/levels. In an exclusive cache, data can be present
in only one cache/level and a key cannot be found in the rest of caches
at the same time. This option affects `get` operation only; if
`:cache_model` is `:inclusive`, when the key is found in a level N,
that entry is duplicated backwards (to all previous levels: 1..N-1).
* `:levels` - The list of caches where each cache corresponds to a level.
The order of the caches in the list defines the the order of the levels
as well, for example, the first cache in the list will be the L1 cache
(level 1) and so on; the Nth elemnt will be the LN cache. This option
is mandatory, if it is not set or empty, an exception will be raised.
* `:fallback` - Defines a fallback function when a key is not present
in any cache level. Function is defined as: `(key -> value)`.
The `:fallback` can be defined in two ways: at compile-time and at run-time.
At compile-time, in the cache config, set the module that implements the
function:
config :my_app, MyApp.MultilevelCache,
fallback: &MyMapp.AnyModule/1
And at run-time, passing the function as an option within the `opts` argument
(only valid for `get` function):
MultilevelCache.get("foo", fallback: fn(key) -> key * 2 end)
## Shared Options
Some functions below accept the following options:
* `:level` - It may be an integer greater than 0 that specifies the cache
level where the operation will take place. By default, the evaluation
is performed throughout the whole cache hierarchy (all levels).
## Example
`Nebulex.Cache` is the wrapper around the Cache. We can define the
multi-level cache as follows:
defmodule MyApp.MultilevelCache do
use Nebulex.Cache,
otp_app: :nebulex,
adapter: Nebulex.Adapters.Multilevel
defmodule L1 do
use Nebulex.Cache,
otp_app: :nebulex,
adapter: Nebulex.Adapters.Local
end
defmodule L2 do
use Nebulex.Cache,
otp_app: :nebulex,
adapter: Nebulex.Adapters.Dist
end
def fallback(_key) do
# maybe fetch the data from Database
nil
end
end
defmodule MyApp.LocalCache do
use Nebulex.Cache,
otp_app: :my_app,
adapter: Nebulex.Adapters.Local
end
Where the configuration for the Cache must be in your application
environment, usually defined in your `config/config.exs`:
config :my_app, MyApp.MultilevelCache,
levels: [
MyApp.MultilevelCache.L1,
MyApp.MultilevelCache.L2
],
fallback: &MyApp.MultilevelCache.fallback/1
config :my_app, MyApp.MultilevelCache.L1,
n_shards: 2,
gc_interval: 3600
config :my_app, MyApp.MultilevelCache.L2,
local: MyApp.LocalCache
config :my_app, MyApp.LocalCache,
n_shards: 2,
gc_interval: 3600
Using the multilevel cache cache:
# Retrieving data from cache
MyCache.get("foo", fallback: fn(_key) ->
# Maybe fetch the key from database
"initial value"
end)
# Entry is set in all cache levels
MyCache.set("foo", "bar")
# Entry is set at second cache level
MyCache.set("foo", "bar", level: 2)
# Entry is deleted from all cache levels
MyCache.delete("foo")
# Entry is deleted from second cache level
MyCache.delete("foo", level: 2)
## Extended API
This adapter provides some additional functions to the `Nebulex.Cache` API.
### `__levels__`
This function returns the configured level list.
MyCache.__levels__
### `__model__`
This function returns the multi-level cache model.
MyCache.__model__
### `__fallback__`
This function returns the default fallback function.
MyCache.__fallback__
## Limitations
Because this adapter reuses other existing/configured adapters, it inherits
all their limitations too. Therefore, it is highly recommended to check the
documentation of the used adapters.
"""
# Provide Cache Implementation
@behaviour Nebulex.Adapter
@behaviour Nebulex.Adapter.Queryable
@behaviour Nebulex.Adapter.Transaction
alias Nebulex.Object
## Adapter
@impl true
defmacro __before_compile__(env) do
otp_app = Module.get_attribute(env.module, :otp_app)
config = Module.get_attribute(env.module, :config)
cache_model = Keyword.get(config, :cache_model, :inclusive)
fallback = Keyword.get(config, :fallback)
levels = Keyword.get(config, :levels)
unless levels do
raise ArgumentError,
"missing :levels configuration in config " <>
"#{inspect(otp_app)}, #{inspect(env.module)}"
end
unless is_list(levels) && length(levels) > 0 do
raise ArgumentError,
":levels configuration in config must have at least one level, " <>
"got: #{inspect(levels)}"
end
quote do
def __levels__, do: unquote(levels)
def __model__, do: unquote(cache_model)
def __fallback__, do: unquote(fallback)
end
end
@impl true
def init(_opts), do: {:ok, []}
@impl true
def get(cache, key, opts) do
fun = fn current, {_, prev} ->
if object = current.__adapter__.get(current, key, opts) do
{:halt, {object, [current | prev]}}
else
{:cont, {nil, [current | prev]}}
end
end
cache.__levels__
|> Enum.reduce_while({nil, []}, fun)
|> maybe_fallback(cache, key, opts)
|> maybe_replicate(cache)
end
@impl true
def get_many(cache, keys, _opts) do
Enum.reduce(keys, %{}, fn key, acc ->
if obj = get(cache, key, []),
do: Map.put(acc, key, obj),
else: acc
end)
end
@impl true
def set(cache, object, opts) do
eval(cache, :set, [object, opts], opts)
end
@impl true
def set_many(cache, objects, opts) do
opts
|> levels(cache)
|> Enum.reduce({objects, []}, fn level, {objects_acc, err_acc} ->
do_set_many(level, objects_acc, opts, err_acc)
end)
|> case do
{_, []} -> :ok
{_, err} -> {:error, err}
end
end
@impl true
def delete(cache, key, opts) do
eval(cache, :delete, [key, opts], opts)
end
@impl true
def take(cache, key, opts) do
opts
|> levels(cache)
|> do_take(nil, key, opts)
end
defp do_take([], result, _key, _opts), do: result
defp do_take([level | rest], nil, key, opts) do
result = level.__adapter__.take(level, key, opts)
do_take(rest, result, key, opts)
end
defp do_take(levels, result, key, _opts) do
_ = eval(levels, :delete, [key, []])
result
end
@impl true
def has_key?(cache, key) do
eval_while(cache, :has_key?, [key], false)
end
@impl true
def object_info(cache, key, attr) do
eval_while(cache, :object_info, [key, attr], nil)
end
@impl true
def expire(cache, key, ttl) do
Enum.reduce(cache.__levels__, nil, fn level_cache, acc ->
if exp = level_cache.__adapter__.expire(level_cache, key, ttl),
do: exp,
else: acc
end)
end
@impl true
def update_counter(cache, key, incr, opts) do
eval(cache, :update_counter, [key, incr, opts], opts)
end
@impl true
def size(cache) do
Enum.reduce(cache.__levels__, 0, fn level_cache, acc ->
level_cache.__adapter__.size(level_cache) + acc
end)
end
@impl true
def flush(cache) do
Enum.each(cache.__levels__, fn level_cache ->
level_cache.__adapter__.flush(level_cache)
end)
end
## Queryable
@impl true
def all(cache, query, opts) do
for level_cache <- cache.__levels__,
elems <- level_cache.__adapter__.all(level_cache, query, opts),
do: elems
end
@impl true
def stream(cache, query, opts) do
Stream.resource(
fn ->
cache.__levels__
end,
fn
[] ->
{:halt, []}
[level | levels] ->
elements =
level
|> level.__adapter__.stream(query, opts)
|> Enum.to_list()
{elements, levels}
end,
& &1
)
end
## Transaction
@impl true
def transaction(cache, fun, opts) do
eval(cache, :transaction, [fun, opts], [])
end
@impl true
def in_transaction?(cache) do
results =
Enum.reduce(cache.__levels__, [], fn level, acc ->
[level.in_transaction?() | acc]
end)
true in results
end
## Helpers
defp eval(ml_cache, fun, args, opts) do
eval(levels(opts, ml_cache), fun, args)
end
defp eval([l1 | next], fun, args) do
Enum.reduce(next, apply(l1.__adapter__, fun, [l1 | args]), fn cache, acc ->
^acc = apply(cache.__adapter__, fun, [cache | args])
end)
end
defp levels(opts, cache) do
case Keyword.get(opts, :level) do
nil -> cache.__levels__
level -> [:lists.nth(level, cache.__levels__)]
end
end
defp eval_while(ml_cache, fun, args, init) do
Enum.reduce_while(ml_cache.__levels__, init, fn cache, acc ->
if return = apply(cache.__adapter__, fun, [cache | args]),
do: {:halt, return},
else: {:cont, acc}
end)
end
defp maybe_fallback({nil, levels}, cache, key, opts) do
object =
if fallback = opts[:fallback] || cache.__fallback__,
do: %Object{key: key, value: eval_fallback(fallback, key)},
else: nil
{object, levels}
end
defp maybe_fallback(return, _, _, _), do: return
defp eval_fallback(fallback, key) when is_function(fallback, 1),
do: fallback.(key)
defp eval_fallback({m, f}, key) when is_atom(m) and is_atom(f),
do: apply(m, f, [key])
defp maybe_replicate({nil, _}, _), do: nil
defp maybe_replicate({%Object{value: nil}, _}, _), do: nil
defp maybe_replicate({object, levels}, cache) do
cache.__model__
|> case do
:exclusive -> []
:inclusive -> levels
end
|> Enum.reduce(object, &replicate(&1, &2))
end
defp replicate(cache, %Object{expire_at: expire_at} = object) do
object =
if expire_at,
do: %{object | expire_at: expire_at - DateTime.to_unix(DateTime.utc_now())},
else: object
true = cache.__adapter__.set(cache, object, [])
object
end
defp do_set_many(cache, entries, opts, acc) do
case cache.__adapter__.set_many(cache, entries, opts) do
:ok ->
{entries, acc}
{:error, err_keys} ->
entries = for {k, _} = e <- entries, not (k in err_keys), do: e
{entries, err_keys ++ acc}
end
end
end
|
lib/nebulex/adapters/multilevel.ex
| 0.882263 | 0.544559 |
multilevel.ex
|
starcoder
|
defmodule Mix.Tasks.Deps.Tree do
use Mix.Task
@shortdoc "Prints the dependency tree"
@recursive true
@moduledoc """
Prints the dependency tree.
mix deps.tree
If no dependency is given, it uses the tree defined in the `mix.exs` file.
## Command line options
* `--only` - the environment to show dependencies for
* `--target` - the target to show dependencies for
* `--exclude` - exclude dependencies which you do not want to see printed.
* `--format` - Can be set to one of either:
* `pretty` - uses Unicode code points for formatting the tree.
This is the default except on Windows.
* `plain` - does not use Unicode code points for formatting the tree.
This is the default on Windows.
* `dot` - produces a DOT graph description of the dependency tree
in `deps_tree.dot` in the current directory.
Warning: this will override any previously generated file.
"""
@switches [only: :string, target: :string, exclude: :keep, format: :string]
@impl true
def run(args) do
Mix.Project.get!()
{opts, args, _} = OptionParser.parse(args, switches: @switches)
deps_opts =
for {switch, key} <- [only: :env, target: :target],
value = opts[switch],
do: {key, :"#{value}"}
deps = Mix.Dep.load_on_environment(deps_opts)
root =
case args do
[] ->
Mix.Project.config()[:app] ||
Mix.raise("no application given and none found in mix.exs file")
[app] ->
app = String.to_atom(app)
find_dep(deps, app) || Mix.raise("could not find dependency #{app}")
end
if opts[:format] == "dot" do
callback = callback(&format_dot/1, deps, opts)
Mix.Utils.write_dot_graph!("deps_tree.dot", "dependency tree", [root], callback, opts)
"""
Generated "deps_tree.dot" in the current directory. To generate a PNG:
dot -Tpng deps_tree.dot -o deps_tree.png
For more options see http://www.graphviz.org/.
"""
|> String.trim_trailing()
|> Mix.shell().info()
else
callback = callback(&format_tree/1, deps, opts)
Mix.Utils.print_tree([root], callback, opts)
end
end
defp callback(formatter, deps, opts) do
excluded = Keyword.get_values(opts, :exclude) |> Enum.map(&String.to_atom/1)
top_level = Enum.filter(deps, & &1.top_level)
fn
%Mix.Dep{app: app} = dep ->
# Do not show dependencies if they were
# already shown at the top level
deps =
if not dep.top_level && find_dep(top_level, app) do
[]
else
find_dep(deps, app).deps
end
{formatter.(dep), exclude_and_sort(deps, excluded)}
app ->
{{Atom.to_string(app), nil}, exclude_and_sort(top_level, excluded)}
end
end
defp exclude_and_sort(deps, excluded) do
deps
|> Enum.reject(&(&1.app in excluded))
|> Enum.sort_by(& &1.app)
end
defp format_dot(%{app: app, requirement: requirement, opts: opts}) do
override =
if opts[:override] do
" *override*"
else
""
end
requirement = requirement && requirement(requirement)
{app, "#{requirement}#{override}"}
end
defp format_tree(%{app: app, scm: scm, requirement: requirement, opts: opts}) do
override =
if opts[:override] do
IO.ANSI.format([:bright, " *override*"])
else
""
end
requirement = requirement && "#{requirement(requirement)} "
{app, "#{requirement}(#{scm.format(opts)})#{override}"}
end
defp requirement(%Regex{} = regex), do: "#{inspect(regex)}"
defp requirement(binary) when is_binary(binary), do: binary
defp find_dep(deps, app) do
Enum.find(deps, &(&1.app == app))
end
end
|
lib/mix/lib/mix/tasks/deps.tree.ex
| 0.804828 | 0.459682 |
deps.tree.ex
|
starcoder
|
defmodule Parser do
use Platform.Parsing.Behaviour
# ELEMENT IoT Parser for Adeunis Field Test Device
# According to documentation provided by Adeunis
# Link: https://www.adeunis.com/en/produit/ftd-868-915-2/
# Documentation: https://www.adeunis.com/wp-content/uploads/2017/08/FTD_LoRaWAN_EU863-870_UG_FR_GB_V1.2.1.pdf
def parse(event, _meta) do
<< status :: binary-1, rest :: binary >> = event
{fields, status_data} = parse_status(status)
field_data = parse_field(fields, rest, [])
data = Map.merge(status_data, field_data)
case data do
%{latitude: lat, longitude: lng} -> {data, location: {lng, lat}}
data -> data
end
end
def parse_field([{_, false} | fields], payload, acc) do
parse_field(fields, payload, acc)
end
def parse_field([{:has_temperature, true} | fields], << temperature :: signed-8, rest :: binary >>, _acc) do
parse_field(fields, rest, [{:temperature, temperature}])
end
def parse_field([{:has_gps, true} | fields], << latitude :: binary-4, longitude :: binary-4, gps_quality :: binary-1, rest :: binary>>, acc) do
<< lat_deg :: bitstring-8, lat_min :: bitstring-20, _ :: 3, lat_hemi :: 1 >> = latitude
<< long_deg :: bitstring-12, long_min :: bitstring-16, _ :: 3, long_hemi :: 1 >> = longitude
lat_deg = parse_bcd(lat_deg, 0)
lat_min = parse_bcd(lat_min, 0)
long_deg = parse_bcd(long_deg, 0)
long_min = parse_bcd(long_min, 0)
lat = hemi_to_sign(lat_hemi) * (lat_deg + (lat_min / 1000 / 60.0))
long = hemi_to_sign(long_hemi) * (long_deg + (long_min / 100 / 60.0))
<< gps_reception_scale :: 4, gps_satellites :: 4 >> = gps_quality
acc = Enum.concat([
latitude: lat,
longitude: long,
gps_reception_scale: gps_reception_scale,
gps_satellites: gps_satellites
], acc)
parse_field(fields, rest, acc)
end
def parse_field([{:has_up_fcnt, true} | fields], << up_fcnt :: 8, rest :: binary>>, acc) do
parse_field(fields, rest, [{:up_fcnt, up_fcnt} | acc])
end
def parse_field([{:has_down_fcnt, true} | fields], << down_fcnt :: 8, rest :: binary>>, acc) do
parse_field(fields, rest, [{:down_fcnt, down_fcnt} | acc])
end
def parse_field([{:has_battery_level, true} | fields], << level :: 16, rest :: binary >>, acc) do
parse_field(fields, rest, [{:battery_voltage, level} | acc])
end
def parse_field([{:has_rssi_and_snr, true} | fields], << rssi :: 8, snr :: signed-8, rest :: binary >>, acc) do
acc = Enum.concat([
rssi: rssi * -1,
snr: snr
], acc)
parse_field(fields, rest, acc)
end
def parse_field([_ | fields], rest, acc) do
# should not happen
parse_field(fields, rest, acc)
end
def parse_field([], _, acc), do: Enum.into(acc, %{})
def parse_status(<< has_temperature :: 1,
trigger_accelerometer :: 1,
trigger_push_button :: 1,
has_gps :: 1,
has_up_fcnt :: 1,
has_down_fcnt :: 1,
has_battery_level :: 1,
has_rssi_and_snr :: 1 >>) do
{[
has_temperature: has_temperature == 1,
has_gps: has_gps == 1,
has_up_fcnt: has_up_fcnt == 1,
has_down_fcnt: has_down_fcnt == 1,
has_battery_level: has_battery_level == 1,
has_rssi_and_snr: has_rssi_and_snr == 1
], %{
trigger_accelerometer: trigger_accelerometer == 1,
trigger_push_button: trigger_push_button == 1
}}
end
def parse_bcd(<< num::4, rest::bitstring>>, acc) do
parse_bcd(rest, acc * 10 + num)
end
def parse_bcd("", acc), do: acc
def hemi_to_sign(0), do: 1
def hemi_to_sign(1), do: -1
end
|
lib/adeunis_ftd.ex
| 0.582966 | 0.405184 |
adeunis_ftd.ex
|
starcoder
|
defmodule Oban.Crontab.Cron do
@moduledoc false
alias Oban.Crontab.Parser
@type expression :: [:*] | list(non_neg_integer())
@type t :: %__MODULE__{
minutes: expression(),
hours: expression(),
days: expression(),
months: expression(),
weekdays: expression(),
reboot: boolean()
}
@part_ranges %{
minutes: {0, 59},
hours: {0, 23},
days: {1, 31},
months: {1, 12},
weekdays: {0, 6}
}
defstruct minutes: [:*], hours: [:*], days: [:*], months: [:*], weekdays: [:*], reboot: false
@spec now?(cron :: t(), datetime :: DateTime.t()) :: boolean()
def now?(cron, datetime \\ DateTime.utc_now())
def now?(%__MODULE__{reboot: true}, _datetime), do: false
def now?(%__MODULE__{} = cron, datetime) do
cron
|> Map.from_struct()
|> Map.drop([:reboot])
|> Enum.all?(fn {part, values} ->
Enum.any?(values, &matches_rule?(part, &1, datetime))
end)
end
defp matches_rule?(_part, :*, _date_time), do: true
defp matches_rule?(:minutes, minute, datetime), do: minute == datetime.minute
defp matches_rule?(:hours, hour, datetime), do: hour == datetime.hour
defp matches_rule?(:days, day, datetime), do: day == datetime.day
defp matches_rule?(:months, month, datetime), do: month == datetime.month
defp matches_rule?(:weekdays, weekday, datetime), do: weekday == day_of_week(datetime)
defp day_of_week(datetime) do
datetime
|> Date.day_of_week()
|> Integer.mod(7)
end
@doc """
Parses a crontab expression into a %Cron{} struct.
The parser can handle common expressions that use minutes, hours, days, months and weekdays,
along with ranges and steps. It also supports common extensions, also called nicknames.
Raises an `ArgumentError` if the expression cannot be parsed.
## Nicknames
- @yearly: Run once a year, "0 0 1 1 *".
- @annually: same as @yearly
- @monthly: Run once a month, "0 0 1 * *".
- @weekly: Run once a week, "0 0 * * 0".
- @daily: Run once a day, "0 0 * * *".
- @midnight: same as @daily
- @hourly: Run once an hour, "0 * * * *".
- @reboot: Run once at boot
## Examples
iex> parse!("@hourly")
%Cron{}
iex> parse!("0 * * * *")
%Cron{}
iex> parse!("60 * * * *")
** (ArgumentError)
"""
@spec parse!(input :: binary()) :: t()
def parse!("@annually"), do: parse!("@yearly")
def parse!("@yearly"), do: parse!("0 0 1 1 *")
def parse!("@monthly"), do: parse!("0 0 1 * *")
def parse!("@weekly"), do: parse!("0 0 * * 0")
def parse!("@midnight"), do: parse!("@daily")
def parse!("@daily"), do: parse!("0 0 * * *")
def parse!("@hourly"), do: parse!("0 * * * *")
def parse!("@reboot"), do: struct!(__MODULE__, reboot: true)
def parse!(input) when is_binary(input) do
input
|> String.trim()
|> Parser.cron()
|> case do
{:ok, parsed, _, _, _, _} ->
struct!(__MODULE__, expand(parsed))
{:error, message, _, _, _, _} ->
raise ArgumentError, message
end
end
defp expand(parsed) when is_list(parsed), do: Enum.map(parsed, &expand/1)
defp expand({part, expressions}) do
{min, max} = Map.get(@part_ranges, part)
expanded =
expressions
|> Enum.flat_map(&expand(&1, min, max))
|> :lists.usort()
{part, expanded}
end
defp expand({:wild, _value}, _min, _max), do: [:*]
defp expand({:literal, value}, min, max) when value in min..max, do: [value]
defp expand({:step, [{:wild, _}, value]}, min, max) when value in (min + 1)..max do
for step <- min..max, rem(step, value) == 0, do: step
end
defp expand({:step, [{:range, [first, last]}, value]}, min, max)
when first >= min and last <= max and last > first and value <= last - first do
for step <- first..last, rem(step, value) == 0, do: step
end
defp expand({:range, [first, last]}, min, max) when first >= min and last <= max do
for step <- first..last, do: step
end
defp expand({_type, value}, min, max) do
raise ArgumentError, "Unexpected value #{inspect(value)} outside of range #{min}..#{max}"
end
@spec reboot?(cron :: t()) :: boolean()
def reboot?(%__MODULE__{reboot: reboot}), do: reboot
end
|
lib/oban/crontab/cron.ex
| 0.889051 | 0.580887 |
cron.ex
|
starcoder
|
defmodule Sippet.Transactions.Server.Invite do
@moduledoc false
use Sippet.Transactions.Server, initial_state: :proceeding
alias Sippet.Message, as: Message
alias Sippet.Message.StatusLine, as: StatusLine
alias Sippet.Transactions.Server.State, as: State
@t2 4000
@before_trying 200
@timer_g 500
@timer_h 64 * @timer_g
@timer_i 5000 # timer I is 5s
def init(%State{key: key} = data) do
# add an alias for incoming ACK requests for status codes != 200
%{key | method: :ack}
|> Sippet.Transactions.Registry.register_alias()
super(data)
end
defp retry({past_wait, passed_time},
%State{extras: %{last_response: last_response}} = data) do
send_response(last_response, data)
new_delay = min(past_wait * 2, @t2)
{:keep_state_and_data, [{:state_timeout, new_delay,
{new_delay, passed_time + new_delay}}]}
end
def proceeding(:enter, _old_state, %State{request: request} = data) do
receive_request(request, data)
{:keep_state_and_data, [{:state_timeout, @before_trying, :still_trying}]}
end
def proceeding(:state_timeout, :still_trying,
%State{request: request} = data) do
response = request |> Message.to_response(100)
data = send_response(response, data)
{:keep_state, data}
end
def proceeding(:cast, {:incoming_request, _request},
%State{extras: %{last_response: last_response}} = data) do
send_response(last_response, data)
:keep_state_and_data
end
def proceeding(:cast, {:incoming_request, _request}, _data),
do: :keep_state_and_data
def proceeding(:cast, {:outgoing_response, response}, data) do
data = send_response(response, data)
case StatusLine.status_code_class(response.start_line) do
1 -> {:keep_state, data}
2 -> {:stop, :normal, data}
_ -> {:next_state, :completed, data}
end
end
def proceeding(:cast, {:error, reason}, data),
do: shutdown(reason, data)
def proceeding(event_type, event_content, data),
do: unhandled_event(event_type, event_content, data)
def completed(:enter, _old_state, %State{request: request}) do
actions =
if reliable?(request) do
[{:state_timeout, @timer_h, {@timer_h, @timer_h}}]
else
[{:state_timeout, @timer_g, {@timer_g, @timer_g}}]
end
{:keep_state_and_data, actions}
end
def completed(:state_timeout, time_event, data) do
{_past_wait, passed_time} = time_event
if passed_time >= @timer_h do
timeout(data)
else
retry(time_event, data)
end
end
def completed(:cast, {:incoming_request, request},
%State{extras: %{last_response: last_response}} = data) do
case request.start_line.method do
:invite ->
send_response(last_response, data)
:keep_state_and_data
:ack ->
{:next_state, :confirmed, data}
_otherwise ->
shutdown(:invalid_method, data)
end
end
def completed(:cast, {:error, reason}, data),
do: shutdown(reason, data)
def completed(event_type, event_content, data),
do: unhandled_event(event_type, event_content, data)
def confirmed(:enter, _old_state, %State{request: request} = data) do
if reliable?(request) do
{:stop, :normal, data}
else
{:keep_state_and_data, [{:state_timeout, @timer_i, nil}]}
end
end
def confirmed(:state_timeout, _nil, data),
do: {:stop, :normal, data}
def confirmed(:cast, {:incoming_request, _request}, _data),
do: :keep_state_and_data
def confirmed(:cast, {:error, _reason}, _data),
do: :keep_state_and_data
def confirmed(event_type, event_content, data),
do: unhandled_event(event_type, event_content, data)
end
|
lib/sippet/transactions/server/invite.ex
| 0.601125 | 0.427098 |
invite.ex
|
starcoder
|
defmodule ExAdmin.Register do
@moduledoc """
Allows registering a resource or a page to be displayed with ExAdmin.
For each model you wanted rendered by ExAdmin, use the
`register_resource` call. For each general page (like a dashboard),
use the `register_page` call.
To allow ExAdmin to manage the resource with defaults, do not place
any additional code in the block of `register_resource`.
## Examples
Register the Survey.Answer model with all defaults.
defmodule Survey.ExAdmin.Answer do
use ExAdmin.Register
register_resource Survey.Answer do
end
end
## Commands available in the register_resource do block
* `menu` - Customize the properties of the menu item
* `index` - Customize the index page
* `show` - Customize the show page
* `form` - Customize the form page
* `query` - Customize the `Ecto` queries for each page
* `options` - Change various options for a resource
* `member_action` - Add a custom action for id based requests
* `filter` - Disable/Customize the filter pages
* `controller` - Override the default controller
* `action_items` - Define which actions are available for a resource
* `batch_actions` - Customize the batch_actions shown on the index page
* `csv` - Customize the csv export file
* `collection_action` - Add a custom action for collection based requests
* `clear_action_items!` - Remove the action item buttons
* `action_item` - Defines custom action items
* `changesets` - Defines custom changeset functions
"""
if File.dir?("/tmp") do
@filename "/tmp/ex_admin_registered"
else
@filename System.tmp_dir <> "/ex_admin_registered"
end
import ExAdmin.Utils
import ExAdmin.DslUtils
defmacro __using__(_) do
quote do
use ExAdmin.Index, except: [actions: 1]
use ExAdmin.Show
use ExAdmin.Form, except: [actions: 1]
use ExAdmin.CSV
import unquote(__MODULE__)
import Phoenix.HTML.Tag
import Ecto.Query, only: [from: 2]
import Xain, except: [input: 1, input: 2, input: 3, menu: 1, form: 2]
import ExAdmin.ViewHelpers
Module.register_attribute __MODULE__, :member_actions, accumulate: true, persist: true
Module.register_attribute __MODULE__, :collection_actions, accumulate: true, persist: true
end
end
File.rm @filename
File.touch @filename
@doc """
Register an Ecto model.
Once registered, ExAdmin adds the resource to the administration
pages. If no additional code is added to the do block, the resource
will be rendered with defaults, including:
* A paginated index page listing all columns in the model's database
table
* A details page (show) listing fields and simple associations
* New and edit pages
* A menu item
* A CSV export link on the index page
# Default Association Rendering
ExAdmin will render an association using the following algorithm in the following order:
* Look for a `:name` field in the association
* Look for a display_name/1 function in the Admin Resource Module
* Look for a display_name/1 function in the Model's Module
* Use the 2nd field in the Model's schema
"""
defmacro register_resource(mod, [do: block]) do
quote location: :keep do
import ExAdmin.ViewHelpers
import ExAdmin.Utils
require Logger
@all_options [:edit, :show, :new, :delete]
Module.register_attribute __MODULE__, :query, accumulate: false, persist: true
Module.register_attribute __MODULE__, :index_filters, accumulate: true, persist: true
Module.register_attribute __MODULE__, :batch_actions, accumulate: true, persist: true
Module.register_attribute __MODULE__, :selectable_column, accumulate: false, persist: true
Module.register_attribute(__MODULE__, :form_items, accumulate: true, persist: true)
Module.register_attribute(__MODULE__, :controller_plugs, accumulate: true, persist: true)
Module.register_attribute(__MODULE__, :sidebars, accumulate: true, persist: true)
Module.register_attribute(__MODULE__, :scopes, accumulate: true, persist: true)
Module.register_attribute __MODULE__, :actions, accumulate: true, persist: true
Enum.each @all_options, &(Module.put_attribute __MODULE__, :actions, &1)
module = unquote(mod)
Module.put_attribute(__MODULE__, :module, module)
Module.put_attribute(__MODULE__, :query, nil)
Module.put_attribute(__MODULE__, :selectable_column, nil)
Module.put_attribute(__MODULE__, :changesets, [])
Module.put_attribute(__MODULE__, :update_changeset, :changeset)
Module.put_attribute(__MODULE__, :create_changeset, :changeset)
@name_column Module.get_attribute(__MODULE__, :name_column) || apply(ExAdmin.Helpers, :get_name_field, [module])
alias unquote(mod)
import Ecto.Query
def config do
apply __MODULE__, :__struct__, []
end
unquote(block)
query_opts = case Module.get_attribute(__MODULE__, :query) do
nil ->
list = module.__schema__(:associations)
|> Enum.map(&(ExAdmin.Register.build_query_association module, &1))
|> Enum.filter(&(not is_nil(&1)))
query = %{all: [preload: list]}
Module.put_attribute __MODULE__, :query, query
query
other -> other
end
controller = case Module.get_attribute(__MODULE__, :controller) do
nil ->
controller_mod = String.to_atom("#{module}Controller")
Module.put_attribute(__MODULE__, :controller, controller_mod)
other ->
Logger.warn "Should not get here - controller: #{inspect other}"
end
menu_opts = case Module.get_attribute(__MODULE__, :menu) do
false ->
%{none: true}
nil ->
%{ priority: 10,
label: (base_name(module) |> Inflex.pluralize)}
other ->
Enum.into other, %{}
end
controller_route = (base_name(module) |> Inflex.underscore |> Inflex.pluralize)
controller_route = case Module.get_attribute(__MODULE__, :options) do
nil -> controller_route
options ->
Keyword.get(options, :controller_route, controller_route)
end
plugs = case Module.get_attribute(__MODULE__, :controller_plugs) do
nil -> []
list -> Enum.reverse list
end
sidebars = case Module.get_attribute(__MODULE__, :sidebars) do
nil -> []
list -> Enum.reverse list
end
scopes = case Module.get_attribute(__MODULE__, :scopes) do
nil -> []
list -> Enum.reverse list
end
controller_filters = (Module.get_attribute(__MODULE__, :controller_filters) || [])
|> ExAdmin.Helpers.group_reduce_by_reverse
action_labels = ExAdmin.Register.get_action_labels(Module.get_attribute(__MODULE__, :actions))
actions =
ExAdmin.Register.get_action_items(Module.get_attribute(__MODULE__, :actions), @all_options)
|> ExAdmin.Register.custom_action_actions(Module.get_attribute(__MODULE__, :member_actions), module, :member_actions)
|> ExAdmin.Register.custom_action_actions(Module.get_attribute(__MODULE__, :collection_actions), module, :collection_actions)
defstruct controller: @controller,
controller_methods: Module.get_attribute(__MODULE__, :controller_methods),
title_actions: &ExAdmin.default_resource_title_actions/2,
type: :resource,
resource_model: module,
resource_name: resource_name(module),
query_opts: query_opts,
controller_route: controller_route,
menu: menu_opts,
actions: actions,
action_labels: action_labels,
member_actions: Module.get_attribute(__MODULE__, :member_actions),
collection_actions: Module.get_attribute(__MODULE__, :collection_actions),
controller_filters: controller_filters,
index_filters: Module.get_attribute(__MODULE__, :index_filters),
selectable_column: Module.get_attribute(__MODULE__, :selectable_column),
position_column: Module.get_attribute(__MODULE__, :position_column),
name_column: @name_column,
batch_actions: Module.get_attribute(__MODULE__, :batch_actions),
changesets: Module.get_attribute(__MODULE__, :changesets),
plugs: plugs,
sidebars: sidebars,
scopes: scopes,
create_changeset: @create_changeset,
update_changeset: @update_changeset
def run_query(repo, defn, action, id \\ nil) do
%__MODULE__{}
|> Map.get(:resource_model)
|> ExAdmin.Query.run_query(repo, defn, action, id, @query)
end
def run_custom_query(query, repo, defn, action, id \\ nil) do
ExAdmin.Query.run_query(query, repo, defn, action, id, @query)
end
def run_query_counts(repo, defn, action, id \\ nil) do
%__MODULE__{}
|> Map.get(:resource_model)
|> ExAdmin.Query.run_query_counts(repo, defn, action, id, @query)
end
def build_admin_search_query(keywords) do
cond do
function_exported?(@module, :admin_search_query, 1) ->
apply(@module, :admin_search_query, [keywords])
function_exported?(__MODULE__, :admin_search_query, 1) ->
apply(__MODULE__, :admin_search_query, [keywords])
true ->
suggest_admin_search_query(keywords)
end
end
defp suggest_admin_search_query(keywords) do
field = @name_column
query = from r in @module, order_by: ^field
case keywords do
nil ->
query
"" ->
query
keywords ->
from r in query, where: ilike(field(r, ^field), ^("%#{keywords}%"))
end
end
def changeset_fn(defn, action) do
Keyword.get(defn.changesets, action, &defn.resource_model.changeset/2)
end
def plugs(), do: @controller_plugs
File.write!(unquote(@filename), "#{__MODULE__}\n", [:append])
end
end
@doc false
def get_action_labels(nil), do: []
def get_action_labels([opts|_]) when is_list(opts) do
opts[:labels] || []
end
def get_action_labels(_), do: []
@doc false
def get_action_items(nil, _), do: []
def get_action_items(actions, all_options) when is_list(actions) do
{atoms, keywords} =
List.flatten(actions)
|> Enum.reduce({[], []}, fn
atom, {acca, acck} when is_atom(atom) -> {[atom | acca], acck}
kw, {acca, acck} -> {acca, [kw | acck]}
end)
atoms = Enum.reverse atoms
keywords = Enum.reverse Keyword.drop(keywords, [:labels])
cond do
keywords[:only] && keywords[:except] ->
raise "options :only and :except cannot be used together"
keywords[:only] ->
Keyword.delete(keywords, :only) ++ keywords[:only]
keywords[:except] ->
Keyword.delete(keywords, :except) ++ all_options -- keywords[:except]
true ->
keywords ++ atoms
end
end
def custom_action_actions(actions, custom_actions, module, type) do
custom_actions
|> Enum.reduce(actions, fn {name, opts}, acc ->
fun = quote do
name = unquote(name)
human_name = case unquote(opts)[:opts][:label] do
nil -> humanize name
label -> label
end
module = unquote(module)
type = unquote(type)
if type == :member_actions do
fn id ->
resource = struct(module.__struct__, id: id)
url = ExAdmin.Utils.admin_resource_path(resource, :member, [name])
ExAdmin.ViewHelpers.action_item_link human_name, href: url, "data-method": :put
end
else
fn id ->
resource = module
url = ExAdmin.Utils.admin_resource_path(resource, :collection, [name])
ExAdmin.ViewHelpers.action_item_link human_name, href: url
end
end
end
action = if type == :member_actions, do: :show, else: :index
[{action, fun} | acc]
end)
end
@doc """
Override the controller for a resource.
Allows custom actions, filters, and plugs for the controller. Commands
in the controller block include:
* `define_method` - Create a controller action with the body of
the action
* `before_filter` - Add a before_filter to the controller
* `after_filter` - Add an after callback to the controller
* `redirect_to` - Redirects to another page
* `plug` - Add a plug to the controller
"""
defmacro controller([do: block]) do
quote do
Module.register_attribute(__MODULE__, :controller_methods, accumulate: false, persist: true)
Module.register_attribute(__MODULE__, :controller_filters, accumulate: true, persist: true)
Module.put_attribute(__MODULE__, :controller_methods, [])
unquote(block)
end
end
defmacro controller(controller_mod) do
quote do
Module.put_attribute __MODULE__, :controller, unquote(controller_mod)
end
end
@doc """
Override the changesets for a controller's update action
"""
defmacro update_changeset(changeset) do
quote do
Module.put_attribute __MODULE__, :update_changeset, unquote(changeset)
end
end
@doc """
Override the changesets for a controller's create action
"""
defmacro create_changeset(changeset) do
quote do
Module.put_attribute __MODULE__, :create_changeset, unquote(changeset)
end
end
@doc """
Override an action on a controller.
Allows the customization of controller actions.
## Examples
Override the index action to redirect to the root page.
controller do
define_method(:index) do
redirect_to "/"
end
end
"""
defmacro define_method(name, [do: block]) do
quote do
methods = Module.get_attribute(__MODULE__, :controller_methods)
Module.put_attribute(__MODULE__, :controller_methods, [{unquote(name), []} | methods])
unquote(block)
end
end
@doc """
Add a before_filter to a controller.
The before filter is executed before the controller action(s) are
executed.
Normally, the function should return the conn struct. However, if you
want to modify the params, then return the tuple `{conn, new_parms}`.
## Examples
The following example illustrates how to add a sync action that will
be run before the index page is loaded.
controller do
before_filter :sync, only: [:index]
def sync(conn, _) do
BackupRestore.sync
conn
end
end
controller do
before_filter :no_change, except: [:create, :modify]
def no_change(conn, params) do
{conn, put_in(params, [:setting, :no_mod], true)}
end
end
"""
defmacro before_filter(name, opts \\ []) do
quote location: :keep do
Module.put_attribute(__MODULE__, :controller_filters, {:before_filter, {unquote(name), unquote(opts)}})
end
end
@doc """
Add an after filter to a controller.
The after filter is executed after the controller action(s) are
executed and before the page is rendered/redirected. In the case of `update`
and `create`, it is only called on success.
Normally, the function should return the conn struct. However, you can also
return a `{conn, params, resource}` to modify the params and resource.
## Examples
controller do
after_filter :do_after, only: [:create, :update]
def do_after(conn, params, resource, :create) do
user = Repo.all(User) |> hd
resource = Product.changeset(resource, %{user_id: user.id})
|> Repo.update!
{Plug.Conn.assign(conn, :product, resource), params, resource}
end
def do_after(conn, _params, _resource, :update) do
Plug.Conn.assign(conn, :answer, 42)
end
end
"""
defmacro after_filter(name, opts \\ []) do
quote location: :keep do
Module.put_attribute(__MODULE__, :controller_filters, {:after_filter, {unquote(name), unquote(opts)}})
end
end
@doc """
Override the changeset function for `update` and `create` actions.
By default, `changeset/2` for the resource will be used.
## Examples
The following example illustrates how to add a sync action that will
be run before the index page is loaded.
changesets create: &__MODULE__.create_changeset/2,
update: &__MODULE__.update_changeset/2
def create_changeset(model, params) do
Ecto.Changeset.cast(model, params, ~w(name password), ~w(age))
end
def update_changeset(model, params) do
Ecto.Changeset.cast(model, params, ~w(name), ~w(age password))
end
"""
defmacro changesets(opts) do
quote location: :keep do
Module.put_attribute(__MODULE__, :changesets, unquote(opts))
end
end
@doc """
Redirect to a given path.
Use this command in a controller block to redirect to another page.
"""
defmacro redirect_to(path) do
quote do
[{name, opts} | tail] = Module.get_attribute(__MODULE__, :controller_methods)
new_opts = [{:redirect_to, unquote(path)} | opts]
Module.put_attribute(__MODULE__, :controller_methods, [{name, new_opts} | tail])
end
end
@doc """
Add a plug to the controller.
Add custom plugs to a controller.
## Example
controller do
plug :my_plug, the_answer: 42
end
"""
defmacro plug(name, opts \\ []) do
quote do
Module.put_attribute(__MODULE__, :controller_plugs, {unquote(name), unquote(opts)})
end
end
@doc """
Register a static page.
Use `register_page` to create a static page, like a dashboard, or
welcome page to the admin interface.
See the default dashboard page for an example.
"""
defmacro register_page(name, [do: block]) do
quote location: :keep do
import ExAdmin.Register, except: [column: 1]
use ExAdmin.Page
Module.register_attribute __MODULE__, :query, accumulate: false, persist: true
Module.register_attribute __MODULE__, :index_filters, accumulate: true, persist: true
Module.register_attribute __MODULE__, :batch_actions, accumulate: true, persist: true
Module.register_attribute __MODULE__, :selectable_column, accumulate: false, persist: true
Module.register_attribute __MODULE__, :form_items, accumulate: true, persist: true
Module.register_attribute(__MODULE__, :sidebars, accumulate: true, persist: true)
Module.put_attribute __MODULE__, :controller_plugs, nil
page_name = unquote(name)
unquote(block)
# query_opts = Module.get_attribute(__MODULE__, :query)
menu_opts = case Module.get_attribute(__MODULE__, :menu) do
false ->
%{none: true}
nil ->
%{label: page_name, priority: 99}
other ->
Enum.into other, %{}
end
controller_methods = Module.get_attribute(__MODULE__, :controller_methods)
page_name = Kernel.to_string(page_name)
plugs = case Module.get_attribute(__MODULE__, :controller_plugs) do
nil -> []
list -> Enum.reverse list
end
sidebars = case Module.get_attribute(__MODULE__, :sidebars) do
nil -> []
list -> Enum.reverse list
end
defstruct controller: Module.concat(Application.get_env(:ex_admin, :project), AdminController),
controller_methods: Module.get_attribute(__MODULE__, :controller_methods),
type: :page,
page_name: page_name,
title_actions: &ExAdmin.default_page_title_actions/2,
controller_route: (page_name |> Inflex.parameterize("_")),
menu: menu_opts,
member_actions: Module.get_attribute(__MODULE__, :member_actions),
collection_actions: Module.get_attribute(__MODULE__, :collection_actions),
controller_filters: Module.get_attribute(__MODULE__, :controller_filters),
index_filters: [false],
# selectable_column: Module.get_attribute(__MODULE__, :selectable_column),
batch_actions: Module.get_attribute(__MODULE__, :batch_actions),
plugs: plugs,
sidebars: sidebars,
scopes: []
def plugs(), do: @controller_plugs
File.write!(unquote(@filename), "#{__MODULE__}\n", [:append])
end
end
@doc """
Add a sidebar to the page.
The available options are:
* `:only` - Filters the list of actions for the filter.
* `:except` - Filters out actions in the except atom or list.
## Examples
sidebar "ExAdmin Demo", only: [:index, :show] do
Phoenix.View.render ExAdminDemo.AdminView, "sidebar_links.html", []
end
sidebar :Orders, only: :show do
attributes_table_for resource do
row "title", fn(_) -> { resource.title } end
row "author", fn(_) -> { resource.author } end
end
end
# customize the panel
sidebar "Expert Administration", box_attributes: ".box.box-warning",
header_attributes: ".box-header.with-border.text-yellow" do
Phoenix.View.render MyApp.AdminView, "sidebar_warning.html", []
end
"""
defmacro sidebar(name, opts \\ [], [do: block]) do
contents = quote do
unquote(block)
end
quote location: :keep, bind_quoted: [name: escape(name), opts: escape(opts), contents: escape(contents)] do
fun_name = "side_bar_#{name}" |> String.replace(" ", "_") |> String.to_atom
def unquote(fun_name)(var!(conn), var!(resource)) do
_ = var!(conn)
_ = var!(resource)
unquote(contents)
end
Module.put_attribute __MODULE__, :sidebars, {name, opts, {__MODULE__, fun_name}}
end
end
@doc """
Scope the index page.
## Examples
scope :all, default: true
scope :available, fn(q) ->
now = Ecto.Date.utc
where(q, [p], p.available_on <= ^now)
end
scope :drafts, fn(q) ->
now = Ecto.Date.utc
where(q, [p], p.available_on > ^now)
end
scope :featured_products, [], fn(q) ->
where(q, [p], p.featured == true)
end
scope :featured
"""
defmacro scope(name) do
quote location: :keep do
Module.put_attribute __MODULE__, :scopes, {unquote(name), []}
end
end
defmacro scope(name, opts_or_fun) do
quote location: :keep do
opts_or_fun = unquote(opts_or_fun)
if is_function(opts_or_fun) do
scope unquote(name), [], unquote(opts_or_fun)
else
Module.put_attribute __MODULE__, :scopes, {unquote(name), opts_or_fun}
end
end
end
defmacro scope(name, opts, fun) do
contents = quote do
unquote(fun)
end
quote location: :keep, bind_quoted: [name: escape(name), opts: escape(opts), contents: escape(contents)] do
fun_name = "scope_#{name}" |> String.replace(" ", "_") |> String.to_atom
def unquote(fun_name)(var!(resource)) do
unquote(contents).(var!(resource))
end
opts = [{:fun, {__MODULE__, fun_name}} | opts]
Module.put_attribute __MODULE__, :scopes, {name, opts}
end
end
@doc """
Customize the resource admin page by setting options for the page.
The available actions are:
* TBD
"""
defmacro options(opts) do
quote do
Module.put_attribute __MODULE__, :options, unquote(opts)
end
end
@doc """
Customize the menu of a page.
The available options are:
* `:priority` - Sets the position of the menu, with 0 being the
left most menu item
* `:label` - The name used in the menu
* `:if` - Only display the menu item if the condition returns non false/nil
* `:url` - The custom URL used in the menu link
## Examples
The following example adds a custom label, sets the priority, and is
only displayed if the current user is a superadmin.
menu label: "Backup & Restore", priority: 14, if: &__MODULE__.is_superadmin/1
This example disables the menu item:
menu false
"""
defmacro menu(opts) do
quote do
Module.put_attribute __MODULE__, :menu, unquote(opts)
end
end
@doc """
Add query options to the Ecto queries.
For the most part, use `query` to setup preload options. Query
customization can be done for all pages, or individually specified.
## Examples
Load the belongs_to :category, has_many :phone_numbers, and
the has_many :groups for all pages for the resource.
query do
%{
all: [preload: [:category, :phone_numbers, :groups]],
}
end
Load the has_many :contacts association, as well as the has_many
:phone_numbers of the contact
query do
%{show: [preload: [contacts: [:phone_numbers]]] }
end
A more complicated example that defines a default preload, with a
more specific preload for the show page.
query do
%{
all: [preload: [:group]],
show: [preload: [:group, messages: [receiver: [:category, :phone_numbers]]]]
}
end
Change the index page default sort order to ascending.
query do
%{index: [default_sort_order: :asc]}
end
Change the index page default sort field and order.
query do
%{index: [default_sort: [asc: :name]]}
end
Change the index page default sort field.
query do
%{index: [default_sort_field: :name]}
end
"""
defmacro query(do: qry) do
quote do
Module.put_attribute __MODULE__, :query, unquote(qry)
end
end
@doc """
Add a column to a table.
Can be used on the index page, or in the table attributes on the
show page.
A number of options are valid:
* `label` - Change the name of the column heading
* `fields` - Add the fields to be included in an association
* `link` - Set to true to add a link to an association
* `fn/1` - An anonymous function to be called to render the field
* `collection` - Add the collection for a belongs_to association
"""
defmacro column(name, opts \\ [], fun \\ nil) do
quote do
opts = ExAdmin.DslUtils.fun_to_opts unquote(opts), unquote(fun)
var!(columns, ExAdmin.Show) = [{unquote(name), (opts)} | var!(columns, ExAdmin.Show)]
end
end
@doc """
Drag&drop control for sortable tables.
`fa_icon_name` is one of [Font Awesome icons](https://fortawesome.github.io/Font-Awesome/icons/),
default - ["bars"](http://fortawesome.github.io/Font-Awesome/icon/bars/)
"""
defmacro sort_handle_column(fa_icon_name \\ "bars") do
quote do
column "", [], fn(_) ->
i "", class: "fa fa-#{unquote(fa_icon_name)} handle", "aria-hidden": "true"
end
end
end
@doc """
Add a row to the attributes table on the show page.
See `column/3` for a list of options.
"""
defmacro row(name, opts \\ [], fun \\ nil) do
quote do
opts = ExAdmin.DslUtils.fun_to_opts unquote(opts), unquote(fun)
var!(rows, ExAdmin.Show) = [{unquote(name), opts} | var!(rows, ExAdmin.Show)]
end
end
@doc """
Add a link to a path
"""
defmacro link_to(name, path, opts \\ quote(do: [])) do
quote do
opts = Keyword.merge [to: unquote(path)], unquote(opts)
Phoenix.HTML.Link.link "#{unquote(name)}", opts
end
end
@doc false
# Note: `actions/2` has been deprecated. Please use `action_items/1` instead
defmacro actions(:all, opts \\ quote(do: [])) do
require Logger
Logger.warn "actions/2 has been deprecated. Please use action_items/1 instead"
quote do
opts = unquote(opts)
Module.put_attribute __MODULE__, :actions, unquote(opts)
end
end
@doc """
Define which actions will be displayed.
Action labels could be overriden with `labels` option.
## Examples
action_items except: [:new, :delete, :edit]
action_items only: [:new]
action_items labels: [delete: "Revoke"]
Notes:
* this replaces the deprecated `actions/2` macro
* `action_items` macro will not remove any custom actions defined by the `action_item` macro.
"""
defmacro action_items(opts \\ nil) do
quote do
opts = unquote(opts)
Module.put_attribute __MODULE__, :actions, unquote(opts)
end
end
@doc """
Add an id based action and show page link.
Member actions are those actions that act on an individual record in
the database.
## Examples
The following example illustrates how to add a restore action to
a backup and restore page.
member_action :restore, &__MODULE__.restore_action/2
...
def restore_action(conn, params) do
case BackupRestore.restore Repo.get(BackupRestore, params[:id]) do
{:ok, filename} ->
Controller.put_flash(conn, :notice, "Restore \#{filename} complete.")
{:error, message} ->
Controller.put_flash(conn, :error, "Restore Failed: \#{message}.")
end
|> Controller.redirect(to: ExAdmin.Utils.admin_resource_path(conn, :index))
end
The above example adds the following:
* a custom `restore` action to the controller, accessible by the route
/admin/:resource/:id/member/restore
* a "Restore" action link to the show page
## Options
* an optional label: "Button Label"
"""
defmacro member_action(name, fun, opts \\ []) do
quote do
Module.put_attribute __MODULE__, :member_actions, {unquote(name), [fun: unquote(fun), opts: unquote(opts)]}
end
end
@doc """
Add a action that acts on a collection and adds a link to the index page.
## Examples
The following example shows how to add a backup action on the index
page.
collection_action :backup, &__MODULE__.backup_action/2, label: "Backup Database!"
def backup_action(conn, _params) do
Repo.insert %BackupRestore{}
Controller.put_flash(conn, :notice, "Backup complete.")
|> Controller.redirect(to: ExAdmin.Utils.admin_resource_path(conn, :index))
end
The above example adds the following:
* a custom `backup` action to the controller, accessible by the route
/admin/:resource/collection/backup
* a "Backup Database!" action link to the show page
## Options
* an optional label: "Button Label" (shown above)
"""
defmacro collection_action(name, fun, opts \\ []) do
quote do
Module.put_attribute __MODULE__, :collection_actions, {unquote(name), [fun: unquote(fun), opts: unquote(opts)]}
end
end
@doc """
Clear the default [:edit, :show, :new, :delete] action items.
Can be used alone, or followed with `action_item` to add custom actions.
"""
defmacro clear_action_items! do
quote do
Module.delete_attribute __MODULE__, :actions
Module.register_attribute __MODULE__, :actions, accumulate: true, persist: true
end
end
@doc """
Add a custom action button to the page.
## Examples
The following example demonstrates how to add a custom button to your
index page, with no other action buttons due to the `clear_action_items!`
call.
clear_action_items!
action_item :index, fn ->
action_item_link "Something Special", href: "/my/custom/route"
end
An example of adding a link to the show page
action_item :show, fn id ->
action_item_link "Show Link", href: "/custom/link", "data-method": :put, id: id
end
"""
defmacro action_item(opts, fun) do
fun = Macro.escape(fun, unquote: true)
quote do
Module.put_attribute __MODULE__, :actions, {unquote(opts), unquote(fun)}
end
end
@doc """
Customize the filter pages on the right side of the index page.
## Examples
Disable the filter view:
filter false
Only show index columns and filters for the specified fields:
filter [:name, :email, :inserted_at]
filter [:name, :inserted_at, email: [label: "EMail Address"]]
filter [:name, :inserted_at, posts: [order_by: [asc: :name]]]
Note: Restricting fields with the `filter` macro also removes the field columns
from the default index table.
"""
defmacro filter(disable) when disable in [nil, false] do
quote do
Module.put_attribute __MODULE__, :index_filters, false
end
end
defmacro filter(fields) when is_list(fields) do
quote do
Module.put_attribute __MODULE__, :index_filters, unquote(fields)
end
end
defmacro filter(field, opts \\ quote(do: [])) do
quote do
Module.put_attribute __MODULE__, :index_filters, {unquote(field), unquote(opts)}
end
end
@doc """
Disable the batch_actions button the index page.
## Examples
batch_actions false
"""
defmacro batch_actions(false) do
quote do
Module.put_attribute __MODULE__, :batch_actions, false
end
end
@doc false
def build_query_association(module, field) do
case module.__schema__(:association, field) do
%Ecto.Association.BelongsTo{cardinality: :one} -> field
%Ecto.Association.Has{cardinality: :many} ->
check_preload field, :preload_many
_ ->
nil
end
end
defp check_preload(field, key) do
if Application.get_env :ex_admin, key, true do
field
else
nil
end
end
end
|
lib/ex_admin/register.ex
| 0.842475 | 0.467149 |
register.ex
|
starcoder
|
defmodule OT.Text.Composition do
@moduledoc """
The composition of two non-concurrent operations into a single operation.
"""
alias OT.Text.{Operation, Scanner}
@doc """
Compose two operations into a single equivalent operation.
The operations are composed in such a way that the resulting operation has the
same effect on document state as applying one operation and then the other:
*S ○ compose(Oa, Ob) = S ○ Oa ○ Ob*.
## Example
iex> OT.Text.Composition.compose([%{i: "Bar"}], [%{i: "Foo"}])
[%{i: "FooBar"}]
"""
@spec compose(Operation.t(), Operation.t()) :: Operation.t()
def compose(op_a, op_b) do
{op_a, op_b}
|> next
|> do_compose
end
@spec do_compose(Scanner.output(), Operation.t()) :: Operation.t()
defp do_compose(next_pair, result \\ [])
# Both operations are exhausted.
defp do_compose({{nil, _}, {nil, _}}, result),
do: result
# A is exhausted.
defp do_compose({{nil, _}, {head_b, tail_b}}, result) do
result
|> Operation.append(head_b)
|> Operation.join(tail_b)
end
# B is exhausted.
defp do_compose({{head_a, tail_a}, {nil, _}}, result) do
result
|> Operation.append(head_a)
|> Operation.join(tail_a)
end
# _ / insert
defp do_compose(
{{head_a, tail_a}, {head_b = %{i: _}, tail_b}},
result
) do
{[head_a | tail_a], tail_b}
|> next
|> do_compose(Operation.append(result, head_b))
end
# insert / retain
defp do_compose(
{{head_a = %{i: _}, tail_a}, {retain_b, tail_b}},
result
)
when is_integer(retain_b) do
{tail_a, tail_b}
|> next
|> do_compose(Operation.append(result, head_a))
end
# insert / delete
defp do_compose({{%{i: _}, tail_a}, {%{d: _}, tail_b}}, result) do
{tail_a, tail_b}
|> next
|> do_compose(result)
end
# retain / retain
defp do_compose({{retain_a, tail_a}, {retain_b, tail_b}}, result)
when is_integer(retain_a) and is_integer(retain_b) do
{tail_a, tail_b}
|> next
|> do_compose(Operation.append(result, retain_a))
end
# retain / delete
defp do_compose(
{{retain_a, tail_a}, {head_b = %{d: _}, tail_b}},
result
)
when is_integer(retain_a) do
{tail_a, tail_b}
|> next
|> do_compose(Operation.append(result, head_b))
end
# delete / retain
defp do_compose(
{{head_a = %{d: _}, tail_a}, {retain_b, tail_b}},
result
)
when is_integer(retain_b) do
{tail_a, [retain_b | tail_b]}
|> next
|> do_compose(Operation.append(result, head_a))
end
# delete / delete
defp do_compose(
{{head_a = %{d: _}, tail_a}, {head_b = %{d: _}, tail_b}},
result
) do
{tail_a, [head_b | tail_b]}
|> next
|> do_compose(Operation.append(result, head_a))
end
@spec next(Scanner.input()) :: Scanner.output()
defp next(scanner_input), do: Scanner.next(scanner_input, :delete)
end
|
lib/ot/text/composition.ex
| 0.814164 | 0.70202 |
composition.ex
|
starcoder
|
defmodule NeuralNet.Backprop do
@moduledoc """
This module provides the code that generates the feedforward and backprop data used for training. `get_feedforward` can also be used for normal network evaluation, and is used by `NeuralNet.eval`.
`get_feedforward` returns {output, time_frames}, where output is vector_data.
`get_backprop` returns {error_sum, time_frames}.
vector_data is a map that at its largest contains the keys :values, :partial_derivs, and :backprops. At its smallest, for instance when the network is simply evaluated, with no intention of perfomring backpropogation, it contains only :values. When `get_feedforward` is evaluated, each vector_data gets its :values term populated with evaluation data, in the form of a map with {component_name, value} key-val-pairs. If `calc_partial_derivs` is true, :partial_derivs also get filled in. This data is later used for backpropogation. When `get_backprop` is run, the :backprops keys get filled in with their corresponding data.
`time_frames` is a list returned by both `get_feedforward` and `get_backprop`. Index 1 is the real "beginning of time" (index 0 stores some initial values for vectors used recurrently). Each time_frame is a map of {vector_name, vector_data} key-val-pairs.
### Example
iex> get_feedforward(net, input, false)
{
%{values: %{a: 1.0, b: -0.5, c: -0.6}},
[
%{},
%{input: %{values: %{x: 1.0, y: 0.5}}, output: %{values: %{a: 0.5, b: 0.0, c: -0.9}},
%{input: %{values: %{x: 0.2, y: -0.6}}, output: %{values: %{a: 0.7, b: -0.3, c: -0.7}},
%{input: %{values: %{x: 0.7, y: -0.9}}, output: %{values: %{a: 1.0, b: -0.5, c: -0.6}}
]
}
"""
alias NeuralNet.ActivationFunctions
@doc "Retrieves feedforward data given a network and an input vector-across-time. Returns {output, time_frames}. For info on a `vector-across-time`, see the `NeuralNet` module doc. For info on the return value, see the above module doc. If `calc_partial_derivs` is false, :partial_derivs data is not calculated."
def get_feedforward(net, input, calc_partial_derivs \\ true, given_time_frames \\ [%{}]) do
acc = given_time_frames ++ Enum.map(input, fn input_frame ->
feedforward = %{values: input_frame}
%{input: (if calc_partial_derivs, do: Map.put(feedforward, :partial_derivs, %{}), else: feedforward)}
end)
#make sure outputs from every time frame are calculated
acc = Enum.reduce 1..(length(acc)-2), acc, fn time, acc ->
{_, acc} = get_feedforward(net, calc_partial_derivs, acc, time, :output)
acc
end
get_feedforward(net, calc_partial_derivs, acc, length(acc)-1, :output)
end
defp get_feedforward(net, calc_partial_derivs, acc, time = 0, vec) do
feedforward = %{values:
Enum.reduce(Map.fetch!(net.vec_defs, vec), %{}, fn id, map ->
Map.put(map, id, 0)
end)
}
feedforward = if calc_partial_derivs, do: Map.put(feedforward, :partial_derivs, feedforward.values), else: feedforward
{feedforward, update_acc(acc, time, vec, feedforward)}
end
defp get_feedforward(net, calc_partial_derivs, acc, time, {:previous, vec}) do
get_feedforward(net, calc_partial_derivs, acc, time - 1, vec)
end
defp get_feedforward(net, calc_partial_derivs, acc, time, vec) do
time_frame = Enum.at(acc, time)
if Map.has_key? time_frame, vec do
{Map.fetch!(time_frame, vec), acc}
else
{vec_specs, inputs} = Map.fetch!(Map.merge(net.operations, net.net_layers), vec)
{input_map, acc} = Enum.reduce inputs, {%{}, acc}, fn input, {input_map, acc} ->
{feedforward, acc} = get_feedforward(net, calc_partial_derivs, acc, time, input)
{Map.put(input_map, input, feedforward.values), acc}
end
feedforward = %{values: %{}}
feedforward = if calc_partial_derivs, do: Map.put(feedforward, :partial_derivs, %{}), else: feedforward
feedforward = Enum.reduce NeuralNet.get_vec_def(net, vec), feedforward, fn output_component, feedforward ->
{values_fun, partial_derivs_fun} = case vec_specs do
:mult ->
product = Enum.reduce(input_map, 1, fn {_input_name, input_vals}, product ->
product * Map.fetch!(input_vals, output_component)
end)
{
fn -> product end,
fn ->
Enum.reduce(input_map, %{}, fn {input_name, input_vals}, partial_derivs_map ->
input_part_val = Map.fetch!(input_vals, output_component)
input_name = case input_name do
{:previous, input_name} -> input_name
input_name -> input_name
end
Map.put(partial_derivs_map, input_name,
(if input_part_val != 0, do: product / input_part_val, else: 0)
)
end)
end
}
{:mult_const, const} ->
{
fn ->
[input] = inputs
const * Map.fetch!(Map.fetch!(input_map, input), output_component)
end,
fn -> const end
}
:add ->
{
fn ->
Enum.reduce(input_map, 0, fn {_input_name, input_vals}, sum ->
sum + Dict.fetch!(input_vals, output_component)
end)
end,
fn -> 1 end
}
{:add_const, const} ->
{
fn ->
[input] = inputs
const + Map.fetch!(Map.fetch!(input_map, input), output_component)
end,
fn -> 1 end
}
:pointwise_tanh ->
{
fn ->
[input] = inputs
x = Map.fetch!(Map.fetch!(input_map, input), output_component)
ActivationFunctions.tanh(x)
end,
fn ->
[input] = inputs
x = Map.fetch!(Map.fetch!(input_map, input), output_component)
ActivationFunctions.tanh_prime(x)
end
}
{:tanh_given_weights, weight_vec, actual_inputs} ->
weight_vals = Map.fetch!(input_map, weight_vec)
sum = Enum.reduce(actual_inputs, 0, fn input_name, sum ->
Enum.reduce(Map.fetch!(input_map, input_name), sum, fn {input_component, component_val}, sum ->
weight = Map.fetch!(weight_vals, {{input_name, input_component}, output_component})
sum + component_val * weight
end)
end)
{
fn -> ActivationFunctions.tanh(sum) end,
fn ->
partial_derivs_map = Enum.reduce(actual_inputs, %{}, fn input_name, partial_derivs_map ->
Enum.reduce(Map.fetch!(input_map, input_name), partial_derivs_map, fn {input_component, _component_val}, partial_derivs_map ->
weight_val = Map.fetch!(weight_vals, {{input_name, input_component}, output_component})
Map.put(partial_derivs_map, {NeuralNet.deconstruct(input_name), input_component}, weight_val * ActivationFunctions.tanh_prime(sum))
end)
end)
Enum.reduce(Map.fetch!(input_map, weight_vec), partial_derivs_map, fn
{weight_component={{input_name, input_component}, ^output_component}, _weight_val}, partial_derivs_map ->
input_val = Map.fetch!(Map.fetch!(input_map, input_name), input_component)
Map.put(partial_derivs_map, {NeuralNet.deconstruct(weight_vec), weight_component}, input_val * ActivationFunctions.tanh_prime(sum))
{{{_, _}, _}, _}, partial_derivs_map ->
partial_derivs_map
end)
end
}
{:net_layer, activation_function, activation_function_prime} ->
sum = Enum.reduce input_map, 0, fn {input_name, input_vals}, sum ->
Enum.reduce(input_vals, sum, fn {input_component, val}, sum ->
sum + val * Map.fetch!(
Map.fetch!(net.weight_map, vec),
{{input_name, input_component}, output_component}
)
end)
end
{ fn -> activation_function.(sum) end, fn -> activation_function_prime.(sum) end }
end
feedforward = Map.update!(feedforward, :values, fn values ->
Map.put(values, output_component, values_fun.())
end)
if calc_partial_derivs do
Map.update!(feedforward, :partial_derivs, fn partial_derivs ->
Map.put(partial_derivs, output_component, partial_derivs_fun.())
end)
else
feedforward
end
end
{feedforward, update_acc(acc, time, vec, feedforward)}
end
end
defp inject_intial_error(acc, time, exp_output) do
output = Enum.at(acc, time).output
{backprop_error, error_sum} = Enum.reduce(output.values, {%{}, 0}, fn {component, value}, {acc, error_sum} ->
expected = Map.fetch!(exp_output, component)
difference = if expected != nil, do: value - expected, else: 0
{Map.put(acc, component, difference), error_sum + (0.5 * :math.pow(difference, 2))}
end)
{update_acc(acc, time, :output, Map.put(output, :initial_error, backprop_error)), error_sum}
end
@doc "Retrieves backprop data given a network, an input vector-across-time, and `exp_outputs`. `exp_outputs` can either be a vector-across-time, or it can just be a single vector, which would be the expected output for the final time frame. Returns {error_sum, time_frames}. For info on a `vector-across-time`, see the `NeuralNet` module doc. For info on what `time_frames` is, see the above module doc."
def get_backprop(net, input, exp_outputs) do
{_output, acc} = get_feedforward(net, input)
{acc, error_sum} = if is_list(exp_outputs) do
if length(exp_outputs) != length(acc) - 1, do: raise "Length of `exp_output` list should be #{length(acc) - 1}, but instead got #{length(exp_outputs)}"
Enum.reduce Enum.with_index(exp_outputs), {acc, 0}, fn {exp_output, time}, {acc, error_sum} ->
{acc, its_error} = inject_intial_error(acc, time+1, exp_output)
{acc, error_sum + its_error}
end
else
inject_intial_error(acc, -1, exp_outputs)
end
acc = Enum.reduce(net.roots, acc, fn root, acc ->
{_, acc} = get_backprop(net, acc, 1, root)
acc
end)
{error_sum, acc}
end
defp get_backprop(net, acc, time, {:previous, vec}), do: get_backprop(net, acc, time - 1, vec)
defp get_backprop(net, acc, time, {:next, vec}), do: get_backprop(net, acc, time + 1, vec)
defp get_backprop(net, acc, time, vec) when time >= length(acc) or time == 0 do
{backprops, values} = Enum.reduce(Map.fetch!(net.vec_defs, vec), {%{}, %{}}, fn component, {backprops, values} ->
{
Map.put(backprops, component, 0),
Map.put(values, component, 0)
}
end)
vec_acc_data = %{backprops: backprops, values: values}
{vec_acc_data.backprops, update_acc(acc, time, vec, vec_acc_data)}
end
defp get_backprop(net, acc, time, vec) do
vec_acc_data = Map.fetch!(Enum.at(acc, time), vec)
if Map.has_key? vec_acc_data, :backprops do
{vec_acc_data.backprops, acc}
else
affects = Map.get(net.affects, vec)
{backprop_error, acc} = Enum.reduce(Map.fetch!(net.vec_defs, vec), {%{}, acc}, fn component, {backprop_error, acc} ->
{sum, acc} = cond do
affects != nil ->
intial_error = if Map.has_key?(vec_acc_data, :initial_error) do
Map.fetch!(vec_acc_data.initial_error, component)
else
0
end
Enum.reduce(affects, {intial_error, acc}, fn affected, {sum, acc} ->
dec_affected = NeuralNet.deconstruct(affected)
{affected_specs, _} = Map.fetch!(Map.merge(net.operations, net.net_layers), dec_affected)
{affected_backprops, acc} = get_backprop(net, acc, time, affected)
addon = case affected_specs do
{:net_layer, _, _} ->
Enum.reduce(Map.fetch!(net.vec_defs, dec_affected), 0, fn affected_component, sum ->
con_vec = case affected do
{:next, _aff} -> {:previous, vec}
_ -> vec
end
sum + Map.fetch!(affected_backprops, affected_component) * Map.fetch!(Map.fetch!(net.weight_map, dec_affected), {{con_vec, component}, affected_component})
end)
{:tanh_given_weights, weight_vec, _actual_inputs} ->
if weight_vec == vec do
{_source, affected_component} = component
Map.fetch!(Map.fetch!(affected_backprops, affected_component), {vec, component})
else
Enum.reduce(Map.fetch!(net.vec_defs, dec_affected), 0, fn affected_component, sum ->
sum + Map.fetch!(Map.fetch!(affected_backprops, affected_component), {vec, component})
end)
end
_ ->
backprop_component = Map.fetch!(affected_backprops, component)
if is_number(backprop_component) do
backprop_component
else
Map.fetch!(backprop_component, vec)
end
end
{sum + addon, acc}
end)
Map.has_key?(vec_acc_data, :initial_error) ->
{Map.fetch!(vec_acc_data.initial_error, component), acc}
:else ->
{0, acc}
end
{Map.put(backprop_error, component, sum), acc}
end)
vec_acc_data = apply_backprop(vec_acc_data, backprop_error)
{vec_acc_data.backprops, update_acc(acc, time, vec, vec_acc_data)}
end
end
#Multiplies in the transmitted backprop with the partial derivatives of this node.
defp apply_backprop(vec_acc_data, backprop_error) do
Map.put(vec_acc_data, :backprops,
Enum.reduce(vec_acc_data.partial_derivs, %{}, fn {component, partial_deriv}, backprops ->
backprop_component = if is_number(partial_deriv) do
partial_deriv * Map.fetch!(backprop_error, component)
else
Enum.reduce(partial_deriv, %{}, fn {source, sub_partial_deriv}, backprop_component_map ->
Map.put(backprop_component_map, source, sub_partial_deriv * Map.fetch!(backprop_error, component))
end)
end
Map.put(backprops, component, backprop_component)
end)
)
end
defp update_acc(acc, time, vec, value) do
List.update_at acc, time, fn time_frame ->
Map.put(time_frame, vec, value)
end
end
def fetch!(acc, time, {:previous, vec}), do: fetch!(acc, time - 1, vec)
@doc "Fetches `vector_data` from `time_frames` at time `time`, at vector `vec`."
def fetch!(time_frames, time, vec) when time >= 0 do
Map.fetch!(Enum.at(time_frames, time), vec)
end
end
|
lib/neural_net/backprop.ex
| 0.920727 | 0.733309 |
backprop.ex
|
starcoder
|
defmodule EIP1559 do
@behaviour Cadex.Behaviour
alias Cadex.Types.{State, SimulationParameters, PartialStateUpdateBlock}
@timesteps 300
@constants %{
BASEFEE_MAX_CHANGE_DENOMINATOR: 8,
TARGET_GAS_USED: 10000000,
MAX_GAS_EIP1559: 16000000,
EIP1559_DECAY_RANGE: 800000,
EIP1559_GAS_INCREMENT_AMOUNT: 10,
INITIAL_BASEFEE: 1 * :math.pow(10, 9),
PER_TX_GASLIMIT: 8000000
}
defmodule Transaction do
defstruct [:gas_premium, :fee_cap, :gas_used, :tx_hash]
end
@spec is_valid(EIP1559.Transaction.t(), any) :: boolean
def is_valid(%Transaction{fee_cap: fee_cap}, basefee), do: fee_cap >= basefee
def generate_spike_scenario(timesteps \\ @timesteps) do
spikey_boi = div(timesteps, 8)
for n <- 0..timesteps, do: 10_000 * :math.exp(-:math.pow(n - spikey_boi, 2)/16.0)
end
def initial_conditions do
%{
scenario: generate_spike_scenario(),
basefee: 5 * :math.pow(10, 9),
demand: %{},
latest_block_txs: [],
loop_time: :os.system_time(:seconds)
}
end
@partial_state_update_blocks [
%PartialStateUpdateBlock{
policies: [
],
variables: [
{:demand, :update_demand_scenario}
]
},
%PartialStateUpdateBlock{
policies: [
:include_valid_txs
],
variables: [
{:demand, :remove_included_txs},
{:basefee, :update_basefee},
{:latest_block, :record_latest_block},
{:loop_time, :end_loop}
]
},
]
@simulation_parameters %SimulationParameters{
T: 0..@timesteps,
N: 1
}
@impl true
def config do
%State{
sim: %{
simulation_parameters: @simulation_parameters,
partial_state_update_blocks: @partial_state_update_blocks
},
current_state: initial_conditions()
}
end
@impl true
def update({:demand, :update_demand_scenario}, _params, _substep, _previous_states, %{timestep: timestep, demand: _demand, scenario: tx_scenario}, _input) do
start = :os.system_time(:seconds)
demand = Enum.map(1..round(Enum.at(tx_scenario, timestep)), fn _i ->
gas_premium = :crypto.rand_uniform(1, 11) * :math.pow(10, 9)
fee_cap = gas_premium + :crypto.rand_uniform(1, 11) * :math.pow(10, 9)
tx = %Transaction{
tx_hash: :crypto.hash(:md5, :crypto.strong_rand_bytes(32)) |> Base.encode16(),
gas_premium: gas_premium,
gas_used: 21000,
fee_cap: fee_cap
}
%Transaction{tx_hash: tx_hash} = tx
{tx_hash, tx}
end)
|> Enum.into(%{})
IO.puts "Step = #{timestep}, mempool size = #{inspect(demand |> Map.to_list() |> length())}, update demand #{:os.system_time(:seconds) - start}"
{:ok, &Map.merge(&1, demand)}
end
@impl true
def policy(:include_valid_txs, _params, _substep, _previous_states, %{demand: demand, basefee: basefee}) do
start = :os.system_time(:seconds)
included_transactions = demand
|> Enum.filter(fn {_tx_hash, tx} -> is_valid(tx, basefee) end)
|> Enum.into([])
|> Enum.sort_by(fn {_tx_hash, tx} -> tx.gas_premium end)
|> Enum.slice(0..570)
IO.puts "time to sort #{:os.system_time(:seconds) - start}"
{:ok, %{block: included_transactions}}
end
def update({:demand, :remove_included_txs}, _params, _substep, _previous_states, %{demand: _demand}, %{block: block}) do
# start = :os.system_time()
{:ok, &(Enum.reject(&1, fn {tx_hash, _tx} ->
tx_hash in block
end) |> Map.new())}
end
def update({:basefee, :update_basefee}, _params, _substep, _previous_states, %{basefee: basefee}, %{block: block}) do
gas_used = block
|> Enum.reduce(0, fn {_tx_hash, tx}, acc -> acc + tx.gas_used end)
%{TARGET_GAS_USED: target, BASEFEE_MAX_CHANGE_DENOMINATOR: max_change} = @constants
delta = gas_used - target
new_basefee = basefee + basefee * round(round(delta / target) / max_change)
{:ok, new_basefee}
end
def update({:latest_block, :record_latest_block}, _params, _substep, _previous_states, _current_state, %{block: block}) do
{:ok, block}
end
def update({:loop_time, :end_loop}, _params, _substep, _previous_states, %{loop_time: loop_time}, _input) do
time = :os.system_time(:seconds)
IO.puts "loop time #{time - loop_time}"
{:ok, time}
end
end
|
lib/examples/eip1559.ex
| 0.689515 | 0.414869 |
eip1559.ex
|
starcoder
|
defmodule AWS.WAFV2 do
@moduledoc """
This is the latest version of the **AWS WAF** API, released in November, 2019.
The names of the entities that you use to access this API, like endpoints and
namespaces, all have the versioning information added, like "V2" or "v2", to
distinguish from the prior version. We recommend migrating your resources to
this version, because it has a number of significant improvements.
If you used AWS WAF prior to this release, you can't use this AWS WAFV2 API to
access any AWS WAF resources that you created before. You can access your old
rules, web ACLs, and other AWS WAF resources only through the AWS WAF Classic
APIs. The AWS WAF Classic APIs have retained the prior names, endpoints, and
namespaces.
For information, including how to migrate your AWS WAF resources to this
version, see the [AWS WAF Developer Guide](https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html).
AWS WAF is a web application firewall that lets you monitor the HTTP and HTTPS
requests that are forwarded to Amazon CloudFront, an Amazon API Gateway REST
API, an Application Load Balancer, or an AWS AppSync GraphQL API. AWS WAF also
lets you control access to your content. Based on conditions that you specify,
such as the IP addresses that requests originate from or the values of query
strings, the API Gateway REST API, CloudFront distribution, the Application Load
Balancer, or the AWS AppSync GraphQL API responds to requests either with the
requested content or with an HTTP 403 status code (Forbidden). You also can
configure CloudFront to return a custom error page when a request is blocked.
This API guide is for developers who need detailed information about AWS WAF API
actions, data types, and errors. For detailed information about AWS WAF features
and an overview of how to use AWS WAF, see the [AWS WAF Developer Guide](https://docs.aws.amazon.com/waf/latest/developerguide/).
You can make calls using the endpoints listed in [AWS Service Endpoints for AWS WAF](https://docs.aws.amazon.com/general/latest/gr/rande.html#waf_region).
* For regional applications, you can use any of the endpoints in the
list. A regional application can be an Application Load Balancer (ALB), an API
Gateway REST API, or an AppSync GraphQL API.
* For AWS CloudFront applications, you must use the API endpoint
listed for US East (N. Virginia): us-east-1.
Alternatively, you can use one of the AWS SDKs to access an API that's tailored
to the programming language or platform that you're using. For more information,
see [AWS SDKs](http://aws.amazon.com/tools/#SDKs).
We currently provide two versions of the AWS WAF API: this API and the prior
versions, the classic AWS WAF APIs. This new API provides the same functionality
as the older versions, with the following major improvements:
* You use one API for both global and regional applications. Where
you need to distinguish the scope, you specify a `Scope` parameter and set it to
`CLOUDFRONT` or `REGIONAL`.
* You can define a Web ACL or rule group with a single call, and
update it with a single call. You define all rule specifications in JSON format,
and pass them to your rule group or Web ACL calls.
* The limits AWS WAF places on the use of rules more closely
reflects the cost of running each type of rule. Rule groups include capacity
settings, so you know the maximum cost of a rule group when you use it.
"""
alias AWS.Client
alias AWS.Request
def metadata do
%AWS.ServiceMetadata{
abbreviation: "WAFV2",
api_version: "2019-07-29",
content_type: "application/x-amz-json-1.1",
credential_scope: nil,
endpoint_prefix: "wafv2",
global?: false,
protocol: "json",
service_id: "WAFV2",
signature_version: "v4",
signing_name: "wafv2",
target_prefix: "AWSWAF_20190729"
}
end
@doc """
Associates a Web ACL with a regional application resource, to protect the
resource.
A regional application can be an Application Load Balancer (ALB), an API Gateway
REST API, or an AppSync GraphQL API.
For AWS CloudFront, don't use this call. Instead, use your CloudFront
distribution configuration. To associate a Web ACL, in the CloudFront call
`UpdateDistribution`, set the web ACL ID to the Amazon Resource Name (ARN) of
the Web ACL. For information, see
[UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html).
"""
def associate_web_acl(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "AssociateWebACL", input, options)
end
@doc """
Returns the web ACL capacity unit (WCU) requirements for a specified scope and
set of rules.
You can use this to check the capacity requirements for the rules you want to
use in a `RuleGroup` or `WebACL`.
AWS WAF uses WCUs to calculate and control the operating resources that are used
to run your rules, rule groups, and web ACLs. AWS WAF calculates capacity
differently for each rule type, to reflect the relative cost of each rule.
Simple rules that cost little to run use fewer WCUs than more complex rules that
use more processing power. Rule group capacity is fixed at creation, which helps
users plan their web ACL WCU usage when they use a rule group. The WCU limit for
web ACLs is 1,500.
"""
def check_capacity(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CheckCapacity", input, options)
end
@doc """
Creates an `IPSet`, which you use to identify web requests that originate from
specific IP addresses or ranges of IP addresses.
For example, if you're receiving a lot of requests from a ranges of IP
addresses, you can configure AWS WAF to block them using an IPSet that lists
those IP addresses.
"""
def create_ip_set(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateIPSet", input, options)
end
@doc """
Creates a `RegexPatternSet`, which you reference in a
`RegexPatternSetReferenceStatement`, to have AWS WAF inspect a web request
component for the specified patterns.
"""
def create_regex_pattern_set(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateRegexPatternSet", input, options)
end
@doc """
Creates a `RuleGroup` per the specifications provided.
A rule group defines a collection of rules to inspect and control web requests
that you can use in a `WebACL`. When you create a rule group, you define an
immutable capacity limit. If you update a rule group, you must stay within the
capacity. This allows others to reuse the rule group with confidence in its
capacity requirements.
"""
def create_rule_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateRuleGroup", input, options)
end
@doc """
Creates a `WebACL` per the specifications provided.
A Web ACL defines a collection of rules to use to inspect and control web
requests. Each rule has an action defined (allow, block, or count) for requests
that match the statement of the rule. In the Web ACL, you assign a default
action to take (allow, block) for any request that does not match any of the
rules. The rules in a Web ACL can be a combination of the types `Rule`,
`RuleGroup`, and managed rule group. You can associate a Web ACL with one or
more AWS resources to protect. The resources can be Amazon CloudFront, an Amazon
API Gateway REST API, an Application Load Balancer, or an AWS AppSync GraphQL
API.
"""
def create_web_acl(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateWebACL", input, options)
end
@doc """
Deletes all rule groups that are managed by AWS Firewall Manager for the
specified web ACL.
You can only use this if `ManagedByFirewallManager` is false in the specified
`WebACL`.
"""
def delete_firewall_manager_rule_groups(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteFirewallManagerRuleGroups", input, options)
end
@doc """
Deletes the specified `IPSet`.
"""
def delete_ip_set(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteIPSet", input, options)
end
@doc """
Deletes the `LoggingConfiguration` from the specified web ACL.
"""
def delete_logging_configuration(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteLoggingConfiguration", input, options)
end
@doc """
Permanently deletes an IAM policy from the specified rule group.
You must be the owner of the rule group to perform this operation.
"""
def delete_permission_policy(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeletePermissionPolicy", input, options)
end
@doc """
Deletes the specified `RegexPatternSet`.
"""
def delete_regex_pattern_set(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteRegexPatternSet", input, options)
end
@doc """
Deletes the specified `RuleGroup`.
"""
def delete_rule_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteRuleGroup", input, options)
end
@doc """
Deletes the specified `WebACL`.
You can only use this if `ManagedByFirewallManager` is false in the specified
`WebACL`.
"""
def delete_web_acl(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteWebACL", input, options)
end
@doc """
Provides high-level information for a managed rule group, including descriptions
of the rules.
"""
def describe_managed_rule_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeManagedRuleGroup", input, options)
end
@doc """
Disassociates a Web ACL from a regional application resource.
A regional application can be an Application Load Balancer (ALB), an API Gateway
REST API, or an AppSync GraphQL API.
For AWS CloudFront, don't use this call. Instead, use your CloudFront
distribution configuration. To disassociate a Web ACL, provide an empty web ACL
ID in the CloudFront call `UpdateDistribution`. For information, see
[UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html).
"""
def disassociate_web_acl(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DisassociateWebACL", input, options)
end
@doc """
Retrieves the specified `IPSet`.
"""
def get_ip_set(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "GetIPSet", input, options)
end
@doc """
Returns the `LoggingConfiguration` for the specified web ACL.
"""
def get_logging_configuration(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "GetLoggingConfiguration", input, options)
end
@doc """
Returns the IAM policy that is attached to the specified rule group.
You must be the owner of the rule group to perform this operation.
"""
def get_permission_policy(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "GetPermissionPolicy", input, options)
end
@doc """
Retrieves the keys that are currently blocked by a rate-based rule.
The maximum number of managed keys that can be blocked for a single rate-based
rule is 10,000. If more than 10,000 addresses exceed the rate limit, those with
the highest rates are blocked.
"""
def get_rate_based_statement_managed_keys(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "GetRateBasedStatementManagedKeys", input, options)
end
@doc """
Retrieves the specified `RegexPatternSet`.
"""
def get_regex_pattern_set(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "GetRegexPatternSet", input, options)
end
@doc """
Retrieves the specified `RuleGroup`.
"""
def get_rule_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "GetRuleGroup", input, options)
end
@doc """
Gets detailed information about a specified number of requests--a sample--that
AWS WAF randomly selects from among the first 5,000 requests that your AWS
resource received during a time range that you choose.
You can specify a sample size of up to 500 requests, and you can specify any
time range in the previous three hours.
`GetSampledRequests` returns a time range, which is usually the time range that
you specified. However, if your resource (such as a CloudFront distribution)
received 5,000 requests before the specified time range elapsed,
`GetSampledRequests` returns an updated time range. This new time range
indicates the actual period during which AWS WAF selected the requests in the
sample.
"""
def get_sampled_requests(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "GetSampledRequests", input, options)
end
@doc """
Retrieves the specified `WebACL`.
"""
def get_web_acl(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "GetWebACL", input, options)
end
@doc """
Retrieves the `WebACL` for the specified resource.
"""
def get_web_acl_for_resource(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "GetWebACLForResource", input, options)
end
@doc """
Retrieves an array of managed rule groups that are available for you to use.
This list includes all AWS Managed Rules rule groups and the AWS Marketplace
managed rule groups that you're subscribed to.
"""
def list_available_managed_rule_groups(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ListAvailableManagedRuleGroups", input, options)
end
@doc """
Retrieves an array of `IPSetSummary` objects for the IP sets that you manage.
"""
def list_ip_sets(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ListIPSets", input, options)
end
@doc """
Retrieves an array of your `LoggingConfiguration` objects.
"""
def list_logging_configurations(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ListLoggingConfigurations", input, options)
end
@doc """
Retrieves an array of `RegexPatternSetSummary` objects for the regex pattern
sets that you manage.
"""
def list_regex_pattern_sets(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ListRegexPatternSets", input, options)
end
@doc """
Retrieves an array of the Amazon Resource Names (ARNs) for the regional
resources that are associated with the specified web ACL.
If you want the list of AWS CloudFront resources, use the AWS CloudFront call
`ListDistributionsByWebACLId`.
"""
def list_resources_for_web_acl(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ListResourcesForWebACL", input, options)
end
@doc """
Retrieves an array of `RuleGroupSummary` objects for the rule groups that you
manage.
"""
def list_rule_groups(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ListRuleGroups", input, options)
end
@doc """
Retrieves the `TagInfoForResource` for the specified resource.
Tags are key:value pairs that you can use to categorize and manage your
resources, for purposes like billing. For example, you might set the tag key to
"customer" and the value to the customer name or ID. You can specify one or more
tags to add to each AWS resource, up to 50 tags for a resource.
You can tag the AWS resources that you manage through AWS WAF: web ACLs, rule
groups, IP sets, and regex pattern sets. You can't manage or view tags through
the AWS WAF console.
"""
def list_tags_for_resource(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ListTagsForResource", input, options)
end
@doc """
Retrieves an array of `WebACLSummary` objects for the web ACLs that you manage.
"""
def list_web_acls(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ListWebACLs", input, options)
end
@doc """
Enables the specified `LoggingConfiguration`, to start logging from a web ACL,
according to the configuration provided.
You can access information about all traffic that AWS WAF inspects using the
following steps:
1. Create an Amazon Kinesis Data Firehose.
Create the data firehose with a PUT source and in the Region that you are
operating. If you are capturing logs for Amazon CloudFront, always create the
firehose in US East (N. Virginia).
Give the data firehose a name that starts with the prefix `aws-waf-logs-`. For
example, `aws-waf-logs-us-east-2-analytics`.
Do not create the data firehose using a `Kinesis stream` as your source.
2. Associate that firehose to your web ACL using a
`PutLoggingConfiguration` request.
When you successfully enable logging using a `PutLoggingConfiguration` request,
AWS WAF will create a service linked role with the necessary permissions to
write logs to the Amazon Kinesis Data Firehose. For more information, see
[Logging Web ACL Traffic Information](https://docs.aws.amazon.com/waf/latest/developerguide/logging.html)
in the *AWS WAF Developer Guide*.
"""
def put_logging_configuration(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "PutLoggingConfiguration", input, options)
end
@doc """
Attaches an IAM policy to the specified resource.
Use this to share a rule group across accounts.
You must be the owner of the rule group to perform this operation.
This action is subject to the following restrictions:
* You can attach only one policy with each `PutPermissionPolicy`
request.
* The ARN in the request must be a valid WAF `RuleGroup` ARN and the
rule group must exist in the same region.
* The user making the request must be the owner of the rule group.
"""
def put_permission_policy(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "PutPermissionPolicy", input, options)
end
@doc """
Associates tags with the specified AWS resource.
Tags are key:value pairs that you can use to categorize and manage your
resources, for purposes like billing. For example, you might set the tag key to
"customer" and the value to the customer name or ID. You can specify one or more
tags to add to each AWS resource, up to 50 tags for a resource.
You can tag the AWS resources that you manage through AWS WAF: web ACLs, rule
groups, IP sets, and regex pattern sets. You can't manage or view tags through
the AWS WAF console.
"""
def tag_resource(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "TagResource", input, options)
end
@doc """
Disassociates tags from an AWS resource.
Tags are key:value pairs that you can associate with AWS resources. For example,
the tag key might be "customer" and the tag value might be "companyA." You can
specify one or more tags to add to each container. You can add up to 50 tags to
each AWS resource.
"""
def untag_resource(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "UntagResource", input, options)
end
@doc """
Updates the specified `IPSet`.
This operation completely replaces any IP address specifications that you
already have in the IP set with the ones that you provide to this call. If you
want to add to or modify the addresses that are already in the IP set, retrieve
those by calling `GetIPSet`, update them, and provide the complete updated array
of IP addresses to this call.
"""
def update_ip_set(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "UpdateIPSet", input, options)
end
@doc """
Updates the specified `RegexPatternSet`.
"""
def update_regex_pattern_set(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "UpdateRegexPatternSet", input, options)
end
@doc """
Updates the specified `RuleGroup`.
A rule group defines a collection of rules to inspect and control web requests
that you can use in a `WebACL`. When you create a rule group, you define an
immutable capacity limit. If you update a rule group, you must stay within the
capacity. This allows others to reuse the rule group with confidence in its
capacity requirements.
"""
def update_rule_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "UpdateRuleGroup", input, options)
end
@doc """
Updates the specified `WebACL`.
A Web ACL defines a collection of rules to use to inspect and control web
requests. Each rule has an action defined (allow, block, or count) for requests
that match the statement of the rule. In the Web ACL, you assign a default
action to take (allow, block) for any request that does not match any of the
rules. The rules in a Web ACL can be a combination of the types `Rule`,
`RuleGroup`, and managed rule group. You can associate a Web ACL with one or
more AWS resources to protect. The resources can be Amazon CloudFront, an Amazon
API Gateway REST API, an Application Load Balancer, or an AWS AppSync GraphQL
API.
"""
def update_web_acl(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "UpdateWebACL", input, options)
end
end
|
lib/aws/generated/waf_v2.ex
| 0.912632 | 0.471588 |
waf_v2.ex
|
starcoder
|
defmodule MrRoboto.Warden do
@moduledoc """
The Warden is responsible for coordinating the retrieval, parsing and checking
of `robots.txt` files.
It maintains a map of hosts checked and the rules for those hosts. When asked
it will retrieve the rule in question and check to see if the specified
`user-agent` is allowed to crawl that path.
"""
use GenServer
alias MrRoboto.Agent
alias MrRoboto.Parser
alias MrRoboto.Rules
defstruct rule: nil, last_applied: 0
def start_link do
GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
end
def handle_call({:crawl?, {agent, url}}, _from, state) do
uri = URI.parse(url)
updated_records = update_records(uri.host, state)
agent
|> fetch_record(uri.host, updated_records)
|> update_applied
|> permitted?(uri.path)
|> case do
true ->
{:reply, :allowed, updated_records}
false ->
{:reply, :disallowed, updated_records}
:ambiguous ->
{:reply, :ambiguous, updated_records}
end
end
def handle_call({:delay_info, {agent, url}}, _from, state) do
uri = URI.parse(url)
last_checked = agent
|> fetch_record(uri.host, state)
|> case do
nil ->
nil
record ->
%{delay: record.rule.crawl_delay, last_checked: record.last_applied}
end
{:reply, last_checked, state}
end
defp fetch_record(user_agent, host, records) do
records
|> get_in([host, user_agent])
|> case do
%__MODULE__{} = found ->
found
_ ->
get_in records, [host, "*"]
end
end
defp update_applied(record) do
struct record, last_applied: :erlang.system_time(:seconds)
end
@doc """
Updates the state for the Warden.
Returns a nested map of Warden structs.
If the `robots.txt` data is stale or it has not been fetched yet it returns a
new nested map of Warden structs. In the event of an `:error` or the data
being current it returns the current records map.
## Examples
_update_records_ is responsible for managing the state for the Warden server.
This state is a collection of `MrRoboto.Warden.t` structs indexed by host
and user-agent, where there is __one__ `MrRoboto.Warden.t` struct per
_user-agent_ and potentially many _user-agents_ per _host_.
```
%{
"google.com" => %{
"*" => %{rule: %MrRoboto.Rules{}, last_applied: time_in_seconds},
}
}
```
"""
def update_records(host, records) do
Agent
|> GenServer.call({:check, host})
|> case do
{:ok, :current} ->
records
{:ok, body} ->
body
|> Parser.start_parse
|> insert(records, host)
{:error, _reason} ->
records
end
end
defp insert(rule_set, current_records, host) do
rules = Enum.into(rule_set, %{}, fn rule ->
{rule.user_agent, %__MODULE__{rule: rule}}
end)
Map.put current_records, host, rules
end
@doc """
Indicates whether the given path can be crawled
Retrns `true`, `false` or `:ambiguous`
The `Warden` takes two factors into consideration when determining whether a
path is legal. The first factor are the directives in `robots.txt` for the
user-agent. The second is the last time a check was recorded for the site.
## Examples
If the rule indicates that the path is legal then the `last_applied` time is
compared to the current time before returning an answer.
```
iex> Warden.permitted? %Warden{rule: %Rules{user_agent: "*", allow: ["/"], disallow: [], crawl_delay: 1000}, last_applied: 0}, "/"
# assuming the current time is large enough
true
# assuming the current time is say 5
false
```
In the case where the `MrRoboto.Rules` struct indicates that the rule is
not permitted then `false` is returned.
__Note__: The `last_applied` is not considered in this case
```
iex> Warden.permitted? %Warden{rule: %Rules{user_agent: "*", allow: [], disallow: ["/"]}}, "/"
false
```
In the case where the `MrRoboto.Rules` struct is ambiguous as to permission
then `:ambiguous` is returned.
__Note__: The `last_applied` is not considered in this case
```
iex> Warden.permitted? %Warden{rule: %Rules{user_agent: "*", allow: ["/"], disallow: ["/"]}}, "/"
```
"""
def permitted?(%__MODULE__{rule: rule, last_applied: _last_applied}, path) do
Rules.permitted?(rule, path || "/")
end
end
|
lib/mr_roboto/warden.ex
| 0.803637 | 0.802246 |
warden.ex
|
starcoder
|
defmodule ApiWeb.SwaggerHelpers do
@moduledoc """
Collect commonly used parameters for the Swagger documentation generation
using PhoenixSwagger.
https://github.com/xerions/phoenix_swagger
"""
alias PhoenixSwagger.{JsonApi, Path, Schema}
@sort_types ~w(ascending descending)s
def comma_separated_list, do: ~S|**MUST** be a comma-separated (U+002C COMMA, ",") list|
def common_index_parameters(path_object, module, name \\ nil, include \\ nil)
when is_atom(module) do
sort_pairs = sort_pairs(module)
path_object
|> Path.parameter(
"page[offset]",
:query,
:integer,
"Offset (0-based) of first element in the page",
minimum: 0
)
|> Path.parameter(
"page[limit]",
:query,
:integer,
"Max number of elements to return",
minimum: 1
)
|> sort_parameter(sort_pairs, include)
|> fields_param(name)
end
def common_show_parameters(path_object, name) do
fields_param(path_object, name)
end
def direction_id_attribute(schema) do
JsonApi.attribute(
schema,
:direction_id,
direction_id_schema(),
"""
Direction in which trip is traveling: `0` or `1`.
#{direction_id_description()}
"""
)
end
def direction_id_description do
"""
The meaning of `direction_id` varies based on the route. You can programmatically get the direction names from \
`/routes` `/data/{index}/attributes/direction_names` or `/routes/{id}` `/data/attributes/direction_names`.
"""
end
@spec occupancy_status_description() :: String.t()
def occupancy_status_description do
"""
The degree of passenger occupancy for the vehicle. See [GTFS-realtime OccupancyStatus](https://github.com/google/transit/blob/master/gtfs-realtime/spec/en/reference.md#enum-vehiclestopstatus).
| _**Value**_ | _**Description**_ |
|--------------------------------|-----------------------------------------------------------------------------------------------------|
| **MANY_SEATS_AVAILABLE** | Not crowded: the vehicle has a large percentage of seats available. |
| **FEW_SEATS_AVAILABLE** | Some crowding: the vehicle has a small percentage of seats available. |
| **FULL** | Crowded: the vehicle is considered full by most measures, but may still be allowing passengers to board. |
"""
end
def direction_id_schema, do: %Schema{type: :integer, enum: [0, 1]}
def include_parameters(path_object, includes, options \\ []) do
Path.parameter(path_object, :include, :query, :string, """
Relationships to include.
#{Enum.map_join(includes, "\n", fn include -> "* `#{include}`" end)}
The value of the include parameter #{comma_separated_list()} of relationship paths. A relationship path is a \
dot-separated (U+002E FULL-STOP, ".") list of relationship names. \
[JSONAPI "include" behavior](http://jsonapi.org/format/#fetching-includes)
#{options[:description]}
""")
end
def filter_param(path_object, name, opts \\ [])
def filter_param(path_object, :route_type, opts) do
Path.parameter(
path_object,
"filter[route_type]",
:query,
:string,
"""
Filter by route_type: https://developers.google.com/transit/gtfs/reference/routes-file.
Multiple `route_type` #{comma_separated_list()}.
#{opts[:desc]}
""",
enum: ["0", "1", "2", "3", "4"]
)
end
def filter_param(path_object, :direction_id, opts) do
Path.parameter(
path_object,
"filter[direction_id]",
:query,
:string,
"""
Filter by direction of travel along the route. Must be used in conjuction with `filter[route]` to apply.
#{direction_id_description()}
#{opts[:desc]}
""",
enum: ["0", "1"]
)
end
def filter_param(path_object, :position, opts) do
desc =
Enum.join(
[opts[:description], "Latitude/Longitude must be both present or both absent."],
" "
)
path_object
|> Path.parameter("filter[latitude]", :query, :string, desc)
|> Path.parameter("filter[longitude]", :query, :string, desc)
end
def filter_param(path_object, :radius, opts) do
parts = [
opts[:description],
"Radius accepts a floating point number, and the default is 0.01. For example, if you query for:",
"latitude: 42, ",
"longitude: -71, ",
"radius: 0.05",
"then you will filter between latitudes 41.95 and 42.05, and longitudes -70.95 and -71.05."
]
desc = Enum.join(parts, " ")
Path.parameter(path_object, "filter[radius]", :query, :string, desc, format: :date)
end
def filter_param(path_object, :date, opts) do
parts = [
opts[:description],
"The active date is the service date.",
"Trips that begin between midnight and 3am are considered part of the previous service day.",
"The format is ISO8601 with the template of YYYY-MM-DD."
]
desc = Enum.join(parts, " ")
Path.parameter(path_object, "filter[date]", :query, :string, desc, format: :date)
end
def filter_param(path_object, :time, opts) do
parts = [
opts[:description],
"The time format is HH:MM."
]
desc = Enum.join(parts, " ")
name = opts[:name] || :time
Path.parameter(path_object, "filter[#{name}]", :query, :string, desc, format: :time)
end
def filter_param(path_object, :stop_id, opts) do
desc = opts[:desc] || ""
desc =
if opts[:includes_children] do
"Parent station IDs are treated as though their child stops were also included. #{desc}"
else
desc
end
filter_param(path_object, :id, Keyword.merge(opts, desc: desc, name: :stop))
end
def filter_param(path_object, :id, opts) do
name = Keyword.fetch!(opts, :name)
json_pointer = "`/data/{index}/relationships/#{name}/data/id`"
Path.parameter(
path_object,
"filter[#{name}]",
:query,
:string,
"""
Filter by #{json_pointer}.
Multiple IDs #{comma_separated_list()}.
#{opts[:desc]}
""",
Keyword.drop(opts, [:desc, :name])
)
end
def page(resource) do
resource
|> JsonApi.page()
|> (fn schema -> %{schema | "properties" => Map.delete(schema["properties"], "meta")} end).()
end
@doc """
returns the path of the controller and its :index or :show action
with the properly formatted id path parameter. The {id} is escaped by a simple
call to `alert_path(ApiWeb.Endpoint, :show, "{id}")`, and does not render
correctly in the json
"""
def path(controller, action) do
controller
|> path_fn
|> call_path(action)
end
def route_type_description do
"""
| Value | Name | Example |
|-------|---------------|------------|
| `0` | Light Rail | Green Line |
| `1` | Heavy Rail | Red Line |
| `2` | Commuter Rail | |
| `3` | Bus | |
| `4` | Ferry | |
"""
end
defp path_fn(module) do
short_name =
module
|> to_string
|> String.split(".")
|> List.last()
|> String.replace_suffix("Controller", "")
|> String.downcase()
String.to_atom("#{short_name}_path")
end
defp attribute_to_json_pointer("id"), do: "/data/{index}/id"
defp attribute_to_json_pointer(attribute), do: "/data/{index}/attributes/#{attribute}"
defp attributes(module) do
for {_, %{"properties" => %{"attributes" => %{"properties" => properties}}}} <-
module.swagger_definitions(),
{attribute, _} <- properties,
do: attribute
end
defp call_path(path_fn, :index),
do: apply(ApiWeb.Router.Helpers, path_fn, [%URI{path: ""}, :index])
defp call_path(path_fn, :show) do
"#{call_path(path_fn, :index)}/{id}"
end
defp direction_to_prefix("ascending"), do: ""
defp direction_to_prefix("descending"), do: "-"
defp fields_param(path_object, name) do
case name do
nil ->
path_object
name ->
Path.parameter(
path_object,
"fields[#{name}]",
:query,
:string,
"""
Fields to include with the response. Multiple fields #{comma_separated_list()}.
Note that fields can also be selected for included data types: see the [V3 API Best Practices](https://www.mbta.com/developers/v3-api/best-practices) for an example.
"""
)
end
end
defp sort_enum(sort_pairs), do: Enum.map(sort_pairs, &sort_pair_to_sort/1)
defp sort_pairs(module) do
for attribute <- attributes(module),
direction <- @sort_types,
do: {attribute, direction}
end
defp sort_pair_to_sort({attribute, direction}),
do: "#{direction_to_prefix(direction)}#{attribute}"
defp sort_parameter(path_object, sort_pairs, :include_distance),
do:
format_sort_parameter(
path_object,
sort_pairs,
"""
Results can be [sorted](http://jsonapi.org/format/#fetching-sorting) by the id or any `/data/{index}/attributes` \
key. Sorting by distance requires `filter[latitude]` and `filter[longitude]` to be set. Assumes ascending; may be \
prefixed with '-' for descending.
#{sort_table(sort_pairs)} #{distance_sort_options()}
""",
for(sort_type <- @sort_types, do: {"distance", sort_type})
)
defp sort_parameter(path_object, sort_pairs, :include_time),
do:
format_sort_parameter(
path_object,
sort_pairs,
"""
Results can be [sorted](http://jsonapi.org/format/#fetching-sorting) by the id or any `/data/{index}/attributes` \
key.
#{sort_table(sort_pairs)} #{time_sort_options()}
""",
for(sort_type <- @sort_types, do: {"time", sort_type})
)
defp sort_parameter(path_object, sort_pairs, _),
do:
format_sort_parameter(
path_object,
sort_pairs,
"""
Results can be [sorted](http://jsonapi.org/format/#fetching-sorting) by the id or any `/data/{index}/attributes` \
key. Assumes ascending; may be prefixed with '-' for descending
#{sort_table(sort_pairs)}
"""
)
defp format_sort_parameter(path_object, sort_pairs, description, extra_options \\ []),
do:
Path.parameter(
path_object,
:sort,
:query,
:string,
description,
enum: sort_enum(sort_pairs ++ extra_options)
)
defp distance_sort_options do
for sort_type <- @sort_types do
"""
| Distance to \
(`#{attribute_to_json_pointer("latitude")}`, `#{attribute_to_json_pointer("longitude")}`) \
| #{sort_type} | `#{sort_pair_to_sort({"distance", sort_type})}` |
"""
end
end
defp time_sort_options do
for sort_type <- @sort_types do
"""
| `/data/{index}/attributes/arrival_time` if present, otherwise `/data/{index}/attributes/departure_time` \
| #{sort_type} | `#{sort_pair_to_sort({"time", sort_type})}` |
"""
end
end
defp sort_row({attribute, direction} = pair) do
"| `#{attribute_to_json_pointer(attribute)}` | #{direction} | `#{sort_pair_to_sort(pair)}` |"
end
defp sort_rows(sort_pairs), do: Enum.map_join(sort_pairs, "\n", &sort_row/1)
defp sort_table(sort_pairs) do
"""
| JSON pointer | Direction | `sort` |
|--------------|-----------|------------|
#{sort_rows(sort_pairs)}
"""
end
end
|
apps/api_web/lib/api_web/swagger_helpers.ex
| 0.867738 | 0.463262 |
swagger_helpers.ex
|
starcoder
|
defmodule Coxir.Struct.Integration do
@moduledoc """
Defines methods used to interact with guild integrations.
Refer to [this](https://discord.com/developers/docs/resources/guild#integration-object)
for a list of fields and a broader documentation.
"""
@type integration :: String.t | map
use Coxir.Struct
@doc false
def get(id),
do: super(id)
@doc false
def select(pattern)
@doc """
Modifies a given integration.
Returns the atom `:ok` upon success
or a map containing error information.
#### Params
Must be an enumerable with the fields listed below.
- `expire_behavior` - when an integration subscription lapses
- `expire_grace_period` - period (in seconds) where lapsed subscriptions will be ignored
- `enable_emoticons` - whether emoticons should be synced for this integration (*Twitch*)
Refer to [this](https://discord.com/developers/docs/resources/guild#modify-guild-integration)
for a broader explanation on the fields and their defaults.
"""
@spec edit(integration, Enum.t) :: :ok | map
def edit(%{id: id, guild_id: guild}, params),
do: edit(id, guild, params)
@doc """
Modifies a given integration.
Refer to `edit/2` for more information.
"""
@spec edit(String.t, String.t, Enum.t) :: :ok | map
def edit(integration, guild, params) do
API.request(:patch, "guilds/#{guild}/integrations/#{integration}", params)
end
@doc """
Synchronizes a given integration.
Returns the atom `:ok` upon success
or a map containing error information.
"""
@spec sync(integration) :: :ok | map
def sync(%{id: id, guild_id: guild}),
do: sync(id, guild)
@doc """
Synchronizes a given integration.
Refer to `sync/1` for more information.
"""
@spec sync(String.t, String.t) :: :ok | map
def sync(integration, guild) do
API.request(:post, "guilds/#{guild}/integrations/#{integration}/sync")
end
@doc """
Deletes a given integration.
Returns the atom `:ok` upon success
or a map containing error information.
"""
@spec delete(integration) :: :ok | map
def delete(%{id: id, guild_id: guild}),
do: delete(id, guild)
@doc """
Deletes a given integration.
Refer to `delete/1` for more information.
"""
@spec delete(String.t, String.t) :: :ok | map
def delete(integration, guild) do
API.request(:delete, "guilds/#{guild}/integrations/#{integration}")
end
end
|
lib/coxir/struct/integration.ex
| 0.855881 | 0.593256 |
integration.ex
|
starcoder
|
defmodule JWT do
@moduledoc """
Encode claims for transmission as a JSON object that is used as the payload of a JSON Web
Signature (JWS) structure, enabling the claims to be integrity protected with a Message
Authentication Code (MAC), to be later verified
see http://tools.ietf.org/html/rfc7519
"""
alias JWT.Jws
@default_algorithm "HS256"
@default_header %{}
# JOSE header types from: https://tools.ietf.org/html/rfc7515
@header_jose_keys [:alg, :jku, :jwk, :kid, :x5u, :x5c, :x5t, :"x5t#S256", :typ, :cty, :crit]
@doc """
Return a JSON Web Token (JWT), a string representing a set of claims as a JSON object that is
encoded in a JWS
## Example
iex> claims = %{iss: "joe", exp: 1300819380, "http://example.com/is_root": true}
...> key = "<KEY>"
...> JWT.sign(claims, key: key)
"<KEY>"
see http://tools.ietf.org/html/rfc7519#section-7.1
"""
@spec sign(map, Keyword.t() | map) :: binary
def sign(claims, options) when is_map(claims) do
header = unify_header(options)
jws_message(header, Jason.encode!(claims), options[:key])
end
defp jws_message(%{alg: "none"} = header, payload, _key) do
Jws.unsecured_message(header, payload)
end
defp jws_message(header, payload, key) do
Jws.sign(header, payload, key)
end
@doc """
Given an options map, return a map of header options
## Example
iex> JWT.unify_header(alg: "RS256", key: "key")
%{typ: "JWT", alg: "RS256"}
Filters out unsupported claims options and ignores any encryption keys
"""
@spec unify_header(Keyword.t() | map) :: map
def unify_header(options) when is_list(options) do
options |> Map.new() |> unify_header
end
def unify_header(options) when is_map(options) do
jose_registered_headers = Map.take(options, @header_jose_keys)
@default_header
|> Map.merge(jose_registered_headers)
|> Map.merge(%{alg: algorithm(options)})
end
@doc """
Return a tuple {:ok, claims (map)} if the JWT signature is verified,
or {:error, "invalid"} otherwise
## Example
iex> jwt ="<KEY>"
...> key = "<KEY>"
...> JWT.verify(jwt, %{key: key})
{:ok, %{"name" => "joe", "datetime" => 1300819380, "http://example.com/is_root" => true}}
see http://tools.ietf.org/html/rfc7519#section-7.2
"""
@spec verify(binary, map) :: {:ok, map} | {:error, Keyword.t()}
def verify(jwt, options) do
with {:ok, [_, payload, _]} <- Jws.verify(jwt, algorithm(options), options[:key]),
{:ok, claims} <- JWT.Coding.decode(payload),
:ok <- JWT.Claim.verify(claims, options) do
{:ok, claims}
else
{:error, reason} -> {:error, reason}
end
end
@spec verify!(binary, map) :: map | no_return
def verify!(jwt, options) do
[_, payload, _] = Jws.verify!(jwt, algorithm(options), options[:key])
claims = JWT.Coding.decode!(payload)
with :ok <- JWT.Claim.verify(claims, options) do
claims
else
{:error, rejected_claims} ->
raise JWT.ClaimValidationError, claims: rejected_claims
end
end
defp algorithm(options) do
Map.get(options, :alg, @default_algorithm)
end
end
|
lib/jwt.ex
| 0.86501 | 0.605274 |
jwt.ex
|
starcoder
|
defmodule Ecto.Query.WindowAPI do
@moduledoc """
Lists all windows functions.
Windows functions must always be used as the first argument
of `over/2` where the second argument is the name of an window:
from e in Employee,
select: {e.depname, e.empno, e.salary, over(avg(e.salary), :department)},
windows: [department: [partition_by: e.depname]]
In the example above, we get the average salary per department.
`:department` is the window name, partitioned by `e.depname`
and `avg/1` is the window function.
However, note that defining a window is not necessary, as the
window definition can be given as the second argument to `over`:
from e in Employee,
select: {e.depname, e.empno, e.salary, over(avg(e.salary), partition_by: e.depname)}
Both queries are equivalent. However, if you are using the same
partitioning over and over again, defining a window will reduce
the query size. See `Ecto.Query.windows/3` for all possible window
expressions, such as `:partition_by` and `:order_by`.
"""
@dialyzer :no_return
@doc """
Counts the entries in the table.
from p in Post, select: count()
"""
def count, do: doc! []
@doc """
Counts the given entry.
from p in Post, select: count(p.id)
"""
def count(value), do: doc! [value]
@doc """
Calculates the average for the given entry.
from p in Payment, select: avg(p.value)
"""
def avg(value), do: doc! [value]
@doc """
Calculates the sum for the given entry.
from p in Payment, select: sum(p.value)
"""
def sum(value), do: doc! [value]
@doc """
Calculates the minimum for the given entry.
from p in Payment, select: min(p.value)
"""
def min(value), do: doc! [value]
@doc """
Calculates the maximum for the given entry.
from p in Payment, select: max(p.value)
"""
def max(value), do: doc! [value]
@doc """
Returns number of the current row within its partition, counting from 1.
from p in Post,
select: row_number() |> over(partition_by: p.category_id, order_by: p.date)
Note that this function must be invoked using window function syntax.
"""
def row_number(), do: doc! []
@doc """
Returns rank of the current row with gaps; same as `row_number/0` of its first peer.
from p in Post,
select: rank() |> over(partition_by: p.category_id, order_by: p.date)
Note that this function must be invoked using window function syntax.
"""
def rank(), do: doc! []
@doc """
Returns rank of the current row without gaps; this function counts peer groups.
from p in Post,
select: dense_rank() |> over(partition_by: p.category_id, order_by: p.date)
Note that this function must be invoked using window function syntax.
"""
def dense_rank(), do: doc! []
@doc """
Returns relative rank of the current row: (rank - 1) / (total rows - 1).
from p in Post,
select: percent_rank() |> over(partition_by: p.category_id, order_by: p.date)
Note that this function must be invoked using window function syntax.
"""
def percent_rank(), do: doc! []
@doc """
Returns relative rank of the current row:
(number of rows preceding or peer with current row) / (total rows).
from p in Post,
select: cume_dist() |> over(partition_by: p.category_id, order_by: p.date)
Note that this function must be invoked using window function syntax.
"""
def cume_dist(), do: doc! []
@doc """
Returns integer ranging from 1 to the argument value, dividing the partition as equally as possible.
from p in Post,
select: ntile(10) |> over(partition_by: p.category_id, order_by: p.date)
Note that this function must be invoked using window function syntax.
"""
def ntile(num_buckets), do: doc! [num_buckets]
@doc """
Returns value evaluated at the row that is the first row of the window frame.
from p in Post,
select: first_value(p.id) |> over(partition_by: p.category_id, order_by: p.date)
Note that this function must be invoked using window function syntax.
"""
def first_value(value), do: doc! [value]
@doc """
Returns value evaluated at the row that is the last row of the window frame.
from p in Post,
select: last_value(p.id) |> over(partition_by: p.category_id, order_by: p.date)
Note that this function must be invoked using window function syntax.
"""
def last_value(value), do: doc! [value]
@doc """
Returns value evaluated at the row that is the nth row of the window
frame (counting from 1); null if no such row.
from p in Post,
select: nth_value(p.id, 4) |> over(partition_by: p.category_id, order_by: p.date)
Note that this function must be invoked using window function syntax.
"""
def nth_value(value, nth), do: doc! [value, nth]
@doc """
Returns value evaluated at the row that is offset rows before
the current row within the partition.
Ff there is no such row, instead return default (which must be of the
same type as value). Both offset and default are evaluated with respect
to the current row. If omitted, offset defaults to 1 and default to null.
from e in Events,
windows: [w: [partition_by: e.name, order_by: e.tick]],
select: {
e.tick,
e.action,
e.name,
lag(e.action) |> over(:w), # previous_action
lead(e.action) |> over(:w) # next_action
}
Note that this function must be invoked using window function syntax.
"""
def lag(value, offset \\ 1, default \\ nil), do: doc! [value, offset, default]
@doc """
Returns value evaluated at the row that is offset rows after
the current row within the partition.
Ff there is no such row, instead return default (which must be of the
same type as value). Both offset and default are evaluated with respect
to the current row. If omitted, offset defaults to 1 and default to null.
from e in Events,
windows: [w: [partition_by: e.name, order_by: e.tick],
select: {
e.tick,
e.action,
e.name,
lag(e.action) |> over(:w), # previous_action
lead(e.action) |> over(:w) # next_action
}
Note that this function must be invoked using window function syntax.
"""
def lead(value, offset \\ 1, default \\ nil), do: doc! [value, offset, default]
defp doc!(_) do
raise "the functions in Ecto.Query.WindowAPI should not be invoked directly, " <>
"they serve for documentation purposes only"
end
end
|
deps/ecto/lib/ecto/query/window_api.ex
| 0.876019 | 0.577704 |
window_api.ex
|
starcoder
|
defmodule ExZample.DSL do
@moduledoc """
Defines a domain-speficic language(DSL) to simplify the creation of your
factories.
You can use this DSL by using by defining a module and adding the `use`
directive. For example:
defmodule MyApp.Factories do
use ExZample.DSL
alias MyApp.User
factory :user do
example do
%User{
id: sequence(:user_id),
first_name: "Abili"
last_name: "<NAME>"
}
end
end
sequence :user_id
end
It will generate the modules, functions and the aliases manifest to be loaded
when the `ex_zample` app starts. Then, to use your factories, don't forget to
start your app. For example:
# in your test_helper.exs
:ok = Application.ensure_started(:ex_zample)
This way, all factorites your defined using the `ExZample.DSL` will be
loaded module.
## Options
You can pass the following options to the `use` directive:
* `scope` (default: `:global`), the `:scope` that all aliases of factories
will be stored
"""
alias ExZample.Manifest
import ExZample.Since
@type scoped_name :: {scope :: atom, name :: atom}
@type name_or_scoped_name :: name :: atom | [scoped_name]
defguardp is_name_or_scoped_name(term) when is_list(term) or is_atom(term)
@doc false
defmacro __using__(opts \\ []) do
quote location: :keep, bind_quoted: [opts: opts] do
import ExZample.DSL, except: [sequence: 2, sequence: 1]
Module.register_attribute(__MODULE__, :ex_zample_factories, accumulate: true)
Module.register_attribute(__MODULE__, :ex_zample_sequences, accumulate: true)
@ex_zample_opts opts
@before_compile ExZample.DSL
@after_compile {ExZample.DSL, :create_manifest}
end
end
@doc false
defmacro __before_compile__(_env) do
quote location: :keep, bind_quoted: [caller: Macro.escape(__CALLER__)] do
Enum.each(
@ex_zample_factories,
&ExZample.DSL.Factory.define(&1, caller)
)
Enum.each(
@ex_zample_sequences,
&ExZample.DSL.Sequence.define(&1, caller)
)
end
end
@doc """
Defines a module factory with helpers imported by default.
If you pass an `atom` for factory name, such as `user`, the module will be
generated with `UserFactory`. If you pass a scope, like: `my_app: :user`, the
module name will become `MyAppUserFactory`.
The factory body has all functions from `ExZample` imported. It also has access
to `example` DSL helper that generates a function definition with behaviour
annotations. Taking those helpers out, everything else work as normal Elixir
module.
"""
since("0.6.0")
@spec factory(name_or_scoped_name, do: Macro.t()) :: Macro.t()
defmacro factory(name_or_scoped_name, do: block)
when is_name_or_scoped_name(name_or_scoped_name) do
{scope, name} = parse_name_and_scope(name_or_scoped_name)
quote location: :keep, bind_quoted: [scope: scope, name: name, block: Macro.escape(block)] do
@ex_zample_factories %ExZample.DSL.Factory{
scope: the_scope(scope, @ex_zample_opts),
name: name,
block: block,
ecto_repo: @ex_zample_opts[:ecto_repo]
}
end
end
@doc """
Defines a sequence function with a given alias `name` and a anonymus function
on `return` as value transformation.
## Examples
def_sequence(:user_id, return: &("user_\#{&1}")
# later you can invoke like this:
ExZample.sequence(:user_id)
"user_1"
A function will be generated in the current module following the pattern:
`{scope}_{sequence_name}_sequence`.
"""
since("0.10.0")
@spec def_sequence(name :: atom, return: ExZample.sequence_fun()) :: Macro.t()
defmacro def_sequence(name, return: fun) when is_atom(name) do
quote location: :keep,
bind_quoted: [scope: nil, name: name, fun: Macro.escape(fun)] do
@ex_zample_sequences {the_scope(scope, @ex_zample_opts), name, fun}
end
end
@doc """
Defines a sequence function with a optional `scope`, mandatory `name` and an
optional anonymus function in `return` as value transformation.
## Examples
def_sequence(:user_id)
def_sequence(scoped: :user_id, return: &"user_\#{&1}")
# later you can invoke like this:
ExZample.sequence(:user_id)
1
ExZample.ex_zample(ex_zample_scope: :scoped)
ExZample.sequence(:user_id)
"user_1"
A function will be generated in the current module following the pattern:
`{scope}_{sequence_name}_sequence`.
"""
since("0.10.0")
@spec def_sequence(Keyword.t() | atom) ::
Macro.t()
defmacro def_sequence(opts_or_name) when is_atom(opts_or_name) do
name = opts_or_name
quote location: :keep,
bind_quoted: [scope: nil, name: name, fun: nil] do
@ex_zample_sequences {the_scope(scope, @ex_zample_opts), name, nil}
end
end
defmacro def_sequence(opts_or_name) when is_list(opts_or_name) do
opts = opts_or_name
{fun_opts, name_opts} = Keyword.split(opts, [:return])
{scope, name} = parse_name_and_scope(name_opts)
fun = if fun = fun_opts[:return], do: Macro.escape(fun)
quote location: :keep,
bind_quoted: [scope: scope, name: name, fun: fun] do
@ex_zample_sequences {the_scope(scope, @ex_zample_opts), name, fun}
end
end
@doc "Sames as def_sequence/2"
since("0.7.0")
@deprecated "Use def_sequence/2 instead"
defmacro sequence(name, return: fun) when is_atom(name) do
quote location: :keep,
bind_quoted: [scope: nil, name: name, fun: Macro.escape(fun)] do
@ex_zample_sequences {the_scope(scope, @ex_zample_opts), name, fun}
end
end
@doc "Sames as def_sequence/1"
since("0.7.0")
@deprecated "Use def_sequence/1 instead"
defmacro sequence(opts_or_name) when is_atom(opts_or_name) do
name = opts_or_name
quote location: :keep,
bind_quoted: [scope: nil, name: name, fun: nil] do
@ex_zample_sequences {the_scope(scope, @ex_zample_opts), name, nil}
end
end
defmacro sequence(opts_or_name) when is_list(opts_or_name) do
opts = opts_or_name
{fun_opts, name_opts} = Keyword.split(opts, [:return])
{scope, name} = parse_name_and_scope(name_opts)
fun = if fun = fun_opts[:return], do: Macro.escape(fun)
quote location: :keep,
bind_quoted: [scope: scope, name: name, fun: fun] do
@ex_zample_sequences {the_scope(scope, @ex_zample_opts), name, fun}
end
end
defp parse_name_and_scope([{scope, name}]) when is_atom(name) and is_atom(scope),
do: {scope, name}
defp parse_name_and_scope(name) when is_atom(name), do: {nil, name}
@doc false
def the_scope(scope, opts \\ []),
do: if(scope, do: scope, else: opts[:scope] || :global)
@doc false
def create_manifest(caller, _binary) do
factories = __MODULE__.Factory.manifest(caller)
sequences = __MODULE__.Sequence.manifest(caller)
file_name = Macro.underscore(caller.module) <> ".ex_zample_manifest.elixir"
file = Path.join([Mix.Project.build_path(), "/ex_zample/manifest/", file_name])
Manifest.write!(file, factories, sequences)
end
end
|
lib/ex_zample/dsl/dsl.ex
| 0.906033 | 0.501831 |
dsl.ex
|
starcoder
|
defmodule Distillery.Releases.Shell do
@moduledoc """
This module provides conveniences for writing output to the shell.
"""
use Distillery.Releases.Shell.Macros
@type verbosity :: :silent | :quiet | :normal | :verbose
# The order of these levels is from least important to most important
# When comparing log levels with `gte`, this ordering is what determines their total ordering
deflevel(:debug, prefix: "==> ", color: :cyan)
deflevel(:info, prefix: "==> ", color: [:bright, :cyan])
deflevel(:notice, color: :yellow)
deflevel(:success, prefix: "==> ", color: [:bright, :green])
deflevel(:warn, prefix: "==> ", color: :yellow, error: :warnings_as_errors)
deflevel(:error, prefix: "==> ", color: :red)
@doc """
Configure the logging verbosity of the release logger.
Valid verbosity settings are:
* `:silent` - no output except errors
* `:quiet` - no output except warnings/errors
* `:normal` - no debug output (default)
* `:verbose` - all output
"""
@spec configure(verbosity) :: :ok
def configure(verbosity) when is_atom(verbosity) do
Application.put_env(:mix, :release_logger_verbosity, verbosity)
end
@default_answer_pattern ~r/^(y(es)?)?$/i
@doc """
Ask the user to confirm an action using the given message.
The confirmation prompt will default to "[Yn]: ", and the
regex for determining whether the action was confirmed will
default to #{inspect(Regex.source(@default_answer_pattern))}.
Use confirm/3 to provide your own prompt and answer regex.
"""
@spec confirm?(String.t()) :: boolean
def confirm?(message) do
confirm?(message, "[Yn]: ", @default_answer_pattern)
end
@doc """
Same as confirm/1, but takes a custom prompt and answer regex pattern.
If the pattern matches the response, the action is considered confirmed.
"""
@spec confirm?(String.t(), String.t(), Regex.t()) :: boolean
def confirm?(message, prompt, answer_pattern) do
IO.puts(IO.ANSI.format([:yellow]))
answer = IO.gets("#{message} #{prompt}") |> String.trim_trailing("\n")
IO.puts(IO.ANSI.format([:reset]))
answer =~ answer_pattern
end
@doc """
Prints an error message, then terminates the VM with a non-zero status code
"""
@spec fail!(iodata) :: no_return
def fail!(message) do
error(message)
System.halt(1)
end
@doc "Write the given iodata directly, bypassing the log level"
def write(message),
do: IO.write(message)
@doc "Write the given iodata, wrapped in the given color, but bypassing the log level"
def writef(message, color),
do: write(colorf(message, color))
@doc "Write a debug level message, but with minimal formatting. Default color is same as debug level"
def debugf(message, color \\ :cyan) do
data = verbosityf(:debug, colorf(message, color))
IO.write(data)
end
## Color helpers
# Formats a message with a given color
# Can use shorthand atoms for colors, or pass the ANSI directly
@doc """
Wraps a message in the given color
"""
def colorf(message, color), do: IO.ANSI.format([color, message, :reset])
end
|
lib/distillery/releases/shell.ex
| 0.820829 | 0.519399 |
shell.ex
|
starcoder
|
defmodule Ecto.Adapter do
@moduledoc """
This module specifies the adapter API that an adapter is required to
implement.
"""
use Behaviour
@type t :: module
@type source :: binary
@type fields :: Keyword.t
@type filters :: Keyword.t
@type returning :: [atom]
@type autogenerate_id :: {field :: atom, type :: :id | :binary_id, value :: term} | nil
@typep repo :: Ecto.Repo.t
@typep options :: Keyword.t
@doc """
The callback invoked in case the adapter needs to inject code.
"""
defmacrocallback __before_compile__(Macro.Env.t) :: Macro.t
@doc """
Starts any connection pooling or supervision and return `{:ok, pid}`
or just `:ok` if nothing needs to be done.
Returns `{:error, {:already_started, pid}}` if the repo already
started or `{:error, term}` in case anything else goes wrong.
"""
defcallback start_link(repo, options) ::
{:ok, pid} | :ok | {:error, {:already_started, pid}} | {:error, term}
@doc """
Stops any connection pooling or supervision started with `start_link/1`.
"""
defcallback stop(repo) :: :ok
@doc """
Returns the binary id type for this adapter.
If the database adapter does not support provide
binary id functionality, Ecto.UUID is recommended.
"""
defcallback id_types(repo) :: %{binary_id: Ecto.Type.custom}
@doc """
Fetches all results from the data store based on the given query.
"""
defcallback all(repo, query :: Ecto.Query.t, params :: list(), options) :: [[term]] | no_return
@doc """
Updates all entities matching the given query with the values given. The
query shall only have `where` expressions and a single `from` expression. Returns
the number of affected entities.
"""
defcallback update_all(repo, query :: Ecto.Query.t,
updates :: Keyword.t, params :: list(),
options) :: integer | no_return
@doc """
Deletes all entities matching the given query.
The query shall only have `where` expressions and a `from` expression.
Returns the number of affected entities.
"""
defcallback delete_all(repo, query :: Ecto.Query.t,
params :: list(), options :: Keyword.t) :: integer | no_return
@doc """
Inserts a single new model in the data store.
## Autogenerate
The `autogenerate_id` tells if there is a primary key to be autogenerated
and, if so, its name, type and value. The type is `:id` or `:binary_id` and
the adapter should raise if it cannot handle those types.
If the value is `nil`, it means no value was supplied by the user and
the database MUST return a new one.
`autogenerate_id` also allows drivers to detect if a value was assigned
to a primary key that does not support assignment. In this case, `value`
will be a non `nil` value.
"""
defcallback insert(repo, source, fields, autogenerate_id, returning, options) ::
{:ok, Keyword.t} | no_return
@doc """
Updates a single model with the given filters.
While `filters` can be any record column, it is expected that
at least the primary key (or any other key that uniquely
identifies an existing record) to be given as filter. Therefore,
in case there is no record matching the given filters,
`{:error, :stale}` is returned.
## Autogenerate
The `autogenerate_id` tells if there is an autogenerated primary key and
if so, its name type and value. The type is `:id` or `:binary_id` and
the adapter should raise if it cannot handle those types.
If the value is `nil`, it means there is no autogenerate primary key.
`autogenerate_id` also allows drivers to detect if a value was assigned
to a primary key that does not support assignment. In this case, `value`
will be a non `nil` value.
"""
defcallback update(repo, source, fields, filters, autogenerate_id, returning, options) ::
{:ok, Keyword.t} | {:error, :stale} | no_return
@doc """
Deletes a sigle model with the given filters.
While `filters` can be any record column, it is expected that
at least the primary key (or any other key that uniquely
identifies an existing record) to be given as filter. Therefore,
in case there is no record matching the given filters,
`{:error, :stale}` is returned.
## Autogenerate
The `autogenerate_id` tells if there is an autogenerated primary key and
if so, its name type and value. The type is `:id` or `:binary_id` and
the adapter should raise if it cannot handle those types.
If the value is `nil`, it means there is no autogenerate primary key.
"""
defcallback delete(repo, source, filters, autogenerate_id, options) ::
{:ok, Keyword.t} | {:error, :stale} | no_return
end
|
lib/ecto/adapter.ex
| 0.909285 | 0.466299 |
adapter.ex
|
starcoder
|
defmodule Membrane.Element.WithOutputPads do
@moduledoc """
Module defining behaviour for source and filter elements.
When used declares behaviour implementation, provides default callback definitions
and imports macros.
For more information on implementing elements, see `Membrane.Element.Base`.
"""
alias Membrane.{Buffer, Element, Pad}
alias Membrane.Core.Child.PadsSpecs
alias Membrane.Element.CallbackContext
@doc """
Callback called when buffers should be emitted by a source or filter.
It is called only for output pads in the pull mode, as in their case demand
is triggered by the input pad of the subsequent element.
In sources, appropriate amount of data should be sent here.
In filters, this callback should usually return `:demand` action with
size sufficient for supplying incoming demand. This will result in calling
`c:Membrane.Filter.handle_process_list/4`, which is to supply
the demand.
If a source is unable to produce enough buffers, or a filter underestimated
returned demand, the `:redemand` action should be used (see
`t:Membrane.Element.Action.redemand_t/0`).
"""
@callback handle_demand(
pad :: Pad.ref_t(),
size :: non_neg_integer,
unit :: Buffer.Metric.unit_t(),
context :: CallbackContext.Demand.t(),
state :: Element.state_t()
) :: Membrane.Element.Base.callback_return_t()
@optional_callbacks handle_demand: 5
@doc """
Macro that defines multiple output pads for the element.
Deprecated in favor of `def_output_pad/2`
"""
@deprecated "Use `def_output_pad/2 for each pad instead"
defmacro def_output_pads(pads) do
PadsSpecs.def_pads(pads, :output, :element)
end
@doc PadsSpecs.def_pad_docs(:output, :element)
defmacro def_output_pad(name, spec) do
PadsSpecs.def_pad(name, :output, spec, :element)
end
defmacro __using__(_) do
quote location: :keep do
@behaviour unquote(__MODULE__)
import unquote(__MODULE__), only: [def_output_pads: 1, def_output_pad: 2]
@impl true
def handle_demand(_pad, _size, _unit, _context, state),
do: {{:error, :handle_demand_not_implemented}, state}
defoverridable handle_demand: 5
end
end
end
|
lib/membrane/element/with_output_pads.ex
| 0.850918 | 0.510985 |
with_output_pads.ex
|
starcoder
|
defmodule Forth do
@moduledoc """
Implements a simple Forth evaluator
"""
@default_dict %{
"dup" => [stackop: :dup],
"drop" => [stackop: :drop],
"swap" => [stackop: :swap],
"over" => [stackop: :over]
}
defstruct [stack: [], dict: @default_dict, startdef: false]
@type t :: %Forth{stack: stack(), dict: %{}, startdef: boolean}
@type state :: :none | :int
@type stack :: [integer | t()]
@type binary_op :: ?+ | ?- | ?* | ?/
@type stack_op :: :dup | :drop | :swap | :over
@doc """
Create a new evaluator.
"""
@spec new() :: t()
def new() do
%Forth{}
end
@doc """
Evaluate an input string, updating the evaluator state.
"""
@spec eval(t(), String.t()) :: t()
def eval(forth, <<>>) do
forth
end
def eval(forth, str) do
{token_type, value, next_str} = Forth.Tokenizer.eval(str)
next_forth = eval_token({token_type, value}, forth)
eval(next_forth, next_str)
end
@doc """
Return the current stack as a string with the element on top of the stack
being the rightmost element in the string.
"""
@spec format_stack(t()) :: String.t()
def format_stack(%Forth{stack: stack}) do
stack |> Enum.reverse() |> Enum.join(" ")
end
# Evaluates a token in the context of a Forth struct and returns an updated
# Forth struct
@spec eval_token({Forth.Tokenizer.token_type(), any}, t()) :: t()
defp eval_token({:enddef, _}, %Forth{startdef: true, stack: [command_def | stack], dict: dict}) do
# Reverse the list that contains the tokens. Now the first token is the
# name of the command to be defined, and the remaining tokens are the
# definition.
case Enum.reverse(command_def) do
[{:id, name} | tokens] ->
%Forth{startdef: false, stack: stack, dict: Map.put(dict, name, tokens)}
[{:int, int} | _] -> raise Forth.InvalidWord, word: int
end
end
# all other tokens where startdef is true
defp eval_token(token, forth = %Forth{startdef: true, stack: [command_def | stack]}) do
%Forth{forth | stack: [[token | command_def] | stack]}
end
# all tokens where startdef is false
defp eval_token({:int, int}, forth = %Forth{stack: stack}) do
%Forth{forth | stack: [int | stack]}
end
defp eval_token({:op, op}, forth = %Forth{stack: stack}) do
%Forth{forth | stack: eval_operator(op, stack)}
end
defp eval_token({:id, command}, forth) do
String.downcase(command) |> execute_command(forth)
end
defp eval_token({:stackop, op}, forth = %Forth{stack: stack}) do
%Forth{forth | stack: eval_stackop(op, stack)}
end
defp eval_token({:startdef, _}, forth = %Forth{stack: stack}) do
# Push an empty list onto the stack, which we will use to collect the
# tokens until we encounter an :enddef.
%Forth{forth | startdef: true, stack: [[] | stack]}
end
# Evaluates a binary operator in the context of a stack
@spec eval_operator(binary_op(), stack()) :: stack()
defp eval_operator(_, []) do
raise Forth.StackUnderflow
end
defp eval_operator(_, [_]) do
raise Forth.StackUnderflow
end
defp eval_operator(?+, [y | [x | rest]]) do
[x + y | rest]
end
defp eval_operator(?-, [y | [x | rest]]) do
[x - y | rest]
end
defp eval_operator(?*, [y | [x | rest]]) do
[x * y | rest]
end
defp eval_operator(?/, [0 | _]) do
raise Forth.DivisionByZero
end
defp eval_operator(?/, [y | [x | rest]]) do
[div(x, y) | rest]
end
# Evaluates a built-in stack operator in the context of a stack
@spec eval_stackop(stack_op(), stack()) :: stack()
defp eval_stackop(_, []) do
raise Forth.StackUnderflow
end
defp eval_stackop(:dup, [head | tail]) do
[head | [head | tail]]
end
defp eval_stackop(:drop, [_ | tail]) do
tail
end
# The following ops require at least two on the stack.
defp eval_stackop(_, [_]) do
raise Forth.StackUnderflow
end
defp eval_stackop(:swap, [y | [x | rest]]) do
[x | [y | rest]]
end
defp eval_stackop(:over, stack = [_ | [x | _]]) do
[x | stack]
end
# Executes a named command
@spec execute_command(String.t(), t()) :: t()
defp execute_command(command, forth) do
case forth.dict do
%{^command => tokens} -> eval_tokens(forth, tokens)
_ -> raise Forth.UnknownWord, word: command
end
end
# Recursively evaluates a list of tokens
@spec eval_tokens(t(), [{Forth.Tokenizer.token_type(), any}]) :: t()
defp eval_tokens(forth, []) do
forth
end
defp eval_tokens(forth, [token | rest]) do
next_forth = eval_token(token, forth)
eval_tokens(next_forth, rest)
end
defmodule StackUnderflow do
defexception []
def message(_), do: "stack underflow"
end
defmodule InvalidWord do
defexception word: nil
def message(e), do: "invalid word: #{inspect(e.word)}"
end
defmodule UnknownWord do
defexception word: nil
def message(e), do: "unknown word: #{inspect(e.word)}"
end
defmodule DivisionByZero do
defexception []
def message(_), do: "division by zero"
end
end
|
lib/forth.ex
| 0.773644 | 0.65971 |
forth.ex
|
starcoder
|
defmodule Resty.Connection.HTTPoison do
alias Resty.Request
@moduledoc """
Default `Resty.Connection` implementation. It will use `HTTPoison` in order
to query the web API.
## Params
All the parameters will be sent to HTTPoison as the `options` you can know
more about the supported options here: `HTTPoison.Request`
## Usage
As this is the default you should not have to manually set it except if you
have changed the default connection in your config.exs file or if you want
to set specific options/params.
```
defmodule MyResource do
use Resty.Resource.Base
set_connection Resty.Connection.HTTPoison, timeout: 8000
end
```
You can also define in your config.exs file default options to be sent with
each request.
```
config :resty, Resty.Connection.HTTPoison, timeout: 8000
```
Thus making it possible to use `Resty.Resource.Base.set_connection/1`
```
defmodule MyResource do
use Resty.Resource.Base
set_connection Resty.Connection.HTTPoison
end
```
"""
@doc false
def send(%Request{} = request, params) do
request
|> to_poison_request()
|> add_httpoison_options(params)
|> HTTPoison.request()
|> process_response()
end
defp to_poison_request(%Request{} = request) do
%HTTPoison.Request{
method: request.method,
url: request.url,
body: request.body,
headers: request.headers,
options: [],
params: %{}
}
end
defp add_httpoison_options(request, []) do
options = Application.get_env(:resty, __MODULE__, [])
%{request | options: options}
end
defp add_httpoison_options(request, options) do
%{request | options: options}
end
defp process_response({:error, exception}) do
{:error, Resty.Error.ConnectionError.new(message: exception.reason)}
end
defp process_response({:ok, %{status_code: status_code, body: body}})
when status_code in [301, 302, 303, 307] do
{:error, Resty.Error.Redirection.new(code: status_code, message: body)}
end
defp process_response({:ok, %{status_code: status_code, body: body}})
when status_code >= 200 and status_code < 400 do
{:ok, body}
end
defp process_response({:ok, %{status_code: 400, body: body}}) do
{:error, Resty.Error.BadRequest.new(message: body)}
end
defp process_response({:ok, %{status_code: 401, body: body}}) do
{:error, Resty.Error.UnauthorizedAccess.new(message: body)}
end
defp process_response({:ok, %{status_code: 403, body: body}}) do
{:error, Resty.Error.ForbiddenAccess.new(message: body)}
end
defp process_response({:ok, %{status_code: 404, body: body}}) do
{:error, Resty.Error.ResourceNotFound.new(message: body)}
end
defp process_response({:ok, %{status_code: 405, body: body}}) do
{:error, Resty.Error.MethodNotAllowed.new(message: body)}
end
defp process_response({:ok, %{status_code: 409, body: body}}) do
{:error, Resty.Error.ResourceConflict.new(message: body)}
end
defp process_response({:ok, %{status_code: 410, body: body}}) do
{:error, Resty.Error.ResourceGone.new(message: body)}
end
defp process_response({:ok, %{status_code: 422, body: body}}) do
{:error, Resty.Error.ResourceInvalid.new(message: body)}
end
defp process_response({:ok, %{status_code: status_code, body: body}})
when status_code >= 400 and status_code < 500 do
{:error, Resty.Error.ClientError.new(code: status_code, message: body)}
end
defp process_response({:ok, %{status_code: status_code, body: body}})
when status_code >= 500 and status_code < 600 do
{:error, Resty.Error.ServerError.new(code: status_code, message: body)}
end
defp process_response({:ok, %{status_code: status_code, body: body}}) do
{:error,
Resty.Error.ConnectionError.new(
code: status_code,
message: "Unknown response code, body was: #{body}"
)}
end
end
|
lib/resty/connection/httpoison.ex
| 0.822368 | 0.453927 |
httpoison.ex
|
starcoder
|
defmodule RethinkDB.Pseudotypes do
@moduledoc false
defmodule Binary do
@moduledoc false
defstruct data: nil
def parse(%{"$reql_type$" => "BINARY", "data" => data}, opts) do
case Dict.get(opts, :binary_format) do
:raw ->
%__MODULE__{data: data}
_ ->
:base64.decode(data)
end
end
end
defmodule Geometry do
@moduledoc false
defmodule Point do
@moduledoc false
defstruct coordinates: []
end
defmodule Line do
@moduledoc false
defstruct coordinates: []
end
defmodule Polygon do
@moduledoc false
defstruct coordinates: []
end
def parse(%{"$reql_type$" => "GEOMETRY", "coordinates" => [x,y], "type" => "Point"}) do
%Point{coordinates: {x,y}}
end
def parse(%{"$reql_type$" => "GEOMETRY", "coordinates" => coords, "type" => "LineString"}) do
%Line{coordinates: Enum.map(coords, &List.to_tuple/1)}
end
def parse(%{"$reql_type$" => "GEOMETRY", "coordinates" => coords, "type" => "Polygon"}) do
%Polygon{coordinates: (for points <- coords, do: Enum.map points, &List.to_tuple/1)}
end
end
defmodule Time do
@moduledoc false
defstruct epoch_time: nil, timezone: nil
def parse(%{"$reql_type$" => "TIME", "epoch_time" => epoch_time, "timezone" => timezone}, opts) do
case Dict.get(opts, :time_format) do
:raw ->
%__MODULE__{epoch_time: epoch_time, timezone: timezone}
_ ->
{seconds, ""} = Calendar.ISO.parse_offset(timezone)
zone_abbr = case seconds do
0 -> "UTC"
_ -> timezone
end
negative = seconds < 0
seconds = abs(seconds)
time_zone = case {div(seconds,3600),rem(seconds,3600)} do
{0,0} -> "Etc/UTC"
{hours,0} ->
"Etc/GMT" <> if negative do "+" else "-" end <> Integer.to_string(hours)
{hours,seconds} ->
"Etc/GMT" <> if negative do "+" else "-" end <> Integer.to_string(hours) <> ":" <>
String.pad_leading(Integer.to_string(seconds), 2, "0")
end
epoch_time * 1000
|> trunc()
|> DateTime.from_unix!(:milliseconds)
|> struct(utc_offset: seconds, zone_abbr: zone_abbr, time_zone: time_zone)
end
end
end
def convert_reql_pseudotypes(nil, opts), do: nil
def convert_reql_pseudotypes(%{"$reql_type$" => "BINARY"} = data, opts) do
Binary.parse(data, opts)
end
def convert_reql_pseudotypes(%{"$reql_type$" => "GEOMETRY"} = data, opts) do
Geometry.parse(data)
end
def convert_reql_pseudotypes(%{"$reql_type$" => "GROUPED_DATA"} = data, opts) do
parse_grouped_data(data)
end
def convert_reql_pseudotypes(%{"$reql_type$" => "TIME"} = data, opts) do
Time.parse(data, opts)
end
def convert_reql_pseudotypes(list, opts) when is_list(list) do
Enum.map(list, fn data -> convert_reql_pseudotypes(data, opts) end)
end
def convert_reql_pseudotypes(map, opts) when is_map(map) do
Enum.map(map, fn {k, v} ->
{k, convert_reql_pseudotypes(v, opts)}
end) |> Enum.into(%{})
end
def convert_reql_pseudotypes(string, opts), do: string
def parse_grouped_data(%{"$reql_type$" => "GROUPED_DATA", "data" => data}) do
Enum.map(data, fn ([k, data]) ->
{k, data}
end) |> Enum.into(%{})
end
def create_grouped_data(data) when is_map(data) do
data = data |> Enum.map(fn {k,v} -> [k, v] end)
%{"$reql_type$" => "GROUPED_DATA", "data" => data}
end
end
|
lib/rethinkdb/pseudotypes.ex
| 0.601711 | 0.550305 |
pseudotypes.ex
|
starcoder
|
defmodule Liquex.Parser.Tag.Iteration do
@moduledoc false
import NimbleParsec
alias Liquex.Parser.Argument
alias Liquex.Parser.Field
alias Liquex.Parser.Literal
alias Liquex.Parser.Tag
alias Liquex.Parser.Tag.ControlFlow
@spec for_expression(NimbleParsec.t()) :: NimbleParsec.t()
def for_expression(combinator \\ empty()) do
combinator
|> for_in_tag()
|> tag(parsec(:document), :contents)
|> tag(:for)
|> optional(ControlFlow.else_tag())
|> ignore(Tag.tag_directive("endfor"))
end
@spec cycle_tag(NimbleParsec.t()) :: NimbleParsec.t()
def cycle_tag(combinator \\ empty()) do
cycle_group =
Literal.literal()
|> ignore(string(":"))
|> ignore(Literal.whitespace())
combinator
|> ignore(Tag.open_tag())
|> ignore(string("cycle"))
|> ignore(Literal.whitespace(empty(), 1))
|> optional(cycle_group |> unwrap_and_tag(:group))
|> tag(argument_sequence(), :sequence)
|> ignore(Tag.close_tag())
|> tag(:cycle)
end
@spec continue_tag(NimbleParsec.t()) :: NimbleParsec.t()
def continue_tag(combinator \\ empty()) do
combinator
|> ignore(Tag.tag_directive("continue"))
|> replace(:continue)
end
@spec break_tag(NimbleParsec.t()) :: NimbleParsec.t()
def break_tag(combinator \\ empty()) do
combinator
|> ignore(Tag.tag_directive("break"))
|> replace(:break)
end
def tablerow_tag(combinator \\ empty()) do
tablerow_parameters = repeat(choice([cols(), limit(), offset()]))
combinator
|> ignore(Tag.open_tag())
|> ignore(string("tablerow"))
|> ignore(Literal.whitespace(empty(), 1))
|> unwrap_and_tag(Field.identifier(), :identifier)
|> ignore(Literal.whitespace(empty(), 1))
|> ignore(string("in"))
|> ignore(Literal.whitespace(empty(), 1))
|> tag(collection(), :collection)
|> ignore(Literal.whitespace())
|> tag(tablerow_parameters, :parameters)
|> ignore(Tag.close_tag())
|> tag(parsec(:document), :contents)
|> ignore(Tag.tag_directive("endtablerow"))
|> tag(:tablerow)
end
defp argument_sequence(combinator \\ empty()) do
combinator
|> Argument.argument()
|> repeat(
ignore(string(","))
|> ignore(Literal.whitespace())
|> Argument.argument()
)
end
defp for_in_tag(combinator) do
combinator
|> ignore(Tag.open_tag())
|> ignore(string("for"))
|> ignore(Literal.whitespace(empty(), 1))
|> unwrap_and_tag(Field.identifier(), :identifier)
|> ignore(Literal.whitespace(empty(), 1))
|> ignore(string("in"))
|> ignore(Literal.whitespace(empty(), 1))
|> tag(collection(), :collection)
|> ignore(Literal.whitespace())
|> tag(for_parameters(), :parameters)
|> ignore(Tag.close_tag())
end
defp collection do
choice([Literal.range(), Argument.argument()])
end
defp for_parameters do
reversed =
replace(string("reversed"), :reversed)
|> unwrap_and_tag(:order)
|> ignore(Literal.whitespace())
repeat(choice([reversed, limit(), offset()]))
end
defp cols do
ignore(string("cols:"))
|> unwrap_and_tag(integer(min: 1), :cols)
|> ignore(Literal.whitespace())
end
defp limit do
ignore(string("limit:"))
|> unwrap_and_tag(integer(min: 1), :limit)
|> ignore(Literal.whitespace())
end
defp offset do
ignore(string("offset:"))
|> unwrap_and_tag(integer(min: 1), :offset)
|> ignore(Literal.whitespace())
end
end
|
lib/liquex/parser/tag/iteration.ex
| 0.736211 | 0.494995 |
iteration.ex
|
starcoder
|
defmodule Geometry.MultiPoint do
@moduledoc """
A set of points from type `Geometry.Point`.
`MultiPoint` implements the protocols `Enumerable` and `Collectable`.
## Examples
iex> Enum.map(
...> MultiPoint.new([
...> Point.new(1, 2),
...> Point.new(3, 4)
...> ]),
...> fn [x, _y] -> x end
...> )
[1, 3]
iex> Enum.into([Point.new(1, 2)], MultiPoint.new())
%MultiPoint{
points:
MapSet.new([
[1, 2]
])
}
"""
alias Geometry.{GeoJson, MultiPoint, Point, WKB, WKT}
defstruct points: MapSet.new()
@type t :: %MultiPoint{points: MapSet.t(Geometry.coordinate())}
@doc """
Creates an empty `MultiPoint`.
## Examples
iex> MultiPoint.new()
%MultiPoint{points: MapSet.new()}
"""
@spec new :: t()
def new, do: %MultiPoint{}
@doc """
Creates a `MultiPoint` from the given `Geometry.Point`s.
## Examples
iex> MultiPoint.new([
...> Point.new(1, 2),
...> Point.new(1, 2),
...> Point.new(3, 4)
...> ])
%MultiPoint{points: MapSet.new([
[1, 2],
[3, 4]
])}
iex> MultiPoint.new([])
%MultiPoint{points: MapSet.new()}
"""
@spec new([Point.t()]) :: t()
def new([]), do: %MultiPoint{}
def new(points) do
%MultiPoint{points: Enum.into(points, MapSet.new(), fn point -> point.coordinate end)}
end
@doc """
Returns `true` if the given `MultiPoint` is empty.
## Examples
iex> MultiPoint.empty?(MultiPoint.new())
true
iex> MultiPoint.empty?(
...> MultiPoint.new(
...> [Point.new(1, 2), Point.new(3, 4)]
...> )
...> )
false
"""
@spec empty?(t()) :: boolean
def empty?(%MultiPoint{} = multi_point), do: Enum.empty?(multi_point.points)
@doc """
Creates a `MultiPoint` from the given coordinates.
## Examples
iex> MultiPoint.from_coordinates(
...> [[-1, 1], [-2, 2], [-3, 3]]
...> )
%MultiPoint{
points: MapSet.new([
[-1, 1],
[-2, 2],
[-3, 3]
])
}
iex> MultiPoint.from_coordinates(
...> [[-1, 1], [-2, 2], [-3, 3]]
...> )
%MultiPoint{
points: MapSet.new([
[-1, 1],
[-2, 2],
[-3, 3]
])
}
"""
@spec from_coordinates([Geometry.coordinate()]) :: t()
def from_coordinates(coordinates), do: %MultiPoint{points: MapSet.new(coordinates)}
@doc """
Returns an `:ok` tuple with the `MultiPoint` from the given GeoJSON term.
Otherwise returns an `:error` tuple.
## Examples
iex> ~s(
...> {
...> "type": "MultiPoint",
...> "coordinates": [
...> [1.1, 1.2],
...> [20.1, 20.2]
...> ]
...> }
...> )
iex> |> Jason.decode!()
iex> |> MultiPoint.from_geo_json()
{:ok, %MultiPoint{points: MapSet.new([
[1.1, 1.2],
[20.1, 20.2]
])}}
"""
@spec from_geo_json(Geometry.geo_json_term()) :: {:ok, t()} | Geometry.geo_json_error()
def from_geo_json(json), do: GeoJson.to_multi_point(json, MultiPoint)
@doc """
The same as `from_geo_json/1`, but raises a `Geometry.Error` exception if it fails.
"""
@spec from_geo_json!(Geometry.geo_json_term()) :: t()
def from_geo_json!(json) do
case GeoJson.to_multi_point(json, MultiPoint) do
{:ok, geometry} -> geometry
error -> raise Geometry.Error, error
end
end
@doc """
Returns the GeoJSON term of a `MultiPoint`.
There are no guarantees about the order of points in the returned
`coordinates`.
## Examples
```elixir
MultiPoint.to_geo_json(
MultiPoint.new([
Point.new(-1.1, -2.2),
Point.new(1.1, 2.2)
])
)
# =>
# %{
# "type" => "MultiPoint",
# "coordinates" => [
# [-1.1, -2.2],
# [1.1, 2.2]
# ]
# }
```
"""
@spec to_geo_json(t()) :: Geometry.geo_json_term()
def to_geo_json(%MultiPoint{points: points}) do
%{
"type" => "MultiPoint",
"coordinates" => MapSet.to_list(points)
}
end
@doc """
Returns an `:ok` tuple with the `MultiPoint` from the given WKT string.
Otherwise returns an `:error` tuple.
If the geometry contains a SRID the id is added to the tuple.
## Examples
iex> MultiPoint.from_wkt(
...> "MultiPoint (-5.1 7.8, 0.1 0.2)"
...> )
{:ok, %MultiPoint{
points: MapSet.new([
[-5.1, 7.8],
[0.1, 0.2]
])
}}
iex> MultiPoint.from_wkt(
...> "SRID=7219;MultiPoint (-5.1 7.8, 0.1 0.2)"
...> )
{:ok, {
%MultiPoint{
points: MapSet.new([
[-5.1, 7.8],
[0.1, 0.2]
])
},
7219
}}
iex> MultiPoint.from_wkt("MultiPoint EMPTY")
...> {:ok, %MultiPoint{}}
"""
@spec from_wkt(Geometry.wkt()) ::
{:ok, t() | {t(), Geometry.srid()}} | Geometry.wkt_error()
def from_wkt(wkt), do: WKT.to_geometry(wkt, MultiPoint)
@doc """
The same as `from_wkt/1`, but raises a `Geometry.Error` exception if it fails.
"""
@spec from_wkt!(Geometry.wkt()) :: t() | {t(), Geometry.srid()}
def from_wkt!(wkt) do
case WKT.to_geometry(wkt, MultiPoint) do
{:ok, geometry} -> geometry
error -> raise Geometry.Error, error
end
end
@doc """
Returns the WKT representation for a `MultiPoint`. With option `:srid` an
EWKT representation with the SRID is returned.
There are no guarantees about the order of points in the returned
WKT-string.
## Examples
```elixir
MultiPoint.to_wkt(MultiPoint.new())
# => "MultiPoint EMPTY"
MultiPoint.to_wkt(
MultiPoint.new([
Point.new(7.1, 8.1),
Point.new(9.2, 5.2)
]
)
# => "MultiPoint (7.1 8.1, 9.2 5.2)"
MultiPoint.to_wkt(
MultiPoint.new([
Point.new(7.1, 8.1),
Point.new(9.2, 5.2)
]),
srid: 123
)
# => "SRID=123;MultiPoint (7.1 8.1, 9.2 5.2)"
"""
@spec to_wkt(t(), opts) :: Geometry.wkt()
when opts: [srid: Geometry.srid()]
def to_wkt(%MultiPoint{points: points}, opts \\ []) do
WKT.to_ewkt(
<<
"MultiPoint ",
points |> MapSet.to_list() |> to_wkt_points()::binary()
>>,
opts
)
end
@doc """
Returns the WKB representation for a `MultiPoint`.
With option `:srid` an EWKB representation with the SRID is returned.
The option `endian` indicates whether `:xdr` big endian or `:ndr` little
endian is returned. The default is `:xdr`.
The `:mode` determines whether a hex-string or binary is returned. The default
is `:binary`.
An example of a simpler geometry can be found in the description for the
`Geometry.Point.to_wkb/1` function.
"""
@spec to_wkb(t(), opts) :: Geometry.wkb()
when opts: [endian: Geometry.endian(), srid: Geometry.srid(), mode: Geometry.mode()]
def to_wkb(%MultiPoint{} = multi_point, opts \\ []) do
endian = Keyword.get(opts, :endian, Geometry.default_endian())
mode = Keyword.get(opts, :mode, Geometry.default_mode())
srid = Keyword.get(opts, :srid)
to_wkb(multi_point, srid, endian, mode)
end
@doc """
Returns an `:ok` tuple with the `MultiPoint` from the given WKB string. Otherwise
returns an `:error` tuple.
If the geometry contains a SRID the id is added to the tuple.
An example of a simpler geometry can be found in the description for the
`Geometry.Point.from_wkb/2` function.
"""
@spec from_wkb(Geometry.wkb(), Geometry.mode()) ::
{:ok, t() | {t(), Geometry.srid()}} | Geometry.wkb_error()
def from_wkb(wkb, mode \\ :binary), do: WKB.to_geometry(wkb, mode, MultiPoint)
@doc """
The same as `from_wkb/2`, but raises a `Geometry.Error` exception if it fails.
"""
@spec from_wkb!(Geometry.wkb(), Geometry.mode()) :: t() | {t(), Geometry.srid()}
def from_wkb!(wkb, mode \\ :binary) do
case WKB.to_geometry(wkb, mode, MultiPoint) do
{:ok, geometry} -> geometry
error -> raise Geometry.Error, error
end
end
@doc """
Returns the number of elements in `MultiPoint`.
## Examples
iex> MultiPoint.size(
...> MultiPoint.new([
...> Point.new(11, 12),
...> Point.new(21, 22)
...> ])
...> )
2
"""
@spec size(t()) :: non_neg_integer()
def size(%MultiPoint{points: points}), do: MapSet.size(points)
@doc """
Checks if `MulitPoint` contains `point`.
## Examples
iex> MultiPoint.member?(
...> MultiPoint.new([
...> Point.new(11, 12),
...> Point.new(21, 22)
...> ]),
...> Point.new(11, 12)
...> )
true
iex> MultiPoint.member?(
...> MultiPoint.new([
...> Point.new(11, 12),
...> Point.new(21, 22)
...> ]),
...> Point.new(1, 2)
...> )
false
"""
@spec member?(t(), Point.t()) :: boolean()
def member?(%MultiPoint{points: points}, %Point{coordinate: coordinate}),
do: MapSet.member?(points, coordinate)
@doc """
Converts `MultiPoint` to a list.
## Examples
iex> MultiPoint.to_list(
...> MultiPoint.new([
...> Point.new(11, 12),
...> Point.new(21, 22)
...> ])
...> )
[
[11, 12],
[21, 22]
]
"""
@spec to_list(t()) :: [Point.t()]
def to_list(%MultiPoint{points: points}), do: MapSet.to_list(points)
@compile {:inline, to_wkt_points: 1}
defp to_wkt_points([]), do: "EMPTY"
defp to_wkt_points([coordinate | points]) do
<<"(",
Enum.reduce(points, Point.to_wkt_coordinate(coordinate), fn coordinate, acc ->
<<acc::binary(), ", ", Point.to_wkt_coordinate(coordinate)::binary()>>
end)::binary(), ")">>
end
@doc false
@compile {:inline, to_wkb: 4}
@spec to_wkb(t(), Geometry.srid(), Geometry.endian(), Geometry.mode()) :: Geometry.wkb()
def to_wkb(%MultiPoint{points: points}, srid, endian, mode) do
<<
WKB.byte_order(endian, mode)::binary(),
wkb_code(endian, not is_nil(srid), mode)::binary(),
WKB.srid(srid, endian, mode)::binary(),
to_wkb_points(MapSet.to_list(points), endian, mode)::binary()
>>
end
@compile {:inline, to_wkb_points: 3}
defp to_wkb_points(points, endian, mode) do
Enum.reduce(points, WKB.length(points, endian, mode), fn point, acc ->
<<acc::binary(), Point.to_wkb(point, nil, endian, mode)::binary()>>
end)
end
@compile {:inline, wkb_code: 3}
defp wkb_code(endian, srid?, :hex) do
case {endian, srid?} do
{:xdr, false} -> "00000004"
{:ndr, false} -> "04000000"
{:xdr, true} -> "20000004"
{:ndr, true} -> "04000020"
end
end
defp wkb_code(endian, srid?, :binary) do
case {endian, srid?} do
{:xdr, false} -> <<0x00000004::big-integer-size(32)>>
{:ndr, false} -> <<0x00000004::little-integer-size(32)>>
{:xdr, true} -> <<0x20000004::big-integer-size(32)>>
{:ndr, true} -> <<0x20000004::little-integer-size(32)>>
end
end
defimpl Enumerable do
# credo:disable-for-next-line Credo.Check.Readability.Specs
def count(multi_point) do
{:ok, MultiPoint.size(multi_point)}
end
# credo:disable-for-next-line Credo.Check.Readability.Specs
def member?(multi_point, val) do
{:ok, MultiPoint.member?(multi_point, val)}
end
# credo:disable-for-next-line Credo.Check.Readability.Specs
def slice(multi_point) do
size = MultiPoint.size(multi_point)
{:ok, size, &Enumerable.List.slice(MultiPoint.to_list(multi_point), &1, &2, size)}
end
# credo:disable-for-next-line Credo.Check.Readability.Specs
def reduce(multi_point, acc, fun) do
Enumerable.List.reduce(MultiPoint.to_list(multi_point), acc, fun)
end
end
defimpl Collectable do
# credo:disable-for-next-line Credo.Check.Readability.Specs
def into(%MultiPoint{points: points}) do
fun = fn
list, {:cont, x} ->
[{x, []} | list]
list, :done ->
new = Enum.into(list, %{}, fn {point, []} -> {point.coordinate, []} end)
%MultiPoint{points: %{points | map: Map.merge(points.map, Map.new(new))}}
_list, :halt ->
:ok
end
{[], fun}
end
end
end
|
lib/geometry/multi_point.ex
| 0.962081 | 0.83622 |
multi_point.ex
|
starcoder
|
defmodule Aeutil.TypeToTag do
@moduledoc """
Conversion from structure types to numeric tags for RLP encoding and reverse.
"""
@spec tag_to_type(non_neg_integer()) :: {:ok, atom()} | {:error, String.t()}
def tag_to_type(10), do: {:ok, Aecore.Account.Account}
def tag_to_type(11), do: {:ok, Aecore.Tx.SignedTx}
def tag_to_type(12), do: {:ok, Aecore.Account.Tx.SpendTx}
def tag_to_type(20), do: {:ok, Aecore.Oracle.Oracle}
def tag_to_type(21), do: {:ok, Aecore.Oracle.OracleQuery}
def tag_to_type(22), do: {:ok, Aecore.Oracle.Tx.OracleRegistrationTx}
def tag_to_type(23), do: {:ok, Aecore.Oracle.Tx.OracleQueryTx}
def tag_to_type(24), do: {:ok, Aecore.Oracle.Tx.OracleResponseTx}
def tag_to_type(25), do: {:ok, Aecore.Oracle.Tx.OracleExtendTx}
def tag_to_type(30), do: {:ok, Aecore.Naming.Name}
def tag_to_type(31), do: {:ok, Aecore.Naming.NameCommitment}
def tag_to_type(32), do: {:ok, Aecore.Naming.Tx.NameClaimTx}
def tag_to_type(33), do: {:ok, Aecore.Naming.Tx.NamePreClaimTx}
def tag_to_type(34), do: {:ok, Aecore.Naming.Tx.NameUpdateTx}
def tag_to_type(35), do: {:ok, Aecore.Naming.Tx.NameRevokeTx}
def tag_to_type(36), do: {:ok, Aecore.Naming.Tx.NameTransferTx}
def tag_to_type(40), do: {:ok, Aecore.Contract.Contract}
def tag_to_type(41), do: {:ok, Aecore.Contract.Call}
def tag_to_type(42), do: {:ok, Aecore.Contract.Tx.ContractCreateTx}
def tag_to_type(43), do: {:ok, Aecore.Contract.Tx.ContractCallTx}
def tag_to_type(50), do: {:ok, Aecore.Channel.Tx.ChannelCreateTx}
def tag_to_type(51), do: {:ok, Aecore.Channel.Tx.ChannelDepositTx}
def tag_to_type(52), do: {:ok, Aecore.Channel.Tx.ChannelWithdrawTx}
# Channel force progress transaction - 521
def tag_to_type(53), do: {:ok, Aecore.Channel.Tx.ChannelCloseMutualTx}
def tag_to_type(54), do: {:ok, Aecore.Channel.Tx.ChannelCloseSoloTx}
def tag_to_type(55), do: {:ok, Aecore.Channel.Tx.ChannelSlashTx}
def tag_to_type(56), do: {:ok, Aecore.Channel.Tx.ChannelSettleTx}
def tag_to_type(57), do: {:ok, Aecore.Channel.ChannelOffChainTx}
# Channel off-chain update transfer - 570
# Channel off-chain update deposit - 571
# Channel off-chain update withdrawal - 572
# Channel off-chain update create contract - 573
# Channel off-chain update call contract - 574
def tag_to_type(58), do: {:ok, Aecore.Channel.ChannelStateOnChain}
def tag_to_type(59), do: {:ok, Aecore.Channel.Tx.ChannelSnapshotSoloTx}
def tag_to_type(60), do: {:ok, Aecore.Poi.Poi}
# Non Epoch tags:
def tag_to_type(100), do: {:ok, Aecore.Chain.Block}
def tag_to_type(tag), do: {:error, "#{__MODULE__}: Unknown tag: #{inspect(tag)}"}
@spec type_to_tag(atom()) :: {:ok, non_neg_integer()} | {:error, String.t()}
def type_to_tag(Aecore.Account.Account), do: {:ok, 10}
def type_to_tag(Aecore.Tx.SignedTx), do: {:ok, 11}
def type_to_tag(Aecore.Account.Tx.SpendTx), do: {:ok, 12}
def type_to_tag(Aecore.Oracle.Oracle), do: {:ok, 20}
def type_to_tag(Aecore.Oracle.OracleQuery), do: {:ok, 21}
def type_to_tag(Aecore.Oracle.Tx.OracleRegistrationTx), do: {:ok, 22}
def type_to_tag(Aecore.Oracle.Tx.OracleQueryTx), do: {:ok, 23}
def type_to_tag(Aecore.Oracle.Tx.OracleResponseTx), do: {:ok, 24}
def type_to_tag(Aecore.Oracle.Tx.OracleExtendTx), do: {:ok, 25}
def type_to_tag(Aecore.Naming.Name), do: {:ok, 30}
def type_to_tag(Aecore.Naming.NameCommitment), do: {:ok, 31}
def type_to_tag(Aecore.Naming.Tx.NameClaimTx), do: {:ok, 32}
def type_to_tag(Aecore.Naming.Tx.NamePreClaimTx), do: {:ok, 33}
def type_to_tag(Aecore.Naming.Tx.NameUpdateTx), do: {:ok, 34}
def type_to_tag(Aecore.Naming.Tx.NameRevokeTx), do: {:ok, 35}
def type_to_tag(Aecore.Naming.Tx.NameTransferTx), do: {:ok, 36}
def type_to_tag(Aecore.Contract.Contract), do: {:ok, 40}
def type_to_tag(Aecore.Contract.Call), do: {:ok, 41}
def type_to_tag(Aecore.Contract.Tx.ContractCreateTx), do: {:ok, 42}
def type_to_tag(Aecore.Contract.Tx.ContractCallTx), do: {:ok, 43}
def type_to_tag(Aecore.Channel.Tx.ChannelCreateTx), do: {:ok, 50}
def type_to_tag(Aecore.Channel.Tx.ChannelDepositTx), do: {:ok, 51}
def type_to_tag(Aecore.Channel.Tx.ChannelWithdrawTx), do: {:ok, 52}
# Channel force progress transaction - 521
def type_to_tag(Aecore.Channel.Tx.ChannelCloseMutualTx), do: {:ok, 53}
def type_to_tag(Aecore.Channel.Tx.ChannelCloseSoloTx), do: {:ok, 54}
def type_to_tag(Aecore.Channel.Tx.ChannelSlashTx), do: {:ok, 55}
def type_to_tag(Aecore.Channel.Tx.ChannelSettleTx), do: {:ok, 56}
def type_to_tag(Aecore.Channel.ChannelOffChainTx), do: {:ok, 57}
# Channel off-chain update transfer - 570
# Channel off-chain update deposit - 571
# Channel off-chain update withdrawal - 572
# Channel off-chain update create contract - 573
# Channel off-chain update call contract - 574
def type_to_tag(Aecore.Channel.ChannelStateOnChain), do: {:ok, 58}
def type_to_tag(Aecore.Channel.Tx.ChannelSnapshotSoloTx), do: {:ok, 59}
def type_to_tag(Aecore.Poi.Poi), do: {:ok, 60}
# Non Epoch tags
def type_to_tag(Aecore.Chain.Block), do: {:ok, 100}
def type_to_tag(type), do: {:error, "#{__MODULE__}: Non serializable type: #{type}"}
end
|
apps/aeutil/lib/type_to_tag.ex
| 0.811078 | 0.434401 |
type_to_tag.ex
|
starcoder
|
defmodule Strava.Activity do
@moduledoc """
Activities are the base object for Strava runs, rides, swims etc.
More info: https://strava.github.io/api/v3/activities/
"""
import Strava.Util, only: [parse_date: 1]
@type t :: %__MODULE__{
id: integer,
resource_state: integer,
external_id: String.t,
upload_id: integer,
athlete: Strava.Athlete.Meta.t,
name: String.t,
description: String.t,
distance: float,
moving_time: integer,
elapsed_time: integer,
total_elevation_gain: float,
elev_high: float,
elev_low: float,
type: String.t,
start_date: NaiveDateTime.t | String.t,
start_date_local: NaiveDateTime.t | String.t,
timezone: String.t,
start_latlng: list(number),
end_latlng: list(number),
achievement_count: integer,
kudos_count: integer,
comment_count: integer,
athlete_count: integer,
photo_count: integer,
total_photo_count: integer,
photos: Strava.Activity.Photo.Summary.t | nil,
map: map,
trainer: boolean,
commute: boolean,
manual: boolean,
private: boolean,
device_name: String.t,
embed_token: String.t,
flagged: boolean,
workout_type: integer,
gear_id: String.t,
gear: map,
average_speed: float,
max_speed: float,
average_cadence: float,
average_temp: float,
average_watts: float,
max_watts: integer,
weighted_average_watts: integer,
kilojoules: float,
device_watts: boolean,
has_heartrate: boolean,
average_heartrate: float,
max_heartrate: integer,
calories: float,
suffer_score: integer,
has_kudoed: boolean,
segment_efforts: list(Strava.SegmentEffort.t) | nil,
splits_metric: list(map),
splits_standard: list(map),
best_efforts: list(map)
}
defstruct [
:id,
:resource_state,
:external_id,
:upload_id,
:athlete,
:name,
:description,
:distance,
:moving_time,
:elapsed_time,
:total_elevation_gain,
:elev_high,
:elev_low,
:type,
:start_date,
:start_date_local,
:timezone,
:start_latlng,
:end_latlng,
:achievement_count,
:kudos_count,
:comment_count,
:athlete_count,
:photo_count,
:total_photo_count,
:photos,
:map,
:trainer,
:commute,
:manual,
:private,
:device_name,
:embed_token,
:flagged,
:workout_type,
:gear_id,
:gear,
:average_speed,
:max_speed,
:average_cadence,
:average_temp,
:average_watts,
:max_watts,
:weighted_average_watts,
:kilojoules,
:device_watts,
:has_heartrate,
:average_heartrate,
:max_heartrate,
:calories,
:suffer_score,
:has_kudoed,
:segment_efforts,
:splits_metric,
:splits_standard,
:best_efforts
]
defmodule Meta do
@type t :: %__MODULE__{
id: integer,
resource_state: integer
}
defstruct [
:id,
:resource_state
]
end
@doc """
Retrieve details about a specific activity.
## Example
Strava.Activity.retrieve(746805584)
Strava.Activity.retrieve(746805584, %{include_all_efforts: true})
More info: https://strava.github.io/api/v3/activities/#get-details
"""
@spec retrieve(integer, map, Strava.Client.t) :: Strava.Activity.t
def retrieve(id, filters \\ %{}, client \\ Strava.Client.new) do
"activities/#{id}?#{Strava.Util.query_string_no_pagination(filters)}"
|> Strava.request(client, as: %Strava.Activity{})
|> parse
end
@doc """
Retrieve a list of activities for the authenticated user. Pagination is supported.
## Example
activities = Strava.Activity.list_athlete_activities(%Strava.Pagination{per_page: 200, page: 1})
activities = Strava.Activity.list_athlete_activities(%Strava.Pagination{per_page: 200, page: 1}, Strava.Client.new("<access_token>>"))
activities = Strava.Activity.list_athlete_activities(%Strava.Pagination{per_page: 200, page: 1}, {before: "2017-04-20T00:00:12Z"})
More info: https://strava.github.io/api/v3/activities/#get-activities
"""
@spec list_athlete_activities(Strava.Pagination.t, map, Strava.Client.t) :: list(Strava.Activity.t)
def list_athlete_activities(pagination, filters \\ %{}, client \\ Strava.Client.new) do
"athlete/activities?#{Strava.Util.query_string(pagination, filters)}"
|> Strava.request(client, as: [%Strava.Activity{}])
|> Enum.map(&Strava.Activity.parse/1)
end
@doc """
Parse the athlete, dates, photos and segment efforts in the activity
"""
@spec parse(Strava.Activity.t) :: Strava.Activity.t
def parse(%Strava.Activity{} = activity) do
activity
|> parse_athlete
|> parse_dates
|> parse_photos
|> parse_segment_efforts
end
@spec parse_athlete(Strava.Activity.t) :: Strava.Activity.t
defp parse_athlete(%Strava.Activity{athlete: athlete} = activity) do
%Strava.Activity{activity |
athlete: struct(Strava.Athlete.Meta, athlete)
}
end
@spec parse_dates(Strava.Activity.t) :: Strava.Activity.t
defp parse_dates(%Strava.Activity{start_date: start_date, start_date_local: start_date_local} = activity) do
%Strava.Activity{activity |
start_date: parse_date(start_date),
start_date_local: parse_date(start_date_local)
}
end
@spec parse_photos(Strava.Activity.t) :: Strava.Activity.t
defp parse_photos(activity)
defp parse_photos(%Strava.Activity{photos: nil} = activity), do: activity
defp parse_photos(%Strava.Activity{photos: photos} = activity) do
%Strava.Activity{activity |
photos: Strava.Activity.Photo.Summary.parse(struct(Strava.Activity.Photo.Summary, photos))
}
end
@spec parse_segment_efforts(Strava.Activity.t) :: Strava.Activity.t
defp parse_segment_efforts(activity)
defp parse_segment_efforts(%Strava.Activity{segment_efforts: nil} = activity), do: activity
defp parse_segment_efforts(%Strava.Activity{segment_efforts: segment_efforts} = activity) do
%Strava.Activity{activity |
segment_efforts: Enum.map(segment_efforts, fn segment_effort ->
Strava.SegmentEffort.parse(struct(Strava.SegmentEffort, segment_effort))
end)
}
end
end
|
lib/strava/activity.ex
| 0.841468 | 0.459076 |
activity.ex
|
starcoder
|
defmodule Bincode.TestUtils do
@moduledoc """
Utilities to remove boilerplate in tests
"""
defmacro test_serialization(input, output, type, opts \\ []) do
quote do
test "#{inspect(unquote(type))} serialization (#{inspect(unquote(input))})" do
assert {:ok, serialized} = Bincode.serialize(unquote(input), unquote(type), unquote(opts))
assert Bincode.serialize!(unquote(input), unquote(type), unquote(opts)) == serialized
assert serialized == unquote(output)
assert Bincode.deserialize(serialized, unquote(type), unquote(opts)) ==
{:ok, {unquote(input), ""}}
assert Bincode.deserialize!(serialized, unquote(type), unquote(opts)) ==
{unquote(input), ""}
end
end
end
defmacro test_serialization_fail(input, output, type, opts \\ []) do
quote do
test "#{inspect(unquote(type))} serialization fail (#{inspect(unquote(input))})" do
assert {:error, _} = Bincode.serialize(unquote(input), unquote(type), unquote(opts))
assert_raise(ArgumentError, fn ->
Bincode.serialize!(unquote(input), unquote(type), unquote(opts))
end)
assert {:error, _} = Bincode.deserialize(unquote(output), unquote(type), unquote(opts))
assert_raise(ArgumentError, fn ->
Bincode.deserialize!(unquote(output), unquote(type), unquote(opts))
end)
end
end
end
defmacro test_struct_serialization(struct, binary, opts \\ []) do
quote do
test "#{to_string(unquote(struct).__struct__)} (#{inspect(unquote(binary))})" do
struct_module = unquote(struct).__struct__
assert {:ok, unquote(binary)} =
Bincode.serialize(unquote(struct), struct_module, unquote(opts))
assert Bincode.serialize!(unquote(struct), struct_module, unquote(opts)) ==
unquote(binary)
assert {:ok, {unquote(struct), ""}} =
Bincode.deserialize(unquote(binary), struct_module, unquote(opts))
assert {unquote(struct), ""} =
Bincode.deserialize!(unquote(binary), struct_module, unquote(opts))
end
end
end
defmacro test_struct_serialization_fail(struct_module, input, output, opts \\ []) do
quote do
test "#{to_string(unquote(struct_module))} fail (#{inspect(unquote(input))})" do
assert {:error, _} =
Bincode.serialize(unquote(input), unquote(struct_module), unquote(opts))
assert_raise(ArgumentError, fn ->
Bincode.serialize!(unquote(input), unquote(struct_module), unquote(opts))
end)
assert {:error, _} =
Bincode.deserialize(unquote(output), unquote(struct_module), unquote(opts))
assert_raise(ArgumentError, fn ->
Bincode.deserialize!(unquote(output), unquote(struct_module), unquote(opts))
end)
end
end
end
end
|
test/support/utils.ex
| 0.752559 | 0.803019 |
utils.ex
|
starcoder
|
defmodule Rondo.Action.Store do
defstruct [affordances: %{},
actions: %{},
validators: %{},
prev_affordances: %{}]
@app_validator Application.get_env(:rondo, :validator, Rondo.Validator.Default)
alias Rondo.Action.Handler
def init(store = %{affordances: affordances}) do
%{store | actions: %{}, prev_affordances: affordances}
end
def put(store = %{affordances: affordances, actions: actions}, action) do
{schema_id, schema, schema_ref, affordances} = create_schema(affordances, action)
{ref, actions} = create_ref(actions, action, schema_ref)
affordance = %Rondo.Affordance{ref: ref, schema_id: schema_id, schema: schema}
store = %{store | actions: actions, affordances: affordances}
{affordance, store}
end
def finalize(s = %{affordances: affordances, validators: validators, prev_affordances: prev_affordances}) do
{affordances, validators} = gc_affordances(affordances, validators, prev_affordances)
%{s | affordances: affordances, validators: validators, prev_affordances: %{}}
end
def prepare_update(store = %{actions: actions}, ref, data) do
case Map.fetch(actions, ref) do
:error ->
{:invalid, [], store}
{:ok, %{schema_ref: schema_ref,
events: events,
action: %{handler: handler,
props: props,
reference: state_descriptor}}} ->
{validator, store} = init_validator(store, schema_ref)
case validate(validator, data) do
{:error, errors} ->
{:invalid, errors, store}
:ok ->
update_fn = &Handler.action(handler, props, &1, data)
events = Enum.map(events, &(&1.(data)))
{:ok, [{state_descriptor, update_fn} | events], store}
end
end
end
defp create_schema(affordances, %{handler: handler, props: props}) do
key = {handler, props}
case Map.fetch(affordances, key) do
{:ok, {id, schema}} ->
{id, schema, key, affordances}
:error ->
schema = Handler.affordance(handler, props)
id = hash(schema)
schema = %Rondo.Schema{schema: schema}
affordances = Map.put(affordances, key, {id, schema})
{id, schema, key, affordances}
end
end
defp create_ref(actions, action, schema_ref) do
ref = hash(action)
actions = Map.put(actions, ref, %{
events: Enum.map(action.events, &init_events/1),
action: action,
schema_ref: schema_ref
})
{ref, actions}
end
defp init_events(%{reference: descriptor, handler: handler, props: props}) do
fn(data) ->
{descriptor, &Rondo.Event.Handler.event(handler, props, &1, data)}
end
end
defp init_validator(store = %{validators: validators, affordances: affordances}, schema_ref) do
case Map.fetch(validators, schema_ref) do
{:ok, validator} ->
{validator, store}
:error ->
{_, %{schema: schema}} = Map.fetch!(affordances, schema_ref)
validator = @app_validator.init(schema)
store = %{store | validators: Map.put(validators, schema_ref, validator)}
{validator, store}
end
end
defp validate(validator, data) do
@app_validator.validate(validator, data)
end
defp hash(contents) do
:erlang.phash2(contents) ## TODO pick a stronger hash?
end
defp gc_affordances(affordances, validators, prev_affordances) do
Enum.reduce(prev_affordances, {affordances, validators}, fn({_, {id, _}}, {affordances, validators}) ->
if Map.has_key?(affordances, id) do
{affordances, validators}
else
{Map.delete(affordances, id), Map.delete(validators, id)}
end
end)
end
end
defimpl Rondo.Diffable, for: Rondo.Action.Store do
def diff(curr, prev, path) do
@protocol.Map.diff(format(curr), format(prev), path)
end
defp format(%{affordances: affordances}) do
Map.values(affordances) |> :maps.from_list()
end
end
|
lib/rondo/action/store.ex
| 0.641422 | 0.442396 |
store.ex
|
starcoder
|
defmodule ConfluentSchemaRegistry do
@moduledoc """
Elixir client for [Confluent Schema Registry](https://docs.confluent.io/current/schema-registry/)
[API](https://docs.confluent.io/current/schema-registry/develop/api.html).
"""
# Argument types
@type id :: pos_integer
@type schema :: binary
@type subject :: binary
@type code :: non_neg_integer
@type reason :: any
@type version :: pos_integer | binary
@type level :: binary
@doc ~S"""
Create client to talk to Schema Registry.
Options are:
* base_url: URL of schema registry (optional, default "http://localhost:8081")
* username: username for BasicAuth (optional)
* password: password for <PASSWORD> (optional)
* adapter: Tesla adapter config
* middleware: List of additional middleware module config (optional)
## Examples
iex> client = ConfluentSchemaRegistry.client()
%Tesla.Client{
adapter: nil,
fun: nil,
post: [],
pre: [
{Tesla.Middleware.BaseUrl, :call, ["http://localhost:8081"]},
{Tesla.Middleware.Headers, :call,
[[{"content-type", "application/vnd.schemaregistry.v1+json"}]]},
{Tesla.Middleware.JSON, :call,
[[decode_content_types: ["application/vnd.schemaregistry.v1+json"]]]}
]
}
"""
@spec client(Keyword.t()) :: Tesla.Client.t()
def client(opts \\ []) do
base_url = opts[:base_url] || "http://localhost:8081"
opts_middleware = opts[:middleware] || []
adapter = opts[:adapter]
middleware =
opts_middleware ++
[
{Tesla.Middleware.BaseUrl, base_url},
{Tesla.Middleware.Headers,
[
{"content-type", "application/vnd.schemaregistry.v1+json"},
{"accept",
"application/vnd.schemaregistry.v1+json, application/vnd.schemaregistry+json, application/json"}
]},
{Tesla.Middleware.JSON,
decode_content_types: [
"application/vnd.schemaregistry.v1+json",
"application/vnd.schemaregistry+json"
]}
] ++ basic_auth(opts)
Tesla.client(middleware, adapter)
end
# Configure Tesla.Middleware.BasicAuth
@spec basic_auth(Keyword.t()) :: [{Tesla.Middleware.BasicAuth, map}]
defp basic_auth(opts) do
if opts[:username] do
auth_opts =
opts
|> Keyword.take([:username, :password])
|> Map.new()
[{Tesla.Middleware.BasicAuth, auth_opts}]
else
[]
end
end
@doc ~S"""
Get the schema string identified by the input ID.
https://docs.confluent.io/current/schema-registry/develop/api.html#get--schemas-ids-int-%20id
Returns binary schema.
## Examples
iex> ConfluentSchemaRegistry.get_schema(client, 21)
{:ok, "{\"type\":\"record\",\"name\":\"test\",\"fields\":[{\"name\":\"field1\",\"type\":\"string\"},{\"name\":\"field2\",\"type\":\"int\"}]}"}
"""
@spec get_schema(Tesla.Client.t(), id) :: {:ok, schema} | {:error, code, reason}
def get_schema(client, id) when is_integer(id) do
case do_get(client, "/schemas/ids/#{id}") do
{:ok, %{"schema" => value}} -> {:ok, value}
{:ok, value} -> {:error, 1, "Unexpected response: " <> value}
error -> error
end
end
@doc ~S"""
Get a list of registered subjects.
https://docs.confluent.io/current/schema-registry/develop/api.html#get--subjects
Returns list of subject name strings.
## Examples
iex> ConfluentSchemaRegistry.get_subjects(client)
{:ok, ["test"]}
"""
@spec get_subjects(Tesla.Client.t()) :: {:ok, list(subject)} | {:error, code, reason}
def get_subjects(client) do
case do_get(client, "/subjects") do
{:ok, _} = result -> result
error -> error
end
end
@doc ~S"""
Get a list of versions registered under the specified subject.
https://docs.confluent.io/current/schema-registry/develop/api.html#get--subjects-(string-%20subject)-versions
```
{:ok, [1, 2, 3, 4]} = ConfluentSchemaRegistry.get_versions(client, "test")
```
Returns list of integer ids.
"""
@spec get_versions(Tesla.Client.t(), subject) :: {:ok, list(id)} | {:error, code, reason}
def get_versions(client, subject) do
case do_get(client, "/subjects/#{subject}/versions") do
{:ok, _} = result -> result
error -> error
end
end
@doc ~S"""
Deletes the specified subject and its associated compatibility level if registered.
It is recommended to use this API only when a topic needs to be recycled or
in development environment.
https://docs.confluent.io/current/schema-registry/develop/api.html#delete--subjects-(string-%20subject)
Returns list of integer ids.
## Examples
iex> ConfluentSchemaRegistry.delete_subject(client, "test")
{:ok, [1]}
"""
@spec delete_subject(Tesla.Client.t(), subject) :: {:ok, list(id)} | {:error, code, reason}
def delete_subject(client, subject) do
case do_delete(client, "/subjects/#{subject}") do
{:ok, _} = result -> result
error -> error
end
end
@doc ~S"""
Get a specific version of the schema registered under this subject
https://docs.confluent.io/current/schema-registry/develop/api.html#delete--subjects-(string-%20subject)
Returns a map with the following keys:
* subject (string) -- Name of the subject that this schema is registered under
* id (int) -- Globally unique identifier of the schema
* version (int) -- Version of the returned schema
* schema (string) -- The Avro schema string
```
case ConfluentSchemaRegistry.get_schema(client, "test", "latest") do
{:ok, reg} ->
# Already registered
schema = reg["schema"]
schema_id = reg["id"]
{:error, 404, %{"error_code" => 40401}} ->
# Subject not found
{:error, 404, %{"error_code" => 40402}} ->
# Version not found
{:error, 422, reason} ->
# Unprocessable Entity, Invalid Avro version
{:error, code, reason} ->
# Other error
end
```
## Examples
iex> ConfluentSchemaRegistry.get_schema(client, "test")
{:ok,
%{
"id" => 21,
"schema" => "{\"type\":\"record\",\"name\":\"test\",\"fields\":[{\"name\":\"field1\",\"type\":\"string\"},{\"name\":\"field2\",\"type\":\"int\"}]}",
"subject" => "test",
"version" => 13
}}
iex> ConfluentSchemaRegistry.get_schema(client, "test", 13)
{:ok,
%{
"id" => 21,
"schema" => "{\"type\":\"record\",\"name\":\"test\",\"fields\":[{\"name\":\"field1\",\"type\":\"string\"},{\"name\":\"field2\",\"type\":\"int\"}]}",
"subject" => "test",
"version" => 13
}}
"""
@spec get_schema(Tesla.Client.t(), subject, version) ::
{:ok, map} | {:error, code, reason}
def get_schema(client, subject, version \\ "latest") do
case do_get(client, "/subjects/#{subject}/versions/#{version}") do
{:ok, _} = result -> result
error -> error
end
end
# NOTE: /subjects/#{subject}/versions/#{version}/schema not implemented, as
# it's redundant with get_schema/3
@doc ~S"""
Register a new schema under the specified subject. If successfully
registered, this returns the unique identifier of this schema in the registry.
https://docs.confluent.io/current/schema-registry/develop/api.html#post--subjects-(string-%20subject)-versions
Returns the integer id.
```
case ConfluentSchemaRegistry.register_schema(client, "test", schema) do
{:ok, schema_id} ->
# Already registered
{:error, 409, reason} ->
# Conflict -- Incompatible Avro schema
{:error, 422, reason} ->
# Unprocessable Entity, Invalid Avro schema
{:error, code, reason} ->
# Other error
end
```
## Examples
iex> ConfluentSchemaRegistry.register_schema(client, "test", schema)
{:ok, 21}
"""
@spec register_schema(Tesla.Client.t(), subject, schema) :: {:ok, id} | {:error, code, reason}
def register_schema(client, subject, schema) do
case do_post(client, "/subjects/#{subject}/versions", %{schema: schema}) do
{:ok, %{"id" => value}} -> {:ok, value}
{:ok, value} -> {:error, 1, "Unexpected response: #{inspect(value)}"}
error -> error
end
end
@doc ~S"""
Check if a schema has already been registered under the specified subject. If
so, this returns the schema string along with its globally unique identifier,
its version under this subject and the subject name.
https://docs.confluent.io/current/schema-registry/develop/api.html#post--subjects-(string-%20subject)
Returns map with the following keys:
* subject (string) -- Name of the subject that this schema is registered under
* id (int) -- Globally unique identifier of the schema
* version (int) -- Version of the returned schema
* schema (string) -- The Avro schema string
```
schema = "{\"type\":\"record\",\"name\":\"test\",\"fields\":[{\"name\":\"field1\",\"type\":\"string\"},{\"name\":\"field2\",\"type\":\"int\"}]}"
case ConfluentSchemaRegistry.is_registered(client, "test", schema) do
{:ok, reg} ->
# Found
schema = reg["schema"]
schema_id = reg["id"]
{:error, 404, %{"error_code" => 40401}} ->
# Subject not found
{:error, 404, %{"error_code" => 40403}} ->
# Schema not found
{:error, code, reason} ->
# Other error
end
```
## Examples
iex> ConfluentSchemaRegistry.is_registered(client, "test", schema)
{:ok,
%{
"id" => 21,
"schema" => "{\"type\":\"record\",\"name\":\"test\",\"fields\":[{\"name\":\"field1\",\"type\":\"string\"},{\"name\":\"field2\",\"type\":\"int\"}]}",
"subject" => "test",
"version" => 1
}}
iex> ConfluentSchemaRegistry.is_registered(client, "test2", schema)
{:error, 404, %{"error_code" => 40401, "message" => "Subject not found. ..."}}
"""
@spec is_registered(Tesla.Client.t(), subject, schema) :: {:ok, map} | {:error, code, reason}
def is_registered(client, subject, schema) do
case do_post(client, "/subjects/#{subject}", %{schema: schema}) do
{:ok, _} = result -> result
error -> error
end
end
@doc ~S"""
Deletes a specific version of the schema registered under this subject. This
only deletes the version and the schema ID remains intact making it still
possible to decode data using the schema ID.
https://docs.confluent.io/current/schema-registry/develop/api.html#delete--subjects-(string-%20subject)-versions-(versionId-%20version)
```
{:ok, 1} = ConfluentSchemaRegistry.delete_version(client, "test") # latest
{:ok, 1} = ConfluentSchemaRegistry.delete_version(client, "test", 1)
```
Returns integer id of deleted version.
"""
@spec delete_version(Tesla.Client.t(), subject, version) :: {:ok, id} | {:error, code, reason}
def delete_version(client, subject, version \\ "latest") do
case do_delete(client, "/subjects/#{subject}/versions/#{version}") do
{:ok, value} when is_integer(value) -> {:ok, value}
{:ok, value} -> {:error, 1, "Unexpected response: #{inspect(value)}"}
error -> error
end
end
@doc ~S"""
Test input schema against a particular version of a subject's schema for
compatibility. Note that the compatibility level applied for the check is the
configured compatibility level for the subject (`get_compatibility/2`).
If this subject's compatibility level was never changed, then the
global compatibility level applies (`get_compatibility/1`).
https://docs.confluent.io/current/schema-registry/develop/api.html#post--compatibility-subjects-(string-%20subject)-versions-(versionId-%20version)
Returns boolean.
## Examples
iex> ConfluentSchemaRegistry.is_compatible(client, "test", schema)
{:ok, true}
iex> ConfluentSchemaRegistry.is_compatible(client, "test", schema, "latest")
{:ok, true}
iex> ConfluentSchemaRegistry.is_compatible(client, "test", schema, 1)
{:ok, true}
"""
@spec is_compatible(Tesla.Client.t(), subject, schema, version) ::
{:ok, boolean} | {:error, code, reason}
def is_compatible(client, subject, schema, version \\ "latest") do
case do_post(client, "/compatibility/subjects/#{subject}/versions/#{version}", %{
schema: schema
}) do
{:ok, %{"is_compatible" => value}} -> {:ok, value}
{:ok, value} -> {:error, 1, "Unexpected response: " <> value}
error -> error
end
end
@doc ~S"""
Update global compatibility level.
Level is a string which must be one of BACKWARD, BACKWARD_TRANSITIVE, FORWARD,
FORWARD_TRANSITIVE, FULL, FULL_TRANSITIVE, NONE
https://docs.confluent.io/current/schema-registry/develop/api.html#put--config
Returns string.
## Examples
iex> ConfluentSchemaRegistry.update_compatibility(client, "test", "FULL")
{:ok, "FULL"}
"""
@spec update_compatibility(Tesla.Client.t(), level) :: {:ok, level} | {:error, code, reason}
when level: binary, code: non_neg_integer, reason: any
def update_compatibility(client, level) do
case do_put(client, "/config", %{compatibility: level}) do
{:ok, %{"compatibility" => value}} -> {:ok, value}
{:ok, value} -> {:error, 1, "Unexpected response: " <> value}
error -> error
end
end
@doc ~S"""
Get global compatibility level.
Level is a string which will be one of BACKWARD, BACKWARD_TRANSITIVE, FORWARD,
FORWARD_TRANSITIVE, FULL, FULL_TRANSITIVE, NONE
https://docs.confluent.io/current/schema-registry/develop/api.html#put--config
Returns string.
## Examples
iex> ConfluentSchemaRegistry.get_compatibility(client)
{:ok, "BACKWARD"}
"""
@spec get_compatibility(Tesla.Client.t()) :: {:ok, level} | {:error, code, reason}
when level: binary, code: non_neg_integer, reason: any
def get_compatibility(client) do
case do_get(client, "/config") do
{:ok, %{"compatibilityLevel" => value}} -> {:ok, value}
{:ok, value} -> {:error, 1, "Unexpected response: #{inspect(value)}"}
error -> error
end
end
@doc ~S"""
Update compatibility level for the specified subject.
Leve is a string which must be one of BACKWARD, BACKWARD_TRANSITIVE, FORWARD,
FORWARD_TRANSITIVE, FULL, FULL_TRANSITIVE, NONE
https://docs.confluent.io/current/schema-registry/develop/api.html#put--config
Returns string.
## Examples
iex> ConfluentSchemaRegistry.update_compatibility(client, "test", "FULL")
{:ok, "FULL"}
"""
@spec update_compatibility(Tesla.Client.t(), subject, level) ::
{:ok, level} | {:error, code, reason}
def update_compatibility(client, subject, level) do
case do_put(client, "/config/#{subject}", %{compatibility: level}) do
{:ok, %{"compatibility" => value}} -> {:ok, value}
{:ok, value} -> {:error, 1, "Unexpected response: #{inspect(value)}"}
error -> error
end
end
@doc ~S"""
Get compatibility level for a subject.
Level is a string which will be one of BACKWARD, BACKWARD_TRANSITIVE, FORWARD,
FORWARD_TRANSITIVE, FULL, FULL_TRANSITIVE, NONE
https://docs.confluent.io/current/schema-registry/develop/api.html#put--config
Returns string.
## Examples
iex> ConfluentSchemaRegistry.get_compatibility(client, "test")
{:ok, "FULL"}
"""
@spec get_compatibility(Tesla.Client.t(), subject) ::
{:ok, level} | {:error, code, reason}
def get_compatibility(client, subject) do
case do_get(client, "/config/#{subject}") do
{:ok, %{"compatibilityLevel" => value}} -> {:ok, value}
{:ok, value} -> {:error, 1, "Unexpected response: " <> value}
error -> error
end
end
# Internal utility functions
@spec do_get(Tesla.Client.t(), binary) :: {:ok, any} | {:error, code, reason}
defp do_get(client, url) do
tesla_response(Tesla.get(client, url))
end
@spec do_delete(Tesla.Client.t(), binary) :: {:ok, any} | {:error, code, reason}
defp do_delete(client, url) do
tesla_response(Tesla.delete(client, url))
end
@spec do_post(Tesla.Client.t(), binary, any) :: {:ok, any} | {:error, code, reason}
defp do_post(client, url, data) when is_binary(data) do
tesla_response(Tesla.post(client, url, data))
end
defp do_post(client, url, data) do
case Jason.encode(data) do
{:ok, encoded} ->
do_post(client, url, encoded)
{:error, reason} ->
{:error, 0, reason}
end
end
@spec do_put(Tesla.Client.t(), binary, any) :: {:ok, any} | {:error, code, reason}
defp do_put(client, url, data) when is_binary(data) do
tesla_response(Tesla.put(client, url, data))
end
defp do_put(client, url, data) do
case Jason.encode(data) do
{:ok, encoded} ->
do_put(client, url, encoded)
{:error, reason} ->
{:error, 0, reason}
end
end
defp tesla_response({:ok, %{status: 200, body: body}}), do: {:ok, body}
defp tesla_response({:ok, %{status: status, body: body}}), do: {:error, status, body}
defp tesla_response({:error, reason}), do: {:error, 0, reason}
end
|
lib/confluent_schema_registry.ex
| 0.841631 | 0.423816 |
confluent_schema_registry.ex
|
starcoder
|
defmodule Intcode do
require Logger
@doc """
An Intcode program is a list of integers separated by commas (like 1,0,0,3,99).
To run one, start by looking at the first integer (called position 0).
Here, you will find an opcode - either 1, 2, or 99. The opcode indicates
what to do; for example, 99 means that the program is finished and should
immediately halt. Encountering an unknown opcode means something went wrong.
Opcode 1 adds together numbers read from two positions and stores the result
in a third position. The three integers immediately after the opcode tell you
these three positions - the first two indicate the positions from which you
should read the input values, and the third indicates the position at which the
output should be stored.
Opcode 2 works exactly like opcode 1, except it multiplies the two inputs instead
of adding them. Again, the three integers after the opcode indicate where the inputs
and outputs are, not their values.
Once you're done processing an opcode, move to the next one by stepping forward 4 positions.
"""
@spec eval(String.t) :: String.t
def eval(program) do
program = String.split(program, ",")
|> Enum.map(&String.to_integer/1)
evaluate(program, program, 0)
|> Enum.join(",")
end
@spec evaluate([integer], [integer], integer) :: [integer]
defp evaluate([1, left, right, out | _], input, cursor) do
a = Enum.at(input, left)
b = Enum.at(input, right)
input = List.replace_at(input, out, a + b)
cursor = cursor + 4
evaluate(Enum.slice(input, cursor..-1), input, cursor)
end
defp evaluate([2, left, right, out | _], input, cursor) do
a = Enum.at(input, left)
b = Enum.at(input, right)
input = List.replace_at(input, out, a * b)
cursor = cursor + 4
evaluate(Enum.slice(input, cursor..-1), input, cursor)
end
defp evaluate([99 | _], input, _) do
input
end
defp evaluate(_, input, _) do
input
end
end
|
lib/intcode.ex
| 0.775817 | 0.557875 |
intcode.ex
|
starcoder
|
defmodule NLTEx.WordVectors.GloVe do
@moduledoc ~S"""
Provides interface to retrieve and preprocess GloVe word vectors.
<NAME>, <NAME>, and <NAME>. 2014.
_GloVe: Global Vectors for Word Representation._
https://nlp.stanford.edu/projects/glove/
"""
@canonical_base_url "http://nlp.stanford.edu/data/"
@file_glove_6b "glove.6B.zip"
# @file_glove_42b "glove.42B.300d.zip"
# @file_glove_840b "glove.840B.300d.zip"
@file_glove_twitter_27b "glove.twitter.27B.zip"
@glove_vecs %{
{:glove_6b, 50} => {@file_glove_6b, 'glove.6B.50d.txt'},
{:glove_6b, 100} => {@file_glove_6b, 'glove.6B.100d.txt'},
{:glove_6b, 200} => {@file_glove_6b, 'glove.6B.200d.txt'},
{:glove_6b, 300} => {@file_glove_6b, 'glove.6B.300d.txt'},
# TODO getting {:error, :badmatch} on unzip # {:glove_42b, 300} => {@file_glove_42b, 'glove.42B.300d.txt'},
# TODO getting {:error, :badmatch} on unzip # {:glove_840b, 300} => {@file_glove_840b, 'glove.840B.300d.txt'},
{:glove_twitter_27b, 25} => {@file_glove_twitter_27b, 'glove.twitter.27B.25d.txt'},
{:glove_twitter_27b, 50} => {@file_glove_twitter_27b, 'glove.twitter.27B.50d.txt'},
{:glove_twitter_27b, 100} => {@file_glove_twitter_27b, 'glove.twitter.27B.100d.txt'},
{:glove_twitter_27b, 200} => {@file_glove_twitter_27b, 'glove.twitter.27B.200d.txt'},
}
alias Scidata.Utils
@doc ~S"""
Download and unpack the requested GloVe vector file and parse it into word vectors.
Available combinations of GloVe libraries and vector sizes are:
- `:glove_6b`
- 50
- 100
- 200
- 300
- `:glove_twitter_27b`
- 25
- 50
- 100
- 200
## Options
- `:base_url` Overrides the canonical Stanford NLP data server URL for alternate hosting of GloVe files
## Examples
iex> w2v = NLTEx.WordVectors.GloVe.download(:glove_6b, 50)
iex> %NLTEx.WordVectors{vectors: _vectors_list, words: _words_list} = w2v
"""
def download(lib, vec_size, opts \\ []) do
base_url = opts[:base_url] || @canonical_base_url #Keyword.get(opts, :base_url, @canonical_base_url) |> IO.inspect()
{lib_file, vec_file} = Map.get(@glove_vecs, {lib, vec_size})
{words, vectors} = Utils.get!(base_url <> lib_file).body
|> extract_vec_data(vec_file)
|> process_vec_data(vec_size)
wordvec = words
|> Enum.zip(vectors)
|> Map.new()
NLTEx.WordVectors.new(wordvec, {vec_size})
end
# Util function to handle extracting specific file from ZIPfile
defp extract_vec_data(zipdata, vec_file) do
{:ok, files} = :zip.unzip(zipdata, [:memory, {:file_list, [vec_file]}])
files
|> hd()
|> elem(1)
end
# Util function to process raw data from ZIPfile into {words, vecs}
defp process_vec_data(data, vec_size) do
data
|> String.split("\n", trim: true)
|> Enum.map(&String.split/1)
|> Enum.filter(fn x -> length(x) == vec_size + 1 end)
|> Enum.map(fn [word | vec] -> {word, Nx.tensor(for x <- vec, do: elem(Float.parse(x), 0))} end)
|> Enum.unzip()
end
end
|
lib/nlt_ex/word_vectors/glove.ex
| 0.545286 | 0.581184 |
glove.ex
|
starcoder
|
defmodule GoogleMaps.Geocode do
@moduledoc """
Perform geocoding-related lookups against the Google Maps API.
"""
use RepoCache, ttl: :timer.hours(24)
alias LocationService.Result
alias GoogleMaps.Geocode.Input
require Logger
@bounds %{
east: 41.3193,
north: -71.9380,
west: 42.8266,
south: -69.6189
}
@http_pool Application.get_env(:location_service, :http_pool)
@path "/maps/api/geocode/json"
# Visits to the "Transit Near Me" page from Algolia search results already have lat/lng geocoding, but use
# different parameters for the address. We track "address" as one of our analytics
# parameters for Algolia search results, but the Phoenix form helper used in the
# /transit-near-me template requires that we use a nested "locations"["address"] data structure.
# This helper function simply looks for the address in one of those two values and falls
# back to using the lat/lng if neither can be found.
# Also used in the "Proposed Sales Location" page to identify whether an address is formatted or a String containing coordinates
def formatted_address(%{"address" => address}, _options), do: address
def formatted_address(%{"location" => %{"address" => address}}, _options), do: address
def formatted_address(%{"latitude" => lat, "longitude" => lng}, options) do
{parsed_lat, _} = Float.parse(lat)
{parsed_lng, _} = Float.parse(lng)
case options.reverse_geocode_fn.(parsed_lat, parsed_lng) do
{:ok, [first | _]} ->
first.formatted
_ ->
"#{lat}, #{lng}"
end
end
@spec calculate_position(
map(),
(String.t() -> LocationService.Address.t())
) :: {LocationService.Address.t(), String.t()}
def calculate_position(%{"latitude" => lat_str, "longitude" => lng_str} = params, geocode_fn) do
case {Float.parse(lat_str), Float.parse(lng_str)} do
{{lat, ""}, {lng, ""}} ->
addr = %LocationService.Address{
latitude: lat,
longitude: lng,
formatted: lat_str <> "," <> lng_str
}
parse_geocode_response({:ok, [addr]})
_ ->
params
|> Map.delete("latitude")
|> Map.delete("longitude")
|> calculate_position(geocode_fn)
end
end
def calculate_position(%{"location" => %{"address" => address}}, geocode_fn) do
address
|> geocode_fn.()
|> parse_geocode_response()
end
def calculate_position(_params, _geocode_fn) do
{%{}, ""}
end
defp parse_geocode_response({:ok, [location | _]}) do
{location, location.formatted}
end
defp parse_geocode_response(_) do
{%{}, ""}
end
@spec check_address(String.t(), map) :: String.t()
def check_address(address, opts) do
# address can be a String containing "lat,lon" so we check for that case
[lat, lon] =
case String.split(address, ",", parts: 2) do
[lat, lon] -> [lat, lon]
_ -> ["error", "error"]
end
if Float.parse(lat) == :error || Float.parse(lon) == :error do
address
else
formatted_address(%{"latitude" => lat, "longitude" => lon}, opts)
end
end
@spec geocode(String.t()) :: LocationService.result()
def geocode(address) when is_binary(address) do
cache(address, fn address ->
address
|> geocode_url
|> GoogleMaps.signed_url()
|> HTTPoison.get([], hackney: [pool: @http_pool])
|> Result.handle_response(%Input{address: address})
end)
end
@spec geocode_by_place_id(String.t()) :: LocationService.result()
def geocode_by_place_id(place_id) do
cache(place_id, fn place_id ->
place_id
|> geocode_by_place_id_url()
|> GoogleMaps.signed_url()
|> HTTPoison.get([], hackney: [pool: @http_pool])
|> Result.handle_response(%Input{address: place_id})
end)
end
@spec reverse_geocode(float, float) :: LocationService.result()
def reverse_geocode(latitude, longitude) when is_float(latitude) and is_float(longitude) do
cache({latitude, longitude}, fn {latitude, longitude} ->
{latitude, longitude}
|> reverse_geocode_url()
|> GoogleMaps.signed_url()
|> HTTPoison.get([], hackney: [pool: @http_pool])
|> Result.handle_response(%Input{latitude: latitude, longitude: longitude})
end)
end
defp geocode_url(address) do
URI.to_string(%URI{
path: @path,
query:
URI.encode_query(
address: address,
bounds: "#{@bounds.east},#{@bounds.north}|#{@bounds.west},#{@bounds.south}"
)
})
end
defp geocode_by_place_id_url(place_id) do
URI.to_string(%URI{
path: @path,
query: URI.encode_query(place_id: place_id)
})
end
defp reverse_geocode_url({latitude, longitude}) do
URI.to_string(%URI{
path: @path,
query: URI.encode_query(latlng: "#{latitude},#{longitude}")
})
end
end
|
apps/location_service/lib/google_maps/geocode.ex
| 0.830285 | 0.529811 |
geocode.ex
|
starcoder
|
defmodule Coxir.Struct.Channel do
@moduledoc """
Defines methods used to interact with Discord channels.
Refer to [this](https://discordapp.com/developers/docs/resources/channel#channel-object)
for a list of fields and a broader documentation.
In addition, the following fields are also embedded.
- `owner` - an user object
"""
@type channel :: String.t | map
use Coxir.Struct
alias Coxir.Struct.{User, Member, Overwrite, Message}
def pretty(struct) do
struct
|> replace(:owner_id, &User.get/1)
end
@doc """
Sends a message to a given channel.
Returns a message object upon success
or a map containing error information.
#### Content
Either a string or an enumerable with
the fields listed below.
- `content` - the message contents (up to 2000 characters)
- `embed` - embedded rich content, refer to
[this](https://discordapp.com/developers/docs/resources/channel#embed-object)
- `nonce` - used for optimistic message sending
- `file` - the path of the file being sent
- `tts` - true if this is a TTS message
Refer to [this](https://discordapp.com/developers/docs/resources/channel#create-message)
for a broader explanation on the fields and their defaults.
"""
@spec send_message(channel, String.t | Enum.t) :: map
def send_message(%{id: id}, content),
do: send_message(id, content)
def send_message(channel, content) do
content = \
cond do
is_binary(content) ->
%{content: content}
file = content[:file] ->
%{file: file}
true ->
content
end
function = \
cond do
content[:file] ->
:request_multipart
true ->
:request
end
arguments = [:post, "channels/#{channel}/messages", content]
API
|> apply(function, arguments)
|> Message.pretty
end
@doc """
Fetches a message from a given channel.
Returns a message object upon success
or a map containing error information.
"""
@spec get_message(channel, String.t) :: map
def get_message(%{id: id}, message),
do: get_message(id, message)
def get_message(channel, message) do
Message.get(message)
|> case do
nil ->
API.request(:get, "channels/#{channel}/messages/#{message}")
|> Message.pretty
message -> message
end
end
@doc """
Fetches messages from a given channel.
Returns a list of message objects upon success
or a map containing error information.
#### Query
Must be a keyword list with the fields listed below.
- `around` - get messages around this message ID
- `before` - get messages before this message ID
- `after` - get messages after this message ID
- `limit` - max number of messages to return
Refer to [this](https://discordapp.com/developers/docs/resources/channel#get-channel-messages)
for a broader explanation on the fields and their defaults.
"""
@spec history(channel, Keyword.t) :: list | map
def history(term, query \\ [])
def history(%{id: id}, query),
do: history(id, query)
def history(channel, query) do
API.request(:get, "channels/#{channel}/messages", "", params: query)
|> case do
list when is_list(list) ->
for message <- list do
Message.pretty(message)
end
error -> error
end
end
@doc """
Fetches the pinned messages from a given channel.
Returns a list of message objects upon success
or a map containing error information.
"""
@spec get_pinned_messages(channel) :: list | map
def get_pinned_messages(%{id: id}),
do: get_pinned_messages(id)
def get_pinned_messages(channel) do
API.request(:get, "channels/#{channel}/pins")
|> case do
list when is_list(list) ->
for message <- list do
Message.pretty(message)
end
error -> error
end
end
@doc """
Deletes multiple messages from a given channel.
Returns the atom `:ok` upon success
or a map containing error information.
"""
@spec bulk_delete_messages(channel, list) :: :ok | map
def bulk_delete_messages(%{id: id}, messages),
do: bulk_delete_messages(id, messages)
def bulk_delete_messages(channel, messages) do
API.request(:post, "channels/#{channel}/messages/bulk-delete", %{messages: messages})
end
@doc """
Triggers the typing indicator on a given channel.
Returns the atom `:ok` upon success
or a map containing error information.
"""
@spec typing(channel) :: :ok | map
def typing(%{id: id}),
do: typing(id)
def typing(channel) do
API.request(:post, "channels/#{channel}/typing")
end
@doc """
Modifies a given channel.
Returns a channel object upon success
or a map containing error information.
#### Params
Must be an enumerable with the fields listed below.
- `name` - channel name (2-100 characters)
- `topic` - channel topic (up to 1024 characters)
- `nsfw` - whether the channel is NSFW
- `position` - the position in the left-hand listing
- `bitrate` - the bitrate in bits of the voice channel
- `user_limit` - the user limit of the voice channel
- `permission_overwrites` - channel or category-specific permissions
- `parent_id` - id of the new parent category
Refer to [this](https://discordapp.com/developers/docs/resources/channel#modify-channel)
for a broader explanation on the fields and their defaults.
"""
@spec edit(channel, Enum.t) :: map
def edit(%{id: id}, params),
do: edit(id, params)
def edit(channel, params) do
API.request(:patch, "channels/#{channel}", params)
|> pretty
end
@doc """
Changes the name of a given channel.
Returns a channel object upon success
or a map containing error information.
"""
@spec set_name(channel, String.t) :: map
def set_name(channel, name),
do: edit(channel, name: name)
@doc """
Changes the topic of a given channel.
Returns a channel object upon success
or a map containing error information.
"""
@spec set_topic(channel, String.t) :: map
def set_topic(channel, topic),
do: edit(channel, topic: topic)
@doc """
Changes the position of a given channel.
Returns a channel object upon success
or a map containing error information.
"""
@spec set_position(channel, integer) :: map
def set_position(channel, position),
do: edit(channel, position: position)
@doc """
Changes the parent category of a given channel.
Returns a channel object upon success
or a map containing error information.
"""
@spec set_parent(channel, String.t) :: map
def set_parent(channel, parent),
do: edit(channel, parent_id: parent)
@doc """
Changes the NSFW flag of a given channel.
Returns a channel object upon success
or a map containing error information.
"""
@spec set_nsfw(channel, boolean) :: map
def set_nsfw(channel, bool),
do: edit(channel, nsfw: bool)
@doc """
Change the slowmode rate of a given channel.
Returns a channel object upon success
or a map containing error information.
"""
@spec set_slowmode(channel, integer) :: map
def set_slowmode(channel, limit),
do: edit(channel, rate_limit_per_user: limit)
@doc """
Changes the bitrate of a given voice channel.
Returns a channel object upon success
or a map containing error information.
"""
@spec set_bitrate(channel, integer) :: map
def set_bitrate(channel, bitrate),
do: edit(channel, bitrate: bitrate)
@doc """
Changes the user limit of a given voice channel.
Returns a channel object upon success
or a map containing error information.
"""
@spec set_user_limit(channel, integer) :: map
def set_user_limit(channel, limit),
do: edit(channel, user_limit: limit)
@doc """
Deletes a given channel.
Returns a channel object upon success
or a map containing error information.
"""
@spec delete(channel) :: map
def delete(%{id: id}),
do: delete(id)
def delete(channel) do
API.request(:delete, "channels/#{channel}")
end
@doc """
Creates a permission overwrite for a given channel.
Refer to `Coxir.Struct.Overwrite.edit/2` for more information.
"""
@spec create_permission(channel, String.t, Enum.t) :: map
def create_permission(%{id: id}, overwrite, params),
do: create_permission(id, overwrite, params)
def create_permission(channel, overwrite, params),
do: Overwrite.edit(overwrite, channel, params)
@doc """
Creates an invite for a given channel.
Returns an invite object upon success
or a map containing error information.
#### Params
Must be an enumerable with the fields listed below.
- `max_uses` - max number of uses (0 if unlimited)
- `max_age` - duration in seconds before expiry (0 if never)
- `temporary` - whether this invite only grants temporary membership
- `unique` - whether not to try to reuse a similar invite
Refer to [this](https://discordapp.com/developers/docs/resources/channel#create-channel-invite)
for a broader explanation on the fields and their defaults.
"""
@spec create_invite(channel, Enum.t) :: map
def create_invite(term, params \\ %{})
def create_invite(%{id: id}, params),
do: create_invite(id, params)
def create_invite(channel, params) do
API.request(:post, "channels/#{channel}/invites", params)
end
@doc """
Fetches the invites from a given channel.
Returns a list of invite objects upon success
or a map containing error information.
"""
@spec get_invites(channel) :: list | map
def get_invites(%{id: id}),
do: get_invites(id)
def get_invites(channel) do
API.request(:get, "channels/#{channel}/invites")
end
@doc """
Creates a webhook for a given channel.
Returns a webhook object upon success
or a map containing error information.
#### Params
Must be an enumerable with the fields listed below.
- `name` - name of the webhook (2-23 characters)
- `avatar` - image for the default webhook avatar
"""
@spec create_webhook(channel, Enum.t) :: map
def create_webhook(%{id: id}, params),
do: create_webhook(id, params)
def create_webhook(channel, params) do
API.request(:post, "channels/#{channel}/webhooks", params)
end
@doc """
Fetches the webhooks from a given channel.
Returns a list of webhook objects upon success
or a map containing error information.
"""
@spec get_webhooks(channel) :: list | map
def get_webhooks(%{id: id}),
do: get_webhooks(id)
def get_webhooks(channel) do
API.request(:get, "channels/#{channel}/webhooks")
end
@doc """
Fetches the users currently in a given voice channel.
Returns a list of user or member objects depending on
whether it's a private or a guild channel respectively
or a map containing error information.
"""
@spec get_voice_members(channel) :: list | map
def get_voice_members(%{id: id}),
do: get_voice_members(id)
def get_voice_members(channel) do
pattern = %{voice_id: channel}
User.select(pattern)
|> case do
[] -> Member.select(pattern)
list -> list
end
end
end
|
lib/coxir/struct/channel.ex
| 0.933877 | 0.489626 |
channel.ex
|
starcoder
|
defmodule Mongo do
@moduledoc """
The main entry point for doing queries. All functions take a pool to
run the query on.
## Read options
All read operations that returns a cursor take the following options
for controlling the behaviour of the cursor.
* `:batch_size` - Number of documents to fetch in each batch
* `:limit` - Maximum number of documents to fetch with the cursor
## Write options
All write operations take the following options for controlling the
write concern.
* `:w` - The number of servers to replicate to before returning from write
operators, a 0 value will return immediately, :majority will wait until
the operation propagates to a majority of members in the replica set
(Default: 1)
* `:j` If true, the write operation will only return after it has been
committed to journal - (Default: false)
* `:wtimeout` - If the write concern is not satisfied in the specified
interval, the operation returns an error
## Logging
All operations take a boolean `log` option, that determines, whether the
pool's `log/5` function will be called.
"""
alias Mongo.Connection
alias Mongo.WriteResult
alias Mongo.Pool
@type collection :: String.t
@opaque cursor :: Mongo.Cursor.t | Mongo.AggregationCursor.t | Mongo.SinglyCursor.t
@type result(t) :: :ok | {:ok, t} | {:error, Mongo.Error.t}
@type result!(t) :: nil | t | no_return
defmacrop bangify(result) do
quote do
case unquote(result) do
{:ok, value} -> value
{:error, error} -> raise error
:ok -> nil
end
end
end
@doc false
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
worker(Mongo.IdServer, []),
worker(Mongo.PBKDF2Cache, [])
]
opts = [strategy: :one_for_one, name: Mongo.Supervisor]
Supervisor.start_link(children, opts)
end
@doc """
Performs aggregation operation using the aggregation pipeline.
## Options
* `:allow_disk_use` - Enables writing to temporary files (Default: false)
* `:max_time` - Specifies a time limit in milliseconds
* `:use_cursor` - Use a cursor for a batched response (Default: true)
"""
@spec aggregate(Pool.t, collection, [BSON.document], Keyword.t) :: cursor
def aggregate(pool, coll, pipeline, opts \\ []) do
query = [
aggregate: coll,
pipeline: pipeline,
allowDiskUse: opts[:allow_disk_use],
maxTimeMS: opts[:max_time]
] |> filter_nils
cursor? = pool.version >= 1 and Keyword.get(opts, :use_cursor, true)
opts = Keyword.drop(opts, ~w(allow_disk_use max_time use_cursor)a)
if cursor? do
query = query ++ [cursor: filter_nils(%{batchSize: opts[:batch_size]})]
aggregation_cursor(pool, "$cmd", query, nil, opts)
else
singly_cursor(pool, "$cmd", query, nil, opts)
end
end
@doc """
Returns the count of documents that would match a `find/4` query.
## Options
* `:limit` - Maximum number of documents to fetch with the cursor
* `:skip` - Number of documents to skip before returning the first
* `:hint` - Hint which index to use for the query
"""
@spec count(Pool.t, collection, BSON.document, Keyword.t) :: result(non_neg_integer)
def count(pool, coll, filter, opts \\ []) do
query = [
count: coll,
query: filter,
limit: opts[:limit],
skip: opts[:skip],
hint: opts[:hint]
] |> filter_nils
opts = Keyword.drop(opts, ~w(limit skip hint)a)
# Mongo 2.4 and 2.6 returns a float
run_command(pool, query, opts)
|> map_result(&(trunc(&1["n"])))
end
@doc """
Similar to `count/4` but unwraps the result and raises on error.
"""
@spec count!(Pool.t, collection, BSON.document, Keyword.t) :: result!(non_neg_integer)
def count!(pool, coll, filter, opts \\ []) do
bangify(count(pool, coll, filter, opts))
end
@doc """
Finds the distinct values for a specified field across a collection.
## Options
* `:max_time` - Specifies a time limit in milliseconds
"""
@spec distinct(Pool.t, collection, String.t | atom, BSON.document, Keyword.t) :: result([BSON.t])
def distinct(pool, coll, field, filter, opts \\ []) do
query = [
distinct: coll,
key: field,
query: filter,
maxTimeMS: opts[:max_time]
] |> filter_nils
opts = Keyword.drop(opts, ~w(max_time))
run_command(pool, query, opts)
|> map_result(&(&1["values"]))
end
@doc """
Similar to `distinct/5` but unwraps the result and raises on error.
"""
@spec distinct!(Pool.t, collection, String.t | atom, BSON.document, Keyword.t) :: result!([BSON.t])
def distinct!(pool, coll, field, filter, opts \\ []) do
bangify(distinct(pool, coll, field, filter, opts))
end
@doc """
Selects documents in a collection and returns a cursor for the selected
documents.
## Options
* `:comment` - Associates a comment to a query
* `:cursor_type` - Set to :tailable or :tailable_await to return a tailable
cursor
* `:max_time` - Specifies a time limit in milliseconds
* `:modifiers` - Meta-operators modifying the output or behavior of a query,
see http://docs.mongodb.org/manual/reference/operator/query-modifier/
* `:cursor_timeout` - Set to false if cursor should not close after 10
minutes (Default: true)
* `:order_by` - Sorts the results of a query in ascending or descending order
* `:projection` - Limits the fields to return for all matching document
* `:skip` - The number of documents to skip before returning (Default: 0)
"""
@spec find(Pool.t, collection, BSON.document, Keyword.t) :: cursor
def find(pool, coll, filter, opts \\ []) do
query = [
{"$comment", opts[:comment]},
{"$maxTimeMS", opts[:max_time]},
{"$orderby", opts[:sort]}
] ++ Enum.into(opts[:modifiers] || [], [])
query = filter_nils(query)
query =
if query == [] do
filter
else
filter = normalize_doc(filter)
filter = if List.keymember?(filter, "$query", 0), do: filter, else: [{"$query", filter}]
filter ++ query
end
select = opts[:projection]
opts = if Keyword.get(opts, :cursor_timeout, true), do: opts, else: [{:no_cursor_timeout, true}|opts]
drop = ~w(comment max_time modifiers sort cursor_type projection cursor_timeout)a
opts = cursor_type(opts[:cursor_type]) ++ Keyword.drop(opts, drop)
cursor(pool, coll, query, select, opts)
end
@doc """
Issue a database command. If the command has parameters use a keyword
list for the document because the "command key" has to be the first
in the document.
"""
@spec run_command(Pool.t, BSON.document, Keyword.t) :: result(BSON.document)
def run_command(pool, query, opts \\ []) do
Pool.run_with_log(pool, :run_command, [query], opts, fn pid ->
case Connection.find_one(pid, "$cmd", query, [], opts) do
%{"ok" => 1.0} = doc ->
{:ok, doc}
%{"ok" => 0.0, "errmsg" => reason} = error ->
{:error, %Mongo.Error{message: "run_command failed: #{reason}", code: error["code"]}}
end
end)
end
@doc """
Similar to `run_command/3` but unwraps the result and raises on error.
"""
@spec run_command!(Pool.t, BSON.document, Keyword.t) :: result!(BSON.document)
def run_command!(pool, query, opts \\ []) do
bangify(run_command(pool, query, opts))
end
@doc """
Insert a single document into the collection.
If the document is missing the `_id` field or it is `nil`, an ObjectId
will be generated, inserted into the document, and returned in the result struct.
"""
@spec insert_one(Pool.t, collection, BSON.document, Keyword.t) :: result(Mongo.InsertOneResult.t)
def insert_one(pool, coll, doc, opts \\ []) do
assert_single_doc!(doc)
Pool.run_with_log(pool, :insert_one, [coll, doc], opts, fn pid ->
Connection.insert(pid, coll, doc, opts)
end)
|> map_result(fn %WriteResult{inserted_ids: ids} ->
%Mongo.InsertOneResult{inserted_id: List.first(ids)}
end)
end
@doc """
Similar to `insert_one/4` but unwraps the result and raises on error.
"""
@spec insert_one!(Pool.t, collection, BSON.document, Keyword.t) :: result!(Mongo.InsertOneResult.t)
def insert_one!(pool, coll, doc, opts \\ []) do
bangify(insert_one(pool, coll, doc, opts))
end
@doc """
Insert multiple documents into the collection.
If any of the documents is missing the `_id` field or it is `nil`, an ObjectId
will be generated, and insertd into the document.
Ids of all documents will be returned in the result struct.
## Options
* `:continue_on_error` - even if insert fails for one of the documents
continue inserting the remaining ones (default: `false`)
"""
# TODO describe the ordered option
@spec insert_many(Pool.t, collection, [BSON.document], Keyword.t) :: result(Mongo.InsertManyResult.t)
def insert_many(pool, coll, docs, opts \\ []) do
assert_many_docs!(docs)
# NOTE: Only for 2.4
ordered? = Keyword.get(opts, :ordered, true)
dbopts = [continue_on_error: not ordered?] ++ opts
Pool.run_with_log(pool, :insert_many, [coll, docs], opts, fn pid ->
Connection.insert(pid, coll, docs, dbopts)
end)
|> map_result(fn %WriteResult{inserted_ids: ids} ->
ids = Enum.with_index(ids) |> Enum.into(%{}, fn {x, y} -> {y, x} end)
%Mongo.InsertManyResult{inserted_ids: ids}
end)
end
@doc """
Similar to `insert_many/4` but unwraps the result and raises on error.
"""
@spec insert_many!(Pool.t, collection, [BSON.document], Keyword.t) :: result!(Mongo.InsertManyResult.t)
def insert_many!(pool, coll, docs, opts \\ []) do
bangify(insert_many(pool, coll, docs, opts))
end
@doc """
Remove a document matching the filter from the collection.
"""
@spec delete_one(Pool.t, collection, BSON.document, Keyword.t) :: result(Mongo.DeleteResult.t)
def delete_one(pool, coll, filter, opts \\ []) do
dbopts = [multi: false] ++ opts
Pool.run_with_log(pool, :delete_one, [coll, filter], opts, fn pid ->
Connection.remove(pid, coll, filter, dbopts)
end)
|> map_result(fn %WriteResult{num_matched: n, num_removed: n} ->
%Mongo.DeleteResult{deleted_count: n}
end)
end
@doc """
Similar to `delete_one/4` but unwraps the result and raises on error.
"""
@spec delete_one!(Pool.t, collection, BSON.document, Keyword.t) :: result!(Mongo.DeleteResult.t)
def delete_one!(pool, coll, filter, opts \\ []) do
bangify(delete_one(pool, coll, filter, opts))
end
@doc """
Remove all documents matching the filter from the collection.
"""
@spec delete_many(Pool.t, collection, BSON.document, Keyword.t) :: result(Mongo.DeleteResult.t)
def delete_many(pool, coll, filter, opts \\ []) do
dbopts = [multi: true] ++ opts
Pool.run_with_log(pool, :delete_many, [coll, filter], opts, fn pid ->
Connection.remove(pid, coll, filter, dbopts)
end)
|> map_result(fn %WriteResult{num_matched: n, num_removed: n} ->
%Mongo.DeleteResult{deleted_count: n}
end)
end
@doc """
Similar to `delete_many/4` but unwraps the result and raises on error.
"""
@spec delete_many!(Pool.t, collection, BSON.document, Keyword.t) :: result!(Mongo.DeleteResult.t)
def delete_many!(pool, coll, filter, opts \\ []) do
bangify(delete_many(pool, coll, filter, opts))
end
@doc """
Replace a single document matching the filter with the new document.
## Options
* `:upsert` - if set to `true` creates a new document when no document
matches the filter (default: `false`)
"""
@spec replace_one(Pool.t, collection, BSON.document, BSON.document, Keyword.t) :: result(Mongo.UpdateResult.t)
def replace_one(pool, coll, filter, replacement, opts \\ []) do
modifier_docs(replacement, :replace)
dbopts = [multi: false] ++ opts
Pool.run_with_log(pool, :replace_one, [coll, filter, replacement], opts, fn pid ->
Connection.update(pid, coll, filter, replacement, dbopts)
end)
|> map_result(fn %WriteResult{num_matched: matched, num_modified: modified, upserted_id: id} ->
%Mongo.UpdateResult{matched_count: matched, modified_count: modified, upserted_id: id}
end)
end
@doc """
Similar to `replace_one/5` but unwraps the result and raises on error.
"""
@spec replace_one!(Pool.t, collection, BSON.document, BSON.document, Keyword.t) :: result!(Mongo.UpdateResult.t)
def replace_one!(pool, coll, filter, replacement, opts \\ []) do
bangify(replace_one(pool, coll, filter, replacement, opts))
end
@doc """
Update a single document matching the filter.
Uses MongoDB update operators to specify the updates. For more information
please refer to the
[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/update/)
Example:
Mongo.update_one(MongoPool,
"my_test_collection",
%{"filter_field": "filter_value"},
%{"$set": %{"modified_field": "new_value"}})
## Options
* `:upsert` - if set to `true` creates a new document when no document
matches the filter (default: `false`)
"""
@spec update_one(Pool.t, collection, BSON.document, BSON.document, Keyword.t) :: result(Mongo.UpdateResult.t)
def update_one(pool, coll, filter, update, opts \\ []) do
modifier_docs(update, :update)
dbopts = [multi: false] ++ opts
Pool.run_with_log(pool, :update_one, [coll, filter, update], opts, fn pid ->
Connection.update(pid, coll, filter, update, dbopts)
end)
|> map_result(fn %WriteResult{num_matched: matched, num_modified: modified, upserted_id: id} ->
%Mongo.UpdateResult{matched_count: matched, modified_count: modified, upserted_id: id}
end)
end
@doc """
Similar to `update_one/5` but unwraps the result and raises on error.
"""
@spec update_one!(Pool.t, collection, BSON.document, BSON.document, Keyword.t) :: result!(Mongo.UpdateResult.t)
def update_one!(pool, coll, filter, update, opts \\ []) do
bangify(update_one(pool, coll, filter, update, opts))
end
@doc """
Update all documents matching the filter.
Uses MongoDB update operators to specify the updates. For more information
please refer to the
[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/update/)
## Options
* `:upsert` - if set to `true` creates a new document when no document
matches the filter (default: `false`)
"""
@spec update_many(Pool.t, collection, BSON.document, BSON.document, Keyword.t) :: result(Mongo.UpdateResult.t)
def update_many(pool, coll, filter, update, opts \\ []) do
modifier_docs(update, :update)
dbopts = [multi: true] ++ opts
Pool.run_with_log(pool, :update_many, [coll, filter, update], opts, fn pid ->
Connection.update(pid, coll, filter, update, dbopts)
end)
|> map_result(fn %WriteResult{num_matched: matched, num_modified: modified, upserted_id: id} ->
%Mongo.UpdateResult{matched_count: matched, modified_count: modified, upserted_id: id}
end)
end
@doc """
Similar to `update_many/5` but unwraps the result and raises on error.
"""
@spec update_many!(Pool.t, collection, BSON.document, BSON.document, Keyword.t) :: result!(Mongo.UpdateResult.t)
def update_many!(pool, coll, filter, update, opts \\ []) do
bangify(update_many(pool, coll, filter, update, opts))
end
@doc """
Updates an existing document or inserts a new one.
If the document does not contain the `_id` field, then the `insert_one/3`
function is used to persist the document, otherwise `replace_one/5` is used,
where the filter is the `_id` field, and the `:upsert` option is set to `true`.
"""
@spec save_one(Pool.t, collection, BSON.document, Keyword.t) :: result(Mongo.SaveOneResult.t)
def save_one(pool, coll, doc, opts \\ []) do
case get_id(doc) do
{:ok, id} ->
opts = [upsert: true] ++ opts
replace_one(pool, coll, %{_id: id}, doc, opts)
|> map_result(fn result ->
%Mongo.SaveOneResult{
matched_count: result.matched_count,
modified_count: result.modified_count,
upserted_id: result.upserted_id}
end)
:error ->
insert_one(pool, coll, doc, opts)
|> map_result(fn result ->
%Mongo.SaveOneResult{
matched_count: 0,
modified_count: 0,
upserted_id: result.inserted_id}
end)
end
end
@doc """
Similar to `save_one/4` but unwraps the result and raises on error.
"""
@spec save_one!(Pool.t, collection, BSON.document, Keyword.t) :: result!(Mongo.SaveOneResult.t)
def save_one!(pool, coll, doc, opts \\ []) do
bangify(save_one(pool, coll, doc, opts))
end
@doc """
Updates documents or inserts them.
For the documents that does not contain the `_id` field, `insert_many/3`
function is used to persist them, for those that do contain the `_id` field,
the `replace_one/5` function is invoked for each document separately, where
the filter is the `_id` field, and the `:upsert` option is set to `true`.
## Options
* `:ordered` - if set to `false` will group all documents to be inserted
together, otherwise it will preserve the order, but it may be slow
for large number of documents (default: `false`)
"""
@spec save_many!(Pool.t, collection, BSON.document, Keyword.t) :: result!(Mongo.SaveManyResult.t)
def save_many!(pool, coll, docs, opts \\ []) do
assert_many_docs!(docs)
# NOTE: Only for 2.4
ordered? = Keyword.get(opts, :ordered, true)
opts = [continue_on_error: not ordered?, upsert: true] ++ opts
docs = docs_id_ix(docs)
if ordered? do
# Ugh, horribly inefficient
save_ordered(pool, coll, docs, opts)
else
save_unordered(pool, coll, docs, opts)
end
end
defp save_ordered(pool, coll, docs, opts) do
chunked_docs = Enum.chunk_by(docs, fn {_, id, _} -> id == :error end)
result = %Mongo.SaveManyResult{matched_count: 0, modified_count: 0, upserted_ids: %{}}
Enum.reduce(chunked_docs, result, fn docs, result ->
{ix, id, _doc} = hd(docs)
if id == :error do
save_insert(result, ix, pool, coll, docs, opts)
else
save_replace(result, ix, pool, coll, docs, opts)
end
end)
end
defp save_unordered(pool, coll, docs, opts) do
docs = Enum.group_by(docs, fn {_, id, _} -> id == :error end)
insert_docs = docs[true] || []
replace_docs = docs[false] || []
%Mongo.SaveManyResult{matched_count: 0, modified_count: 0, upserted_ids: %{}}
|> save_insert(0, pool, coll, insert_docs, opts)
|> save_replace(length(insert_docs), pool, coll, replace_docs, opts)
end
defp save_insert(result, _ix, _pool, _coll, [], _opts) do
result
end
defp save_insert(result, ix, pool, coll, docs, opts) do
docs = Enum.map(docs, &elem(&1, 2))
case insert_many(pool, coll, docs, opts) do
:ok ->
nil
{:ok, insert} ->
ids = list_ix(insert.inserted_ids, ix)
|> Enum.into(result.upserted_ids)
%{result | upserted_ids: ids}
{:error, error} ->
raise error
end
end
defp save_replace(result, ix, pool, coll, docs, opts) do
Enum.reduce(docs, {ix, result}, fn {_ix, {:ok, id}, doc}, {ix, result} ->
case replace_one(pool, coll, %{_id: id}, doc, opts) do
:ok ->
{0, nil}
{:ok, replace} ->
ids =
if replace.upserted_id do
Map.put(result.upserted_ids, ix, replace.upserted_id)
|> Enum.into(result.upserted_ids)
else
result.upserted_ids
end
result =
%{result | matched_count: result.matched_count + replace.matched_count,
modified_count: result.modified_count + replace.modified_count,
upserted_ids: ids}
{ix+1, result}
{:error, error} ->
raise error
end
end)
|> elem(1)
end
defp list_ix(enum, offset) do
Enum.map(enum, fn {ix, elem} ->
{ix+offset, elem}
end)
end
defp map_result(:ok, _fun), do: :ok
defp map_result({:ok, value}, fun), do: {:ok, fun.(value)}
defp map_result({:error, _} = error, _fun), do: error
defp docs_id_ix(docs) do
Enum.reduce(docs, {0, []}, fn doc, {ix, docs} ->
{ix+1, [{ix, get_id(doc), doc} | docs]}
end)
|> elem(1)
|> Enum.reverse
end
defp modifier_docs([{key, _}|_], type),
do: key |> key_to_string |> modifier_key(type)
defp modifier_docs(map, _type) when is_map(map) and map_size(map) == 0,
do: :ok
defp modifier_docs(map, type) when is_map(map),
do: Enum.at(map, 0) |> elem(0) |> key_to_string |> modifier_key(type)
defp modifier_docs(list, type) when is_list(list),
do: Enum.map(list, &modifier_docs(&1, type))
defp modifier_key(<<?$, _::binary>>, :replace),
do: raise(ArgumentError, "replace does not allow atomic modifiers")
defp modifier_key(<<?$, _::binary>>, :update),
do: :ok
defp modifier_key(<<_, _::binary>>, :update),
do: raise(ArgumentError, "update only allows atomic modifiers")
defp modifier_key(_, _),
do: :ok
defp key_to_string(key) when is_atom(key),
do: Atom.to_string(key)
defp key_to_string(key) when is_binary(key),
do: key
defp cursor(pool, coll, query, select, opts) do
%Mongo.Cursor{
pool: pool,
coll: coll,
query: query,
select: select,
opts: opts}
end
defp singly_cursor(pool, coll, query, select, opts) do
%Mongo.SinglyCursor{
pool: pool,
coll: coll,
query: query,
select: select,
opts: opts}
end
defp aggregation_cursor(pool, coll, query, select, opts) do
%Mongo.AggregationCursor{
pool: pool,
coll: coll,
query: query,
select: select,
opts: opts}
end
defp filter_nils(keyword) when is_list(keyword) do
Enum.reject(keyword, fn {_key, value} -> is_nil(value) end)
end
defp filter_nils(map) when is_map(map) do
Enum.reject(map, fn {_key, value} -> is_nil(value) end)
|> Enum.into(%{})
end
defp normalize_doc(doc) do
Enum.reduce(doc, {:unknown, []}, fn
{key, _value}, {:binary, _acc} when is_atom(key) ->
invalid_doc(doc)
{key, _value}, {:atom, _acc} when is_binary(key) ->
invalid_doc(doc)
{key, value}, {_, acc} when is_atom(key) ->
{:atom, [{key, value}|acc]}
{key, value}, {_, acc} when is_binary(key) ->
{:binary, [{key, value}|acc]}
end)
|> elem(1)
|> Enum.reverse
end
defp invalid_doc(doc) do
message = "invalid document containing atom and string keys: #{inspect doc}"
raise ArgumentError, message
end
defp cursor_type(nil),
do: []
defp cursor_type(:tailable),
do: [tailable_cursor: true]
defp cursor_type(:tailable_await),
do: [tailable_cursor: true, await_data: true]
defp get_id(doc) do
case fetch_value(doc, "_id") do
{:ok, id} -> {:ok, id}
:error -> fetch_value(doc, :_id)
end
end
defp fetch_value(doc, key) do
case Dict.fetch(doc, key) do
{:ok, nil} -> :error
{:ok, id} -> {:ok, id}
:error -> :error
end
end
defp assert_single_doc!(doc) when is_map(doc), do: :ok
defp assert_single_doc!([]), do: :ok
defp assert_single_doc!([{_, _} | _]), do: :ok
defp assert_single_doc!(other) do
raise ArgumentError, "expected single document, got: #{inspect other}"
end
defp assert_many_docs!([first | _]) when not is_tuple(first), do: :ok
defp assert_many_docs!(other) do
raise ArgumentError, "expected list of documents, got: #{inspect other}"
end
end
|
lib/mongo.ex
| 0.911108 | 0.664935 |
mongo.ex
|
starcoder
|
defmodule Softmax.Distributed do
@master_rank 0
@world_size 6
def start(rank, list) do
name = String.to_atom("node_#{inspect(rank)}")
Process.register(self(), name)
send({:orchestrator, node()}, {:alive, rank})
wait_for_nodes()
node_normalization(list, rank)
end
def wait_for_nodes() do
receive do
:ok -> :ok
end
end
def node_normalization(list, rank) do
receive do
{:compute, level, report_to} ->
norm = compute_normalization(list, level, rank)
send(report_to, {:result, rank, norm})
end
node_softmax(list, rank)
end
def compute_normalization(list, level, rank) do
next_level = Integer.floor_div(level, 2)
case level > 1 do
true ->
case rank == @world_size - 1 do
false ->
next_rank = rank + next_level
name = String.to_atom("node_#{inspect(next_rank)}")
send(
{name, node()},
{:compute, next_level, self()}
)
norm = compute_normalization(list, next_level, rank)
case next_rank >= @world_size do
false ->
receive do
{:result, _, next_norm} ->
Softmax.Parallel.merge(norm, next_norm)
end
true -> norm
end
_ ->
Softmax.Parallel.normalize(list)
end
false ->
Softmax.Parallel.normalize(list)
end
end
def node_softmax(list, @master_rank) do
receive do
{:result, _, norm} ->
node_ranks = 1..(@world_size - 1)
pairs = Enum.map(node_ranks, fn _ -> nil end)
empty_map = Enum.into(Enum.zip(node_ranks, pairs), %{})
pending = Enum.into(node_ranks, MapSet.new())
for n <- node_ranks,
do: send({String.to_atom("node_#{inspect(n)}"), node()}, {:norm, norm, self()})
{mv, dv} = norm
values = Softmax.Parallel.rescale(list, mv, dv)
pairs = Map.put(empty_map, 0, values)
result = gather_list(pairs, pending)
send({:orchestrator, node()}, {:result, result})
end
end
def node_softmax(list, rank) do
receive do
{:norm, {mv, dv}, master} ->
values = Softmax.Parallel.rescale(list, mv, dv)
send(master, {:values, rank, values})
end
end
def gather_list(chunk_map, pending) do
case MapSet.size(pending) > 0 do
true ->
receive do
{:values, rank, values} ->
chunk_map = Map.put(chunk_map, rank, values)
pending = MapSet.delete(pending, rank)
gather_list(chunk_map, pending)
end
false ->
chunk_map
|> Map.values()
|> Enum.flat_map(fn x -> x end)
end
end
def are_ranks_ready(node_set) do
case MapSet.size(node_set) > 0 do
true ->
receive do
{:alive, rank} ->
node_set = MapSet.delete(node_set, rank)
are_ranks_ready(node_set)
end
false -> :ok
end
end
def softmax(x) do
Process.register(self(), :orchestrator)
chunk_size = Integer.floor_div(length(x), @world_size)
chunks = Enum.chunk_every(x, chunk_size)
idx = 0..length(chunks)-1
chunk_map = Enum.into(Enum.zip(idx, chunks), %{})
chunks = case Map.size(chunk_map) == @world_size do
true -> Map.values(chunk_map)
false ->
rem = Enum.flat_map(@world_size..Map.size(chunk_map)-1,
fn n -> Map.get(chunk_map, n) end)
{_, chunk_map} = Map.get_and_update(
chunk_map, @world_size-1, fn value -> {value, Enum.concat(value, rem)} end)
Map.values(chunk_map)
end
level = :math.pow(2, :math.ceil(:math.log(@world_size)/:math.log(2)))
|> round
ranks = 0..(@world_size-1)
pids = Enum.map(Enum.zip(ranks, chunks),
fn {rank, list} -> spawn_link(__MODULE__, :start, [rank, list]) end)
:ok = are_ranks_ready(MapSet.new(ranks))
for pid <- pids, do: send(pid, :ok)
send({:node_0, node()}, {:compute, level, {:node_0, node()}})
result = receive do
{:result, result} -> result
end
Process.unregister(:orchestrator)
result
end
end
|
lib/distributed_softmax.ex
| 0.532911 | 0.491639 |
distributed_softmax.ex
|
starcoder
|
defmodule McamServerWeb.CameraLiveHelper do
@moduledoc """
Helper functions for `McamServerWeb.CameraLive`
"""
import Phoenix.LiveView.Utils, only: [assign: 3]
alias McamServer.{Accounts, Cameras, Cameras.Camera, Subscriptions}
alias Phoenix.LiveView.Socket
@doc """
Extract the camera from the list of `:all_cameras` assigned in the socket, using the "camera_id"
(String key) set in the params. If there is no camera id in the params, or it is not found,
returns the first camera.
`:no_camera` is returned if the `:all_cameras` list is empty.
"""
@spec selected_camera(map(), Socket.t()) :: Camera.t() | :no_camera
def selected_camera(%{"camera_id" => camera_id}, socket) when is_binary(camera_id) do
selected_camera(%{"camera_id" => String.to_integer(camera_id)}, socket)
end
def selected_camera(params, %{assigns: %{all_cameras: own_cameras}}) do
case do_selected_camera(params, own_cameras) do
nil -> :no_camera
camera -> camera
end
end
defp do_selected_camera(_, []), do: nil
defp do_selected_camera(%{"camera_id" => camera_id}, [default | _] = cameras) do
Enum.find(cameras, default, fn %{id: id} -> id == camera_id end)
end
defp do_selected_camera(_, [first | _]), do: first
@doc """
Similar to `selected_camera/2`, except that the list of guest cameras assgigned (`:guest_cameras` key) to
the socket is used instead of `:all_cameras`.
If the id is invalid then `:no_camera` is returned - not the first guest camera.
"""
@spec selected_guest_camera(map(), Socket.t()) :: Camera.t() | :no_camera
def selected_guest_camera(%{"camera_id" => camera_id}, socket) when is_binary(camera_id) do
selected_guest_camera(%{"camera_id" => String.to_integer(camera_id)}, socket)
rescue
ArgumentError ->
:no_camera
end
def selected_guest_camera(%{"camera_id" => camera_id}, %{
assigns: %{guest_cameras: guest_cameras}
}) do
Enum.find(guest_cameras, :no_camera, fn %{id: id} -> id == camera_id end)
end
def selected_guest_camera(_, _), do: :no_camera
@doc """
Handles a camera update, using the socket assigns to retur a tuple containing
* first element - the assigned `:camera`. This is replaced with the update if the id matches, reflecting the update.
* second element - the last of `:all_cameras`, replacing one with the update if it the id maatches
* third element - the list of `:guest_cameras`, replacing one with the update if the id matches
"""
@spec update_camera(Camera.t(), Socket.t()) :: {Camera.t(), list(Camera.t()), list(Camera.t())}
def update_camera(
%{id: updated_id} = updated_camera,
%{assigns: %{camera: camera, all_cameras: all_cameras, guest_cameras: guest_cameras}}
) do
camera =
case camera do
%{id: ^updated_id} -> updated_camera
_ -> camera
end
all_cameras = do_update_camera(updated_camera, [], all_cameras)
guest_cameras = do_update_camera(updated_camera, [], guest_cameras)
{camera, all_cameras, guest_cameras}
end
defp do_update_camera(%{id: id} = updated, acc, [%{id: id} | rest]) do
Enum.reverse([updated | acc], rest)
end
defp do_update_camera(updated, acc, [camera | rest]) do
do_update_camera(updated, [camera | acc], rest)
end
defp do_update_camera(_, acc, []), do: Enum.reverse(acc)
@doc """
Very basic email validation, checking presence of a some characters then `a` then taking
some liberties and requiring at least a domain and a tld.
"""
@spec basic_email_validate(String.t()) :: :bad_email | :ok
def basic_email_validate(alleged_email) do
if alleged_email =~ ~r/.+@.+\..+/, do: :ok, else: :bad_email
end
@doc """
The common parts of a LiveView mount for a camera:
* Gets the user using the session token
* Gets all the user's cameras
* Gets all the guest cameras for the user
* Subscribes to new camera registrations, so that
* Subscribes to name change updates for all the above cameras
* Assigns `:user`, `:all_cmeras`, and `:guest_cameras`
"""
@spec mount_camera(map(), map(), Phoenix.LiveView.Socket.t()) ::
{:ok, Phoenix.LiveView.Socket.t()}
def mount_camera(_params, %{"user_token" => user_token}, socket) do
user = Accounts.get_user_by_session_token(user_token)
all_cameras = Cameras.user_cameras(user)
guest_cameras = Cameras.guest_cameras(user)
{subscription_plan, camera_quota} = Subscriptions.camera_quota(user)
Cameras.subscribe_to_registrations(user)
for cam <- all_cameras ++ guest_cameras, do: Cameras.subscribe_to_name_change(cam)
{:ok,
socket
|> assign(:user, user)
|> assign(:camera_quota, camera_quota)
|> assign(:subscription_plan, subscription_plan)
|> assign(:all_cameras, all_cameras)
|> assign(:all_camera_count, length(all_cameras))
|> assign(:guest_cameras, guest_cameras)}
end
def local_network_url(%{board_id: board_id}), do: local_network_url(board_id)
def local_network_url(board_id) do
board_id
|> String.slice(-4..-1)
|> prepend("nerves-")
|> Common.hostname_to_nerves_local_url()
end
defp prepend(str, pre), do: pre <> str
end
|
apps/mcam_server_web/lib/mcam_server_web/live/camera/camera_live_helper.ex
| 0.858467 | 0.517327 |
camera_live_helper.ex
|
starcoder
|
defmodule Speedtest.Result do
import Speedtest.Decoder
alias Speedtest.Result
@default_key "<KEY>"
@moduledoc """
A speedtest result.
"""
defstruct download: nil,
upload: nil,
ping: nil,
server: nil,
client: nil,
timestamp: nil,
bytes_received: 0,
bytes_sent: 0,
share: nil
@doc """
Create a result from a speedtest
"""
def create(speedtest, {upload_reply, download_reply}) do
upload_times =
Enum.map(upload_reply, fn x ->
x.elapsed_time
end)
download_times =
Enum.map(download_reply, fn x ->
x.elapsed_time
end)
download_sizes =
Enum.map(download_reply, fn x ->
to_integer(x.bytes)
end)
upload_time = Enum.sum(upload_times)
upload_sizes =
Enum.map(upload_reply, fn x ->
to_integer(x.bytes)
end)
upload_size_total_bytes = Enum.sum(upload_sizes)
upload_size_total_mb = upload_size_total_bytes / 1024 / 1024
download_time = Enum.sum(download_times)
download_size_total_bytes = Enum.sum(download_sizes)
download_size_total_mb = download_size_total_bytes / 1024 / 1024
download_size_total_mb = download_size_total_mb * 8.0
download_time_in_sec = download_time / 1_000_000
upload_time_in_sec = upload_time / 1_000_000
download = download_size_total_mb / download_time_in_sec
upload = upload_size_total_mb / upload_time_in_sec
upload_avg_sec = upload_time_in_sec / Enum.count(upload_reply)
upload_avg_sec = upload_avg_sec * Enum.count(upload_reply)
upload_avg_sec = upload_size_total_mb / upload_avg_sec
download_avg_sec = download_time_in_sec / Enum.count(download_reply)
download_avg_sec = download_avg_sec * Enum.count(download_reply)
download_avg_sec = download_size_total_mb / download_avg_sec
client = %{speedtest.config.client | ispdlavg: download_avg_sec}
client = %{client | ispulavg: upload_avg_sec}
result = %Result{
download: download,
upload: upload,
ping: speedtest.selected_server.ping,
server: speedtest.selected_server,
client: client,
timestamp: DateTime.utc_now(),
bytes_received: download_size_total_bytes,
bytes_sent: upload_size_total_bytes,
share: nil
}
reply = %{speedtest | result: result}
{:ok, reply}
end
@doc """
Share the results with speedtest.net
"""
def share(%Result{} = result) do
config_key = Application.get_env(:speedtest, :key)
key =
case config_key do
nil ->
@default_key
_ ->
config_key
end
{_, _, ping} = result.ping
hash =
:crypto.hash(
:md5,
to_string(ping) <>
"-" <> to_string(result.upload) <> "-" <> to_string(result.download) <> "-" <> key
)
|> Base.encode16()
download = round(result.download / 1000.0)
ping = round(ping)
upload = round(result.upload / 1000.0)
api_data = [
"recommendedserverid=" <> to_string(result.server.id),
"ping=" <> to_string(ping),
"screenresolution=",
"promo=",
"download=" <> to_string(download),
"screendpi=",
"upload=" <> to_string(upload),
"testmethod=http",
"hash=" <> hash,
"touchscreen=none",
"startmode=pingselect",
"accuracy=1",
"bytesreceived=" <> to_string(result.bytes_received),
"bytessent=" <> to_string(result.bytes_sent),
"serverid=" <> to_string(result.server.id)
]
url = "https://www.speedtest.net/api/api.php"
headers = [{"Referer", "http://c.speedtest.net/flash/speedtest.swf"}]
body = Enum.join(api_data, "&")
{_, response} = HTTPoison.post(url, body, headers)
res = Regex.run(~r{resultid=(.)}, response.body)
image = List.last(res)
share = "http://www.speedtest.net/result/" <> image <> ".png"
%{result | share: share}
end
end
|
lib/result.ex
| 0.68742 | 0.448185 |
result.ex
|
starcoder
|
defmodule Terminus.Bitsocket do
@moduledoc """
Module for interfacing with the [Bitsocket](https://bitsocket.network) API.
Bitsocket sends you realtime events from the Bitcoin blockchain. It uses
[Server Sent Events](https://en.wikipedia.org/wiki/Server-sent_events) to
stream new **unconfirmed** transactions as soon as they appear on the Bitcoin
network.
> Bitsocket is like Websocket, but for Bitcoin. With just a single Bitsocket
> connection, you get access to a live, filterable stream of all transaction
> events across the entire bitcoin peer network.
## Schema
Realtime transactions have a similar schema to Bitbus documents. However, as
these are unconfirmed transactions, they have no `blk` infomation and provide
a `timestamp` attribute reflecting when Bitsocket first saw the transaction.
%{
"_id" => "...", # Bitbus document ID
"in" => [...], # List of inputs
"lock" => int, # Lock time
"out" => [...], # List of outputs
"timestamp" => int, # Timestamp of when tx seen
"tx" => %{
"h" => "..." # Transaction hash
}
}
Terminus supports both of the Bitsocket public enpoints. The endpoint can be
selected by passing the `:host` option to any API method.
The available endpoints are:
* `:txo` - Query and return transactions in the [Transaction Object](https://bitquery.planaria.network/#/?id=txo) schema. Default.
* `:bob` - Query and return transactions in the [Bitcoin OP_RETURN Bytecode](https://bitquery.planaria.network/#/?id=bob) schema.
```
iex> Terminus.Bitsocket.listen(query, host: :bob)
```
## Usage
Subscribe to realtime Bitcoin transactions using `listen/3` and stream the
results into your own data processing pipeline.
iex> Terminus.Bitsocket.listen!(query)
...> |> Stream.map(&Terminus.BitFS.scan_tx/1)
...> |> Stream.each(&save_to_db/1)
...> |> Stream.run
:ok
Bitsocket also provides an API for querying and crawling the transaction event
database which indexes all transactions in the previous 24 hours. Both `crawl/3`
and `fetch/2` can be used to query these events.
iex> Terminus.Bitsocket.fetch(%{
...> find: %{
...> "out.s2" => "1LtyME6b5AnMopQrBPLk4FGN8UBuhxKqrn",
...> "timestamp" => %{"$gt": :os.system_time(:millisecond) - 60000}
...> },
...> sort: %{ "timestamp": -1 }
...> }, token: token)
{:ok, [
%{
"tx" => %{"h" => "fca7bdd7658613418c54872212811cf4c5b4f8ee16864eaf70cb1393fb0df6ca"},
...
},
...
]}
"""
use Terminus.HTTPStream,
hosts: [
txo: "https://txo.bitsocket.network",
bob: "https://bob.bitsocket.network"
],
headers: [
{"cache-control", "no-cache"}
]
@doc """
Crawls the Bitsocket event database for transactions using the given query and
returns a stream.
Returns the result in an `:ok` / `:error` tuple pair.
All requests must provide a valid [Planaria token](https://token.planaria.network).
By default a streaming `t:Enumerable.t/0` is returned. Optionally a linked
GenStage [`pid`](`t:pid/0`) can be returned for using in combination with your
own GenStage consumer.
If a [`callback`](`t:Terminus.callback/0`) is provided, the stream is
automatically run and the callback is called on each transaction.
## Options
The accepted options are:
* `token` - Planaria authentication token. **Required**.
* `host` - The Bitsocket host. Defaults to `txo.bitsocket.network`.
* `stage` - Return a linked GenStage [`pid`](`t:pid/0`). Defaults to `false`.
## Examples
Queries should be in the form of any valid [Bitquery](https://bitquery.planaria.network/).
query = %{
find: %{ "out.s2" => "1LtyME6b5AnMopQrBPLk4FGN8UBuhxKqrn" }
}
By default `Terminus.Bitsocket.crawl/2` returns a streaming `t:Enumerable.t/0`.
iex> Terminus.Bitsocket.crawl(query, token: token)
{:ok, %Stream{}}
Optionally the [`pid`](`t:pid/0`) of the GenStage producer can be returned.
iex> Terminus.Bitsocket.crawl(query, token: token, stage: true)
{:ok, #PID<>}
If a [`callback`](`t:Terminus.callback/0`) is provided, the function
returns `:ok` and the callback is called on each transaction.
iex> Terminus.Bitsocket.crawl(query, [token: token], fn tx ->
...> IO.inspect tx
...> end)
:ok
"""
@spec crawl(Terminus.bitquery, keyword, Terminus.callback) ::
{:ok, Enumerable.t | pid} | :ok |
{:error, Exception.t}
def crawl(query, options \\ [], ondata \\ nil)
def crawl(query, options, nil) when is_function(options),
do: crawl(query, [], options)
def crawl(%{} = query, options, ondata),
do: query |> normalize_query |> Jason.encode! |> crawl(options, ondata)
def crawl(query, options, ondata) when is_binary(query) do
options = options
|> Keyword.take([:token, :host, :stage])
|> Keyword.put(:headers, [{"content-type", "application/json"}])
|> Keyword.put(:body, query)
|> Keyword.put(:decoder, :ndjson)
case request(:stream, "POST", "/crawl", options) do
{:ok, pid} when is_pid(pid) ->
{:ok, pid}
{:ok, stream} ->
handle_callback(stream, ondata)
{:error, error} ->
{:error, error}
end
end
@doc """
As `crawl/3` but returns the result or raises an exception if it fails.
"""
@spec crawl!(Terminus.bitquery, keyword, Terminus.callback) ::
Enumerable.t | pid | :ok
def crawl!(query, options \\ [], ondata \\ nil) do
case crawl(query, options, ondata) do
:ok -> :ok
{:ok, stream} ->
stream
{:error, error} ->
raise error
end
end
@doc """
Crawls the Bitsocket event database for transactions using the given query and
returns a stream.
Returns the result in an `:ok` / `:error` tuple pair.
This function is suitable for smaller limited queries as the entire result set
is loaded in to memory an returned. For large crawls, `crawl/3` is preferred
as the results can be streamed and processed more efficiently.
## Options
The accepted options are:
* `token` - Planaria authentication token. **Required**.
* `host` - The Bitsocket host. Defaults to `txo.bitsocket.network`.
## Examples
iex> Terminus.Bitsocket.fetch(query, token: token)
[
%{
"tx" => %{"h" => "bbae7aa467cb34010c52033691f6688e00d9781b2d24620cab51827cd517afb8"},
...
},
...
]
"""
@spec fetch(Terminus.bitquery, keyword) ::
{:ok, list} |
{:error, Exception.t}
def fetch(query, options \\ [])
def fetch(%{} = query, options),
do: query |> normalize_query |> Jason.encode! |> fetch(options)
def fetch(query, options) do
options = Keyword.take(options, [:token, :host])
|> Keyword.put(:headers, [{"content-type", "application/json"}])
|> Keyword.put(:body, query)
|> Keyword.put(:decoder, :ndjson)
request(:fetch, "POST", "/crawl", options)
end
@doc """
As `fetch/2` but returns the result or raises an exception if it fails.
"""
@spec fetch!(Terminus.bitquery, keyword) :: list
def fetch!(query, options \\ []) do
case fetch(query, options) do
{:ok, data} ->
data
{:error, error} ->
raise error
end
end
@doc """
Subscribes to Bitsocket and streams realtime transaction events using the
given query.
Returns the result in an `:ok` / `:error` tuple pair.
By default a streaming `t:Enumerable.t/0` is returned. Optionally a linked
GenStage [`pid`](`t:pid/0`) can be returned for using in combination with your
own GenStage consumer.
If a [`callback`](`t:Terminus.callback/0`) is provided, the stream is
automatically run and the callback is called on each transaction.
As Bitsocket streams transactions using [Server Sent Events](https://en.wikipedia.org/wiki/Server-sent_events),
the stream will stay open (and blocking) permanently. This is best managed
inside a long-running Elixir process.
## Options
The accepted options are:
* `host` - The Bitsocket host. Defaults to `txo.bitsocket.network`.
* `stage` - Return a linked GenStage [`pid`](`t:pid/0`) instead of a stream.
* `recycle` - Number of seconds after which to recycle to a quiet Bitsocket request. Defaults to `900`.
## Examples
Queries should be in the form of any valid [Bitquery](https://bitquery.planaria.network/).
query = %{
find: %{ "out.s2" => "1LtyME6b5AnMopQrBPLk4FGN8UBuhxKqrn" }
}
By default `Terminus.Bitsocket.listen/2` returns a streaming `t:Enumerable.t/0`.
iex> Terminus.Bitsocket.listen(query, token: token)
{:ok, %Stream{}}
Optionally the [`pid`](`t:pid/0`) of the GenStage producer can be returned.
iex> Terminus.Bitsocket.listen(query, token: token, stage: true)
{:ok, #PID<>}
If a [`callback`](`t:Terminus.callback/0`) is provided, the stream returns `:ok`
and the callback is called on each transaction.
iex> Terminus.Bitsocket.listen(query, [token: token], fn tx ->
...> IO.inspect tx
...> end)
:ok
"""
@spec listen(Terminus.bitquery, keyword, Terminus.callback) ::
{:ok, Enumerable.t | pid} | :ok |
{:error, Exception.t}
def listen(query, options \\ [], ondata \\ nil)
def listen(query, options, nil) when is_function(options),
do: listen(query, [], options)
def listen(%{} = query, options, ondata),
do: query |> normalize_query |> Jason.encode! |> listen(options, ondata)
def listen(query, options, ondata) when is_binary(query) do
path = "/s/" <> Base.encode64(query)
recycle_after = Keyword.get(options, :recycle, 900)
options = options
|> Keyword.take([:token, :host, :stage])
|> Keyword.put(:headers, [{"accept", "text/event-stream"}])
|> Keyword.put(:decoder, :eventsource)
|> Keyword.put(:recycle_after, recycle_after)
case request(:stream, "GET", path, options) do
{:ok, pid} when is_pid(pid) ->
{:ok, pid}
{:ok, stream} ->
handle_callback(stream, ondata)
{:error, error} ->
{:error, error}
end
end
@doc """
As `listen/3` but returns the result or raises an exception if it fails.
"""
@spec listen!(Terminus.bitquery, keyword) :: Enumerable.t | pid | :ok
def listen!(query, options \\ []) do
case listen(query, options) do
:ok -> :ok
{:ok, stream} ->
stream
{:error, error} ->
raise error
end
end
end
|
lib/terminus/bitsocket.ex
| 0.90774 | 0.869548 |
bitsocket.ex
|
starcoder
|
defmodule Edeliver.Relup.Instructions.FinishRunningRequests do
@moduledoc """
Notify request processes that a release upgrade starts.
This upgrade instruction waits a short time until current
requests finished and notifies the remaining, that a
code upgrade will appear. If a `phoenix` version is used
which supports the upgrade notification feature, the
remaining requests that did not finish but failed durining
the upgrade will be replayed with the original request
when the code upgrade is done. This instruction should be
used in conjunction with and after the
`Edeliver.Relup.Instructions.SuspendRanchAcceptors`
instruction which avoids that new requets are accepted
during the upgrade.
To make sure that the http request connections can
be found on the node, use this instruction after the
`Edeliver.Relup.Instructions.CheckRanchConnections`
instruction which will abort the upgrade if the http
request connections accepted by ranch cannot be found
in the supervision tree.
"""
use Edeliver.Relup.RunnableInstruction
alias Edeliver.Relup.Instructions.CheckRanchAcceptors
alias Edeliver.Relup.Instructions.CheckRanchConnections
@doc """
Appends this instruction to the instructions after the
"point of no return"
but before any instruction which
loads or unloads new code, (re-)starts or stops
any running processes, or (re-)starts or stops any
application or the emulator.
"""
def insert_where, do: &append_after_point_of_no_return/2
@doc """
Returns name of the application and the timeout in ms to wait
until running requests finish.
These values taken as argument for the `run/1` function
"""
def arguments(_instructions = %Instructions{}, _config = %{name: name}) when is_atom(name) do
{name, 500}
end
def arguments(_instructions = %Instructions{}, _config = %{name: name}) when is_binary(name) do
{name |> String.to_atom, 500}
end
@doc """
This module depends on the `Edeliver.Relup.Instructions.CheckRanchAcceptors` and
the `Edeliver.Relup.Instructions.CheckRanchConnections` module
which must be loaded before this instruction for upgrades and unload after this instruction
for downgrades.
"""
@spec dependencies() :: [Edeliver.Relup.Instructions.CheckRanchAcceptors]
def dependencies do
[Edeliver.Relup.Instructions.CheckRanchAcceptors, Edeliver.Relup.Instructions.CheckRanchConnections]
end
@doc """
Waits until the list of processes terminated.
Waits up to `timeout` ms and the returns the process ids of the processes which are still running
"""
@spec bulk_wait_for_termination(processes::[pid], timeout::non_neg_integer) :: [pid::pid]
def bulk_wait_for_termination(_processes = [], _timeout), do: []
def bulk_wait_for_termination(processes, timeout) do
proc = self()
waiting_pid = Process.spawn(fn() ->
pids_and_monitor_refs = for pid <- processes do
{pid, :erlang.monitor(:process, pid)}
end
wait_fun = fn(pids_and_monitor_refs, wait_fun) ->
receive do
{:DOWN, monitor_ref, :process, pid, _reason} ->
wait_fun.(pids_and_monitor_refs -- [{pid, monitor_ref}], wait_fun)
:timeout -> send proc, {:remaining, pids_and_monitor_refs |> Enum.map(&(:erlang.element(1, &1)))}
end
end
wait_fun.(pids_and_monitor_refs, wait_fun)
end, [:link])
receive do
:all_terminated -> []
after timeout ->
send waiting_pid, :timeout
receive do
{:remaining, remaining_pids} -> remaining_pids
end
end
end
@doc """
Sends the given event to all processes representing http requests
"""
@spec notify_running_requests([pid], event::term) :: :ok
def notify_running_requests([], _event), do: :ok
def notify_running_requests([pid|remaining_requests], event) do
send pid, event
notify_running_requests(remaining_requests, event)
end
@doc """
Waits `timeout` milliseconds until current http requests finished
and notifies remaining request processes that a code upgrad is running
and new code will be loaded. This enables phoenix to rerun requests
which failed during code loading.
"""
@spec run({otp_application_name::atom, timeout::non_neg_integer}) :: :ok
def run({otp_application_name, timeout}) do
info "Waiting up to #{inspect timeout} ms until running requests finished..."
ranch_listener_sup = CheckRanchAcceptors.ranch_listener_sup(otp_application_name)
assume true = is_pid(ranch_listener_sup), "Failed to wait until requests finished. Ranch listener supervisor not found."
ranch_connections_sup = CheckRanchConnections.ranch_connections_sup(ranch_listener_sup)
assume true = is_pid(ranch_connections_sup), "Failed to wait until requests finished. Ranch connections supervisor not found."
assume true = is_list(connections = CheckRanchConnections.ranch_connections(ranch_connections_sup)), "FFailed to wait until requests finished. No connection processes found."
request_connections = case CheckRanchConnections.websocket_channel_connections(otp_application_name, connections) do
[] -> connections
websocket_connections = [_|_] -> connections -- websocket_connections
:not_detected -> connections
end
requests_count = Enum.count(request_connections)
if requests_count == 0 do
info "No requests running."
else
info "Waiting for #{inspect requests_count} requests..."
remaining_requests = bulk_wait_for_termination(request_connections, timeout)
remaining_requests_count = Enum.count(remaining_requests)
info "#{inspect requests_count-remaining_requests_count} requets finished."
if remaining_requests_count > 0 do
info "#{inspect remaining_requests_count} requests will be restarted after upgrade if they failed."
notify_running_requests(remaining_requests, :upgrade_started)
end
end
end
end
|
lib/edeliver/relup/instructions/finish_running_requests.ex
| 0.711631 | 0.414573 |
finish_running_requests.ex
|
starcoder
|
defmodule Cluster.Strategy.ErlangHosts do
@moduledoc """
This clustering strategy relies on Erlang's built-in distribution protocol by
using a `.hosts.erlang` file (as used by the `:net_adm` module).
Please see [the net_adm docs](http://erlang.org/doc/man/net_adm.html) for more details.
In short, the following is the gist of how it works:
> File `.hosts.erlang` consists of a number of host names written as Erlang terms. It is looked for in the current work
> directory, the user's home directory, and $OTP_ROOT (the root directory of Erlang/OTP), in that order.
This looks a bit like the following in practice:
```erlang
'super.eua.ericsson.se'.
'renat.eua.ericsson.se'.
'grouse.eua.ericsson.se'.
'gauffin1.eua.ericsson.se'.
```
You can have `libcluster` automatically connect nodes on startup for you by configuring
the strategy like below:
config :libcluster,
topologies: [
erlang_hosts_example: [
strategy: #{__MODULE__},
config: [timeout: 30_000]
]
]
An optional timeout can be specified in the config. This is the timeout that
will be used in the GenServer to connect the nodes. This defaults to
`:infinity` meaning that the connection process will only happen when the
worker is started. Any integer timeout will result in the connection process
being triggered. In the example above, it has been configured for 30 seconds.
"""
use GenServer
use Cluster.Strategy
alias Cluster.Strategy.State
def start_link([%State{topology: topology} = state]) do
case :net_adm.host_file() do
{:error, _} ->
Cluster.Logger.warn(topology, "couldn't find .hosts.erlang file - not joining cluster")
:ignore
file ->
new_state = %State{state | :meta => file}
GenServer.start_link(__MODULE__, [new_state])
end
end
@impl true
def init([state]) do
new_state = connect_hosts(state)
{:ok, new_state, configured_timeout(new_state)}
end
@impl true
def handle_info(:timeout, state) do
handle_info(:connect, state)
end
def handle_info(:connect, state) do
new_state = connect_hosts(state)
{:noreply, new_state, configured_timeout(new_state)}
end
defp configured_timeout(%State{config: config}) do
Keyword.get(config, :timeout, :infinity)
end
defp connect_hosts(%State{meta: hosts_file} = state) do
nodes =
hosts_file
|> Enum.map(&{:net_adm.names(&1), &1})
|> gather_node_names([])
|> List.delete(node())
Cluster.Strategy.connect_nodes(state.topology, state.connect, state.list_nodes, nodes)
state
end
defp gather_node_names([], acc), do: acc
defp gather_node_names([{{:ok, names}, host} | rest], acc) do
names = Enum.map(names, fn {name, _} -> String.to_atom("#{name}@#{host}") end)
gather_node_names(rest, names ++ acc)
end
defp gather_node_names([_ | rest], acc), do: gather_node_names(rest, acc)
end
|
lib/strategy/erlang_hosts.ex
| 0.811639 | 0.783077 |
erlang_hosts.ex
|
starcoder
|
defmodule Membrane.RTSP.Request do
@moduledoc """
This module represents a RTSP 1.0 request.
"""
@enforce_keys [:method]
defstruct @enforce_keys ++ [:path, headers: [], body: ""]
@type t :: %__MODULE__{
method: binary(),
body: binary(),
headers: Membrane.RTSP.headers(),
path: nil | binary()
}
@doc """
Attaches a header to a RTSP request struct.
```
iex> Request.with_header(%Request{method: "DESCRIBE"}, "header_name", "header_value")
%Request{method: "DESCRIBE", headers: [{"header_name","header_value"}]}
```
"""
@spec with_header(t(), binary(), binary()) :: t()
def with_header(%__MODULE__{headers: headers} = request, name, value)
when is_binary(name) and is_binary(value),
do: %__MODULE__{request | headers: [{name, value} | headers]}
@doc """
Renders the a RTSP request struct into a binary that is a valid
RTSP request string that can be transmitted via communication channel.
```
iex> uri = URI.parse("rtsp://domain.net:554/path:movie.mov")
iex> Request.stringify(%Request{method: "DESCRIBE"}, uri)
"DESCRIBE rtsp://domain.net:554/path:movie.mov RTSP/1.0\\r\\n\\r\\n"
iex> Request.stringify(%Request{method: "PLAY", path: "trackID=2"}, uri)
"PLAY rtsp://domain.net:554/path:movie.mov/trackID=2 RTSP/1.0\\r\\n\\r\\n"
```
Access credentials won't be rendered into an url present in a RTSP start line.
```
iex> uri = URI.parse("rtsp://user:[email protected]:554/path:movie.mov")
iex> Request.stringify(%Request{method: "DESCRIBE"}, uri)
"DESCRIBE rtsp://domain.net:554/path:movie.mov RTSP/1.0\\r\\n\\r\\n"
```
"""
@spec stringify(t(), URI.t()) :: binary()
def stringify(%__MODULE__{method: method, headers: headers} = request, uri) do
Enum.join([
method,
" ",
process_uri(request, uri),
" RTSP/1.0",
render_headers(headers),
"\r\n\r\n"
])
end
@doc """
Returns the encoded URI as a binary. This is handy for
digest auth since this value must be encoded as per the digest
algorithm
"""
@spec process_uri(t(), URI.t()) :: binary()
def process_uri(request, uri) do
%URI{uri | userinfo: nil}
|> to_string()
|> apply_path(request)
end
defp apply_path(url, %__MODULE__{path: nil}), do: url
defp apply_path(url, %__MODULE__{path: path}),
do: Path.join(url, path)
defp render_headers([]), do: ""
defp render_headers(list) do
list
|> Enum.map_join("\r\n", &header_to_string/1)
|> String.replace_prefix("", "\r\n")
end
defp header_to_string({header, value}), do: header <> ": " <> value
end
|
lib/membrane_rtsp/request.ex
| 0.876931 | 0.643616 |
request.ex
|
starcoder
|
defmodule BSV.Contract do
@moduledoc """
A behaviour module for implementing Bitcoin transaction contracts.
A Bitcoin transaction contains two sides: inputs and outputs.
Transaction outputs are script puzzles, called "locking scripts" (sometimes
also known as a "ScriptPubKey") which lock a number of satoshis. Transaction
inputs are contain an "unlocking script" (or the "ScriptSig") and unlock the
satoshis contained in the previous transaction's outputs.
Therefore, each locking script is unlocked by a corresponding unlocking script.
The `BSV.Contract` module provides a way to define a locking script and
unlocking script in a plain Elixir function. Because it is *just Elixir*, it
is trivial to add helper functions and macros to reduce boilerplate and create
more complex contract types and scripts.
## Defining a contract
The following module implements a Pay to Public Key Hash contract.
Implementing a contract is just a case of defining `c:locking_script/2` and
`c:unlocking_script/2`.
defmodule P2PKH do
@moduledoc "Pay to Public Key Hash contract."
use BSV.Contract
@impl true
def locking_script(ctx, %{address: address}) do
ctx
|> op_dup
|> op_hash160
|> push(address.pubkey_hash)
|> op_equalverify
|> op_checksig
end
@impl true
def unlocking_script(ctx, %{keypair: keypair}) do
ctx
|> signature(keypair.privkey)
|> push(BSV.PubKey.to_binary(keypair.pubkey))
end
end
## Locking a contract
A contract locking script is initiated by calling `lock/2` on the contract
module, passing the number of satoshis and a map of parameters expected by
`c:locking_script/2` defined in the contract.
# Initiate the contract locking script
contract = P2PKH.lock(10_000, %{address: Address.from_pubkey(bob_pubkey)})
script = Contract.to_script(contract) # returns the locking script
txout = Contract.to_txout(contract) # returns the full txout
## Unlocking a contract
To unlock and spend the contract, a `t:BSV.UTXO.t/0` is passed to `unlock/2`
with the parameters expected by `c:unlocking_script/2` defined in the contract.
# Initiate the contract unlocking script
contract = P2PKH.unlock(utxo, %{keypair: keypair})
Optionally the current transaction [`context`](`t:BSV.Contract.ctx/0`) can be
given to the [`contract`](`t:BSV.Contract.t/0`). This allows the correct
[`sighash`](`t:BSV.Sig.sighash/0`) to be calculated for any signatures.
# Pass the current transaction ctx
contract = Contract.put_ctx(contract, {tx, vin})
# returns the signed txin
txin = Contract.to_txin(contract)
## Building transactions
The `BSV.Contract` behaviour is taken advantage of in the `BSV.TxBuilder`
module, resulting in transaction building semantics that are easy to grasp and
pleasing to work with.
builder = %TxBuilder{
inputs: [
P2PKH.unlock(utxo, %{keypair: keypair})
],
outputs: [
P2PKH.lock(10_000, %{address: address})
]
}
# Returns a fully signed transaction
TxBuilder.to_tx(builder)
For more information, refer to `BSV.TxBuilder`.
"""
alias BSV.{Script, Tx, TxBuilder, TxIn, TxOut, UTXO, VM}
defstruct ctx: nil, mfa: nil, opts: [], subject: nil, script: %Script{}
@typedoc "BSV Contract struct"
@type t() :: %__MODULE__{
ctx: ctx() | nil,
mfa: {module(), atom(), list()},
opts: keyword(),
subject: non_neg_integer() | UTXO.t(),
script: Script.t()
}
@typedoc """
Transaction context.
A tuple containing a `t:BSV.Tx.t/0` and [`vin`](`t:BSV.TxIn.vin/0`). When
attached to a contract, the he correct [`sighash`](`t:BSV.Sig.sighash/0`) to
be calculated for any signatures.
"""
@type ctx() :: {Tx.t(), non_neg_integer()}
defmacro __using__(_) do
quote do
alias BSV.Contract
use Contract.Helpers
@behaviour Contract
@doc """
Returns a locking script contract with the given parameters.
"""
@spec lock(non_neg_integer(), map(), keyword()) :: Contract.t()
def lock(satoshis, %{} = params, opts \\ []) do
struct(Contract, [
mfa: {__MODULE__, :locking_script, [params]},
opts: opts,
subject: satoshis
])
end
@doc """
Returns an unlocking script contract with the given parameters.
"""
@spec unlock(UTXO.t(), map(), keyword()) :: Contract.t()
def unlock(%UTXO{} = utxo, %{} = params, opts \\ []) do
struct(Contract, [
mfa: {__MODULE__, :unlocking_script, [params]},
opts: opts,
subject: utxo
])
end
end
end
@doc """
Callback executed to generate the contract locking script.
Is passed the [`contract`](`t:BSV.Contract.t/0`) and a map of parameters. It
must return the updated [`contract`](`t:BSV.Contract.t/0`).
"""
@callback locking_script(t(), map()) :: t()
@doc """
Callback executed to generate the contract unlocking script.
Is passed the [`contract`](`t:BSV.Contract.t/0`) and a map of parameters. It
must return the updated [`contract`](`t:BSV.Contract.t/0`).
"""
@callback unlocking_script(t(), map()) :: t()
@optional_callbacks unlocking_script: 2
@doc """
Puts the given [`transaction context`](`t:BSV.Contract.ctx/0`) (tx and vin)
onto the contract.
When the transaction context is attached, the contract can generate valid
signatures. If it is not attached, all signatures will be 71 bytes of zeros.
"""
@spec put_ctx(t(), ctx()) :: t()
def put_ctx(%__MODULE__{} = contract, {%Tx{} = tx, vin}) when is_integer(vin),
do: Map.put(contract, :ctx, {tx, vin})
@doc """
Appends the given value onto the end of the contract script.
"""
@spec script_push(t(), atom() | integer() | binary()) :: t()
def script_push(%__MODULE__{} = contract, val),
do: update_in(contract.script, & Script.push(&1, val))
@doc """
Returns the size (in bytes) of the contract script.
"""
@spec script_size(t()) :: non_neg_integer()
def script_size(%__MODULE__{} = contract) do
contract
|> to_script()
|> Script.to_binary()
|> byte_size()
end
@doc """
Compiles the contract and returns the script.
"""
@spec to_script(t()) :: Script.t()
def to_script(%__MODULE__{mfa: {mod, fun, args}} = contract) do
%{script: script} = apply(mod, fun, [contract | args])
script
end
@doc """
Compiles the unlocking contract and returns the `t:BSV.TxIn.t/0`.
"""
@spec to_txin(t()) :: TxIn.t()
def to_txin(%__MODULE__{subject: %UTXO{outpoint: outpoint}} = contract) do
sequence = Keyword.get(contract.opts, :sequence, 0xFFFFFFFF)
script = to_script(contract)
struct(TxIn, outpoint: outpoint, script: script, sequence: sequence)
end
@doc """
Compiles the locking contract and returns the `t:BSV.TxIn.t/0`.
"""
@spec to_txout(t()) :: TxOut.t()
def to_txout(%__MODULE__{subject: satoshis} = contract)
when is_integer(satoshis)
do
script = to_script(contract)
struct(TxOut, satoshis: satoshis, script: script)
end
@doc """
Simulates the contract with the given locking and unlocking parameters.
Internally this works by creating a fake transaction containing the locking
script, and then attempts to spend that UTXO in a second fake transaction.
The entire script is concatenated and passed to `VM.eval/2`.
## Example
iex> alias BSV.Contract.P2PKH
iex> keypair = BSV.KeyPair.new()
iex> lock_params = %{address: BSV.Address.from_pubkey(keypair.pubkey)}
iex> unlock_params = %{keypair: keypair}
iex>
iex> {:ok, vm} = Contract.simulate(P2PKH, lock_params, unlock_params)
iex> BSV.VM.valid?(vm)
true
"""
@spec simulate(module(), map(), map()) :: {:ok, VM.t()} | {:error, VM.t()}
def simulate(mod, %{} = lock_params, %{} = unlock_params) when is_atom(mod) do
%Tx{outputs: [txout]} = lock_tx = TxBuilder.to_tx(%TxBuilder{
outputs: [apply(mod, :lock, [1000, lock_params])]
})
utxo = UTXO.from_tx(lock_tx, 0)
%Tx{inputs: [txin]} = tx = TxBuilder.to_tx(%TxBuilder{
inputs: [apply(mod, :unlock, [utxo, unlock_params])]
})
VM.eval(%VM{ctx: {tx, 0, txout}}, txin.script.chunks ++ txout.script.chunks)
end
end
|
lib/bsv/contract.ex
| 0.911643 | 0.645679 |
contract.ex
|
starcoder
|
defmodule RedisGraph.Edge do
@moduledoc """
An Edge component relating two Nodes in a Graph.
Edges must have a source node and destination node, describing a relationship
between two entities in a Graph. The nodes must exist in the Graph in order
for the edge to be added.
Edges must have a relation which identifies the type of relationship being
described between entities
Edges, like Nodes, may also have properties, a map of values which describe
attributes of the relationship between the associated Nodes.
"""
alias RedisGraph.Util
@type t() :: %__MODULE__{
id: integer(),
src_node: Node.t() | number(),
dest_node: Node.t() | number(),
relation: String.t(),
properties: %{optional(String.t()) => any()}
}
@enforce_keys [:src_node, :dest_node, :relation]
defstruct [:id, :src_node, :dest_node, :relation, properties: %{}]
@doc """
Create a new Edge from a map.
## Example
edge = Edge.new(%{
src_node: john,
dest_node: japan,
relation: "visited"
})
"""
@spec new(map()) :: t()
def new(map) do
struct(__MODULE__, map)
end
@doc "Convert an edge's properties to a query-appropriate string."
@spec properties_to_string(t()) :: String.t()
def properties_to_string(edge) do
inner =
Map.keys(edge.properties)
|> Enum.map(fn key -> "#{key}:#{Util.quote_string(edge.properties[key])}" end)
|> Enum.join(",")
if String.length(inner) > 0 do
"{" <> inner <> "}"
else
""
end
end
@doc "Convert an edge to a query-appropriate string."
@spec to_query_string(t()) :: String.t()
def to_query_string(edge) do
src_node_string = "(" <> edge.src_node.alias <> ")"
edge_string =
case edge.relation do
"" -> "-[" <> properties_to_string(edge) <> "]->"
nil -> "-[" <> properties_to_string(edge) <> "]->"
other -> "-[:" <> other <> properties_to_string(edge) <> "]->"
end
dest_node_string = "(" <> edge.dest_node.alias <> ")"
src_node_string <> edge_string <> dest_node_string
end
@doc """
Compare two edges with respect to equality.
Comparison logic:
* If the ids differ, returns ``false``
* If the source nodes differ, returns ``false``
* If the destination nodes differ, returns ``false``
* If the relations differ, returns ``false``
* If the properties differ, returns ``false``
* Otherwise returns `true`
"""
@spec compare(t(), t()) :: boolean()
def compare(left, right) do
cond do
left.id != right.id -> false
left.src_node != right.src_node -> false
left.dest_node != right.dest_node -> false
left.relation != right.relation -> false
map_size(left.properties) != map_size(right.properties) -> false
not Map.equal?(left.properties, right.properties) -> false
true -> true
end
end
end
|
lib/redis_graph/edge.ex
| 0.922639 | 0.714155 |
edge.ex
|
starcoder
|
defmodule Iyzico.Card do
@moduledoc """
A module representing cards used in monetary transactions.
"""
@enforce_keys ~w(holder_name number exp_year exp_month)a
defstruct [
:holder_name,
:number,
:exp_year,
:exp_month,
:cvc,
:registration_alias,
]
@typedoc """
Represents type of a card.
## Card types
- `:credit`: A credit card performs a transaction by borrowing money made available to a individual, who is a customer
of a financial institution. The transferred funds are payed as a debt from the supplier bank to the vendor, which is
ultimately paid by the credit card user.
- `:debit`: A debit card performs a transaction by directly withdrawing the funds from its coupled bank account.
- `:prepaid`: A reloadable card which performs a transaction by using pre-deposited funds.
*Reference: [YoungMoney](http://finance.youngmoney.com/credit_debt/credit_basics/credit_debit_prepaid/).*
"""
@type card_type :: :credit | :debit | :prepaid
@typedoc """
Represents supplier association of a card.
## Caveats
`:troy` is a Turkish supplier and only available in Turkey.
"""
@type card_assoc :: :mastercard | :visa | :amex | :troy
@typedoc """
Represents family of a card.
"""
@type card_family :: :bonus | :axess | :world | :maximum | :paraf | :cardfinans | :advantage | :neo | :denizbank |
:cardfinans | :halkbank | :is_bank | :vakifbank | :yapi_kredi | :hsbc | :garanti
@typedoc """
Represents a card to perform the checkout.
## Fields
- `:holder_name`: Name of the holder of the card.
- `:number`: Number of the card.
- `:exp_year`: Latest two digits of expiration year of the card, *(e.g.: 21 for 2021)*.
- `:exp_month`: Index of the expiration month starting form 1, *(e.g.: 1 for January)*.
- `:cvc`: CVC or CVV number of the card, typically three to four digits.
- `:registration_alias`: Alias of the card if it needs to be registered with ongoing transaction, optional.
"""
@type t :: %__MODULE__{
holder_name: binary,
number: binary,
exp_year: integer,
exp_month: integer,
cvc: integer,
registration_alias: binary
}
@doc """
Converts a card association string into existing atom.
## Examples
iex> Iyzico.Card.get_card_assoc "MASTER_CARD"
:mastercard
iex> Iyzico.Card.get_card_assoc "VISA"
:visa
iex> Iyzico.Card.get_card_assoc "AMERICAN_EXPRESS"
:amex
iex> Iyzico.Card.get_card_assoc "TROY"
:troy
"""
@spec get_card_assoc(String.t) :: card_assoc
def get_card_assoc(assoc) do
case assoc do
"MASTER_CARD" ->
:mastercard
"VISA" ->
:visa
"AMERICAN_EXPRESS" ->
:amex
"TROY" ->
:troy
end
end
@doc """
Converts a card type string into existing atom.
## Examples
iex> Iyzico.Card.get_card_type "CREDIT_CARD"
:credit
iex> Iyzico.Card.get_card_type "DEBIT_CARD"
:debit
iex> Iyzico.Card.get_card_type "PREPAID_CARD"
:prepaid
"""
@spec get_card_type(String.t) :: card_type
def get_card_type(type) do
case type do
"CREDIT_CARD" ->
:credit
"DEBIT_CARD" ->
:debit
"PREPAID_CARD" ->
:prepaid
end
end
@doc """
Converts given card family string to existing atom.
## Examples
iex> Iyzico.Card.get_card_family "Bonus"
:bonus
iex> Iyzico.Card.get_card_family "Axess"
:axess
iex> Iyzico.Card.get_card_family "World"
:world
iex> Iyzico.Card.get_card_family "Maximum"
:maximum
iex> Iyzico.Card.get_card_family "Paraf"
:paraf
iex> Iyzico.Card.get_card_family "Cardfinans"
:cardfinans
iex> Iyzico.Card.get_card_family "Advantage"
:advantage
iex> Iyzico.Card.get_card_family "Neo"
:neo
iex> Iyzico.Card.get_card_family "Denizbank DC"
:denizbank
iex> Iyzico.Card.get_card_family "Cardfinans DC"
:cardfinans
iex> Iyzico.Card.get_card_family "Halkbank DC"
:halkbank
iex> Iyzico.Card.get_card_family "Bankamatik"
:is_bank
iex> Iyzico.Card.get_card_family "Vakıfbank DC"
:vakifbank
iex> Iyzico.Card.get_card_family "Tlcard"
:yapi_kredi
iex> Iyzico.Card.get_card_family "Advantage DC"
:hsbc
iex> Iyzico.Card.get_card_family "Paracard"
:garanti
"""
@spec get_card_family(String.t) :: card_family
def get_card_family(family) do
case family do
"Bonus" ->
:bonus
"Axess" ->
:axess
"World" ->
:world
"Maximum" ->
:maximum
"Paraf" ->
:paraf
"Cardfinans" ->
:cardfinans
"Advantage" ->
:advantage
"Neo" ->
:neo
"Denizbank DC" ->
:denizbank
"Denizbank CC" ->
:denizbank
"Cardfinans DC" ->
:cardfinans
"Halkbank DC" ->
:halkbank
"Bankamatik" ->
:is_bank
"Vakıfbank DC" ->
:vakifbank
"Tlcard" ->
:yapi_kredi
"Advantage DC" ->
:hsbc
"Paracard" ->
:garanti
end
end
end
defimpl Iyzico.IOListConvertible, for: Iyzico.Card do
def to_iolist(data) do
case data.registration_alias do
nil ->
[{"cardHolderName", data.holder_name},
{"cardNumber", data.number},
{"expireYear", data.exp_year},
{"expireMonth", data.exp_month},
{"cvc", data.cvc},
{"registerCard", 0}]
_any ->
[{"cardAlias", data.registration_alias},
{"cardNumber", data.number},
{"expireYear", data.exp_year},
{"expireMonth", data.exp_month},
{"cardHolderName", data.holder_name}]
end
end
end
|
lib/model/card.ex
| 0.919072 | 0.58166 |
card.ex
|
starcoder
|
defmodule Reach.Game do
@type t :: %{optional(String.t) => %Reach.Team{}}
def start_link() do
Agent.start_link(fn ->
Map.new
|> Map.put("shiani", Reach.Team.new("shiani"))
|> Map.put("tano", Reach.Team.new("tano"))
end, name: __MODULE__)
end
@doc """
Gets the current game state.
"""
@spec get() :: t
def get() do
Agent.get(__MODULE__, &(&1))
end
@doc """
Add a new team to the game.
"""
@spec add_team(String.t) :: t
def add_team(name) do
Agent.get_and_update(__MODULE__, fn state ->
result = Map.put(state, name, Reach.Team.new(name))
{result, result}
end)
end
@doc """
Remove a team from the game.
"""
@spec remove_team(String.t) :: t
def remove_team(name) do
Agent.get_and_update(__MODULE__, fn state ->
result = Map.delete(state, name)
{result, result}
end)
end
@doc """
Add a new member to a team.
"""
@spec add_member(String.t, String.t) :: t | none
def add_member(team, name) do
Agent.get_and_update(__MODULE__, fn state ->
case state[team] do
nil -> {state, state}
_ ->
result = update_in(state[team], &Reach.Team.add(&1, name))
{result, result}
end
end)
end
@doc """
Removes a player from a team.
"""
@spec remove_member(String.t, String.t) :: t | none
def remove_member(team, name) do
Agent.get_and_update(__MODULE__, fn state ->
case state[team] do
nil -> {state, state}
_ ->
result = update_in(state[team], &Reach.Team.remove(&1, name))
{result, result}
end
end)
end
@doc """
Adjust the score of the team.
"""
@spec score_change(String.t, integer) :: t
def score_change(team, value) do
Agent.get_and_update(__MODULE__, fn state ->
case state[team] do
nil -> {state, state}
_ ->
result = update_in(state[team], &Reach.Team.modify_score(&1, value))
{result, result}
end
end)
end
@doc """
Resets the game state to the start of a new game.
"""
@spec reset() :: t
def reset() do
Agent.get_and_update(__MODULE__, fn state ->
result = Enum.map(state, fn {k, v} -> {k, %{v | :score => 0, :buzzed => false}} end) |> Enum.into(%{})
{result, result}
end)
end
@doc """
Allows all teams to buzz again.
"""
@spec unblock() :: t
def unblock() do
Agent.get_and_update(__MODULE__, fn state ->
result = Enum.map(state, fn {k, v} -> {k, %{v | :buzzed => false}} end) |> Enum.into(%{})
{result, result}
end)
end
@doc """
Checks to see if the team can block.
"""
@spec block?(String.t) :: boolean
def block?(team) do
case team do
nil -> false
_ ->
Agent.get_and_update(__MODULE__, fn state ->
case state[team] do
nil -> {false, state}
_ -> {true, update_in(state[team].buzzed, fn _ -> true end)}
end
end)
end
end
end
|
lib/reach/game.ex
| 0.652352 | 0.416203 |
game.ex
|
starcoder
|
defmodule XtbClient.Messages.Candle do
alias XtbClient.Messages.QuoteId
@moduledoc """
Info representing aggregated price & volume values for candle.
Default interval for one candle is one minute.
## Parameters
- `open` open price in base currency,
- `high` highest value in the given period in base currency,
- `low` lowest value in the given period in base currency,
- `close` close price in base currency,
- `vol` volume in lots,
- `ctm` candle start time in CET time zone (Central European Time),
- `ctm_string` string representation of the `ctm` field,
- `quote_id` source of price, see `XtbClient.Messages.QuoteId`,
- `symbol` symbol name.
"""
@type t :: %__MODULE__{
open: float(),
high: float(),
low: float(),
close: float(),
vol: float(),
ctm: DateTime.t(),
ctm_string: binary(),
quote_id: QuoteId.t(),
symbol: binary()
}
@enforce_keys [
:open,
:high,
:low,
:close,
:vol,
:ctm,
:ctm_string,
:quote_id,
:symbol
]
@derive Jason.Encoder
defstruct open: 0.0,
high: 0.0,
low: 0.0,
close: 0.0,
vol: 0.0,
ctm: nil,
ctm_string: "",
quote_id: nil,
symbol: ""
def new(
%{
"open" => open,
"high" => high,
"low" => low,
"close" => close,
"vol" => vol,
"ctm" => ctm_value,
"ctmString" => ctm_string
},
digits
)
when is_number(open) and is_number(high) and is_number(low) and is_number(close) and
is_number(vol) and is_number(ctm_value) and is_binary(ctm_string) and
is_number(digits) do
%__MODULE__{
open: to_base_currency(open, digits),
high: to_base_currency(open + high, digits),
low: to_base_currency(open + low, digits),
close: to_base_currency(open + close, digits),
vol: vol,
ctm: DateTime.from_unix!(ctm_value, :millisecond),
ctm_string: ctm_string,
quote_id: nil,
symbol: ""
}
end
def new(%{
"open" => open,
"high" => high,
"low" => low,
"close" => close,
"vol" => vol,
"ctm" => ctm_value,
"ctmString" => ctm_string,
"quoteId" => quote_id,
"symbol" => symbol
})
when is_number(open) and is_number(high) and is_number(low) and is_number(close) and
is_number(vol) and
is_number(ctm_value) and is_binary(ctm_string) and
is_integer(quote_id) and
is_binary(symbol) do
%__MODULE__{
open: open,
high: high,
low: low,
close: close,
vol: vol,
ctm: DateTime.from_unix!(ctm_value, :millisecond),
ctm_string: ctm_string,
quote_id: QuoteId.parse(quote_id),
symbol: symbol
}
end
defp to_base_currency(value, digits) do
value / :math.pow(10, digits)
end
end
|
lib/xtb_client/messages/candle.ex
| 0.854475 | 0.434641 |
candle.ex
|
starcoder
|
defmodule LiveViewExamples.Tabs.Home do
import LiveViewExamples.Format
@top_attributes [:memory, :reductions]
def collect(%{
stats: %{
io: io_stats,
gc: gc_stats,
schedulers: schedulers
} = stats,
settings: _
} = state) do
put_in(state[:stats], Map.merge(stats, base_stats()))
|> put_in([:stats, :mem_stats], mem_stats())
|> put_in([:stats, :reds_stats], reds_stats())
|> put_in([:stats, :io], io_stats(io_stats))
|> put_in([:stats, :runq_stats], runq_stats())
|> put_in([:stats, :gc], gc_stats(gc_stats))
|> put_in([:stats, :schedulers], schedulers_stats(schedulers))
|> put_in([:stats, :process_top], process_top(state))
|> put_in([:stats, :allocators], [])
end
def system_info do
schedulers_online = :erlang.system_info(:schedulers_online)
multi_scheduling = :erlang.system_info(:multi_scheduling)
schedulers_available = case multi_scheduling do
:enabled -> schedulers_online
_ -> 1
end
%{
system_version: :erlang.system_info(:system_version),
version: :erlang.system_info(:version),
proc_limit: :erlang.system_info(:process_limit),
port_limit: :erlang.system_info(:port_limit),
atom_limit: :erlang.system_info(:atom_limit),
smp_support: :erlang.system_info(:smp_support),
multi_scheduling: multi_scheduling,
logical_processors: :erlang.system_info(:logical_processors),
logical_processors_online: :erlang.system_info(:logical_processors_online),
logical_processors_available: :erlang.system_info(:logical_processors_available),
schedulers: :erlang.system_info(:schedulers),
schedulers_online: schedulers_online,
schedulers_available: schedulers_available,
otp_release: :erlang.system_info(:otp_release),
system_architecture: :erlang.system_info(:system_architecture),
kernel_poll: :erlang.system_info(:kernel_poll),
threads: :erlang.system_info(:threads),
thread_pool_size: :erlang.system_info(:thread_pool_size),
wordsize_internal: :erlang.system_info({:wordsize, :internal}),
wordsize_external: :erlang.system_info({:wordsize, :external})
}
end
def base_stats do
base_stats = %{
proc_count: :erlang.system_info(:process_count),
port_count: :erlang.system_info(:port_count),
atom_count: :erlang.system_info(:atom_count),
mem_allocated: :recon_alloc.memory(:allocated),
mem_used: :recon_alloc.memory(:used)
}
unused_mem = base_stats[:mem_allocated] - base_stats[:mem_used]
without_perc = put_in(base_stats[:mem_unused], number_to_human_size(unused_mem))
|> put_in([:mem_allocated], number_to_human_size(base_stats[:mem_allocated]))
|> put_in([:mem_used], number_to_human_size(base_stats[:mem_used]))
without_perc
|> put_in([:mem_used_perc], to_percentage(base_stats[:mem_used] / base_stats[:mem_allocated]))
|> put_in([:mem_unused_perc], to_percentage(unused_mem / base_stats[:mem_allocated]))
end
def mem_stats do
for {k, v} <- :erlang.memory, into: %{}, do: {k, number_to_human_size(v)}
end
def reds_stats do
{_, reds} = :erlang.statistics(:reductions)
reds
end
def io_stats(%{input: last_input, output: last_output}) do
{{:input, total_input}, {:output, total_output}} = :erlang.statistics(:io)
input = total_input - last_input
output = total_output - last_output
%{
input: input,
total_input_human: number_to_human_size(total_input),
input_human: number_to_human_size(input),
output: output,
total_output_human: number_to_human_size(total_output),
output_human: number_to_human_size(output)
}
end
def runq_stats do
%{
run_queue: :erlang.statistics(:run_queue),
error_logger_queue: error_logger_queue()
}
end
defp error_logger_queue do
case Process.whereis(:error_logger) do
logger when is_pid(logger) ->
{_, len} = Process.info(logger, :message_queue_len)
len
_ -> ?0
end
end
def gc_stats(%{gcs: last_gcs, words: last_words}) do
{gcs, words, _} = :erlang.statistics(:garbage_collection)
%{
gcs: gcs - last_gcs,
words: words - last_words
}
end
defp process_top(%{settings: %{
interval: interval,
top_processes_limit: top_processes_limit,
top_attribute: attribute,
top_order: order
}}) when attribute in @top_attributes do
procs = case order do
"desc" -> :recon.proc_count(attribute, top_processes_limit)
"asc" -> :recon.proc_window(attribute, top_processes_limit, interval)
end
for {pid, stat, info} <- procs do
name = case info do
[a, b, _] when is_atom(a) and is_tuple(b) -> a
_ -> nil
end
[reductions: reds, message_queue_len: msq] =
case Process.info(pid, [:reductions, :message_queue_len]) do
nil -> [reductions: nil, message_queue_len: nil]
info -> info
end
%{
pid: pid,
stat: format_stat(stat, attribute),
name: name,
reductions: reds,
message_queue_len: msq,
current_function: Access.get(info, :current_function),
initial_call: Access.get(info, :initial_call)
}
end
end
defp schedulers_stats(%{wall: nil} = stats) do
schedulers_stats(put_in(stats[:wall], :erlang.statistics(:scheduler_wall_time)))
end
defp schedulers_stats(%{wall: wall} = stats) do
new_wall = :erlang.statistics(:scheduler_wall_time)
diff = :recon_lib.scheduler_usage_diff(new_wall, wall)
stats
|> put_in([:wall], new_wall)
|> put_in([:formatted], format_schedulers(diff))
end
defp format_schedulers(wall) do
schedulers = length(wall)
rows = round(schedulers / 4)
wall
|> Enum.map(fn {sched, v} -> {sched, Float.round(v * 100, 4)} end)
|> Enum.group_by(fn
{n, _} when rem(n, rows) == 0 -> rows
{n, _} -> rem(n, rows)
end)
end
defp format_stat(value, :memory), do: number_to_human_size(value)
defp format_stat(value, _), do: value
end
|
lib/live_view_examples/tabs/home.ex
| 0.588061 | 0.40539 |
home.ex
|
starcoder
|
defmodule Rummage.Ecto.Hook.Sort do
@moduledoc """
`Rummage.Ecto.Hook.Sort` is the default sort hook that comes with
`Rummage.Ecto`.
This module provides a operations that can add sorting functionality to
a pipeline of `Ecto` queries. This module works by taking the `field` that should
be used to `order_by`, `order` which can be `asc` or `desc` and `assoc`,
which is a keyword list of assocations associated with those `fields`.
NOTE: This module doesn't return a list of entries, but a `Ecto.Query.t`.
This module `uses` `Rummage.Ecto.Hook`.
_____________________________________________________________________________
# ABOUT:
## Arguments:
This Hook expects a `queryable` (an `Ecto.Queryable`) and
`sort_params` (a `Map`). The map should be in the format:
`%{field: :field_name, assoc: [], order: :asc}`
Details:
* `field`: The field name (atom) to sorted by.
* `assoc`: List of associations in the sort.
* `order`: Specifies the type of order `asc` or `desc`.
* `ci` : Case Insensitivity. Defaults to `false`
For example, if we want to sort products with descending `price`, we would
do the following:
```elixir
Rummage.Ecto.Hook.Sort.run(Product, %{field: :price,
assoc: [], order: :desc})
```
## Assoications:
Assocaitions can be given to this module's run function as a key corresponding
to params associated with a field. For example, if we want to sort products
that belong to a category by ascending category_name, we would do the
following:
```elixir
params = %{field: :category_name, assoc: [inner: :category],
order: :asc}
Rummage.Ecto.Hook.Sort.run(Product, params)
```
The above operation will return an `Ecto.Query.t` struct which represents
a query equivalent to:
```elixir
from p0 in Product
|> join(:inner, :category)
|> order_by([p, c], {asc, c.category_name})
```
____________________________________________________________________________
# ASSUMPTIONS/NOTES:
* This Hook has the default `order` of `:asc`.
* This Hook has the default `assoc` of `[]`.
* This Hook assumes that the field passed is a field on the `Ecto.Schema`
that corresponds to the last association in the `assoc` list or the `Ecto.Schema`
that corresponds to the `from` in `queryable`, if `assoc` is an empty list.
NOTE: It is adviced to not use multiple associated sorts in one operation
as `assoc` still has some minor bugs when used with multiple sorts. If you
need to use two sorts with associations, I would pipe the call to another
sort operation:
```elixir
Sort.run(queryable, params1}
|> Sort.run(%{field2: params2}
```
____________________________________________________________________________
# USAGE:
For a regular sort:
This returns a `queryable` which upon running will give a list of `Parent`(s)
sorted by ascending `field_1`
```elixir
alias Rummage.Ecto.Hook.Sort
sorted_queryable = Sort.run(Parent, %{assoc: [], field: :name, order: :asc}})
```
For a case-insensitive sort:
This returns a `queryable` which upon running will give a list of `Parent`(s)
sorted by ascending case insensitive `field_1`.
Keep in mind that `case_insensitive` can only be called for `text` fields
```elixir
alias Rummage.Ecto.Hook.Sort
sorted_queryable = Sort.run(Parent, %{assoc: [], field: :name, order: :asc, ci: true}})
```
This module can be overridden with a custom module while using `Rummage.Ecto`
in `Ecto` struct module.
In the `Ecto` module:
```elixir
Rummage.Ecto.rummage(queryable, rummage, sort: CustomHook)
```
OR
Globally for all models in `config.exs`:
```elixir
config :rummage_ecto,
Rummage.Ecto,
sort: CustomHook
```
The `CustomHook` must use `Rummage.Ecto.Hook`. For examples of `CustomHook`,
check out some `custom_hooks` that are shipped with `Rummage.Ecto`:
`Rummage.Ecto.CustomHook.SimpleSearch`, `Rummage.Ecto.CustomHook.SimpleSort`,
`Rummage.Ecto.CustomHook.SimplePaginate`
"""
use Rummage.Ecto.Hook
import Ecto.Query
@expected_keys ~w{field order assoc}a
@err_msg ~s{Error in params, No values given for keys: }
# Only for Postgres (only one interpolation is supported)
# TODO: Fix this once Ecto 3.0 comes out with `unsafe_fragment`
@supported_fragments_one [
"date_part('day', ?)",
"date_part('month', ?)",
"date_part('year', ?)",
"date_part('hour', ?)",
"lower(?)",
"upper(?)"
]
@supported_fragments_two ["concat(?, ?)", "coalesce(?, ?)"]
@doc """
This is the callback implementation of Rummage.Ecto.Hook.run/2.
Builds a sort `Ecto.Query.t` on top of the given `Ecto.Queryable` variable
using given `params`.
Besides an `Ecto.Query.t` an `Ecto.Schema` module can also be passed as it
implements `Ecto.Queryable`
Params is a `Map` which is expected to have the keys `#{Enum.join(@expected_keys, ", ")}`.
This funciton expects a `field` atom, `order` which can be `asc` or `desc`,
`ci` which is a boolean indicating the case-insensitivity and `assoc` which
is a list of associations with their join types.
## Examples
When an empty map is passed as `params`:
iex> alias Rummage.Ecto.Hook.Sort
iex> Sort.run(Parent, %{})
** (RuntimeError) Error in params, No values given for keys: field, order, assoc
When a non-empty map is passed as `params`, but with a missing key:
iex> alias Rummage.Ecto.Hook.Sort
iex> Sort.run(Parent, %{field: :name})
** (RuntimeError) Error in params, No values given for keys: order, assoc
When a valid map of params is passed with an `Ecto.Schema` module:
iex> alias Rummage.Ecto.Hook.Sort
iex> Sort.run(Rummage.Ecto.Product, %{field: :name, assoc: [], order: :asc})
#Ecto.Query<from p0 in subquery(from p0 in Rummage.Ecto.Product), order_by: [asc: p0.name]>
When the `queryable` passed is an `Ecto.Query` variable:
iex> alias Rummage.Ecto.Hook.Sort
iex> import Ecto.Query
iex> queryable = from u in "products"
#Ecto.Query<from p0 in "products">
iex> Sort.run(queryable, %{field: :name, assoc: [], order: :asc})
#Ecto.Query<from p0 in subquery(from p0 in "products"), order_by: [asc: p0.name]>
When the `queryable` passed is an `Ecto.Query` variable, with `desc` order:
iex> alias Rummage.Ecto.Hook.Sort
iex> import Ecto.Query
iex> queryable = from u in "products"
#Ecto.Query<from p0 in "products">
iex> Sort.run(queryable, %{field: :name, assoc: [], order: :desc})
#Ecto.Query<from p0 in subquery(from p0 in "products"), order_by: [desc: p0.name]>
When the `queryable` passed is an `Ecto.Query` variable, with `ci` true:
iex> alias Rummage.Ecto.Hook.Sort
iex> import Ecto.Query
iex> queryable = from u in "products"
#Ecto.Query<from p0 in "products">
iex> Sort.run(queryable, %{field: :name, assoc: [], order: :asc, ci: true})
#Ecto.Query<from p0 in subquery(from p0 in "products"), order_by: [asc: fragment("lower(?)", p0.name)]>
When the `queryable` passed is an `Ecto.Query` variable, with associations:
iex> alias Rummage.Ecto.Hook.Sort
iex> import Ecto.Query
iex> queryable = from u in "products"
#Ecto.Query<from p0 in "products">
iex> Sort.run(queryable, %{field: :name, assoc: [inner: :category, left: :category], order: :asc})
#Ecto.Query<from p0 in subquery(from p0 in "products"), join: c1 in assoc(p0, :category), left_join: c2 in assoc(c1, :category), order_by: [asc: c2.name]>
When the `queryable` passed is an `Ecto.Schema` module with associations,
`desc` order and `ci` true:
iex> alias Rummage.Ecto.Hook.Sort
iex> queryable = Rummage.Ecto.Product
Rummage.Ecto.Product
iex> Sort.run(queryable, %{field: :name, assoc: [inner: :category], order: :desc, ci: true})
#Ecto.Query<from p0 in subquery(from p0 in Rummage.Ecto.Product), join: c1 in assoc(p0, :category), order_by: [desc: fragment("lower(?)", c1.name)]>
"""
@spec run(Ecto.Query.t(), map()) :: Ecto.Query.t()
def run(queryable, sort_params) do
:ok = validate_params(sort_params)
handle_sort(queryable, sort_params)
end
# Helper function which handles addition of paginated query on top of
# the sent queryable variable
defp handle_sort(queryable, sort_params) do
order = Map.get(sort_params, :order)
field =
sort_params
|> Map.get(:field)
|> resolve_field(queryable)
assocs = Map.get(sort_params, :assoc)
ci = Map.get(sort_params, :ci, false)
assocs
|> Enum.reduce(from(e in subquery(queryable)), &join_by_assoc(&1, &2))
|> handle_ordering(field, order, ci)
end
# Helper function which handles associations in a query with a join
# type.
defp join_by_assoc({join, assoc}, query) do
join(query, join, [..., p1], p2 in assoc(p1, ^assoc))
end
# This is a helper macro to get case_insensitive query using fragments
defmacrop case_insensitive(field) do
quote do
fragment("lower(?)", unquote(field))
end
end
# NOTE: These functions can be used in future for multiple sort fields that
# are associated.
# defp applied_associations(queryable) when is_atom(queryable), do: []
# defp applied_associations(queryable), do: Enum.map(queryable.joins, & Atom.to_string(elem(&1.assoc, 1)))
# Helper function that handles adding order_by to a query based on order type
# case insensitivity and field
defp handle_ordering(queryable, field, order, ci) do
order_by_assoc(queryable, order, field, ci)
end
for fragment <- @supported_fragments_one do
defp order_by_assoc(queryable, order_type, {:fragment, unquote(fragment), field}, false) do
order_by(queryable, [p0, ..., p2], [
{^order_type, fragment(unquote(fragment), field(p2, ^field))}
])
end
defp order_by_assoc(queryable, order_type, {:fragment, unquote(fragment), field}, true) do
order_by(queryable, [p0, ..., p2], [
{^order_type, case_insensitive(fragment(unquote(fragment), field(p2, ^field)))}
])
end
end
for fragment <- @supported_fragments_two do
defp order_by_assoc(
queryable,
order_type,
{:fragment, unquote(fragment), field1, field2},
false
) do
order_by(queryable, [p0, ..., p2], [
{^order_type, fragment(unquote(fragment), field(p2, ^field1), field(p2, ^field2))}
])
end
defp order_by_assoc(
queryable,
order_type,
{:fragment, unquote(fragment), field1, field2},
true
) do
order_by(queryable, [p0, ..., p2], [
{^order_type,
case_insensitive(fragment(unquote(fragment), field(p2, ^field1), field(p2, ^field2)))}
])
end
end
defp order_by_assoc(queryable, order_type, field, false) do
order_by(queryable, [p0, ..., p2], [{^order_type, field(p2, ^field)}])
end
defp order_by_assoc(queryable, order_type, field, true) do
order_by(queryable, [p0, ..., p2], [{^order_type, case_insensitive(field(p2, ^field))}])
end
# Helper function that validates the list of params based on
# @expected_keys list
defp validate_params(params) do
key_validations = Enum.map(@expected_keys, &Map.fetch(params, &1))
case Enum.filter(key_validations, &(&1 == :error)) do
[] -> :ok
_ -> raise @err_msg <> missing_keys(key_validations)
end
end
# Helper function used to build error message using missing keys
defp missing_keys(key_validations) do
key_validations
|> Enum.with_index()
|> Enum.filter(fn {v, _i} -> v == :error end)
|> Enum.map(fn {_v, i} -> Enum.at(@expected_keys, i) end)
|> Enum.map(&to_string/1)
|> Enum.join(", ")
end
@doc """
Callback implementation for Rummage.Ecto.Hook.format_params/3.
This function ensures that params for each field have keys `assoc`, `order1`
which are essential for running this hook module.
## Examples
iex> alias Rummage.Ecto.Hook.Sort
iex> Sort.format_params(Parent, %{}, [])
%{assoc: [], order: :asc}
"""
@spec format_params(Ecto.Query.t(), map() | tuple(), keyword()) :: map()
def format_params(queryable, {sort_scope, order}, opts) do
module = get_module(queryable)
name = :"__rummage_sort_#{sort_scope}"
sort_params =
case function_exported?(module, name, 1) do
true -> apply(module, name, [order])
_ -> raise "No scope `#{sort_scope}` of type sort defined in the #{module}"
end
format_params(queryable, sort_params, opts)
end
def format_params(_queryable, sort_params, _opts) do
sort_params
|> Map.put_new(:assoc, [])
|> Map.put_new(:order, :asc)
end
end
|
lib/rummage_ecto/hooks/sort.ex
| 0.816589 | 0.946547 |
sort.ex
|
starcoder
|
defmodule Garlic.Crypto.Ed25519 do
@moduledoc """
Hand-crafted Ed25519 primitives and public key blinding
"""
use Bitwise
import Integer, only: [mod: 2]
@t254 0x4000000000000000000000000000000000000000000000000000000000000000
@p 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED
@d -4_513_249_062_541_557_337_682_894_930_092_624_173_785_641_285_191_125_241_628_941_591_882_900_924_598_840_740
@i 19_681_161_376_707_505_956_807_079_304_988_542_015_446_066_515_923_890_162_744_021_073_123_829_784_752
@base {15_112_221_349_535_400_772_501_151_409_588_531_511_454_012_693_041_857_206_046_113_283_949_847_762_202,
46_316_835_694_926_478_169_428_394_003_475_163_141_307_993_866_256_225_615_783_033_603_165_251_855_960}
@spec base_string() :: binary
def base_string() do
"(#{elem(@base, 0)}, #{elem(@base, 1)})"
end
@doc """
Blinds a public key with supplied param as described in Section A.2 of rend-spec-v3.txt
## Parameters
- `public_key` - a public key
- `param` - hashed param
"""
@spec blind_public_key(binary, binary) :: binary
def blind_public_key(public_key, param) do
point = decode_point(public_key)
unless on_curve?(point) do
raise ArgumentError, "point off curve"
end
param
|> a_from_hash()
|> scalarmult(point)
|> encode_point()
end
defp scalarmult(0, _), do: {0, 1}
defp scalarmult(e, p) do
q = e |> div(2) |> scalarmult(p)
q = edwards(q, q)
case e &&& 1 do
1 -> edwards(q, p)
_ -> q
end
end
defp edwards({x1, y1}, {x2, y2}) do
x = (x1 * y2 + x2 * y1) * inv(1 + @d * x1 * x2 * y1 * y2)
y = (y1 * y2 + x1 * x2) * inv(1 - @d * x1 * x2 * y1 * y2)
{mod(x, @p), mod(y, @p)}
end
defp expmod(b, e, m) when b > 0 do
b
|> :crypto.mod_pow(e, m)
|> :binary.decode_unsigned()
end
defp expmod(b, e, m) do
i =
b
|> abs()
|> :crypto.mod_pow(e, m)
|> :binary.decode_unsigned()
cond do
mod(e, 2) == 0 -> i
i == 0 -> i
true -> m - i
end
end
defp inv(x), do: expmod(x, @p - 2, @p)
defp encode_point({x, y}) do
val =
y
|> band(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
|> bor((x &&& 1) <<< 255)
<<val::little-size(256)>>
end
defp decode_point(<<n::little-size(256)>>) do
xc = n >>> 255
y = n &&& 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
x = xrecover(y)
if (x &&& 1) == xc, do: {x, y}, else: {@p - x, y}
end
def on_curve?({x, y}), do: mod(-x * x + y * y - 1 - @d * x * x * y * y, @p) == 0
def on_curve?(binary) when is_binary(binary) do
binary
|> decode_point
|> on_curve?
end
defp a_from_hash(<<h::little-size(256), _rest::binary>>) do
@t254 + band(h, 0xF3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8)
end
defp xrecover(y) do
xx = (y * y - 1) * inv(@d * y * y + 1)
x = expmod(xx, div(@p + 3, 8), @p)
x =
case mod(x * x - xx, @p) do
0 -> x
_ -> mod(x * @i, @p)
end
case mod(x, 2) do
0 -> @p - x
_ -> x
end
end
end
|
lib/garlic/crypto/ed25519.ex
| 0.757525 | 0.439507 |
ed25519.ex
|
starcoder
|
defmodule Snitch.Data.Model.TaxRate do
@moduledoc """
Exposes APIs for tax rate CRUD.
"""
use Snitch.Data.Model
alias Snitch.Data.Schema.TaxRate
@doc """
Creates a tax rate for the supplied params.
Expects the following keys in the `params`:
- `*name`: Name of the tax rate.
- `*tax_zone_id`: id of the tax zone for which tax rate would be created.
- `is_active?`: a boolean value which represents if the tax rate would be treated
as active or not, this is optional param and is set to true by default.
- `priority`: The priority in which the taxes would be calculated. To see further
details. See `Snitch.Data.Schema.TaxRate`.
- `*tax_rate_class_values`: A set of values to be set for different tax classes. The values
set are used to calculate the taxes for the order falling in the tax zone having the tax
rate.
The `tax_rate_class_values` is a map which expects the following keys:
- `*tax_rate_class_id`: The class for which value would be stored for the tax rate.
- `*percent_amount`: The amount to be stored for the `tax_class`.
The `tax_rate_class_values` are being handled using
`Ecto.Changeset.cast_assoc(changeset, name, opts \\ [])` with tax rate.
> The tax rate names are unique for every tax zone.
> Also, a tax rate can be associated with a class in the `tax_rate_class_values` table only once.
> `*` are required params.
"""
@spec create(map) :: {:ok, TaxRate.t()} | {:error, Ecto.Changeset.t()}
def create(params) do
QH.create(TaxRate, params, Repo)
end
@doc """
Updates a `TaxRate` with the supplied `params`.
To know about the expected keys see `create/1`
> Since `:tax_rate_class_values` for a tax rate are updated with cast_assoc
rules added by `Ecto.Changeset.cast_assoc/3` are applied.
"""
@spec update(TaxRate.t(), map) :: {:ok, TaxRate.t()} | {:error, Ecto.Changeset.t()}
def update(tax_rate, params) do
tax_rate = tax_rate |> Repo.preload(tax_rate_class_values: :tax_class)
QH.update(TaxRate, params, tax_rate, Repo)
end
@doc """
Deletes a TaxRate.
"""
def delete(id) do
QH.delete(TaxRate, id, Repo)
end
@doc """
Returns a tax rate preloaded with it's values corresponding to
tax classes under the key `:tax_rate_class_values`
"""
def get(id) do
TaxRate
|> QH.get(id, Repo)
|> case do
{:ok, tax_rate} ->
{:ok, Repo.preload(tax_rate, tax_rate_class_values: :tax_class)}
{:error, _} = error ->
error
end
end
@doc """
Returns a list of `TaxRates` preloaded with values for
tax class it is associated with.
"""
@spec get_all() :: [TaxRate.t()]
def get_all() do
TaxRate |> Repo.all() |> Repo.preload(:tax_rate_class_values)
end
@doc """
Returns all the tax rates for a `tax_zone`.
"""
@spec get_all_by_tax_zone(non_neg_integer) :: [TaxRate.t()]
def get_all_by_tax_zone(tax_zone_id) do
query =
from(
tax_rate in TaxRate,
where: tax_rate.tax_zone_id == ^tax_zone_id,
select: %TaxRate{
name: tax_rate.name,
is_active?: tax_rate.is_active?,
priority: tax_rate.priority,
id: tax_rate.id
}
)
query |> Repo.all() |> Repo.preload(tax_rate_class_values: :tax_class)
end
end
|
apps/snitch_core/lib/core/data/model/tax/tax_rate.ex
| 0.878581 | 0.867317 |
tax_rate.ex
|
starcoder
|
defmodule GymAgent do
@moduledoc false
alias GymAgent.Experience
@batch_size 10
@history_size_min 100
@history_size_max 10_000
defstruct num_actions: 0, num_states: 0, gamma: 0.99, eps: 0.25, eps_decay: 0.99, learner: nil, fit: false, trained: false, history: nil, s: nil, a: nil
def new(opts \\ []) do
agent = %GymAgent{}
# Default overridable options
|> struct(opts)
# Force defaults for internal items
|> struct(fit: false)
|> struct(trained: false)
|> struct(history: Deque.new(@history_size_max))
# Continue updating agent based on initialization params
agent
|> struct(learner: create_learner(agent))
end
def create_learner(agent) do
hidden_size = agent.num_states * 10
Annex.sequence([
Annex.dense(hidden_size, agent.num_states),
Annex.activation(:tanh),
Annex.dense(agent.num_actions, hidden_size),
Annex.activation(:linear)
])
end
def querysetstate(agent, s) do
agent
|> update_state(s)
|> update_action(get_action(agent, s))
|> decay_eps()
end
def query(agent, r, s_prime, done) do
agent
|> update_q(r, s_prime, done)
|> train()
end
def update_q(agent, r, s_prime, done) do
a_prime = get_action(agent, s_prime)
xp = %Experience{s: agent.s, a: agent.a, r: r, s_prime: s_prime, done: done}
agent
|> update_history(xp)
|> update_action(a_prime)
|> update_state(s_prime)
end
def update_state(agent, s) do
struct(agent, s: s)
end
def update_action(agent, a) do
struct(agent, a: a)
end
def update_history(agent, xp) do
struct(agent, history: Deque.append(agent.history, xp))
end
def train(%GymAgent{trained: true} = agent), do: agent
def train(%GymAgent{trained: false} = agent) do
fit = Enum.count(agent.history) >= @history_size_min
case fit do
true ->
samples = Enum.take_random(agent.history, @batch_size)
|> gen_data_labels(agent)
{learner, _output} = Annex.train(
agent.learner,
samples,
halt_condition: {:epochs, 1}
)
agent
|> struct(learner: learner)
|> struct(fit: fit)
_ -> agent
end
end
def gen_data_labels([], _), do: []
def gen_data_labels([xp | samples], agent) do
data = xp.s #|> IO.inspect()
v = get_values(agent, xp.s) #|> IO.inspect()
vr = if xp.done, do: xp.r, else: (xp.r + (agent.gamma * Enum.max(get_values(agent, xp.s_prime))))
labels = List.replace_at(v, xp.a, vr) #|> Enum.map(&Annex.Layer.Activation.sigmoid/1) #|> Enum.map(&:math.tanh/1) #|> IO.inspect()
xy = {data, labels} #|> IO.inspect()
[xy | gen_data_labels(samples, agent)]
end
def get_action(%GymAgent{fit: false} = agent, _s) do
get_random_action(agent)
end
def get_action(%GymAgent{fit: true} = agent, s) do
cond do
:rand.uniform_real() <= agent.eps -> get_random_action(agent)
true -> get_learned_action(agent, s)
end
end
def get_learned_action(agent, s) do
get_values(agent, s)
|> argmax()
end
def get_random_action(agent) do
:rand.uniform(agent.num_actions) - 1
end
def decay_eps(%GymAgent{fit: true} = agent) do
eps = agent.eps * agent.eps_decay
struct(agent, eps: eps)
end
def decay_eps(%GymAgent{fit: false} = agent), do: agent
def get_values(%GymAgent{fit: false} = agent, _s) do
for _ <- 1..agent.num_actions, do: :rand.uniform()
end
def get_values(%GymAgent{fit: true} = agent, s) do
Annex.predict(agent.learner, s)
end
def argmax(values) do
red_values = values |> Enum.with_index()
red_values |> Enum.reduce(hd(red_values), &reduce_argmax/2) |> elem(1)
end
defp reduce_argmax({val, idx}, {acc_val, acc_idx}), do: if (val > acc_val), do: {val, idx}, else: {acc_val, acc_idx}
end
|
lib/gym_agent.ex
| 0.723505 | 0.53279 |
gym_agent.ex
|
starcoder
|
defmodule RDF.Star.Quad do
@moduledoc """
Helper functions for RDF-star quads.
An RDF-star quad is represented as a plain Elixir tuple consisting of four valid
RDF values for subject, predicate, object and a graph name.
As opposed to an `RDF.Quad` the subject or object can be a triple.
"""
alias RDF.Star.Statement
alias RDF.PropertyMap
@type t :: {
Statement.subject(),
Statement.predicate(),
Statement.object(),
Statement.graph_name()
}
@type coercible ::
{
Statement.coercible_subject(),
Statement.coercible_predicate(),
Statement.coercible_object(),
Statement.coercible_graph_name()
}
@doc """
Creates a `RDF.Star.Quad` with proper RDF-star values.
An error is raised when the given elements are not coercible to RDF-star values.
Note: The `RDF.quad` function is a shortcut to this function.
## Examples
iex> RDF.Star.Quad.new("http://example.com/S", "http://example.com/p", 42, "http://example.com/Graph")
{~I<http://example.com/S>, ~I<http://example.com/p>, RDF.literal(42), ~I<http://example.com/Graph>}
iex> RDF.Star.Quad.new(EX.S, EX.p, 42, EX.Graph)
{RDF.iri("http://example.com/S"), RDF.iri("http://example.com/p"), RDF.literal(42), RDF.iri("http://example.com/Graph")}
iex> RDF.Star.Quad.new(EX.S, :p, 42, EX.Graph, RDF.PropertyMap.new(p: EX.p))
{RDF.iri("http://example.com/S"), RDF.iri("http://example.com/p"), RDF.literal(42), RDF.iri("http://example.com/Graph")}
iex> RDF.Star.Quad.new(EX.S, :p, 42, EX.Graph, RDF.PropertyMap.new(p: EX.p))
{RDF.iri("http://example.com/S"), RDF.iri("http://example.com/p"), RDF.literal(42), RDF.iri("http://example.com/Graph")}
iex> RDF.Star.Quad.new({EX.S, :p, 42}, :p2, 43, EX.Graph, RDF.PropertyMap.new(p: EX.p, p2: EX.p2))
{{~I<http://example.com/S>, ~I<http://example.com/p>, RDF.literal(42)}, ~I<http://example.com/p2>, RDF.literal(43), ~I<http://example.com/Graph>}
"""
@spec new(
Statement.coercible_subject(),
Statement.coercible_predicate(),
Statement.coercible_object(),
Statement.coercible_graph_name(),
PropertyMap.t() | nil
) :: t
def new(subject, predicate, object, graph_name, property_map \\ nil)
def new(subject, predicate, object, graph_name, nil) do
{
Statement.coerce_subject(subject),
Statement.coerce_predicate(predicate),
Statement.coerce_object(object),
Statement.coerce_graph_name(graph_name)
}
end
def new(subject, predicate, object, graph_name, %PropertyMap{} = property_map) do
{
Statement.coerce_subject(subject, property_map),
Statement.coerce_predicate(predicate, property_map),
Statement.coerce_object(object, property_map),
Statement.coerce_graph_name(graph_name)
}
end
@doc """
Creates a `RDF.Star.Quad` with proper RDF-star values.
An error is raised when the given elements are not coercible to RDF-star values.
Note: The `RDF.quad` function is a shortcut to this function.
## Examples
iex> RDF.Star.Quad.new {"http://example.com/S", "http://example.com/p", 42, "http://example.com/Graph"}
{~I<http://example.com/S>, ~I<http://example.com/p>, RDF.literal(42), ~I<http://example.com/Graph>}
iex> RDF.Star.Quad.new {EX.S, EX.p, 42, EX.Graph}
{RDF.iri("http://example.com/S"), RDF.iri("http://example.com/p"), RDF.literal(42), RDF.iri("http://example.com/Graph")}
iex> RDF.Star.Quad.new {EX.S, EX.p, 42}
{RDF.iri("http://example.com/S"), RDF.iri("http://example.com/p"), RDF.literal(42), nil}
iex> RDF.Star.Quad.new {EX.S, :p, 42, EX.Graph}, RDF.PropertyMap.new(p: EX.p)
{RDF.iri("http://example.com/S"), RDF.iri("http://example.com/p"), RDF.literal(42), RDF.iri("http://example.com/Graph")}
iex> RDF.Star.Quad.new({{EX.S, :p, 42}, :p2, 43, EX.Graph}, RDF.PropertyMap.new(p: EX.p, p2: EX.p2))
{{~I<http://example.com/S>, ~I<http://example.com/p>, RDF.literal(42)}, ~I<http://example.com/p2>, RDF.literal(43), ~I<http://example.com/Graph>}
"""
@spec new(Statement.coercible(), PropertyMap.t() | nil) :: t
def new(statement, property_map \\ nil)
def new({subject, predicate, object, graph_name}, property_map) do
new(subject, predicate, object, graph_name, property_map)
end
def new({subject, predicate, object}, property_map) do
new(subject, predicate, object, nil, property_map)
end
@doc """
Checks if the given tuple is a valid RDF quad.
The elements of a valid RDF-star quad must be RDF terms. On the subject position
only IRIs, blank nodes and triples are allowed, while on the predicate and graph name
position only IRIs allowed. The object position can be any RDF term or triple.
"""
@spec valid?(t | any) :: boolean
def valid?(tuple)
def valid?({_, _, _, _} = quad), do: Statement.valid?(quad)
def valid?(_), do: false
end
|
lib/rdf/star/quad.ex
| 0.88761 | 0.62342 |
quad.ex
|
starcoder
|
defmodule Absinthe.Fixtures.ContactSchema do
use Absinthe.Schema
use Absinthe.Fixture
@bruce %{name: "Bruce", age: 35}
@others [
%{name: "Joe", age: 21},
%{name: "Jill", age: 43}
]
@business %{name: "Someplace", employee_count: 11}
query do
field :person,
type: :person,
resolve: fn _, _ ->
{:ok, @bruce}
end
field :contact,
type: :contact,
args: [
business: [type: :boolean, default_value: false]
],
resolve: fn
%{business: false}, _ ->
{:ok, %{entity: @bruce}}
%{business: true}, _ ->
{:ok, %{entity: @business}}
end
field :first_search_result,
type: :search_result,
resolve: fn _, _ ->
{:ok, @bruce}
end
field :search_results,
type: non_null(list_of(non_null(:search_result))),
resolve: fn _, _ ->
{:ok, [@bruce, @business]}
end
field :profile,
type: :person,
args: [name: [type: non_null(:string)]],
resolve: fn
%{name: "Bruce"}, _ ->
{:ok, @bruce}
_, _ ->
{:ok, nil}
end
end
mutation do
field :person,
type: :person,
args: [
profile: [type: :profile_input]
],
resolve: fn %{profile: profile} ->
# Return it like it's a person
{:ok, profile}
end
end
subscription do
end
input_object :profile_input do
description "The basic details for a person"
field :code, type: non_null(:string)
field :name, type: :string, description: "The person's name", default_value: "Janet"
field :age, type: :integer, description: "The person's age", default_value: 43
end
interface :named_entity do
description "A named entity"
field :name, type: :string
resolve_type fn
%{age: _}, _ ->
:person
%{employee_count: _}, _ ->
:business
end
end
object :person do
description "A person"
field :name, :string
field :age, :integer
field :address, :string, deprecate: "change of privacy policy"
field :others,
type: list_of(:person),
resolve: fn _, _ ->
{:ok, @others}
end
interface :named_entity
end
object :business do
description "A business"
field :name, :string
field :employee_count, :integer
interface :named_entity
end
union :search_result do
description "A search result"
types [:business, :person]
resolve_type fn
%{age: _}, _ ->
:person
%{employee_count: _}, _ ->
:business
end
end
object :contact do
field :entity, :named_entity
import_fields :contact_method
end
object :contact_method do
field :phone_number, :string
field :address, :string
end
scalar :name do
serialize &to_string/1
parse fn
%Absinthe.Blueprint.Input.String{} = string ->
string.value
_ ->
:error
end
end
object :unused do
field :an_unused_field, :string
end
end
|
test/support/fixtures/contact_schema.ex
| 0.628179 | 0.404243 |
contact_schema.ex
|
starcoder
|
defmodule TicTacToe.Board do
@moduledoc false
alias TicTacToe.Board
defstruct [
:player_1,
:player_2,
:tiles,
:scale
]
@doc """
Inits a board with given scale and player tiles
"""
def init(scale, p1 \\ :X, p2 \\ :O) do
%Board{
player_1: p1,
player_2: p2,
tiles: empty_board(scale),
scale: scale
}
end
defp empty_board(scale) do
1..(scale * scale) |> Map.new(fn move -> {move, :empty} end)
end
@doc """
Updates a board with a move for a given player
"""
def update(board, move, player) do
%{board | tiles: update_tiles(board, move, player)}
end
defp update_tiles(board, move, player) do
%{board.tiles | move => Board.tile_symbol(board, player)}
end
@doc """
Returns true if tile at position is empty
"""
def empty_at?(board, move) do
tile = board.tiles[move]
tile == :empty
end
@doc """
Returns a list of possible moves
"""
def possible_moves(board), do: moves_(board.tiles, :empty)
@doc """
Returns a list of moves made by a given player
"""
def moves(board, :player_1), do: moves_(board.tiles, board.player_1)
def moves(board, :player_2), do: moves_(board.tiles, board.player_2)
defp moves_(tiles, tile_type) do
tiles
|> Map.to_list()
|> Enum.filter(fn {_, tile} -> tile == tile_type end)
|> Enum.map(fn {move, _} -> move end)
end
@doc """
Returns true if the given player has won
"""
def winner?(board, player) do
mvs = moves(board, player)
winning_states(board.scale)
|> Enum.map(fn win_state -> match_winning_moves(win_state, mvs) end)
|> Enum.any?(fn xs -> length(xs) == board.scale end)
end
def match_winning_moves(win_state, moves) do
moves |> Enum.filter(fn x -> Enum.member?(win_state, x) end)
end
@doc """
Returns the status of the game
"""
def status(board) do
cond do
winner?(board, :player_1) -> :player_1_win
winner?(board, :player_2) -> :player_2_win
full?(board) -> :draw
true -> :non_terminal
end
end
@doc """
Returns true if all the board tiles have been taken
"""
def full?(board) do
mvs = possible_moves(board) |> length()
mvs == 0
end
@doc """
Gets tile symbol for given player
"""
def tile_symbol(board, player) do
case player do
:player_1 -> board.player_1
:player_2 -> board.player_2
end
end
@doc """
Swaps player for alternate one
"""
def swap_player(:player_1), do: :player_2
def swap_player(:player_2), do: :player_1
@doc """
Swaps tile symbol for alternate one
"""
def swap_symbol(:X), do: :O
def swap_symbol(:O), do: :X
@doc """
Returns all possible winning states for a given size of board
"""
def winning_states(n) do
rows(n) ++ columns(n)
++ [left_diag(n)]
++ [right_diag(n)]
end
defp rows(n), do: 1..(n * n) |> Enum.chunk(n)
defp columns(n), do: 1..n |> Enum.map(fn x -> col n, x end)
defp col(n, y), do: 0..(n - 1) |> Enum.map(fn x -> x * n + y end)
defp left_diag(n), do: 1..n |> Enum.scan(fn _, x -> x + n + 1 end)
defp right_diag(n), do: n..(n + n - 1) |> Enum.scan(fn _, x -> x + n - 1 end)
end
|
lib/tic_tac_toe/board.ex
| 0.877588 | 0.745398 |
board.ex
|
starcoder
|
defmodule Neuron do
defstruct id: nil,
cx_id: nil,
af: nil,
input_idps: [],
output_ids: []
def gen(exoself_pid) do
spawn_link fn -> loop(exoself_pid) end
end
def loop(exoself_pid) do
'''
Standby for initialization order from exoself
'''
receive do
{^exoself_pid, {id, cx_pid, af, input_pidps, output_pids}} ->
loop(id, cx_pid, af, {input_pidps, input_pidps}, output_pids, 0)
end
end
def loop(id, cx_pid, af, {[{input_pid, weights}|next_input_pidps], input_pidps_memory} = input_pidps, output_pids, acc) do
'''
Standby for input signal from preceding neurons/sensors, or for
backup order from cortex or finally for termination order.
'''
receive do
{^input_pid, :forward, input} ->
# Accumulating a single input into the input vector
result = dot(input, weights, 0)
loop(id, cx_pid, af, {next_input_pidps, input_pidps_memory}, output_pids, result+acc)
{^cx_pid, :get_backup} ->
send(cx_pid, {self(), id, input_pidps_memory})
# Go back standby for inputs
loop(id, cx_pid, af, input_pidps, output_pids, acc)
{^cx_pid, :terminate} ->
:ok
end
end
def loop(id, cx_pid, af, {[bias], input_pidps_memory}, output_pids, acc) do
'''
In case if there is a bias at the end of the input vector, take it
in account and apply the given activation function `af`.
'''
output = apply(__MODULE__, af, [acc+bias])
Enum.map(output_pids, fn(output_pid) ->
send(output_pid, {self(), :forward, [output]}) end)
# Clear the accumulator and go back standby for input/termination
loop(id, cx_pid, af, {input_pidps_memory, input_pidps_memory}, output_pids, 0)
end
def loop(id, cx_pid, af, {[], input_pidps_memory}, output_pids, acc) do
'''
If there's no bias at the end of the input vector, simply
apply the given activation function `af` to it.
'''
output = apply(__MODULE__, af, [acc])
Enum.map(output_pids, fn(output_pid) -> send(output_pid, {self(), :forward, [output]}) end)
loop(id, cx_pid, af, {input_pidps_memory, input_pidps_memory}, output_pids, 0)
end
def tanh(x), do: :math.tanh(x)
def dot([i|next_inputs], [w|next_weights], acc) do
dot(next_inputs, next_weights, i*w+acc)
end
def dot([], [bias], acc), do: acc+bias
def dot([], [], acc), do: acc
end
|
lib/neuron.ex
| 0.620852 | 0.528777 |
neuron.ex
|
starcoder
|
defmodule RoboticaUi.Components.Nav do
@moduledoc false
use Scenic.Component
alias Scenic.Cache.Static.Texture
alias Scenic.Graph
import Scenic.Primitives
import Scenic.Clock.Components
def verify(tab) when is_atom(tab), do: {:ok, tab}
def verify(_), do: :invalid_data
# build the path to the static asset file (compile time)
@timezone Application.compile_env(:robotica_common, :timezone)
@schedule_path :code.priv_dir(:robotica_ui) |> Path.join("/static/images/schedule.png")
@local_path :code.priv_dir(:robotica_ui) |> Path.join("/static/images/local.png")
# pre-compute the hash (compile time)
@schedule_hash Scenic.Cache.Support.Hash.file!(@schedule_path, :sha)
@local_hash Scenic.Cache.Support.Hash.file!(@local_path, :sha)
@scenes [
{:clock, {0, 0}},
{:schedule, {0, 100}},
{:local, {0, 200}}
]
defp in_bounding_box({click_x, click_y}, {x, y}) do
x2 = x + 100
y2 = y + 100
click_x >= x and click_x < x2 and click_y >= y and click_y < y2
end
@graph Graph.build(styles: %{}, font_size: 20)
|> rect({100, 400}, fill: :green)
|> line({{0, 100}, {100, 100}}, stroke: {1, :red})
|> line({{0, 200}, {100, 200}}, stroke: {1, :red})
|> line({{0, 300}, {100, 300}}, stroke: {1, :red})
def init(tab, opts) do
schedule_path = :code.priv_dir(:robotica_ui) |> Path.join("/static/images/schedule.png")
local_path = :code.priv_dir(:robotica_ui) |> Path.join("/static/images/local.png")
Texture.load(schedule_path, @schedule_hash, scope: :global)
Texture.load(local_path, @local_hash, scope: :global)
scenes = Enum.filter(@scenes, fn {scene_tab, _} -> scene_tab == tab end)
icon_position =
case scenes do
[{_, icon_position} | _] -> icon_position
_ -> {0, 0}
end
graph =
@graph
|> rect({100, 100}, fill: :red, translate: icon_position)
|> analog_clock(radius: 40, translate: {50, 50}, timezone: @timezone)
|> rect({80, 80}, fill: {:black, 0}, translate: {10, 10})
|> rect({80, 80}, fill: {:image, @schedule_hash}, translate: {10, 110})
|> rect({80, 80}, fill: {:image, @local_hash}, translate: {10, 210})
{:ok, %{graph: graph, viewport: opts[:viewport]}, push: graph}
end
def handle_input({:cursor_button, {:left, :press, 0, click_pos}}, _context, state) do
scenes = Enum.filter(@scenes, fn {_, icon_pos} -> in_bounding_box(click_pos, icon_pos) end)
case scenes do
[{tab, _} | _] -> RoboticaUi.RootManager.set_tab(tab)
_ -> nil
end
RoboticaUi.RootManager.reset_screensaver()
{:noreply, state}
end
def handle_input(_event, _context, state) do
RoboticaUi.RootManager.reset_screensaver()
{:noreply, state}
end
end
|
robotica_ui/lib/components/nav.ex
| 0.711732 | 0.48438 |
nav.ex
|
starcoder
|
defmodule Moeda do
@moduledoc """
Este módulo possui listas com informações sobre as moedas.
A lista está em compliance com o ISO 4217.
Acesse https://pt.wikipedia.org/wiki/ISO_4217 para saber mais.
"""
@doc """
Lista as informações das moedas.
## Exemplo
iex> Moeda.moeda_info[:AED].peso
2
iex> Moeda.moeda_info[:USD].simbolo
$
"""
def info do
[
AED: %{
nome: "<NAME>",
simbolo: "د.إ",
peso: 2,
expoente: 2
},
AFN: %{
nome: "Afghani",
simbolo: "؋",
peso: 1,
expoente: 2
},
ALL: %{
nome: "Lek",
simbolo: "Lek",
peso: 1,
expoente: 2
},
AMD: %{
nome: "<NAME>",
simbolo: "AMD",
peso: 1,
expoente: 2
},
ANG: %{
nome: "Netherlands Antillian Guilder",
simbolo: "ƒ",
peso: 1,
expoente: 2
},
AOA: %{
nome: "Kwanza",
simbolo: "Kz",
peso: 1,
expoente: 2
},
ARS: %{
nome: "<NAME>",
simbolo: "$",
peso: 1,
expoente: 2
},
AUD: %{
nome: "Australian Dollar",
simbolo: "$",
peso: 1,
expoente: 2
},
AWG: %{
nome: "<NAME>",
simbolo: "ƒ",
peso: 1,
expoente: 2
},
AZN: %{
nome: "Azerbaijan<NAME>",
simbolo: "ман",
peso: 1,
expoente: 2
},
BAM: %{
nome: "Convertible Marks",
simbolo: "KM",
peso: 1,
expoente: 2
},
BBD: %{
nome: "<NAME>",
simbolo: "$",
peso: 1,
expoente: 2
},
BDT: %{
nome: "Taka",
simbolo: "৳",
peso: 1,
expoente: 2
},
BGN: %{
nome: "Bulgarian Lev",
simbolo: "лв",
peso: 1,
expoente: 2
},
BHD: %{
nome: "<NAME>",
simbolo: ".د.ب",
peso: 1,
expoente: 3
},
BIF: %{
nome: "<NAME>",
simbolo: "FBu",
peso: 1,
expoente: 0
},
BMD: %{
nome: "Bermudian Dollar (customarily known as Bermuda Dollar)",
simbolo: "$",
peso: 1,
expoente: 2
},
BND: %{
nome: "<NAME>",
simbolo: "$",
peso: 1,
expoente: 2
},
BOB: %{
nome: "<NAME>",
simbolo: "$b",
peso: 1,
expoente: 2
},
BOV: %{
nome: "<NAME>",
simbolo: "$b",
peso: 1,
expoente: 2
},
BRL: %{
nome: "Brazilian Real",
simbolo: "R$",
peso: 5,
expoente: 2
},
BSD: %{
nome: "Bah<NAME>",
simbolo: "$",
peso: 1,
expoente: 2
},
BTN: %{
nome: "Indian Rupee Ngultrum",
simbolo: "Nu.",
peso: 1,
expoente: 2
},
BWP: %{
nome: "Pula",
simbolo: "P",
peso: 1,
expoente: 2
},
BYR: %{
nome: "Belarussian Ruble",
simbolo: "p.",
peso: 1,
expoente: 0
},
BZD: %{
nome: "<NAME>",
simbolo: "BZ$",
peso: 1,
expoente: 2
},
CAD: %{
nome: "Canad<NAME>",
simbolo: "$",
peso: 1,
expoente: 2
},
CDF: %{
nome: "<NAME>",
simbolo: "CF",
peso: 1,
expoente: 2
},
CHF: %{
nome: "<NAME>",
simbolo: "CHF",
peso: 1,
expoente: 2
},
CLF: %{
nome: "Chilean Peso Unidades de fomento",
simbolo: "$",
peso: 1,
expoente: 4
},
CLP: %{
nome: "Chilean Peso Unidades de fomento",
simbolo: "$",
peso: 1,
expoente: 0
},
CNY: %{
nome: "<NAME>",
simbolo: "¥",
peso: 1,
expoente: 2
},
COP: %{
nome: "Colombian Peso",
simbolo: "$",
peso: 1,
expoente: 2
},
COU: %{
nome: "Colombian Peso Unidad de Valor Real",
simbolo: "$",
peso: 1,
expoente: 2
},
CRC: %{
nome: "<NAME>",
simbolo: "₡",
peso: 1,
expoente: 2
},
CUC: %{
nome: "Cuban Peso Peso Convertible",
simbolo: "₱",
peso: 1,
expoente: 2
},
CUP: %{
nome: "Cuban Peso Peso Convertible",
simbolo: "₱",
peso: 1,
expoente: 2
},
CVE: %{
nome: "Cape Verde Escudo",
simbolo: "$",
peso: 1,
expoente: 0
},
CZK: %{
nome: "Czech Koruna",
simbolo: "Kč",
peso: 1,
expoente: 2
},
DJF: %{
nome: "<NAME>",
simbolo: "Fdj",
peso: 1,
expoente: 0
},
DKK: %{
nome: "<NAME>",
simbolo: "kr",
peso: 1,
expoente: 2
},
DOP: %{
nome: "Dominican Peso",
simbolo: "RD$",
peso: 1,
expoente: 2
},
DZD: %{
nome: "Al<NAME>",
simbolo: "دج",
peso: 1,
expoente: 2
},
EEK: %{
nome: "Kroon",
simbolo: "KR",
peso: 1,
expoente: 2
},
EGP: %{
nome: "Egyptian Pound",
simbolo: "£",
peso: 1,
expoente: 2
},
ERN: %{
nome: "Nakfa",
simbolo: "Nfk",
peso: 1,
expoente: 2
},
ETB: %{
nome: "Ethiop<NAME>",
simbolo: "Br",
peso: 1,
expoente: 2
},
EUR: %{
nome: "Euro",
simbolo: "€",
peso: 1,
expoente: 2
},
FJD: %{
nome: "Fiji Dollar",
simbolo: "$",
peso: 1,
expoente: 2
},
FKP: %{
nome: "Falkland Islands Pound",
simbolo: "£",
peso: 1,
expoente: 2
},
GBP: %{
nome: "Pound Sterling",
simbolo: "£",
peso: 1,
expoente: 2
},
GEL: %{
nome: "Lari",
simbolo: "₾",
peso: 1,
expoente: 2
},
GHS: %{
nome: "Cedi",
simbolo: "GH₵",
peso: 1,
expoente: 2
},
GIP: %{
nome: "G<NAME>",
simbolo: "£",
peso: 1,
expoente: 2
},
GMD: %{
nome: "Dalasi",
simbolo: "D",
peso: 1,
expoente: 2
},
GNF: %{
nome: "<NAME>",
simbolo: "FG",
peso: 1,
expoente: 0
},
GTQ: %{
nome: "Quetzal",
simbolo: "Q",
peso: 1,
expoente: 2
},
GYD: %{
nome: "Guyana Dollar",
simbolo: "$",
peso: 1,
expoente: 2
},
HKD: %{
nome: "Hong Kong Dollar",
simbolo: "$",
peso: 1,
expoente: 2
},
HNL: %{
nome: "Lempira",
simbolo: "L",
peso: 1,
expoente: 2
},
HRK: %{
nome: "<NAME>",
simbolo: "kn",
peso: 1,
expoente: 2
},
HTG: %{
nome: "<NAME>",
simbolo: " ",
peso: 1,
expoente: 2
},
HUF: %{
nome: "Forint",
simbolo: "Ft",
peso: 1,
expoente: 2
},
IDR: %{
nome: "Rupiah",
simbolo: "Rp",
peso: 1,
expoente: 2
},
ILS: %{
nome: "New Israeli Sheqel",
simbolo: "₪",
peso: 1,
expoente: 2
},
INR: %{
nome: "Indian Rupee",
simbolo: "₹",
peso: 1,
expoente: 2
},
IQD: %{
nome: "<NAME>",
simbolo: "ع.د",
peso: 1,
expoente: 3
},
IRR: %{
nome: "<NAME>",
simbolo: "﷼",
peso: 1,
expoente: 2
},
ISK: %{
nome: "<NAME>",
simbolo: "kr",
peso: 1,
expoente: 0
},
JMD: %{
nome: "<NAME>",
simbolo: "J$",
peso: 1,
expoente: 2
},
JOD: %{
nome: "<NAME>",
simbolo: "JOD",
peso: 1,
expoente: 3
},
JPY: %{
nome: "Yen",
simbolo: "¥",
peso: 1,
expoente: 0
},
KES: %{
nome: "<NAME>",
simbolo: "KSh",
peso: 1,
expoente: 2
},
KGS: %{
nome: "Som",
simbolo: "лв",
peso: 1,
expoente: 2
},
KHR: %{
nome: "Riel",
simbolo: "៛",
peso: 1,
expoente: 2
},
KMF: %{
nome: "<NAME>",
simbolo: "CF",
peso: 1,
expoente: 0
},
KPW: %{
nome: "North Korean Won",
simbolo: "₩",
peso: 1,
expoente: 2
},
KRW: %{
nome: "Won",
simbolo: "₩",
peso: 1,
expoente: 0
},
KWD: %{
nome: "<NAME>",
simbolo: "د.ك",
peso: 1,
expoente: 3
},
KYD: %{
nome: "<NAME>",
simbolo: "$",
peso: 1,
expoente: 2
},
KZT: %{
nome: "Tenge",
simbolo: "лв",
peso: 1,
expoente: 2
},
LAK: %{
nome: "Kip",
simbolo: "₭",
peso: 1,
expoente: 2
},
LBP: %{
nome: "Lebanese Pound",
simbolo: "£",
peso: 1,
expoente: 2
},
LKR: %{
nome: "Sri Lanka Rupee",
simbolo: "₨",
peso: 1,
expoente: 2
},
LRD: %{
nome: "Liberian Dollar",
simbolo: "$",
peso: 1,
expoente: 2
},
LSL: %{
nome: "<NAME>",
simbolo: " ",
peso: 1,
expoente: 2
},
LTL: %{
nome: "<NAME>",
simbolo: "Lt",
peso: 1,
expoente: 2
},
LVL: %{
nome: "<NAME>",
simbolo: "Ls",
peso: 1,
expoente: 2
},
LYD: %{
nome: "<NAME>",
simbolo: "ل.د",
peso: 1,
expoente: 3
},
MAD: %{
nome: "<NAME>",
simbolo: "د.م.",
peso: 1,
expoente: 2
},
MDL: %{
nome: "<NAME>",
simbolo: "MDL",
peso: 1,
expoente: 2
},
MGA: %{
nome: "<NAME>",
simbolo: "Ar",
peso: 1,
expoente: 2
},
MKD: %{
nome: "Denar",
simbolo: "ден",
peso: 1,
expoente: 2},
MMK: %{
nome: "Kyat",
simbolo: "K",
peso: 1,
expoente: 2
},
MNT: %{
nome: "Tugrik",
simbolo: "₮",
peso: 1,
expoente: 2
},
MOP: %{
nome: "Pataca",
simbolo: "MOP$",
peso: 1,
expoente: 2
},
MRO: %{
nome: "Ouguiya",
simbolo: "UM",
peso: 1,
expoente: 2
},
MUR: %{
nome: "<NAME>",
simbolo: "₨",
peso: 1,
expoente: 2
},
MVR: %{
nome: "Rufiyaa",
simbolo: "Rf",
peso: 1,
expoente: 2
},
MWK: %{
nome: "Kwacha",
simbolo: "MK",
peso: 1,
expoente: 2
},
MXN: %{
nome: "Mexican Peso",
simbolo: "$",
peso: 1,
expoente: 2
},
MXV: %{
nome: "Mexican Peso Mexican Unidad de Inversion (UDI)",
simbolo: "UDI",
peso: 1,
expoente: 2
},
MYR: %{
nome: "<NAME>",
simbolo: "RM",
peso: 1,
expoente: 2
},
MZN: %{
nome: "Metical",
simbolo: "MT",
peso: 1,
expoente: 2
},
NAD: %{
nome: "<NAME>",
simbolo: "$",
peso: 1,
expoente: 2
},
NGN: %{
nome: "Naira",
simbolo: "₦",
peso: 1,
expoente: 2
},
NIO: %{
nome: "<NAME>",
simbolo: "C$",
peso: 1,
expoente: 2
},
NOK: %{
nome: "<NAME>",
simbolo: "kr",
peso: 1,
expoente: 2
},
NPR: %{
nome: "Nepalese Rupee",
simbolo: "₨",
peso: 1,
expoente: 2
},
NZD: %{
nome: "New Zealand Dollar",
simbolo: "$",
peso: 1,
expoente: 2
},
OMR: %{
nome: "<NAME>",
simbolo: "﷼",
peso: 1,
expoente: 3
},
PAB: %{
nome: "<NAME>",
simbolo: "B/.",
peso: 1,
expoente: 2
},
PEN: %{
nome: "<NAME>",
simbolo: "S/.",
peso: 1,
expoente: 2
},
PGK: %{
nome: "Kina",
simbolo: "K",
peso: 1,
expoente: 2
},
PHP: %{
nome: "<NAME>",
simbolo: "Php",
peso: 1,
expoente: 2
},
PKR: %{
nome: "Pakistan Rupee",
simbolo: "₨",
peso: 1,
expoente: 2
},
PLN: %{
nome: "Zloty",
simbolo: "zł",
peso: 1,
expoente: 2
},
PYG: %{
nome: "Guarani",
simbolo: "Gs",
peso: 1,
expoente: 0
},
QAR: %{
nome: "<NAME>",
simbolo: "﷼",
peso: 1,
expoente: 2
},
RON: %{
nome: "New Leu",
simbolo: "lei",
peso: 1,
expoente: 2
},
RSD: %{
nome: "<NAME>",
simbolo: "Дин.",
peso: 1,
expoente: 2
},
RUB: %{
nome: "Russian Ruble",
simbolo: "₽",
peso: 1,
expoente: 2
},
RWF: %{
nome: "<NAME>",
simbolo: " ",
peso: 1,
expoente: 0
},
SAR: %{
nome: "<NAME>",
simbolo: "﷼",
peso: 1,
expoente: 2
},
SBD: %{
nome: "Solomon Islands Dollar",
simbolo: "$",
peso: 1,
expoente: 2
},
SCR: %{
nome: "Seychelles Rupee",
simbolo: "₨",
peso: 1,
expoente: 2
},
SDG: %{
nome: "Sudanese Pound",
simbolo: "SDG",
peso: 1,
expoente: 2
},
SEK: %{
nome: "Swedish Krona",
simbolo: "kr",
peso: 1,
expoente: 2
},
SGD: %{
nome: "Singapore Dollar",
simbolo: "$",
peso: 1,
expoente: 2
},
SHP: %{
nome: "<NAME>",
simbolo: "£",
peso: 1,
expoente: 2
},
SLL: %{
nome: "Leone",
simbolo: "Le",
peso: 1,
expoente: 2
},
SOS: %{
nome: "<NAME>",
simbolo: "S",
peso: 1,
expoente: 2
},
SRD: %{
nome: "<NAME>",
simbolo: "$",
peso: 1,
expoente: 2
},
STD: %{
nome: "Dobra",
simbolo: "Db",
peso: 1,
expoente: 2
},
SVC: %{
nome: "El Salvador Colon US Dollar",
simbolo: "$",
peso: 1,
expoente: 2
},
SYP: %{
nome: "<NAME>",
simbolo: "£",
peso: 1,
expoente: 2
},
SZL: %{
nome: "Lilangeni",
simbolo: "E",
peso: 1,
expoente: 2
},
THB: %{
nome: "Baht",
simbolo: "฿",
peso: 1,
expoente: 2
},
TJS: %{
nome: "Somoni",
simbolo: " ",
peso: 1,
expoente: 2
},
TMT: %{
nome: "Manat",
simbolo: "₼",
peso: 1,
expoente: 2
},
TND: %{
nome: "<NAME>",
simbolo: "د.ت",
peso: 1,
expoente: 2
},
TOP: %{
nome: "Pa'anga",
simbolo: "T$",
peso: 1,
expoente: 2
},
TRY: %{
nome: "Tur<NAME>",
simbolo: "TL",
peso: 1,
expoente: 2
},
TTD: %{
nome: "Trinidad and Tobago Dollar",
simbolo: "TT$",
peso: 1,
expoente: 2
},
TWD: %{
nome: "New Taiwan Dollar",
simbolo: "NT$",
peso: 1,
expoente: 2
},
TZS: %{
nome: "<NAME>",
simbolo: "Tsh",
peso: 1,
expoente: 2
},
UAH: %{
nome: "Hryvnia",
simbolo: "₴",
peso: 1,
expoente: 2
},
UGX: %{
nome: "<NAME>",
simbolo: "Ush",
peso: 1,
expoente: 0
},
USD: %{
nome: "US Dollar",
simbolo: "$",
peso: 10,
expoente: 2
},
UYI: %{
nome: "Peso Uruguayo Uruguay Peso en Unidades Indexadas",
simbolo: "$U",
peso: 1,
expoente: 0
},
UYU: %{
nome: "Peso Uruguayo Uruguay Peso en Unidades Indexadas",
simbolo: "$U",
peso: 1,
expoente: 2
},
UZS: %{
nome: "<NAME>",
simbolo: "лв",
peso: 1,
expoente: 2
},
VEF: %{
nome: "<NAME>",
simbolo: "Bs",
peso: 1,
expoente: 2
},
VND: %{
nome: "Dong",
simbolo: "₫",
peso: 1,
expoente: 0
},
VUV: %{
nome: "Vatu",
simbolo: "VT",
peso: 1,
expoente: 0
},
WST: %{
nome: "Tala",
simbolo: "WS$",
peso: 1,
expoente: 2
},
XAF: %{
nome: "<NAME>",
simbolo: "FCFA",
peso: 1,
expoente: 0
},
XAG: %{
nome: "Silver",
simbolo: " ",
peso: 1,
expoente: 2
},
XAU: %{
nome: "Gold",
simbolo: " ",
peso: 1,
expoente: 2
},
XBA: %{
nome: "Bond Markets Units European Composite Unit (EURCO)",
simbolo: " ",
peso: 1,
expoente: 2
},
XBB: %{
nome: "European Monetary Unit (E.M.U.-6)",
simbolo: " ",
peso: 1,
expoente: 2
},
XBC: %{
nome: "European Unit of Account 9(E.U.A.-9)",
simbolo: " ",
peso: 1,
expoente: 2
},
XBD: %{
nome: "European Unit of Account 17(E.U.A.-17)",
simbolo: " ",
peso: 1,
expoente: 2
},
XCD: %{
nome: "East Caribbean Dollar",
simbolo: "$",
peso: 1,
expoente: 2
},
XDR: %{
nome: "SDR",
simbolo: " ",
peso: 1,
expoente: 2
},
XFU: %{
nome: "UIC-Franc",
simbolo: " ",
peso: 1,
expoente: 2
},
XOF: %{
nome: "<NAME>",
simbolo: " ",
peso: 1,
expoente: 0
},
XPD: %{
nome: "Palladium",
simbolo: " ",
peso: 1,
expoente: 2
},
XPF: %{
nome: "<NAME>",
simbolo: " ",
peso: 1,
expoente: 0
},
XPT: %{
nome: "Platinum",
simbolo: " ",
peso: 1,
expoente: 2
},
XTS: %{
nome: "Codes specifically reserved for testing purposes",
simbolo: " ",
peso: 1,
expoente: 2
},
YER: %{
nome: "<NAME>",
simbolo: "﷼",
peso: 1,
expoente: 2
},
ZAR: %{
nome: "Rand",
simbolo: "R",
peso: 1,
expoente: 2
},
ZMK: %{
nome: "<NAME>",
simbolo: "ZK",
peso: 1,
expoente: 2
},
ZWL: %{
nome: "<NAME>",
simbolo: "$",
peso: 1,
expoente: 2
}
]
end
@doc """
Lista com as moedas para a criação de novos usuários no sistema.
Todas moedas começam com valor 0.
## Exemplo
iex> usuario[Pedro: Moeda.novo()]
[AED: 0, AFN: 0, ALL: 0, AMD: 0, ANG: 0, AOA: 0, ARS: 0, AUD: 0, AWG: 0, AZN: 0,
BAM: 0, BBD: 0, BDT: 0, BGN: 0, BHD: 0, BIF: 0, BMD: 0, BND: 0, BOB: 0, BOV: 0,...
"""
def novo do
[
AED: 0,
AFN: 0,
ALL: 0,
AMD: 0,
ANG: 0,
AOA: 0,
ARS: 0,
AUD: 0,
AWG: 0,
AZN: 0,
BAM: 0,
BBD: 0,
BDT: 0,
BGN: 0,
BHD: 0,
BIF: 0,
BMD: 0,
BND: 0,
BOB: 0,
BOV: 0,
BRL: 0,
BSD: 0,
BTN: 0,
BWP: 0,
BYR: 0,
BZD: 0,
CAD: 0,
CDF: 0,
CHF: 0,
CLF: 0,
CLP: 0,
CNY: 0,
COP: 0,
COU: 0,
CRC: 0,
CUC: 0,
CUP: 0,
CVE: 0,
CZK: 0,
DJF: 0,
DKK: 0,
DOP: 0,
DZD: 0,
EEK: 0,
EGP: 0,
ERN: 0,
ETB: 0,
EUR: 0,
FJD: 0,
FKP: 0,
GBP: 0,
GEL: 0,
GHS: 0,
GIP: 0,
GMD: 0,
GNF: 0,
GTQ: 0,
GYD: 0,
HKD: 0,
HNL: 0,
HRK: 0,
HTG: 0,
HUF: 0,
IDR: 0,
ILS: 0,
INR: 0,
IQD: 0,
IRR: 0,
ISK: 0,
JMD: 0,
JOD: 0,
JPY: 0,
KES: 0,
KGS: 0,
KHR: 0,
KMF: 0,
KPW: 0,
KRW: 0,
KWD: 0,
KYD: 0,
KZT: 0,
LAK: 0,
LBP: 0,
LKR: 0,
LRD: 0,
LSL: 0,
LTL: 0,
LVL: 0,
LYD: 0,
MAD: 0,
MDL: 0,
MGA: 0,
MKD: 0,
MMK: 0,
MNT: 0,
MOP: 0,
MRO: 0,
MUR: 0,
MVR: 0,
MWK: 0,
MXN: 0,
MXV: 0,
MYR: 0,
MZN: 0,
NAD: 0,
NGN: 0,
NIO: 0,
NOK: 0,
NPR: 0,
NZD: 0,
OMR: 0,
PAB: 0,
PEN: 0,
PGK: 0,
PHP: 0,
PKR: 0,
PLN: 0,
PYG: 0,
QAR: 0,
RON: 0,
RSD: 0,
RUB: 0,
RWF: 0,
SAR: 0,
SBD: 0,
SCR: 0,
SDG: 0,
SEK: 0,
SGD: 0,
SHP: 0,
SLL: 0,
SOS: 0,
SRD: 0,
STD: 0,
SVC: 0,
SYP: 0,
SZL: 0,
THB: 0,
TJS: 0,
TMT: 0,
TND: 0,
TOP: 0,
TRY: 0,
TTD: 0,
TWD: 0,
TZS: 0,
UAH: 0,
UGX: 0,
USD: 0,
UYI: 0,
UYU: 0,
UZS: 0,
VEF: 0,
VND: 0,
VUV: 0,
WST: 0,
XAF: 0,
XAG: 0,
XAU: 0,
XBA: 0,
XBB: 0,
XBC: 0,
XBD: 0,
XCD: 0,
XDR: 0,
XFU: 0,
XOF: 0,
XPD: 0,
XPF: 0,
XPT: 0,
XTS: 0,
YER: 0,
ZAR: 0,
ZMK: 0,
ZWL: 0
]
end
end
|
lib/financeiro/moeda.ex
| 0.631026 | 0.422028 |
moeda.ex
|
starcoder
|
defmodule Etherscan.API.Accounts do
@moduledoc """
Module to wrap Etherscan account endpoints.
[Etherscan API Documentation](https://etherscan.io/apis#accounts)
"""
use Etherscan.API
use Etherscan.Constants
alias Etherscan.{MinedBlock, MinedUncle, Transaction, InternalTransaction}
@account_transaction_default_params %{
startblock: 0,
endblock: nil,
sort: "asc",
page: 1,
offset: 20
}
@blocks_mined_default_params %{
page: 1,
offset: 20
}
@doc """
Get ether balance for a single `address`.
## Example
iex> Etherscan.get_balance("#{@test_address1}")
{:ok, #{@test_address1_balance}}
"""
@spec get_balance(address :: String.t(), network :: String.t()) :: {:ok, non_neg_integer()} | {:error, atom()}
def get_balance(address, network \\ :default)
def get_balance(address, network) when is_address(address) do
"account"
|> get("balance", %{address: address, tag: "latest"}, network)
|> parse()
|> format_balance()
|> wrap(:ok)
end
def get_balance(_, _), do: @error_invalid_address
@doc """
Get ether balance for a list of multiple `addresses`, up to a maximum of 20.
## Example
iex> addresses = [
"#{@test_address1}",
"#{@test_address2}",get_logs/2
]
iex> Etherscan.get_balances(addresses)
{:ok, [#{@test_address1_balance}, #{@test_address2_balance}]}
"""
@spec get_balances(addresses :: list(String.t()), network :: String.t()) :: {:ok, map()} | {:error, atom()}
def get_balances(addresses, network \\ :default)
def get_balances([head | _] = addresses, network)
when is_list(addresses) and is_address(head) and length(addresses) <= 20 do
"account"
|> get("balancemulti", %{address: Enum.join(addresses, ","), tag: "latest"}, network)
|> parse()
|> Enum.map(fn account ->
Map.update(account, "balance", 0, &format_balance/1)
end)
|> wrap(:ok)
end
def get_balances(_, _), do: @error_invalid_addresses
@doc """
Get a list of 'Normal' transactions by `address`.
Returns up to a maximum of the last 10,000 transactions only.
## Example
iex> params = %{
page: 1, # Page number
offset: 10, # Max records returned
sort: "asc", # Sort returned records
startblock: 0, # Start block number
endblock: 99999999, # End block number
}
iex> Etherscan.get_transactions("#{@test_address1}", params)
{:ok, [%Etherscan.Transaction{}]}
"""
@spec get_transactions(address :: String.t(), params :: map(), network :: String.t()) ::
{:ok, list(Transaction.t())} | {:error, atom()}
def get_transactions(address, params \\ %{}, network \\ :default)
def get_transactions(address, params, network) when is_address(address) do
params =
params
|> merge_params(@account_transaction_default_params)
|> Map.put(:address, address)
"account"
|> get("txlist", params, network)
|> parse(as: %{"result" => [%Transaction{}]})
|> wrap(:ok)
end
def get_transactions(_, _, _), do: @error_invalid_address
@doc """
Get a list of 'ERC20 - Token Transfer Events' by `address`.
Returns up to a maximum of the last 10,000 transactions only.
## Example
iex> params = %{
page: 1, # Page number
offset: 10, # Max records returned
sort: "asc", # Sort returned records
startblock: 0, # Start block number
endblock: 99999999, # End block number
}
iex> Etherscan.get_transactions("#{@test_address1}", params)
{:ok, [%Etherscan.Transaction{}]}
"""
@spec get_ERC20_transactions(address :: String.t(), params :: map(), network :: String.t()) ::
{:ok, list(Transaction.t())} | {:error, atom()}
def get_ERC20_transactions(address, params \\ %{}, network \\ :default)
def get_ERC20_transactions(address, params, network) when is_address(address) do
params =
params
|> merge_params(@account_transaction_default_params)
|> Map.put(:address, address)
"account"
|> get("tokentx", params, network)
|> parse(as: %{"result" => [%Transaction{}]})
|> wrap(:ok)
end
def get_ERC20_transactions(_, _, _), do: @error_invalid_address
@doc """
Get a list of 'Internal' transactions by `address`.
Returns up to a maximum of the last 10,000 transactions only.
## Example
iex> params = %{
page: 1, # Page number
offset: 10, # Max records returned
sort: "asc", # Sort returned records
startblock: 0, # Start block number
endblock: 99999999, # End block number
}
iex> Etherscan.get_internal_transactions("#{@test_address1}", params)
{:ok, [%Etherscan.InternalTransaction{}]}
"""
@spec get_internal_transactions(address :: String.t(), params :: map(), network :: String.t()) ::
{:ok, list(InternalTransaction.t())} | {:error, atom()}
def get_internal_transactions(address, params \\ %{}, network \\ :default)
def get_internal_transactions(address, params, network) when is_address(address) do
params =
params
|> merge_params(@account_transaction_default_params)
|> Map.put(:address, address)
"account"
|> get("txlistinternal", params, network)
|> parse(as: %{"result" => [%InternalTransaction{}]})
|> wrap(:ok)
end
def get_internal_transactions(_, _, _), do: @error_invalid_address
@doc """
Get a list of 'Internal Transactions' by `transaction_hash`.
Returns up to a maximum of the last 10,000 transactions only.
## Example
iex> Etherscan.get_internal_transactions_by_hash("#{@test_transaction_hash}")
{:ok, [%Etherscan.InternalTransaction{}]}
"""
@spec get_internal_transactions_by_hash(transaction_hash :: String.t(), network :: String.t()) ::
{:ok, list(InternalTransaction.t())} | {:error, atom()}
def get_internal_transactions_by_hash(transaction_hash, network \\ :default)
def get_internal_transactions_by_hash(transaction_hash, network) when is_address(transaction_hash) do
"account"
|> get("txlistinternal", %{txhash: transaction_hash}, network)
|> parse(as: %{"result" => [%InternalTransaction{hash: transaction_hash}]})
|> wrap(:ok)
end
def get_internal_transactions_by_hash(_, _), do: @error_invalid_transaction_hash
@doc """
Get a list of blocks mined by `address`.
## Example
iex> params = %{
page: 1, # Page number
offset: 10, # Max records returned
}
iex> Etherscan.get_blocks_mined("#{@test_miner_address}", params)
{:ok, [%Etherscan.MinedBlock{}]}
"""
@spec get_blocks_mined(address :: String.t(), params :: map(), network :: String.t()) ::
{:ok, list(MinedBlock.t())} | {:error, atom()}
def get_blocks_mined(address, params \\ %{}, network \\ :default)
def get_blocks_mined(address, params, network) when is_address(address) do
params =
params
|> merge_params(@blocks_mined_default_params)
|> Map.put(:blocktype, "blocks")
|> Map.put(:address, address)
"account"
|> get("getminedblocks", params, network)
|> parse(as: %{"result" => [%MinedBlock{}]})
|> wrap(:ok)
end
def get_blocks_mined(_, _, _), do: @error_invalid_address
@doc """
Get a list of uncles mined by `address`.
## Example
iex> params = %{
page: 1, # Page number
offset: 10, # Max records returned
}
iex> Etherscan.get_uncles_mined("#{@test_miner_address}", params)
{:ok, [%Etherscan.MinedUncle{}]}
"""
@spec get_uncles_mined(address :: String.t(), params :: map(), network :: String.t()) ::
{:ok, list(MinedUncle.t())} | {:error, atom()}
def get_uncles_mined(address, params \\ %{}, network \\ :default)
def get_uncles_mined(address, params, network) when is_address(address) do
params =
params
|> merge_params(@blocks_mined_default_params)
|> Map.put(:blocktype, "uncles")
|> Map.put(:address, address)
"account"
|> get("getminedblocks", params, network)
|> parse(as: %{"result" => [%MinedUncle{}]})
|> wrap(:ok)
end
def get_uncles_mined(_, _, _), do: @error_invalid_address
@doc """
Get the ERC20 token balance of the `address` for token at `token_address`.
[More Info](https://etherscan.io/apis#tokens)
## Example
iex> address = "#{@test_token_owner_address}"
iex> token_address = "#{@test_token_address}"
iex> Etherscan.get_token_balance(address, token_address)
{:ok, #{@test_token_address_balance}}
"""
@spec get_token_balance(address :: String.t(), token_address :: String.t(), network :: String.t()) ::
{:ok, non_neg_integer()} | {:error, atom()}
def get_token_balance(address, token_address, network \\ :default)
def get_token_balance(address, token_address, network)
when is_address(address) and is_address(token_address) do
"account"
|> get("tokenbalance", %{address: address, contractaddress: token_address, tag: "latest"}, network)
|> parse()
|> String.to_integer()
|> wrap(:ok)
end
def get_token_balance(address, token_address, network)
when not is_address(address) and is_address(token_address),
do: @error_invalid_address
def get_token_balance(address, token_address, network)
when not is_address(token_address) and is_address(address),
do: @error_invalid_token_address
def get_token_balance(_, _, _), do: @error_invalid_address_and_token_address
end
|
lib/etherscan/api/accounts.ex
| 0.926976 | 0.444022 |
accounts.ex
|
starcoder
|
defmodule Appsignal.TransactionRegistry do
@moduledoc """
Internal module which keeps a registry of the transaction handles
linked to their originating process.
This is used on various places to link a calling process to its transaction.
For instance, the `Appsignal.ErrorHandler` module uses it to be able to
complete the transaction in case the originating process crashed.
The transactions are stored in an ETS table (with
`{:write_concurrency, true}`, so no bottleneck is created); and the
originating process is monitored to clean up the ETS table when the
process has finished.
"""
require Logger
alias Appsignal.{Config, Transaction}
alias Appsignal.Transaction.{ETS, Receiver}
@doc """
Register the current process as the owner of the given transaction.
"""
@spec register(Transaction.t()) :: :ok
def register(transaction) do
if Config.active?() && receiver_alive?() do
pid = self()
true = ETS.insert({pid, transaction, Receiver.monitor(pid)})
:ok
end
end
@doc """
Given a process ID, return its associated transaction.
"""
@spec lookup(pid) :: Transaction.t() | nil
def lookup(pid) do
case Config.active?() && receiver_alive?() && ETS.lookup(pid) do
[{^pid, %Transaction{} = transaction, _}] -> transaction
[{^pid, %Transaction{} = transaction}] -> transaction
[{^pid, :ignore}] -> :ignored
_ -> nil
end
end
@doc false
@spec lookup(pid, boolean) :: Transaction.t() | nil | :removed
def lookup(pid, return_removed) do
IO.warn(
"Appsignal.TransactionRegistry.lookup/2 is deprecated. Use Appsignal.TransactionRegistry.lookup/1 instead"
)
case receiver_alive?() && ETS.lookup(pid) do
[{^pid, :removed}] ->
case return_removed do
false -> nil
true -> :removed
end
[{^pid, transaction, _}] ->
transaction
[{^pid, transaction}] ->
transaction
false ->
nil
[] ->
nil
end
end
@doc """
Unregister the current process as the owner of the given transaction.
"""
@spec remove_transaction(Transaction.t()) :: :ok | {:error, :not_found} | {:error, :no_receiver}
def remove_transaction(%Transaction{} = transaction) do
if receiver_alive?() do
Receiver.demonitor(transaction)
remove(transaction)
else
{:error, :no_receiver}
end
end
defp remove(transaction) do
case pids_and_monitor_references(transaction) do
[[_pid, _reference] | _] = pids_and_refs ->
delete(pids_and_refs)
[[_pid] | _] = pids ->
delete(pids)
[] ->
{:error, :not_found}
end
end
@doc """
Ignore a process in the error handler.
"""
@spec ignore(pid()) :: :ok
def ignore(pid) do
if receiver_alive?() do
ETS.insert({pid, :ignore})
:ok
else
{:error, :no_receiver}
end
end
@doc """
Check if a progress is ignored.
"""
@deprecated "Use Appsignal.TransactionRegistry.lookup/1 instead."
@spec ignored?(pid()) :: boolean()
def ignored?(pid) do
case receiver_alive?() && ETS.lookup(pid) do
[{^pid, :ignore}] -> true
_ -> false
end
end
defp delete([[pid, _] | tail]) do
ETS.delete(pid)
delete(tail)
end
defp delete([[pid] | tail]) do
ETS.delete(pid)
delete(tail)
end
defp delete([]), do: :ok
defp receiver_alive? do
pid = Process.whereis(Receiver)
!is_nil(pid) && Process.alive?(pid)
end
def pids_and_monitor_references(transaction) do
ETS.match({:"$1", transaction, :"$2"}) ++ ETS.match({:"$1", transaction})
end
end
|
lib/appsignal/transaction/registry.ex
| 0.839356 | 0.546678 |
registry.ex
|
starcoder
|
defmodule KaufmannEx.Config do
@moduledoc """
Convenience Getters for pulling config.exs values
A config.exs may look like
```
# test env
config :kaufmann_ex,
consumer_group: System.get_env("CONSUMER_GROUP"),
default_topic: System.get_env("KAFKA_TOPIC"),
event_handler_demand: 50,
event_handler_mod: nil, # Be sure to specify your event handler
gen_consumer_mod: KaufmannEx.Stages.GenConsumer,
producer_mod: KaufmannEx.Publisher,
schema_path: "priv/schemas",
schema_registry_uri: System.get_env("SCHEMA_REGISTRY_PATH"),
service_id: System.get_env("HOSTNAME"),
service_name: "SampleService"
```
"""
@doc """
`Application.get_env(:kaufmann_ex, :consumer_group)`
"""
@spec consumer_group() :: String.t() | nil
def consumer_group, do: Application.get_env(:kaufmann_ex, :consumer_group)
@doc """
`Application.get_env(:kaufmann_ex, :default_topic)`
"""
@spec default_topic() :: String.t() | nil
def default_topic, do: Application.get_env(:kaufmann_ex, :default_topic)
@doc """
`default_topic/0` in a list
`[KaufmannEx.Config.default_topic()]`
"""
@spec default_topics() :: [String.t()]
def default_topics, do: [default_topic()]
@spec default_publish_topic() :: String.t() | nil
def default_publish_topic,
do: Application.get_env(:kaufmann_ex, :default_publish_topic, default_topic())
@doc """
`Application.get_env(:kaufmann_ex, :event_handler_mod)`
"""
@spec event_handler() :: atom | nil
def event_handler, do: Application.get_env(:kaufmann_ex, :event_handler_mod)
@doc """
`Application.get_env(:kaufmann_ex, :producer_mod)`
"""
@spec producer_mod() :: atom | nil
def producer_mod, do: Application.get_env(:kaufmann_ex, :producer_mod, KaufmannEx.Publisher)
@doc """
`Application.get_env(:kaufmann_ex, :schema_path)`
"""
@spec schema_path() :: String.t() | nil
def schema_path, do: Application.get_env(:kaufmann_ex, :schema_path, "priv/schemas")
@doc """
`Application.get_env(:kaufmann_ex, :schema_registry_uri)`
"""
@spec schema_registry_uri() :: String.t() | nil
def schema_registry_uri, do: Application.get_env(:kaufmann_ex, :schema_registry_uri)
@doc """
`Application.get_env(:kaufmann_ex, :service_name)`
"""
@spec service_name() :: String.t() | nil
def service_name, do: Application.get_env(:kaufmann_ex, :service_name)
@doc """
`Application.get_env(:kaufmann_ex, :service_id)`
"""
@spec service_id() :: String.t() | nil
def service_id, do: Application.get_env(:kaufmann_ex, :service_id)
@doc """
Application.get_env(:kaufmann_ex, :event_handler_demand, 50)
"""
@spec event_handler_demand() :: integer()
def event_handler_demand, do: Application.get_env(:kaufmann_ex, :event_handler_demand, 50)
@doc """
Application.get_env(:kaufmann_ex, :gen_consumer_mod)
"""
@spec gen_consumer_mod() :: atom
def gen_consumer_mod,
do: Application.get_env(:kaufmann_ex, :gen_consumer_mod, KaufmannEx.Stages.GenConsumer)
@doc """
Application.get_env(:kaufmann_ex, :partition_strategy, :random)
"""
@spec partition_strategy() :: atom
def partition_strategy, do: Application.get_env(:kaufmann_ex, :partition_strategy, :random)
@spec topic_strategy() :: atom
def topic_strategy, do: Application.get_env(:kaufmann_ex, :topic_strategy, :default)
@spec schema_cache_expires_in_ms() :: integer
def schema_cache_expires_in_ms,
do: Application.get_env(:kaufmann_ex, :schema_cache_expires_in_ms, 60_000)
end
|
lib/config.ex
| 0.766294 | 0.429549 |
config.ex
|
starcoder
|
defmodule Canvas do
@colour_to_ansi_fn %{
black: &IO.ANSI.black_background/0,
blue: &IO.ANSI.blue_background/0,
cyan: &IO.ANSI.cyan_background/0,
green: &IO.ANSI.green_background/0,
light_black: &IO.ANSI.light_black_background/0,
light_blue: &IO.ANSI.light_blue_background/0,
light_cyan: &IO.ANSI.light_cyan_background/0,
light_green: &IO.ANSI.light_green_background/0,
light_magenta: &IO.ANSI.light_magenta_background/0,
light_red: &IO.ANSI.light_red_background/0,
light_white: &IO.ANSI.light_white_background/0,
light_yellow: &IO.ANSI.light_yellow_background/0,
magenta: &IO.ANSI.magenta_background/0,
red: &IO.ANSI.red_background/0,
reset: &IO.ANSI.reset/0,
white: &IO.ANSI.white_background/0,
yellow: &IO.ANSI.yellow_background/0
}
@allowed_colours Map.keys(@colour_to_ansi_fn)
@reset :reset
@typep cells_t :: %{optional({pos_integer, pos_integer}) => atom}
@type t :: %Canvas{cells: cells_t, row_count: pos_integer, column_count: pos_integer}
defstruct cells: %{}, row_count: 0, column_count: 0
defguardp in_canvas?(row_count, column_count, row, column)
when row > 0 and row <= row_count and column > 0 and
column <= column_count
defguardp allow_colour?(colour) when colour in @allowed_colours
@spec new(pos_integer, atom) :: Canvas.t()
def new(row_count, column_count) do
%Canvas{row_count: row_count, column_count: column_count}
end
@spec draw_in_cell(Canvas.t(), pos_integer, pos_integer, atom) :: Canvas.t()
def draw_in_cell(
%Canvas{cells: cells, row_count: row_count, column_count: column_count} = canvas,
row,
column,
colour
)
when in_canvas?(row_count, column_count, row, column) and
allow_colour?(colour) do
new_cells = Map.put(cells, {row, column}, colour)
%{canvas | cells: new_cells}
end
@spec draw_in_row(Canvas.t(), pos_integer, pos_integer, pos_integer, atom) :: Canvas.t()
def draw_in_row(
%Canvas{row_count: row_count, column_count: column_count} = canvas,
row,
from_column,
to_column,
colour
)
when in_canvas?(row_count, column_count, row, from_column) and
in_canvas?(row_count, column_count, row, to_column) and
allow_colour?(colour) do
from_column..to_column
|> Enum.reduce(canvas, fn column, canvas -> draw_in_cell(canvas, row, column, colour) end)
end
@spec draw_in_column(Canvas.t(), pos_integer, pos_integer, pos_integer, atom) :: Canvas.t()
def draw_in_column(
%Canvas{row_count: row_count, column_count: column_count} = canvas,
column,
from_row,
to_row,
colour
)
when in_canvas?(row_count, column_count, from_row, column) and
in_canvas?(row_count, column_count, to_row, column) and allow_colour?(colour) do
from_row..to_row
|> Enum.reduce(canvas, fn row, canvas -> draw_in_cell(canvas, row, column, colour) end)
end
@spec flood(Canvas.t(), pos_integer, pos_integer, atom) :: Canvas.t()
def flood(
%Canvas{row_count: row_count, column_count: column_count} = canvas,
row,
column,
new_colour
)
when in_canvas?(row_count, column_count, row, column) and allow_colour?(new_colour) do
visited = MapSet.new()
original_colour = Map.get(canvas.cells, {row, column})
{new_canvas, _} = flood(canvas, row, column, original_colour, new_colour, visited)
new_canvas
end
defp flood(
%Canvas{cells: cells, row_count: row_count, column_count: column_count} = canvas,
row,
column,
original_colour,
new_colour,
visited
)
when in_canvas?(row_count, column_count, row, column) and allow_colour?(new_colour) do
if Map.get(cells, {row, column}) !== original_colour do
{canvas, visited}
else
new_visited = MapSet.put(visited, {row, column})
new_canvas = draw_in_cell(canvas, row, column, new_colour)
adjacent_cells =
[
{row - 1, column},
{row + 1, column},
{row, column - 1},
{row, column + 1}
]
|> Enum.filter(&(!MapSet.member?(new_visited, &1)))
|> Enum.filter(fn {row, column} -> in_canvas?(row_count, column_count, row, column) end)
Enum.reduce(adjacent_cells, {new_canvas, new_visited}, fn {next_row, next_column},
{new_canvas, new_visited} ->
flood(new_canvas, next_row, next_column, original_colour, new_colour, new_visited)
end)
end
end
def draw(%Canvas{cells: cells, row_count: row_count, column_count: column_count}) do
1..row_count
|> Enum.map(&draw_columns(cells, column_count, &1))
|> Enum.join(IO.ANSI.black_background() <> "\n")
|> Kernel.<>(IO.ANSI.black_background())
end
defp draw_columns(cells, column_count, row) do
Enum.map(1..column_count, &draw_cell(cells, row, &1))
|> Enum.join()
end
defp draw_cell(cells, row, column) do
colour = Map.get(cells, {row, column}, @reset)
colour_fn = Map.get(@colour_to_ansi_fn, colour)
colour_fn.() <> " "
end
end
|
elixir/lib/canvas.ex
| 0.756358 | 0.422117 |
canvas.ex
|
starcoder
|
defmodule LessVerifiesAlexa.Plug do
@moduledoc """
`LessVerifiesAlexa.Plug` is a plug that validates requests that
Amazon's Alexa service sends.
Add the plug to your router like this:
```
plug LessVerifiesAlexa.Plug, application_id: "your_app_id"
```
In order for the plug to work, there's an additional change you have to make.
In your `endpoint.ex`, you have to change your Parsers plug to use a custom
JSON parser that this plug provides.
Just change `:json` to `:alexajson` and you should end up with something
like this:
```
plug Plug.Parsers,
parsers: [:alexajson, :urlencoded, :multipart],
pass: ["*/*"],
json_decoder: Poison
```
You have to do this due to a Plug implementation detail we won't go into here.
Hopefully, we'll soon be submitting a PR to plug itself that should remove the
need for this custom adapter.
"""
import Plug.Conn
@spec init(keyword()) :: keyword()
def init(opts), do: opts
@spec call(Plug.Conn.t, keyword()) :: Plug.Conn.t
def call(conn, opts) do
conn
|> check_signature_url
|> check_application_id(opts[:application_id])
|> check_certificate_validity
|> check_request_timestamp
end
defp check_signature_url(conn) do
[signature_certchain_url] = get_req_header(conn, "signaturecertchainurl")
case is_alexa_url?(signature_certchain_url) do
true -> conn
false -> halt(conn)
end
end
defp check_application_id(_conn, nil) do
raise ArgumentError, "LessVerifiesAlexa.Plug expects an :application_id option"
end
defp check_application_id(conn, app_id) do
# TODO: Error checking
received_id = conn.body_params["session"]["application"]["applicationId"]
case received_id == app_id do
true -> conn
false -> halt(conn)
end
end
defp check_certificate_validity(conn) do
try do
[signature] = get_req_header(conn, "signature")
[cert_url] = get_req_header(conn, "signaturecertchainurl")
raw_body = conn.private[:raw_body]
{:ok, cert} = LessVerifiesAlexa.Certificate.fetch(cert_url)
case LessVerifiesAlexa.Certificate.valid?(signature, cert, raw_body) do
:ok -> conn
_ -> halt(conn)
end
rescue
MatchError -> halt(conn)
end
end
defp is_alexa_url?(chain_url) do
case Regex.run(~r/^https:\/\/s3.amazonaws.com(:443)?(\/echo\.api\/)/i, chain_url) do
[_, "", "/echo.api/"] -> true
[_, ":443", "/echo.api/"] -> true
_ -> false
end
end
defp check_request_timestamp(conn) do
{:ok, request_date_time, _offset} =
DateTime.from_iso8601(conn.params["request"]["timestamp"])
request_unix_time = DateTime.to_unix(request_date_time)
case requested_within_150_seconds(request_unix_time) do
true -> conn
false -> halt(conn)
end
end
defp requested_within_150_seconds(request_unix_time) do
now_unix_time = DateTime.to_unix(DateTime.utc_now)
abs(now_unix_time - request_unix_time) <= 150
end
end
|
lib/less_verifies_alexa/plug.ex
| 0.685002 | 0.746878 |
plug.ex
|
starcoder
|
defmodule RubberBand.Client.Codec do
@moduledoc false
alias RubberBand.Client.CodecError
alias RubberBand.Client.Config
@doc """
Decodes data using the JSON codec from the given config.
"""
@spec decode(Config.t(), String.t(), any) ::
{:ok, any} | {:error, CodecError.t()}
def decode(config, content_type, data)
def decode(_config, _content_type, nil), do: {:ok, nil}
def decode(_config, _content_type, ""), do: {:ok, nil}
def decode(config, "application/json", data) when is_binary(data) do
with {:error, error} <- config.json_codec.decode(data, keys: :atoms) do
{:error,
%CodecError{operation: :decode, data: data, original_error: error}}
end
end
def decode(_config, _content_type, data) when is_binary(data) do
{:ok, data}
end
def decode(_config, _content_type, data) do
{:error, %CodecError{operation: :decode, data: data}}
end
@doc """
Decodes data using the JSON codec from the given config. Raises when the
decoding fails.
"""
@spec decode!(Config.t(), String.t(), any) :: any | no_return
def decode!(config, content_type, data) do
case decode(config, content_type, data) do
{:ok, decoded_data} -> decoded_data
{:error, error} -> raise error
end
end
@doc """
Encodes data using the JSON codec from the given config.
"""
@spec encode(Config.t(), any) :: {:ok, any} | {:error, CodecError.t()}
def encode(config, data)
def encode(_config, nil), do: {:ok, ""}
def encode(_config, data) when is_binary(data), do: {:ok, data}
def encode(config, data) do
with {:error, error} <- config.json_codec.encode(data) do
{:error,
%CodecError{operation: :encode, data: data, original_error: error}}
end
end
@doc """
Encodes data using the JSON codec from the given config. Raises when the
encoding fails.
"""
@spec encode!(Config.t(), any) :: any | no_return
def encode!(config, data) do
case encode(config, data) do
{:ok, encoded_data} -> encoded_data
{:error, error} -> raise error
end
end
end
|
lib/rubber_band/client/codec.ex
| 0.878796 | 0.400955 |
codec.ex
|
starcoder
|
defmodule GeoTIFF do
@doc ~S"""
Reads the headers of a GeoTIFF file.
### Examples:
iex> filename = "./test/resources/example_ii.tif"
iex> {:ok, response} = GeoTIFF.read_headers(filename)
iex> response.first_ifd_offset
270_276
iex> ifd = Enum.at response.ifds, 0
iex> Enum.at ifd.tags, 2
%{count: 15, tag: "GeoAsciiParamsTag", type: "ASCII", value: "unnamed|NAD27|"}
iex> Enum.at Enum.at(ifd.tags, 14).value, 0
7710
iex> Enum.at(ifd.tags, 0).value
8
iex> filename = "spam.eggs"
iex> GeoTIFF.read_headers(filename)
{:error, "Failed to open file 'spam.eggs'. Reason: enoent."}
"""
def read_headers(filename) do
with {:ok, file} <- :file.open(filename, [:read, :binary]),
{:ok, header_bytes} <- header_bytes(file),
{:ok, endianess} <- endianess(header_bytes),
first_ifd_offset <- first_ifd_offset(header_bytes, endianess),
partial_ifds <- parse_ifds(file, first_ifd_offset, endianess, []),
ifds <- resolve_tag_values(file, partial_ifds, endianess) do
:file.close(file)
{:ok, %{:filename => filename, :endianess => endianess, :first_ifd_offset => first_ifd_offset, :ifds => ifds}}
else
{:error, reason} -> {:error, format_error(filename, reason)}
end
end
def resolve_tag_values(file, ifds, endianess) do
ifd = Enum.at ifds, 0
tags = Enum.map ifd.tags, &(resolve_tag_value(file, &1, endianess))
nu_ifd = Map.merge(ifd, %{:tags => tags})
[nu_ifd]
end
def resolve_tag_value(file, tag, endianess), do: if tag.count > 4, do: resolve_tag_reference(file, tag, endianess), else: tag
def resolve_tag_reference(file, tag, endianess) do
case tag.type do
"ASCII" ->
:file.position(file, tag.value)
{:ok, bytes} = :file.read(file, tag.count)
codepoints = String.codepoints(bytes)
value = Enum.slice(codepoints, 0, length(codepoints) - 1) |> List.to_string
Map.merge tag, %{:value => value}
"LONG" ->
:file.position(file, tag.value)
{:ok, bytes} = :file.read(file, 4 * tag.count)
values = Enum.map(1..tag.count, &(decode(bytes, {(&1 - 1) * 4, 4}, endianess)))
Map.merge tag, %{:value => values}
"SHORT" ->
:file.position(file, tag.value)
{:ok, bytes} = :file.read(file, 2 * tag.count)
values = Enum.map(1..tag.count, &(decode(bytes, {(&1 - 1) * 2, 2}, endianess)))
Map.merge tag, %{:value => values}
_ -> tag
end
end
def inspect(filename) do
read_headers(filename)
|> case do
{:ok, headers} -> GeoTIFFFormatter.format_headers(headers) |> IO.puts
{:error, message} -> IO.puts message
end
end
@doc ~S"""
Decodes the IFDs of a TIFF file.
### Examples:
iex> {:ok, file} = :file.open('./test/resources/example_ii.tif', [:read, :binary])
iex> ifds = GeoTIFF.parse_ifds(file, 270_276, :little, [])
iex> length ifds
1
"""
def parse_ifds(file, ifd_offset, endianess, ifds) do
with ifd <- parse_ifd(file, ifd_offset, endianess) do
case ifd.next_ifd do
0 -> [ifd | ifds]
_ -> ifds ++ parse_ifds(file, ifd.next_ifd, endianess, ifds)
end
end
end
@doc ~S"""
Decodes a single IFD.
### Examples:
iex> {:ok, file} = :file.open('./test/resources/example_ii.tif', [:read, :binary])
iex> ifd = GeoTIFF.parse_ifd(file, 270_276, :little)
iex> ifd.entries
16
iex> ifd.next_ifd
0
iex> length ifd.tags
16
"""
def parse_ifd(file, ifd_offset, endianess) do
entries = ifd_entries(file, ifd_offset, endianess)
:file.position(file, 2 + ifd_offset)
{:ok, bytes} = :file.read(file, entries * 12 + 4)
tags = Enum.map(0..15, &(read_tag(bytes, 12 * &1, endianess))) |> Enum.sort(&(&1.tag <= &2.tag))
next_ifd = decode(bytes, {entries * 12, 4}, endianess)
%{:offset => ifd_offset, :entries => entries, :tags => tags, :next_ifd => next_ifd}
end
@doc ~S"""
Decodes a single TIFF tag.
### Examples:
iex> bytes = <<0, 1, 3, 0, 1, 0, 0, 0, 2, 2, 0, 0>>
iex> GeoTIFF.read_tag(bytes, 0, :little)
%{count: 1, tag: "ImageWidth", type: "SHORT", value: 514}
"""
def read_tag(bytes, offset, endianess) do
%{
:tag => decode(bytes, {offset + 0, 2}, endianess) |> GeoTIFFTags.decode_tag_name(),
:type => decode(bytes, {offset + 2, 2}, endianess) |> GeoTIFFTags.decode_data_type(),
:count => decode(bytes, {offset + 4, 4}, endianess),
:value => decode(bytes, {offset + 8, 4}, endianess)
}
end
@doc ~S"""
Determines how many entries are avilable for a given IFD.
### Examples:
iex> {:ok, file} = :file.open('./test/resources/example_ii.tif', [:read, :binary])
iex> GeoTIFF.ifd_entries(file, 270_276, :little)
16
"""
def ifd_entries(file, offset, endianess) do
:file.position(file, offset)
{:ok, entries_bytes} = :file.read(file, 2)
decode(entries_bytes, {0, 2}, endianess)
end
@doc ~S"""
Decodes a subset of bytes.
### Examples:
iex> GeoTIFF.decode(<<73, 73, 42, 0, 196, 31, 4, 0>>, {4, 3}, :little)
270_276
"""
def decode(bytes, range, endianess) do
:binary.bin_to_list(bytes, range)
|> :erlang.list_to_binary
|> :binary.decode_unsigned(endianess)
end
@doc ~S"""
Reads the header (first 8 bytes) of the TIFF file.
### Examples:
iex> filename = "./test/resources/example_ii.tif"
iex> {:ok, file} = :file.open(filename, [:read, :binary])
iex> GeoTIFF.header_bytes(file)
{:ok, <<73, 73, 42, 0, 196, 31, 4, 0>>}
"""
def header_bytes(file) do
:file.position(file, 0)
:file.read(file, 8)
end
@doc ~S"""
Determines the endianess of the bytes from the first two bytes of the header.
### Examples:
iex> GeoTIFF.endianess(<<73, 73>>)
{:ok, :little}
iex> GeoTIFF.endianess(<<77, 77>>)
{:ok, :big}
iex> GeoTIFF.endianess(<<105, 105>>)
{:error, "Cannot determine endianess for 'ii'."}
"""
def endianess(header_bytes) do
:binary.bin_to_list(header_bytes, {0, 2})
|> :erlang.list_to_binary()
|> order2endianess
end
@doc ~S"""
Determines the address of the first IFD of the file.
### Examples:
iex> header_bytes = <<0, 0, 0, 0, 0, 0, 0, 42>>
iex> GeoTIFF.first_ifd_offset(header_bytes, :little)
704_643_072
iex> header_bytes = <<0, 0, 0, 0, 42, 0, 0, 0>>
iex> GeoTIFF.first_ifd_offset(header_bytes, :big)
704_643_072
"""
def first_ifd_offset(header_bytes, endianness) do
:binary.bin_to_list(header_bytes, {4, 4})
|> :erlang.list_to_binary()
|> :binary.decode_unsigned(endianness)
end
defp order2endianess(order) do
case order do
"II" -> {:ok, :little}
"MM" -> {:ok, :big}
_ -> {:error, "Cannot determine endianess for '#{order}'."}
end
end
defp format_error(filename, reason), do: "Failed to open file '#{filename}'. Reason: #{reason}."
end
|
lib/geotiff.ex
| 0.589953 | 0.437343 |
geotiff.ex
|
starcoder
|
defmodule Bertex do
@moduledoc """
This is a work TOTALLY based on @mojombo and @eproxus work:
More at: https://github.com/eproxus/bert.erl and http://github.com/mojombo/bert.erl
"""
import :erlang, only: [binary_to_term: 1,
binary_to_term: 2,
term_to_binary: 1]
defprotocol Bert do
@fallback_to_any true
def encode(term)
def decode(term)
end
defimpl Bert, for: Atom do
def encode(false), do: {:bert, false}
def encode(true), do: {:bert, true}
def encode(atom), do: atom
def decode(atom), do: atom
end
defimpl Bert, for: List do
def encode([]), do: {:bert, nil}
def encode(list) do
Enum.map(list, &Bert.encode(&1))
end
def decode(list) do
Enum.map(list, &Bert.decode(&1))
end
end
# Inspired by talentdeficit/jsex solution
defimpl Bert, for: Tuple do
def encode(tuple) do
Tuple.to_list(tuple)
|> Enum.map(&Bert.encode(&1))
|> List.to_tuple
end
def decode({:bert, nil}), do: []
def decode({:bert, true}), do: true
def decode({:bert, false}), do: false
def decode({:bert, :dict, dict}), do: Enum.into(Bert.decode(dict), %{})
def decode(tuple) do
Tuple.to_list(tuple)
|> Enum.map(&Bert.decode(&1))
|> List.to_tuple
end
end
defimpl Bert, for: Map do
def encode(dict), do: {:bert, :dict, Dict.to_list(dict)}
# This should never happen.
def decode(dict), do: Enum.into(dict, %{})
end
defimpl Bert, for: HashDict do
def encode(dict), do: {:bert, :dict, Dict.to_list(dict)}
# This should never happen.
def decode(dict), do: Enum.into(dict, %{})
end
defimpl Bert, for: Any do
def encode(term), do: term
def decode(term), do: term
end
@doc """
iex> Bertex.encode([42, :banana, {:xy, 5, 10}, "robot", true, false])
<<131,108,0,0,0,6,97,42,100,0,6,98,97,110,97,110,97,104,3,100,0,2,120,121,97,5,97,10,109,0,0,0,5,114,111,98,111,116,104,2,100,0,4,98,101,114,116,100,0,4,116,114,117,101,104,2,100,0,4,98,101,114,116,100,0,5,102,97,108,115,101,106>>
"""
@spec encode(term) :: binary
def encode(term) do
Bert.encode(term) |> term_to_binary
end
@doc """
iex> Bertex.decode(<<131,108,0,0,0,6,97,42,100,0,6,98,97,110,97,110,97,104,3,100,0,2,120,121,97,5,97,10,109,0,0,0,5,114,111,98,111,116,104,2,100,0,4,98,101,114,116,100,0,4,116,114,117,101,104,2,100,0,4,98,101,114,116,100,0,5,102,97,108,115,101,106>>)
[42, :banana, {:xy, 5, 10}, "robot", true, false]
"""
@spec decode(binary) :: term
def decode(bin) do
binary_to_term(bin) |> Bert.decode
end
@spec safe_decode(binary) :: term
def safe_decode(bin) do
binary_to_term(bin, [:safe]) |> Bert.decode
end
end
|
lib/bertex.ex
| 0.736401 | 0.51379 |
bertex.ex
|
starcoder
|
defmodule Broadway.Options do
@moduledoc false
@basic_types [
:any,
:keyword_list,
:non_empty_keyword_list,
:atom,
:non_neg_integer,
:pos_integer,
:mfa,
:mod_arg
]
def validate(opts, spec) do
case validate_unknown_options(opts, spec) do
:ok -> validate_options(spec, opts)
error -> error
end
end
defp validate_unknown_options(opts, spec) do
valid_opts = Keyword.keys(spec)
case Keyword.keys(opts) -- valid_opts do
[] ->
:ok
keys ->
{:error, "unknown options #{inspect(keys)}, valid options are: #{inspect(valid_opts)}"}
end
end
defp validate_options(spec, opts) do
case Enum.reduce_while(spec, opts, &reduce_options/2) do
{:error, _} = result -> result
result -> {:ok, result}
end
end
defp reduce_options({key, spec_opts}, parent_opts) do
case validate_option(parent_opts, key, spec_opts) do
{:error, _} = result ->
{:halt, result}
{:ok, value} ->
{:cont, Keyword.update(parent_opts, key, value, fn _ -> value end)}
:no_value ->
{:cont, parent_opts}
end
end
defp validate_option(opts, key, spec) do
with {:ok, opts} <- validate_value(opts, key, spec),
value <- opts[key],
:ok <- validate_type(spec[:type], key, value) do
if spec[:keys] do
keys = normalize_keys(spec[:keys], value)
validate(opts[key], keys)
else
{:ok, value}
end
end
end
defp validate_value(opts, key, spec) do
required? = Keyword.get(spec, :required, false)
has_key? = Keyword.has_key?(opts, key)
has_default? = Keyword.has_key?(spec, :default)
case {required?, has_key?, has_default?} do
{_, true, _} ->
{:ok, opts}
{true, false, _} ->
{:error,
"required option #{inspect(key)} not found, received options: " <>
inspect(Keyword.keys(opts))}
{_, false, true} ->
{:ok, Keyword.put(opts, key, spec[:default])}
{_, false, false} ->
:no_value
end
end
defp validate_type(:non_neg_integer, key, value) when not is_integer(value) or value < 0 do
{:error, "expected #{inspect(key)} to be a non negative integer, got: #{inspect(value)}"}
end
defp validate_type(:pos_integer, key, value) when not is_integer(value) or value < 1 do
{:error, "expected #{inspect(key)} to be a positive integer, got: #{inspect(value)}"}
end
defp validate_type(:atom, key, value) when not is_atom(value) do
{:error, "expected #{inspect(key)} to be an atom, got: #{inspect(value)}"}
end
defp validate_type(:keyword_list, key, value) do
if keyword_list?(value) do
:ok
else
{:error, "expected #{inspect(key)} to be a keyword list, got: #{inspect(value)}"}
end
end
defp validate_type(:non_empty_keyword_list, key, value) do
if keyword_list?(value) && value != [] do
:ok
else
{:error, "expected #{inspect(key)} to be a non-empty keyword list, got: #{inspect(value)}"}
end
end
defp validate_type(:mfa, _key, {m, f, args}) when is_atom(m) and is_atom(f) and is_list(args) do
:ok
end
defp validate_type(:mfa, key, value) when not is_nil(value) do
{:error, "expected #{inspect(key)} to be a tuple {Mod, Fun, Args}, got: #{inspect(value)}"}
end
defp validate_type(:mod_arg, _key, {m, _arg}) when is_atom(m) do
:ok
end
defp validate_type(:mod_arg, key, value) do
{:error, "expected #{inspect(key)} to be a tuple {Mod, Arg}, got: #{inspect(value)}"}
end
defp validate_type({:fun, arity}, key, value) when is_integer(arity) and arity >= 0 do
expected = "expected #{inspect(key)} to be a function of arity #{arity}, "
if is_function(value) do
case :erlang.fun_info(value, :arity) do
{:arity, ^arity} ->
:ok
{:arity, fun_arity} ->
{:error, expected <> "got: function of arity #{inspect(fun_arity)}"}
end
else
{:error, expected <> "got: #{inspect(value)}"}
end
end
defp validate_type(nil, key, value) do
validate_type(:any, key, value)
end
defp validate_type(type, _key, _value) when type in @basic_types do
:ok
end
defp validate_type(type, _key, _value) do
{:error, "invalid option type #{inspect(type)}, available types: #{available_types()}"}
end
defp tagged_tuple?({key, _value}) when is_atom(key), do: true
defp tagged_tuple?(_), do: false
defp keyword_list?(value) do
is_list(value) && Enum.all?(value, &tagged_tuple?/1)
end
defp normalize_keys(keys, opts) do
case keys[:*] do
nil ->
keys
spec_opts ->
Enum.map(opts, fn {k, _} -> {k, [type: :keyword_list, keys: spec_opts]} end)
end
end
defp available_types() do
types = Enum.map(@basic_types, &inspect/1) ++ ["{:fun, arity}"]
Enum.join(types, ", ")
end
end
|
lib/broadway/options.ex
| 0.626467 | 0.446374 |
options.ex
|
starcoder
|
defmodule PokerHands.DealtHand do
defstruct cards: [],
grouped_card_values: []
alias PokerHands.Card
@doc """
## Examples
iex> PokerHands.DealtHand.init("2H 4S 2S AH")
%PokerHands.DealtHand{
cards: [
%PokerHands.Card{value: "A", suit: "H", int_value: 14},
%PokerHands.Card{value: "4", suit: "S", int_value: 4},
%PokerHands.Card{value: "2", suit: "S", int_value: 2},
%PokerHands.Card{value: "2", suit: "H", int_value: 2}
],
grouped_card_values: [["2", "2"], ["A"], ["4"]]
}
"""
def init(denotation_string) do
cards = init_cards(denotation_string)
%__MODULE__{
cards: cards,
grouped_card_values: group_card_values(cards)
}
end
@doc """
## Examples
iex> PokerHands.DealtHand.type(
iex> PokerHands.DealtHand.init("2H 4S TS AH 6D")
iex> )
PokerHands.Hand.HighCard
iex> PokerHands.DealtHand.type(
iex> PokerHands.DealtHand.init("2H 4S 2S AH 6D")
iex> )
PokerHands.Hand.Pair
iex> PokerHands.DealtHand.type(
iex> PokerHands.DealtHand.init("2H 4S 2S AH 4D")
iex> )
PokerHands.Hand.TwoPairs
iex> PokerHands.DealtHand.type(
iex> PokerHands.DealtHand.init("2H 4S 2S AH 2D")
iex> )
PokerHands.Hand.ThreeOfAKind
iex> PokerHands.DealtHand.type(
iex> PokerHands.DealtHand.init("2H 4S 3S 5H 6D")
iex> )
PokerHands.Hand.Straight
iex> PokerHands.DealtHand.type(
iex> PokerHands.DealtHand.init("JH 4H QH 5H TH")
iex> )
PokerHands.Hand.Flush
iex> PokerHands.DealtHand.type(
iex> PokerHands.DealtHand.init("3H 2D 3D 3C 2S")
iex> )
PokerHands.Hand.FullHouse
iex> PokerHands.DealtHand.type(
iex> PokerHands.DealtHand.init("2H 4S 2S 2H 2D")
iex> )
PokerHands.Hand.FourOfAKind
iex> PokerHands.DealtHand.type(
iex> PokerHands.DealtHand.init("2H 4H 3H 5H 6H")
iex> )
PokerHands.Hand.StraightFlush
"""
def type(dealt_hand) do
Enum.find(
%PokerHands.Definitions{}.hands,
&(&1.valid?(dealt_hand))
)
end
defp init_cards(denotation_string) do
denotation_string
|> String.split(" ")
|> Enum.map(&(Card.init(&1)))
|> Enum.sort_by(&(&1.int_value))
|> Enum.reverse()
end
defp group_card_values(cards) do
cards
|> Enum.group_by(&(&1.int_value))
|> Enum.sort_by(fn({int_value, _items}) -> int_value end)
|> Enum.sort_by(fn({_int_value, items}) -> Kernel.length(items) end)
|> Enum.reverse()
|> Enum.map(fn({_int_value, items}) -> Enum.map(items, &(&1.value)) end)
end
end
|
lib/poker_hands/dealt_hand.ex
| 0.617282 | 0.449151 |
dealt_hand.ex
|
starcoder
|
defmodule Chunky.Sequence.OEIS.Combinatorics do
@moduledoc """
Sequences from the [Online Encyclopedia of Integer Sequences](https://oeis.org) dealing with combinatorics, set
manipulations, and permutations.
## Available Sequences
### Catalan Numbers
Via [Catalan Number - Wikipedia](https://en.wikipedia.org/wiki/Catalan_number):
> In combinatorial mathematics, the Catalan numbers form a sequence of natural numbers that occur in various
> counting problems, often involving recursively-defined objects. They are named after the Belgian
> mathematician Eugène Charles Catalan
- `create_sequence_a159981/1` - A159981 - Catalan numbers read modulo 4
- `create_sequence_a159984/1` - A159984 - Catalan numbers read modulo 5
- `create_sequence_a159986/1` - A159986 - Catalan numbers read modulo 7
- `create_sequence_a159987/1` - A159987 - Catalan numbers read modulo 8
- `create_sequence_a159988/1` - A159988 - Catalan numbers read modulo 11
- `create_sequence_a159989/1` - A159989 - Catalan numbers read modulo 12
- `create_sequence_a289682/1` - A289682 - Catalan numbers read modulo 16
"""
import Chunky.Sequence, only: [sequence_for_function: 1]
alias Chunky.Math
@doc """
OEIS Sequence `A159981` - Catalan numbers read modulo 4 .
From [OEIS A159981](https://oeis.org/A159981):
> Catalan numbers read modulo 4 .
**Sequence IDs**: `:a159981`
**Finite**: False
**Offset**: 0
## Example
iex> Sequence.create(Elixir.Chunky.Sequence.OEIS.Combinatorics, :a159981) |> Sequence.take!(105)
[1,1,2,1,2,2,0,1,2,2,0,2,0,0,0,1,2,2,0,2,0,0,0,2,0,0,0,0,0,0,0,1,2,2,0,2,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,0,2,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0]
"""
@doc offset: 0,
sequence: "Catalan numbers read modulo 4 .",
references: [{:oeis, :a159981, "https://oeis.org/A159981"}]
def create_sequence_a159981(_opts) do
sequence_for_function(&Elixir.Chunky.Sequence.OEIS.Combinatorics.seq_a159981/1)
end
@doc false
@doc offset: 0
def seq_a159981(idx) do
Math.catalan_number(idx) |> rem(4)
end
@doc """
OEIS Sequence `A159984` - Catalan numbers read modulo 5 .
From [OEIS A159984](https://oeis.org/A159984):
> Catalan numbers read modulo 5 .
**Sequence IDs**: `:a159984`
**Finite**: False
**Offset**: 0
## Example
iex> Sequence.create(Elixir.Chunky.Sequence.OEIS.Combinatorics, :a159984) |> Sequence.take!(105)
[1,1,2,0,4,2,2,4,0,2,1,1,2,0,0,0,0,0,0,0,0,0,0,0,4,2,2,4,0,3,4,4,3,0,4,2,2,4,0,0,0,0,0,0,0,0,0,0,0,2,1,1,2,0,4,2,2,4,0,2,1,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
"""
@doc offset: 0,
sequence: "Catalan numbers read modulo 5 .",
references: [{:oeis, :a159984, "https://oeis.org/A159984"}]
def create_sequence_a159984(_opts) do
sequence_for_function(&Elixir.Chunky.Sequence.OEIS.Combinatorics.seq_a159984/1)
end
@doc false
@doc offset: 0
def seq_a159984(idx) do
Math.catalan_number(idx) |> rem(5)
end
@doc """
OEIS Sequence `A159986` - Catalan numbers read modulo 7 .
From [OEIS A159986](https://oeis.org/A159986):
> Catalan numbers read modulo 7 .
**Sequence IDs**: `:a159986`
**Finite**: False
**Offset**: 0
## Example
iex> Sequence.create(Elixir.Chunky.Sequence.OEIS.Combinatorics, :a159986) |> Sequence.take!(106)
[1,1,2,5,0,0,6,2,2,4,3,0,0,4,6,6,5,2,0,0,4,6,6,5,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,2,2,4,3,0,0,5,4,4,1,6,0,0,1,5,5,3,4,0,0,1,5,5,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,6,6,5,2,0,0,1,5]
"""
@doc offset: 0,
sequence: "Catalan numbers read modulo 7 .",
references: [{:oeis, :a159986, "https://oeis.org/A159986"}]
def create_sequence_a159986(_opts) do
sequence_for_function(&Elixir.Chunky.Sequence.OEIS.Combinatorics.seq_a159986/1)
end
@doc false
@doc offset: 0
def seq_a159986(idx) do
Math.catalan_number(idx) |> rem(7)
end
@doc """
OEIS Sequence `A159987` - Catalan numbers read modulo 8.
From [OEIS A159987](https://oeis.org/A159987):
> Catalan numbers read modulo 8.
**Sequence IDs**: `:a159987`
**Finite**: False
**Offset**: 0
## Example
iex> Sequence.create(Elixir.Chunky.Sequence.OEIS.Combinatorics, :a159987) |> Sequence.take!(105)
[1,1,2,5,6,2,4,5,6,6,4,2,4,4,0,5,6,6,4,6,4,4,0,2,4,4,0,4,0,0,0,5,6,6,4,6,4,4,0,6,4,4,0,4,0,0,0,2,4,4,0,4,0,0,0,4,0,0,0,0,0,0,0,5,6,6,4,6,4,4,0,6,4,4,0,4,0,0,0,6,4,4,0,4,0,0,0,4,0,0,0,0,0,0,0,2,4,4,0,4,0,0,0,4,0]
"""
@doc offset: 0,
sequence: "Catalan numbers read modulo 8.",
references: [{:oeis, :a159987, "https://oeis.org/A159987"}]
def create_sequence_a159987(_opts) do
sequence_for_function(&Elixir.Chunky.Sequence.OEIS.Combinatorics.seq_a159987/1)
end
@doc false
@doc offset: 0
def seq_a159987(idx) do
Math.catalan_number(idx) |> rem(8)
end
@doc """
OEIS Sequence `A159988` - Catalan numbers read modulo 11 .
From [OEIS A159988](https://oeis.org/A159988):
> Catalan numbers read modulo 11 .
**Sequence IDs**: `:a159988`
**Finite**: False
**Offset**: 0
## Example
iex> Sequence.create(Elixir.Chunky.Sequence.OEIS.Combinatorics, :a159988) |> Sequence.take!(85)
[1,1,2,5,3,9,0,0,0,0,10,2,2,4,10,6,7,0,0,0,0,8,6,6,1,8,7,10,0,0,0,0,1,9,9,7,1,5,4,0,0,0,0,9,4,4,8,9,1,3,0,0,0,0,6,10,10,9,6,8,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
"""
@doc offset: 0,
sequence: "Catalan numbers read modulo 11 .",
references: [{:oeis, :a159988, "https://oeis.org/A159988"}]
def create_sequence_a159988(_opts) do
sequence_for_function(&Elixir.Chunky.Sequence.OEIS.Combinatorics.seq_a159988/1)
end
@doc false
@doc offset: 0
def seq_a159988(idx) do
Math.catalan_number(idx) |> rem(11)
end
@doc """
OEIS Sequence `A159989` - Catalan numbers read modulo 12.
From [OEIS A159989](https://oeis.org/A159989):
> Catalan numbers read modulo 12.
**Sequence IDs**: `:a159989`
**Finite**: False
**Offset**: 0
## Example
iex> Sequence.create(Elixir.Chunky.Sequence.OEIS.Combinatorics, :a159989) |> Sequence.take!(119)
[1,1,2,5,2,6,0,9,2,2,8,10,4,4,0,9,6,6,0,6,0,0,0,6,0,0,8,8,8,4,4,1,6,6,0,10,4,4,8,2,8,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,6,6,0,6,0,0,0,6,0,0,0,0,0,0,0,6,8,8,8,4,4,4,0,0,0,4,4,4,8,8,8,6,0,0,0,0,0,0,0,0,0,0,0,4,4,4,8,8,8,0,0,0,8,8,8]
"""
@doc offset: 0,
sequence: "Catalan numbers read modulo 12.",
references: [{:oeis, :a159989, "https://oeis.org/A159989"}]
def create_sequence_a159989(_opts) do
sequence_for_function(&Elixir.Chunky.Sequence.OEIS.Combinatorics.seq_a159989/1)
end
@doc false
@doc offset: 0
def seq_a159989(idx) do
Math.catalan_number(idx) |> rem(12)
end
@doc """
OEIS Sequence `A289682` - Catalan numbers read modulo 16.
From [OEIS A289682](https://oeis.org/A289682):
> Catalan numbers read modulo 16.
**Sequence IDs**: `:a289682`
**Finite**: False
**Offset**: 0
## Example
iex> Sequence.create(Elixir.Chunky.Sequence.OEIS.Combinatorics, :a289682) |> Sequence.take!(88)
[1,1,2,5,14,10,4,13,6,14,12,2,12,4,8,13,6,6,12,6,4,12,8,2,12,12,8,4,8,8,0,13,6,6,12,14,4,12,8,6,4,4,8,12,8,8,0,2,12,12,8,12,8,8,0,4,8,8,0,8,0,0,0,13,6,6,12,14,4,12,8,14,4,4,8,12,8,8,0,6,4,4,8,4,8,8,0,12]
"""
@doc offset: 0,
sequence: "Catalan numbers read modulo 16.",
references: [{:oeis, :a289682, "https://oeis.org/A289682"}]
def create_sequence_a289682(_opts) do
sequence_for_function(&Elixir.Chunky.Sequence.OEIS.Combinatorics.seq_a289682/1)
end
@doc false
@doc offset: 0
def seq_a289682(idx) do
Math.catalan_number(idx) |> rem(16)
end
end
|
lib/sequence/oeis/combinatorics.ex
| 0.86757 | 0.804866 |
combinatorics.ex
|
starcoder
|
defmodule Membrane.Time do
@moduledoc """
Module containing functions needed to perform handling of time.
Membrane always internally uses nanosecond as a time unit. This is how all time
units should represented in the code unless there's a good reason to act
differently.
Please note that Erlang VM may internally use different units and that may
differ from platform to platform. Still, unless you need to perform calculations
that do not touch hardware clock, you should use Membrane units for consistency.
"""
@compile {:inline,
native_units: 1, native_unit: 0, nanoseconds: 1, nanosecond: 0, second: 0, seconds: 1}
@type t :: integer
@type non_neg_t :: non_neg_integer
@units [
%{plural: :days, singular: :day, abbrev: "d", duration: 86_400_000_000_000},
%{plural: :hours, singular: :hour, abbrev: "h", duration: 3_600_000_000_000},
%{plural: :minutes, singular: :minute, abbrev: "min", duration: 60_000_000_000},
%{plural: :seconds, singular: :second, abbrev: "s", duration: 1_000_000_000},
%{plural: :milliseconds, singular: :millisecond, abbrev: "ms", duration: 1_000_000},
%{plural: :microseconds, singular: :microsecond, abbrev: "us", duration: 1_000},
%{plural: :nanoseconds, singular: :nanosecond, abbrev: "ns", duration: 1}
]
# Difference between 01.01.1900 (start of NTP epoch) and 01.01.1970 (start of Unix epoch) in seconds
@ntp_unix_epoch_diff 2_208_988_800
@two_to_pow_32 Ratio.pow(2, 32)
@deprecated "Use `is_time/1` instead"
defguard is_t(value) when is_integer(value)
@doc """
Checks whether a value is `Membrane.Time.t`.
"""
defguard is_time(value) when is_integer(value)
@doc """
Returns duration as a string with unit. Chosen unit is the biggest possible
that doesn't involve precission loss.
## Examples
iex> import #{inspect(__MODULE__)}
iex> 10 |> milliseconds() |> pretty_duration()
"10 ms"
iex> 60_000_000 |> microseconds() |> pretty_duration()
"1 min"
iex> 2 |> nanoseconds() |> pretty_duration()
"2 ns"
"""
@spec pretty_duration(t) :: String.t()
def pretty_duration(time) when is_time(time) do
{time, unit} = time |> best_unit()
"#{time} #{unit.abbrev}"
end
@doc """
Returns quoted code producing given amount time. Chosen unit is the biggest possible
that doesn't involve precission loss.
## Examples
iex> import #{inspect(__MODULE__)}
iex> 10 |> milliseconds() |> to_code() |> Macro.to_string()
quote do 10 |> #{inspect(__MODULE__)}.milliseconds() end |> Macro.to_string()
iex> 60_000_000 |> microseconds() |> to_code() |> Macro.to_string()
quote do #{inspect(__MODULE__)}.minute() end |> Macro.to_string()
iex> 2 |> nanoseconds() |> to_code() |> Macro.to_string()
quote do 2 |> #{inspect(__MODULE__)}.nanoseconds() end |> Macro.to_string()
"""
@spec to_code(t) :: Macro.t()
def to_code(time) when is_time(time) do
case best_unit(time) do
{1, unit} ->
quote do
unquote(__MODULE__).unquote(unit.singular)()
end
{time, unit} ->
quote do
unquote(time) |> unquote(__MODULE__).unquote(unit.plural)()
end
end
end
@doc """
Returns string representation of result of `to_code/1`.
"""
@spec to_code_str(t) :: Macro.t()
def to_code_str(time) when is_time(time) do
time |> to_code() |> Macro.to_string()
end
@doc """
Returns current time in pretty format (currently iso8601), as string
Uses `system_time/0` under the hood.
"""
@spec pretty_now :: String.t()
def pretty_now do
system_time() |> to_iso8601()
end
@doc """
Returns current monotonic time based on `System.monotonic_time/0`
in `Membrane.Time` units.
"""
@spec monotonic_time() :: t
def monotonic_time do
System.monotonic_time() |> native_units
end
@doc """
Returns current POSIX time of operating system based on `System.os_time/0`
in `Membrane.Time` units.
This time is not monotonic.
"""
@spec os_time() :: t
def os_time() do
System.os_time() |> native_units
end
@doc """
Returns current Erlang VM system time based on `System.system_time/0`
in `Membrane.Time` units.
It is the VM view of the `os_time/0`. They may not match in case of time warps.
It is not monotonic.
"""
@spec vm_time() :: t
def vm_time() do
System.system_time() |> native_units
end
@doc """
Returns current time of Erlang VM based on `System.system_time/0`
in `Membrane.Time` units.
"""
@deprecated "Use os_time/0 or vm_time/0 instead"
@spec system_time() :: t
def system_time do
System.system_time() |> native_units
end
@doc """
Converts iso8601 string to `Membrane.Time` units.
If `value` is invalid, throws match error.
"""
@spec from_iso8601!(String.t()) :: t
def from_iso8601!(value) when is_binary(value) do
{:ok, datetime, _shift} = value |> DateTime.from_iso8601()
datetime |> from_datetime
end
@doc """
Returns time as a iso8601 string.
"""
@spec to_iso8601(t) :: String.t()
def to_iso8601(value) when is_time(value) do
value |> to_datetime |> DateTime.to_iso8601()
end
@doc """
Converts `DateTime` to `Membrane.Time` units.
"""
@spec from_datetime(DateTime.t()) :: t
def from_datetime(%DateTime{} = value) do
value |> DateTime.to_unix(:nanosecond) |> nanoseconds
end
@doc """
Returns time as a `DateTime` struct. TimeZone is set to UTC.
"""
@spec to_datetime(t) :: DateTime.t()
def to_datetime(value) when is_time(value) do
DateTime.from_unix!(value |> nanoseconds, :nanosecond)
end
@doc """
Converts NTP timestamp (time since 0h on 1st Jan 1900) into Unix timestamp
(time since 1st Jan 1970) represented in `Membrane.Time` units.
NTP timestamp uses fixed point representation with the integer part in the first 32 bits
and the fractional part in the last 32 bits.
"""
@spec from_ntp_timestamp(ntp_time :: <<_::64>>) :: t()
def from_ntp_timestamp(<<ntp_seconds::32, ntp_fraction::32>>) do
fractional = (ntp_fraction * second()) |> div(@two_to_pow_32)
unix_seconds = (ntp_seconds - @ntp_unix_epoch_diff) |> seconds()
unix_seconds + fractional
end
@doc """
Converts the timestamp into NTP timestamp. May introduce small rounding errors.
"""
@spec to_ntp_timestamp(timestamp :: t()) :: <<_::64>>
def to_ntp_timestamp(timestamp) do
seconds = timestamp |> div(second())
ntp_seconds = seconds + @ntp_unix_epoch_diff
fractional = rem(timestamp, second())
ntp_fractional = (fractional * @two_to_pow_32) |> div(second())
<<ntp_seconds::32, ntp_fractional::32>>
end
@doc """
Returns one VM native unit in `Membrane.Time` units.
"""
@spec native_unit() :: t
def native_unit() do
native_units(1)
end
@spec native_unit(integer) :: t
@deprecated "Use `native_unit/0` or `native_units/1` instead."
def native_unit(number) when is_integer(number) do
native_units(number)
end
@doc """
Returns given amount of VM native units in `Membrane.Time` units.
"""
@spec native_units(integer) :: t
def native_units(number) when is_integer(number) do
number |> System.convert_time_unit(:native, :nanosecond) |> nanoseconds
end
@doc """
Returns time in VM native units. Rounded using Kernel.round/1.
"""
@spec to_native_units(t) :: integer
def to_native_units(value) when is_time(value) do
round(value / native_unit())
end
Enum.map(@units, fn unit ->
@doc """
Returns one #{unit.singular} in `#{inspect(__MODULE__)}` units.
"""
@spec unquote(unit.singular)() :: t
# credo:disable-for-next-line Credo.Check.Readability.Specs
def unquote(unit.singular)() do
unquote(unit.duration)
end
@deprecated "Use `#{unit.singular}/0` or `#{unit.plural}/1` instead."
@spec unquote(unit.singular)(integer) :: t
# credo:disable-for-next-line Credo.Check.Readability.Specs
def unquote(unit.singular)(number) when is_integer(number) do
number * unquote(unit.duration)
end
@doc """
Returns given amount of #{unit.plural} in `#{inspect(__MODULE__)}` units.
"""
@spec unquote(unit.plural)(integer) :: t
# credo:disable-for-next-line Credo.Check.Readability.Specs
def unquote(unit.plural)(number) when is_integer(number) do
number * unquote(unit.duration)
end
to_fun_name = :"to_#{unit.plural}"
@doc """
Returns time in #{unit.plural}. Rounded using `Kernel.round/1`.
"""
@spec unquote(to_fun_name)(t) :: integer
# credo:disable-for-next-line Credo.Check.Readability.Specs
def unquote(to_fun_name)(time) when is_time(time) do
round(time / unquote(unit.duration))
end
as_fun_name = :"as_#{unit.plural}"
@doc """
Returns time in #{unit.plural}, represented as a rational number.
"""
@spec unquote(as_fun_name)(t) :: integer | Ratio.t()
# credo:disable-for-next-line Credo.Check.Readability.Specs
def unquote(as_fun_name)(time) when is_time(time) do
Ratio./(time, unquote(unit.duration))
end
end)
defp best_unit(time) do
unit = @units |> Enum.find(&(rem(time, &1.duration) == 0))
{time |> div(unit.duration), unit}
end
end
|
lib/membrane/time.ex
| 0.935744 | 0.698368 |
time.ex
|
starcoder
|
defmodule ResxCSV.Encoder do
@moduledoc """
Encode data resources into strings of CSV.
### Media Types
Only `x.erlang.native` types are valid. This can either be a subtype or suffix.
Valid: `application/x.erlang.native`, `application/geo+x.erlang.native`.
If an error is being returned when attempting to open a data URI due to
`{ :invalid_reference, "invalid media type: \#{type}" }`, the MIME type
will need to be added to the config.
To add additional media types to be encoded, that can be done by configuring
the `:native_types` option.
config :resx_csv,
native_types: [
{ "application/x.my-type", &("application/\#{&1}"), &(&1) }
]
The `:native_types` field should contain a list of 3 element tuples with the
format `{ pattern :: String.pattern | Regex.t, (replacement_type :: String.t -> replacement :: String.t), preprocessor :: (Resx.Resource.content -> Resx.Resource.content) }`.
The `pattern` and `replacement` are arguments to `String.replace/3`. While the
preprocessor performs any operations on the content before it is encoded.
The replacement becomes the new media type of the transformed resource. Nested
media types will be preserved. By default the current matches will be replaced
(where the `x.erlang.native` type part is), with the new type (currently `csv`),
in order to denote that the content is now a CSV type. If this behaviour is not desired
simply override the match with `:native_types` for the media types that should
not be handled like this.
### Encoding
The CSV format (final encoding type) is specified when calling transform,
by providing an atom or string to the `:format` option. This type is then
used to infer how the content should be encoded, as well as what type will
be used for the media type.
Resx.Resource.transform(resource, ResxCSV.Encoder, format: :csv)
The current formats are:
* `:csv` - This encodes the data into CSV. This is the default encoding format.
* `:tsv` - This encodes the data into TSV (tab-separated-values).
Otherwise can pass in any string to explicitly denote another format.
Resx.Resource.transform(resource, ResxCSV.Encoder, format: "dsv", separator: ?;)
### Options
`:format` - expects an `atom` or `String.t` value, defaults to `:csv`. This
option specifies the encoding format.
`:separator` - expects a `char` value, defaults to the separator literal that
is returned for the given encoding format. This option allows for the separator
to be overriden.
`:delimiter` - expects a `String.t` value, defaults to `"\\r\\n"`. This option
specifies the delimiter use to separate the different rows.
`:headers` - expects a `boolean` or `list` value, defaults to `true`. This
option specifies whether the encoding should include headers or not. If `false`
then no headers will be included in the final output, if `true` then the content
will be parsed first in order to get the headers, if a `list` of keys then those
keys will be used as the header. If a header is being used, and given a row of
type `map`, it will use the header to retrieve the individual values, whereas if
the row is a `list` then it will use the list as is. If the content is a stream
and headers are being inferred, this may have unintended effects if any stage of
the stream prior has any side-effects. To alleviate this, you should cache the
previous stage of the stream.
`:validate_row_length` - expects a `boolean` value, defaults to `true`. This
option specifies whether the row length needs to be the same or whether it
can be of variable length. If `true` then it will enforce all rows are of
equal size to the first row, so if a row is a `list` it should match the size
as the previous rows or headers. If `false` then it will use any `list` row
as is.
"""
use Resx.Transformer
alias Resx.Resource.Content
@impl Resx.Transformer
def transform(resource = %{ content: content }, opts) do
case format(opts[:format] || :csv) do
{ format, separator } ->
case validate_type(content.type, format) do
{ :ok, { type, preprocessor } } ->
content = prepare_content(Callback.call(preprocessor, [content]))
rows = case Keyword.get(opts, :headers, true) do
false ->
Stream.map(content, fn
row when is_map(row) -> Map.values(row)
row -> row
end)
headers ->
headers = fn -> get_headers(content, headers) end
Stream.transform(content, { headers, true }, fn
row, acc = { headers, false } when is_map(row) ->
row = Enum.reduce(headers, [], &([row[&1]|&2])) |> Enum.reverse
{ [row], acc }
row, acc = { _, false } -> { [row], acc }
row, { headers, true } when is_map(row) ->
headers = headers.()
row = Enum.reduce(headers, [], &([row[&1]|&2])) |> Enum.reverse
{ [headers, row], { headers, false } }
row, { headers, true } ->
headers = headers.()
{ [headers, row], { headers, false } }
end)
end
rows = if Keyword.get(opts, :validate_row_length, true) do
Stream.transform(rows, nil, fn
row, nil -> { [row], length(row) }
row, n when length(row) == n -> { [row], length(row) }
end)
else
rows
end
opts = [
separator: opts[:separator] || separator,
delimiter: opts[:delimiter] || "\r\n"
]
{ :ok, %{ resource | content: %{ content | type: type, data: rows |> CSV.encode(opts) } } }
error -> error
end
format -> { :error, { :internal, "Unknown encoding format: #{inspect(format)}" } }
end
end
defp prepare_content(content = %Content.Stream{}), do: content
defp prepare_content(content = %Content{}), do: %Content.Stream{ type: content.type, data: content.data }
defp get_headers(content, true) do
Enum.reduce(content, MapSet.new, fn
map, acc when is_map(map) -> map |> Map.keys |> MapSet.new |> MapSet.union(acc)
_, acc -> acc
end)
|> MapSet.to_list
end
defp get_headers(_, headers), do: headers
defp format(format) when format in [:csv, "csv"], do: { "csv", ?, }
defp format(format) when format in [:tsv, "tab-separated-values"], do: { "tab-separated-values", ?\t }
defp format(format) when is_binary(format), do: { format, ?, }
defp format(format), do: format
defp validate_type(types, format) do
cond do
new_type = validate_type(types, Application.get_env(:resx_csv, :native_types, []), format) -> { :ok, new_type }
new_type = validate_type(types, [{ ~r/\/(x\.erlang\.native(\+x\.erlang\.native)?|(.*?\+)x\.erlang\.native)(;|$)/, &("/\\3#{&1}\\4"), &(&1) }], format) -> { :ok, new_type }
true -> { :error, { :internal, "Invalid resource type" } }
end
end
defp validate_type(_, [], _), do: nil
defp validate_type(type_list = [type|types], [{ match, replacement, preprocessor }|matches], format) do
if type =~ match do
{ [String.replace(type, match, Callback.call(replacement, [format]))|types], preprocessor }
else
validate_type(type_list, matches, format)
end
end
end
|
lib/resx_csv/encoder.ex
| 0.910124 | 0.498962 |
encoder.ex
|
starcoder
|
defmodule Journey do
@moduledoc """
Represents a schedule at a stop (origin or destination) or a pair of stops (origin and destination)
"""
alias Predictions.Prediction
alias Schedules.{Schedule, Trip}
defstruct [:departure, :arrival, :trip]
@type t :: %__MODULE__{
departure: PredictedSchedule.t() | nil,
arrival: PredictedSchedule.t() | nil,
trip: Trip.t() | nil
}
@spec has_departure_schedule?(__MODULE__.t()) :: boolean
def has_departure_schedule?(%__MODULE__{departure: departure}),
do: PredictedSchedule.has_schedule?(departure)
def has_departure_schedule?(%__MODULE__{}), do: false
@spec has_departure_prediction?(__MODULE__.t()) :: boolean
def has_departure_prediction?(%__MODULE__{departure: departure}) when not is_nil(departure) do
PredictedSchedule.has_prediction?(departure)
end
def has_departure_prediction?(%__MODULE__{}), do: false
@spec has_arrival_prediction?(__MODULE__.t()) :: boolean
def has_arrival_prediction?(%__MODULE__{arrival: arrival}) when not is_nil(arrival) do
PredictedSchedule.has_prediction?(arrival)
end
def has_arrival_prediction?(%__MODULE__{}), do: false
@spec has_prediction?(__MODULE__.t()) :: boolean
def has_prediction?(journey),
do: has_departure_prediction?(journey) or has_arrival_prediction?(journey)
@spec prediction(__MODULE__.t()) :: Prediction.t() | nil
def prediction(journey) do
cond do
has_departure_prediction?(journey) ->
journey.departure.prediction
has_arrival_prediction?(journey) ->
journey.arrival.prediction
true ->
nil
end
end
@spec time(t) :: DateTime.t() | nil
def time(journey), do: departure_time(journey)
@spec departure_time(__MODULE__.t()) :: DateTime.t() | nil
def departure_time(%__MODULE__{departure: nil}), do: nil
def departure_time(%__MODULE__{departure: departure}), do: PredictedSchedule.time(departure)
@spec arrival_time(__MODULE__.t()) :: DateTime.t() | nil
def arrival_time(%__MODULE__{arrival: nil}), do: nil
def arrival_time(%__MODULE__{arrival: arrival}), do: PredictedSchedule.time(arrival)
@spec departure_prediction_time(__MODULE__.t() | nil) :: DateTime.t() | nil
def departure_prediction_time(%__MODULE__{
departure: %PredictedSchedule{prediction: %Prediction{time: time}}
}),
do: time
def departure_prediction_time(%__MODULE__{}), do: nil
def departure_prediction_time(nil), do: nil
@spec departure_schedule_time(__MODULE__.t() | nil) :: DateTime.t() | nil
def departure_schedule_time(%__MODULE__{
departure: %PredictedSchedule{schedule: %Schedule{time: time}}
}),
do: time
def departure_schedule_time(%__MODULE__{}), do: nil
def departure_schedule_time(nil), do: nil
def departure_schedule_before?(
%__MODULE__{departure: %PredictedSchedule{schedule: %Schedule{time: time}}},
cmp_time
)
when not is_nil(time) do
Timex.before?(time, cmp_time)
end
def departure_schedule_before?(%__MODULE__{}), do: false
def departure_schedule_after?(
%__MODULE__{departure: %PredictedSchedule{schedule: %Schedule{time: time}}},
cmp_time
)
when not is_nil(time) do
Timex.after?(time, cmp_time)
end
def departure_schedule_after?(%__MODULE__{}, _cmp_time), do: false
@doc """
Compares two Journeys and returns true if the first one (left) is before the second (right).
* If both have departure times, compares those
* If both have arrival times, compares those
* If neither have times, compares the status text fields
"""
@spec before?(t, t) :: boolean
def before?(left, right) do
left_departure_time = departure_prediction_time(left) || departure_time(left)
right_departure_time = departure_prediction_time(right) || departure_time(right)
cmp_departure = safe_time_compare(left_departure_time, right_departure_time)
cond do
cmp_departure == -1 ->
true
cmp_departure == 1 ->
false
true ->
arrival_before?(left, right)
end
end
defp safe_time_compare(left, right) when is_nil(left) or is_nil(right) do
0
end
defp safe_time_compare(left, right) do
Timex.compare(left, right)
end
defp arrival_before?(left, right) do
left_arrival_time = arrival_time(left)
right_arrival_time = arrival_time(right)
cmp_arrival = safe_time_compare(left_arrival_time, right_arrival_time)
cond do
is_nil(left_arrival_time) && is_nil(right_arrival_time) ->
# both are nil, sort the statuses (if we have predictions)
prediction_before?(left, right)
cmp_arrival == -1 ->
true
cmp_arrival == 1 ->
false
true ->
is_nil(left_arrival_time)
end
end
defp prediction_before?(left, right) do
left_prediction = prediction(left)
right_prediction = prediction(right)
cond do
is_nil(left_prediction) ->
true
is_nil(right_prediction) ->
false
true ->
status_before?(left_prediction.status, right_prediction.status)
end
end
defp status_before?(left, right) when is_binary(left) and is_binary(right) do
case {Integer.parse(left), Integer.parse(right)} do
{{left_int, _}, {right_int, _}} ->
# both stops away, the lower one is before: "1 stop away" <= "2 stops away"
left_int <= right_int
{{_left_int, _}, _} ->
# right int isn't stops away, so it's before: "1 stop away" >= "Boarding"
false
{_, {_right_int, _}} ->
# left int isn't stops away, so it's before: "Boarding" <= "1 stop away"
true
_ ->
# fallback: sort them in reverse order: "Boarding" <= "Approaching"
left >= right
end
end
defp status_before?(nil, _) do
false
end
defp status_before?(_, nil) do
true
end
@doc """
Returns a message containing the maximum delay between scheduled and predicted times for an arrival
and departure, or the empty string if there's no delay.
"""
@spec display_status(PredictedSchedule.t() | nil, PredictedSchedule.t() | nil) ::
Phoenix.HTML.Safe.t()
def display_status(departure, arrival \\ nil)
def display_status(
%PredictedSchedule{schedule: _, prediction: %Prediction{status: status, track: track}},
_
)
when not is_nil(status) do
status = String.capitalize(status)
case track do
nil ->
Phoenix.HTML.Tag.content_tag(:span, status)
track ->
Phoenix.HTML.Tag.content_tag(
:span,
[
status,
" on ",
Phoenix.HTML.Tag.content_tag(:span, ["track ", track], class: "no-wrap")
]
)
end
end
def display_status(departure, arrival) do
case Enum.max([PredictedSchedule.delay(departure), PredictedSchedule.delay(arrival)]) do
delay when delay > 0 ->
Phoenix.HTML.Tag.content_tag(:span, [
"Delayed ",
Integer.to_string(delay),
" ",
Inflex.inflect("minute", delay)
])
_ ->
""
end
end
end
|
apps/site/lib/journey.ex
| 0.893417 | 0.689021 |
journey.ex
|
starcoder
|
defmodule Hangman.Application do
use Application
@moduledoc """
Main `Hangman` application.
From `Wikipedia`
`Hangman` is a paper and pencil guessing game for two or more players.
One player thinks of a word, phrase or sentence and the other tries
to guess it by suggesting letters or numbers, within a certain number of
guesses.
The word to guess is represented by a row of dashes, representing each letter
of the word. In most variants, proper nouns, such as names, places, and brands,
are not allowed.
If the guessing player suggests a letter which occurs in the word, the other
player writes it in all its correct positions. If the suggested letter or
number does not occur in the word, the other player draws one element of a
hanged man stick figure as a tally mark.
The player guessing the word may, at any time, attempt to guess the whole word.
If the word is correct, the game is over and the guesser wins.
Otherwise, the other player may choose to penalize the guesser by adding an
element to the diagram. On the other hand, if the other player makes enough
incorrect guesses to allow his opponent to complete the diagram, the game is
also over, this time with the guesser losing. However, the guesser can also
win by guessing all the letters or numbers that appears in the word, thereby
completing the word, before the diagram is completed.
The game show `Wheel of Fortune` is based on `Hangman`, but with
the addition of a roulette-styled wheel and cash is awarded for each letter.
NOTE: The game implementation of `Hangman` has removed the ability to guess
the word at any time, but only at the end. No visual depiction of a man is
drawn, simply the word represented by a row of dashes.
`Usage:
--name (player id) --type ("human" or "robot") --random (num random secrets, max 10)
[--secret (hangman word(s)) --baseline] [--log --display]`
or
`Aliase Usage:
-n (player id) -t ("human" or "robot") -r (num random secrets, max 10)
[-s (hangman word(s)) -bl] [-l -d]`
"""
require Logger
@doc """
Main `application` callback start method. Calls `Root.Supervisor`
and Web http server.
"""
# @callback start(term, Keyword.t) :: Supervisor.on_start
def start(_type, args) do
_ = Logger.debug("Starting Hangman Application, args: #{inspect(args)}")
response = Hangman.Supervisor.start_link(args)
Hangman.Web.start_server()
response
end
end
|
lib/hangman.ex
| 0.705278 | 0.722967 |
hangman.ex
|
starcoder
|
defmodule Zoneinfo do
@moduledoc """
Elixir time zone support for your OS-supplied time zone database
Tell Elixir to use this as the default time zone database by running:
```elixir
Calendar.put_time_zone_database(Zoneinfo.TimeZoneDatabase)
```
Time zone data is loaded from the path returned by `tzpath/0`. The default
is to use `/usr/share/zoneinfo`, but that may be changed by setting the
`$TZPATH` environment or adding the following to your project's `config.exs`:
```elixir
config :zoneinfo, tzpath: "/custom/location"
```
Call `time_zones/0` to get the list of supported time zones.
"""
@doc """
Return all known time zones
This function scans the path returned by `tzpath/0` for all time zones and
performs a basic check on each file. It may not be fast. It will not return
the aliases that zoneinfo uses for backwards compatibility even though they
may still work.
"""
@spec time_zones() :: [String.t()]
def time_zones() do
path = Path.expand(tzpath())
Path.join(path, "**")
|> Path.wildcard()
# Filter out directories and symlinks to old names of time zones
|> Enum.filter(fn f -> File.lstat!(f, time: :posix).type == :regular end)
# Filter out anything that doesn't look like a TZif file
|> Enum.filter(&contains_tzif?/1)
# Fix up the remaining paths to look like time zones
|> Enum.map(&String.replace_leading(&1, path <> "/", ""))
end
@doc """
Return the path to the time zone files
"""
@spec tzpath() :: binary()
def tzpath() do
with nil <- Application.get_env(:zoneinfo, :tzpath),
nil <- System.get_env("TZPATH") do
"/usr/share/zoneinfo"
end
end
@doc """
Return whether a time zone is valid
"""
@spec valid_time_zone?(String.t()) :: boolean
def valid_time_zone?(time_zone) do
case Zoneinfo.Cache.get(time_zone) do
{:ok, _} ->
true
_ ->
false
end
end
@doc """
Return Zoneinfo metadata on a time zone
The returned metadata is limited to what's available in the source TZif data
file for the time zone. It's mostly useful for verifying that time zone
information is available for dates used in your application. Note that proper
time zone calculations depend on many things and it's possible that they'll
work outside of the returned ranged. However, it's also possible that a time
zone database was built and then a law changed which invalidates a record.
"""
@spec get_metadata(String.t()) :: {:ok, Zoneinfo.Meta.t()} | {:error, atom()}
defdelegate get_metadata(time_zone), to: Zoneinfo.Cache, as: :meta
defp contains_tzif?(path) do
case File.open(path, [:read], &contains_tzif_helper/1) do
{:ok, result} -> result
_error -> false
end
end
defp contains_tzif_helper(io) do
with buff when is_binary(buff) and byte_size(buff) == 8 <- IO.binread(io, 8),
{:ok, _version} <- Zoneinfo.TZif.version(buff) do
true
else
_anything -> false
end
end
end
|
lib/zoneinfo.ex
| 0.759404 | 0.61086 |
zoneinfo.ex
|
starcoder
|
defmodule Easypost.Address do
alias Easypost.Requester
defstruct [
id: "",
object: "Address",
street1: "",
street2: "",
city: "",
state: "",
zip: "",
country: "",
name: "",
company: "",
phone: "",
email: "",
residential: false,
created_at: "",
updated_at: ""
]
@type t :: %__MODULE__{
id: String.t,
object: String.t,
street1: String.t,
street2: String.t,
city: String.t,
state: String.t,
zip: String.t,
country: String.t,
name: String.t,
company: String.t,
phone: String.t,
email: String.t,
residential: boolean(),
created_at: String.t,
updated_at: String.t
}
@spec create_address(map(), t) :: {:ok, t} | {:error, Easypost.Error.t}
def create_address(conf, address) do
params = %{"address" => address}
case Requester.post("/addresses", params, conf) do
{:ok, address} -> {:ok, struct(Easypost.Address, address)}
{:error, _status, reason} -> {:error, struct(Easypost.Error, reason)}
end
end
@spec create_and_verify_address(map(), t) :: {:ok, t, map()} | {:error, Easypost.Error.t}
def create_and_verify_address(conf, address) do
params = %{"address" => address, "verify[]" => "delivery"}
case Requester.post("/addresses", params, conf) do
{:ok, response} ->
if response[:verifications][:delivery][:success] do
{:ok, struct(Easypost.Address, response), extract_details(response)}
else
reason = [
code: "ADDRESS.VERIFY.FAILURE",
errors: extract_errors(response),
message: "Unable to verify address."
]
{:error, struct(Easypost.Error, reason)}
end
{:error, _status, reason} -> {:error, struct(Easypost.Error, reason)}
end
end
defp extract_details(response) do
response[:verifications][:delivery][:details]
|> Enum.into(%{})
end
defp extract_errors(response) do
response[:verifications][:delivery][:errors]
end
end
|
lib/Easypost/address.ex
| 0.601594 | 0.418429 |
address.ex
|
starcoder
|
defmodule Peach do
@moduledoc """
Peach provides fuzzy matching as well as tools for preprocessing text
## Example
iex> "hɘllo🧐 " |> Peach.pre_process |> Peach.levenshtein_distance("hello")
1
"""
@doc """
Normalize text
Unicode NFKC (Normalisation Form Compatibility Composition) normalisation.
"""
def normalise_text(phrase) do
# https://hexdocs.pm/elixir/1.9.4/String.html#normalize/2
# erlang.org/doc/man/unicode.html#characters_to_nfkc_binary-1
:unicode.characters_to_nfkc_binary(phrase)
end
@doc """
Remove emojis from a string.
WARNING: this currently does not work for 0️⃣ 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣ 8️⃣ 9️⃣ #️⃣ *️⃣ ©️ ®️
it replaces it with the symbol, rather than remove it completely
"""
def remove_emojis(phrase) do
RemoveEmoji.sanitize(phrase)
end
@doc """
Replace spans of whitespace with a single space
"""
def normalise_whitespace(phrase) do
String.replace(phrase, ~r/\s+/u, " ")
|> String.trim()
end
@doc """
Remove punctuation without substitution
"""
def remove_punc(phrase) do
String.replace(phrase, ~r/[\p{P}\p{S}]/u, "")
end
@doc """
Replace punctuation marks with spaces
"""
def replace_punc(phrase) do
String.replace(phrase, ~r/[\p{P}\p{S}]/u, " ")
end
@doc """
Remove numbers without substitution. Applied before keyword matching
"""
def remove_numbers(phrase) do
String.replace(phrase, ~r/\b\d+\s*/u, "")
end
@doc """
Pre-process an utterance in prepartion for number AND keyword matching
"""
def pre_process(phrase) do
phrase
|> String.downcase()
|> normalise_text
|> remove_emojis
|> replace_punc
|> normalise_whitespace
end
@doc """
Get string in to one line
"""
def convert_to_one_line(phrase) do
phrase
|> String.replace("\n", "\\n")
|> String.replace("\r", "\\r")
end
@doc """
Extract the first few characters of the utterance.
"""
def get_brief(phrase, num_chars \\ 20) do
single_line_value = convert_to_one_line(phrase)
if String.length(single_line_value) < num_chars do
phrase
else
end_slice_value = num_chars - 4
String.slice(phrase, 0..end_slice_value) <> "..."
end
end
@doc """
Calculate the Levenshtein edit distance.
"""
def levenshtein_distance(first_phrase, second_phrase) do
Levenshtein.distance(first_phrase, second_phrase)
end
@doc """
Find if there is an exact match to keyword set. The keywords may be numbers.
"""
def find_exact_match(input, keyword_set),
do:
Enum.find(keyword_set, fn
^input -> true
_other -> false
end)
@doc """
Find the fuzzy matches to the keyword_threshold set. Each keyword has its own threshold.
"""
def find_fuzzy_matches(input, keyword_threshold_set) do
cleaned_input = remove_numbers(input)
case cleaned_input do
"" ->
[]
_ ->
keyword_threshold_set
# add the edit distance.
|> Enum.map(fn {keyword, threshold} ->
{keyword, levenshtein_distance(cleaned_input, keyword), threshold}
end)
# only keep close matches.
|> Enum.filter(fn {_keyword, distance, threshold} ->
distance <= threshold
end)
# drop threshold.
|> Enum.map(fn {keyword, distance, _threshold} ->
{keyword, distance}
end)
# order from best to worst matches.
|> Enum.sort(&(elem(&1, 1) < elem(&2, 1)))
end
end
@doc """
Find the fuzzy matches to the keyword set. All keywords use the same threshold.
"""
def find_fuzzy_matches(input, keyword_set, threshold) do
# build keyword_threshold_set.
keyword_threshold_set =
keyword_set
|> Enum.map(fn keyword ->
{keyword, threshold}
end)
find_fuzzy_matches(input, keyword_threshold_set)
end
end
|
lib/peach.ex
| 0.798069 | 0.406509 |
peach.ex
|
starcoder
|
defmodule Elasr.KategorijaController do
use Elasr.Web, :controller
alias Elasr.Kategorija
def index(conn, _params) do
kategorije = Repo.all(Kategorija)
render(conn, "index.html", kategorije: kategorije)
end
def new(conn, _params) do
changeset = Kategorija.changeset(%Kategorija{})
render(conn, "new.html", changeset: changeset)
end
def create(conn, %{"kategorija" => kategorija_params}) do
changeset = Kategorija.changeset(%Kategorija{}, kategorija_params)
case Repo.insert(changeset) do
{:ok, _kategorija} ->
conn
|> put_flash(:info, "Kategorija created successfully.")
|> redirect(to: kategorija_path(conn, :index))
{:error, changeset} ->
render(conn, "new.html", changeset: changeset)
end
end
def show(conn, %{"id" => id}) do
kategorija = Repo.get!(Kategorija, id)
render(conn, "show.html", kategorija: kategorija)
end
def edit(conn, %{"id" => id}) do
kategorija = Repo.get!(Kategorija, id)
changeset = Kategorija.changeset(kategorija)
render(conn, "edit.html", kategorija: kategorija, changeset: changeset)
end
def update(conn, %{"id" => id, "kategorija" => kategorija_params}) do
kategorija = Repo.get!(Kategorija, id)
changeset = Kategorija.changeset(kategorija, kategorija_params)
case Repo.update(changeset) do
{:ok, kategorija} ->
conn
|> put_flash(:info, "Kategorija updated successfully.")
|> redirect(to: kategorija_path(conn, :show, kategorija))
{:error, changeset} ->
render(conn, "edit.html", kategorija: kategorija, changeset: changeset)
end
end
def delete(conn, %{"id" => id}) do
kategorija = Repo.get!(Kategorija, id)
# Here we use delete! (with a bang) because we expect
# it to always work (and if it does not, it will raise).
Repo.delete!(kategorija)
conn
|> put_flash(:info, "Kategorija deleted successfully.")
|> redirect(to: kategorija_path(conn, :index))
end
end
|
web/controllers/kategorija_controller.ex
| 0.614163 | 0.489992 |
kategorija_controller.ex
|
starcoder
|
defmodule XPlane.Data do
@moduledoc """
Get and set X-Plane data.
"""
@startup_grace_period 1100
@listen_port 59000
use GenServer
# API
@doc """
Start GenServer to exchange data references with a specific X-Plane
instance.
## Parameters
- instance: X-Plane instance from list returned by `XPlane.Instance.list/0`
"""
@spec start(XPlane.Instance.t, list) :: {:ok, pid} | {:error, any} | :ignore
def start(instance, opts \\ []) do
GenServer.start(__MODULE__,
{:ok, instance},
[name: name(instance)] ++ opts)
end
@doc """
Start GenServer linked to current process to exchange data references with
a specific X-Plane instance.
## Parameters
- instance: X-Plane instance from list returned by `XPlane.Instance.list/0`
"""
@spec start_link(XPlane.Instance.t, list) :: {:ok, pid} | {:error, any} | :ignore
def start_link(instance, opts \\ []) do
GenServer.start_link(__MODULE__,
{:ok, instance},
[name: name(instance)] ++ opts)
end
@doc """
Request updates of the specified data references at the corresponding frequency.
Values can then be retrieved using `XPlane.Data.latest_updates/2`. A small
delay occurs during the call to give the GenServer a chance to collect at least
one value for each requested data reference.
## Parameters
- instance: X-Plane instance from list returned by `XPlane.Instance.list/0`
- data_ref_id_freq: Keyword list of data reference ids and integer updates
per second
## Example
```
iex> XPlane.Data.request_updates(master, [flightmodel_position_indicated_airspeed: 10])
:ok
```
"""
@spec request_updates(XPlane.Instance.t, list({atom, integer})) :: :ok | {:error, list}
def request_updates(instance, data_ref_id_freq) do
case GenServer.call(name(instance), {:request_updates, data_ref_id_freq}) do
e = {:error, _} ->
e
r ->
:timer.sleep(@startup_grace_period) # Allow time for data to be received
r
end
end
@doc """
Request latest values of the listed data reference ids. Values will not be
available until you have called `XPlane.Data.request_updates/2`. If you request
a data reference that we have not received a value for, an:
```
{:error, {no_values, [list of requested data reference ids missing values]}}`
```
message is returned. This seemed to be more a more useful way to handle missing
values, because most clients will need all the requested values to do their work.
## Parameters
- instance: X-Plane instance from list returned by `XPlane.Instance.list/0`
- data_ref_ids: List of data reference ids to return values for
## Example
```
iex> master |> XPlane.Data.latest_updates([:flightmodel_position_elevation])
%{flightmodel_position_elevation: ...}`
```
"""
@spec latest_updates(XPlane.Instance.t, list(atom)) :: %{atom: float | nil}
def latest_updates(instance, data_ref_id_list) do
GenServer.call(name(instance), {:latest_updates, data_ref_id_list})
end
@doc """
Set one or more writable data reference values.
## Parameters
- instance: X-Plane instance from list returned by `XPlane.Instance.list/0`
- data_ref_id_values: Keyword list of data reference ids and floating point
new values to set
## Example
```
iex> XPlane.Data.set(master, [flightmodel_position_local_y: 1000.0])
:ok
```
"""
@spec set(XPlane.Instance.t, list({atom, number})) :: :ok | {:error, list}
def set(instance, data_ref_id_values) do
case GenServer.call(name(instance), {:set, data_ref_id_values}) do
e = {:error, _} -> e
r -> r
end
end
@doc """
Stop the GenServer listening for data reference updates, and tell X-Plane to
stop sending any we are currently subscribed to.
"""
@spec stop(XPlane.Instance.t) :: :ok | {:error, any}
def stop(instance) do
GenServer.cast(name(instance), :stop)
end
# GensServer Callbacks
@impl true
def init({:ok, instance}) do
{:ok, sock} = :gen_udp.open(@listen_port, [:binary, active: true])
{:ok, {XPlane.DataRef.load_version(instance.version_number), %{}, instance, sock}}
end
@impl true
def handle_call({:request_updates, data_ref_id_freq}, _from, state={data_refs, _, instance, sock}) do
code_freq = for {data_ref_id, freq} <- data_ref_id_freq do
if data_refs |> Map.has_key?(data_ref_id) do
if is_integer(freq) and freq in 0..400 do
{:ok, freq, data_refs[data_ref_id].code, data_refs[data_ref_id].name}
else
{:error, {:freq, data_ref_id, freq}}
end
else
{:error, {:data_ref_id, data_ref_id, freq}}
end
end
errors = code_freq |> Enum.filter(&(match?({:error, _}, &1)))
if Enum.empty?(errors) do
for {:ok, freq, code, name} <- code_freq do
padded_name = pad_with_trailing_zeros(name, 400)
:ok = :gen_udp.send(
sock,
instance.ip,
instance.port,
<<"RREF\0",
freq::native-integer-32,
code::native-integer-32,
padded_name::binary>>
)
end
{:reply, :ok, state}
else
{:reply, {:error,
for {_, {type, data_ref_id, freq}} <- errors do
case type do
:freq ->
"Invalid frequency #{freq} for data reference #{data_ref_id}"
:data_ref_id ->
"Invalid data reference id: #{Atom.to_string(data_ref_id)}"
end
end
}, state}
end
end
def handle_call({:latest_updates, data_ref_ids}, _from, state={data_refs, code_data, _, _}) do
data = for data_ref_id <- data_ref_ids do
{
data_ref_id,
if Map.has_key?(data_refs, data_ref_id) do
code_data |> Map.get(data_refs[data_ref_id].code, nil)
else
nil
end
}
end |> Map.new
{:reply, data, state}
end
def handle_call({:set, data_ref_values}, _from, state={data_refs, _, instance, sock}) do
name_values = for {data_ref_id, value} <- data_ref_values do
if data_refs |> Map.has_key?(data_ref_id) do
if data_refs[data_ref_id].writable do
if is_float(value) do
{:ok, data_refs[data_ref_id].name, value}
else
if is_integer(value) do
# Divide by 1 to force float
{:ok, data_refs[data_ref_id].name, value / 1}
else
{:error, {:invalid_value, {data_ref_id, value}}}
end
end
else
{:error, {:not_writable, data_ref_id}}
end
else
{:error, {:invalid_id, data_ref_id}}
end
end
errors = name_values |> Enum.filter(&(match?({:error, _}, &1)))
if Enum.empty?(errors) do
for {:ok, name, value} <- name_values do
padded_name = pad_with_trailing_zeros(name, 500)
:ok = :gen_udp.send(
sock,
instance.ip,
instance.port,
<<"DREF\0",
value::native-float-32,
padded_name::binary>>
)
end
{:reply, :ok, state}
else
{:reply, {:error,
for {_, {type, detail}} <- errors do
case type do
:invalid_value ->
{data_ref_id, value} = detail
"Invalid value #{value} for data reference #{data_ref_id}"
:invalid_id ->
"Invalid data reference id: #{detail}"
:not_writable ->
"Data reference id #{detail} is not writable"
end
end
}, state}
end
end
@impl true
def handle_cast(:stop, {data_refs, code_data, instance, sock}) do
# Cancel updates from X-Plane by setting frequency to 0
for code <- Map.keys(code_data) do
%XPlane.DataRef{name: name} = data_refs |> XPlane.DataRef.withCode(code)
padded_name = pad_with_trailing_zeros(name, 400)
:ok = :gen_udp.send(
sock,
instance.ip,
instance.port,
<<"RREF\0",
0::native-integer-32,
code::native-integer-32,
padded_name::binary>>
)
end
:gen_udp.close(sock)
{:stop, :normal, nil}
end
@impl true
def handle_info({:udp, _sock, _ip, _port,
<<"RREF",
# "O" for X-Plane 10
# "," for X-Plane 11
# neither match documentation...
_::size(8),
tail::binary>>},
{data_refs, code_data, instance, sock}) do
{:noreply,
{
data_refs,
unpack_xdata(code_data, tail),
instance,
sock
}
}
end
def handle_info(msg, state) do
IO.inspect({:unexpected_msg, msg})
{:noreply, state}
end
# Helpers
defp unpack_xdata(code_data, <<>>) do
code_data
end
defp unpack_xdata(code_data,
<<code::native-integer-32,
data::native-float-32,
tail::binary>>) do
unpack_xdata(code_data |> Map.put(code, data), tail)
end
defp name(instance) do
String.to_atom("#{__MODULE__}_#{instance.addr}")
end
defp pad_with_trailing_zeros(bin, len) do
pad_len = 8 * (len - byte_size(bin))
<<bin::binary, 0::size(pad_len)>>
end
end
|
lib/xplane_data.ex
| 0.822474 | 0.742958 |
xplane_data.ex
|
starcoder
|
defmodule PassiveSupport.PostBody do
@moduledoc """
Functions for working with `www-form-urlencoded` data
"""
@doc ~s"""
Deep-parses the map into a string formatted according to the `www-form-urlencoded` spec.
## Examples
iex> form_encoded(%{
...> "success_url" => "https://localhost:4001/foo/bert?id={ID}",
...> "cancel_url" => "https://localhost:4001/foo/bar",
...> "blips" => ["blop", "blorp", "blep"],
...> "array" => [
...> %{"something" => "five dollars", "quantity" => 1},
...> %{"line" => "line", "item" => "item"},
...> %{"let's" => ~W[really flerf this up]}
...> ],
...> "mode" => "median",
...> "just_to_make_sure" => %{
...> "we got" => "all", "the edge" => "cases", "we can think of" => "covered"
...> }
...> })
~S(array[0][quantity]=1&#{
}array[0][something]=five+dollars&#{
}array[1][item]=item&#{
}array[1][line]=line&#{
}array[2][let%27s][0]=really&#{
}array[2][let%27s][1]=flerf&#{
}array[2][let%27s][2]=this&#{
}array[2][let%27s][3]=up&#{
}blips[0]=blop&#{
}blips[1]=blorp&#{
}blips[2]=blep&#{
}cancel_url="https://localhost:4001/foo/bar"&#{
}just_to_make_sure[the+edge]=cases&#{
}just_to_make_sure[we+can+think+of]=covered&#{
}just_to_make_sure[we+got]=all&#{
}mode=median&#{
}success_url="https://localhost:4001/foo/bert?id={ID}"#{
})
iex> form_encoded(%{something: :dotcom})
"something=dotcom"
"""
@spec form_encoded(map) :: String.t
# Need to differentiate keyword lists, keywordish lists, and maps from generic lists;
# the former can all be form encoded, generic lists cannot be.
def form_encoded([{_,_}|_] = enum), do: do_form_encoding(enum)
def form_encoded(enum) when is_map(enum), do: do_form_encoding(enum)
defp do_form_encoding(enum, data_path \\ [])
defp do_form_encoding([{_,_}|_] = enum, data_path) do
enum
|> Enum.map(fn
{key, value} ->
if Enumerable.impl_for(value),
do: do_form_encoding(value, [key | data_path]),
else: [construct_path([key | data_path]), sanitize_input(value)] |> Enum.join("=")
end)
|> Enum.join("&")
end
defp do_form_encoding(%{} = enum, data_path) do
enum
|> Enum.map(fn
{key, value} ->
if Enumerable.impl_for(value),
do: do_form_encoding(value, [key | data_path]),
else: [construct_path([key | data_path]), sanitize_input(value)] |> Enum.join("=")
end)
|> Enum.join("&")
end
defp do_form_encoding([_|_] = enum, data_path) do
enum
|> Stream.with_index
|> Enum.map(fn
{value, index} ->
if Enumerable.impl_for(value),
do: do_form_encoding(value, [index | data_path]),
else: [construct_path([index | data_path]), sanitize_input(value)] |> Enum.join("=")
end)
|> Enum.join("&")
end
defp construct_path(path, path_iolist \\ [])
defp construct_path([key | []], path_iolist),
do: IO.chardata_to_string([sanitize_input(key) | path_iolist])
defp construct_path([key_or_index | path], path_iolist),
do: construct_path(path, [["[" , sanitize_input(key_or_index), "]"], path_iolist])
defp sanitize_input(index) when is_integer(index) or is_atom(index), do: to_string(index)
defp sanitize_input("" <> input) do
case String.match?(input, ~r"[/&?]") do
true -> input |> URI.parse |> to_string |> inspect
false -> URI.encode_www_form(input)
end
end
end
|
lib/passive_support/ext/post_body.ex
| 0.627495 | 0.435601 |
post_body.ex
|
starcoder
|
defmodule CollectableUtils do
@doc """
Routes an Enumerable into Collectables based on a `key_fun`.
This function is essentially a cross between `Enum.into/2` and `Enum.group_by/2`. Rather than
the simple lists of `Enum.group_by/2`, `into_by/3` populates a set of Collectables.
Like `Enum.group_by/2`, the caller supplies a routing function `key_fun`, specifying a
"bucket name" for each element to be placed into.
Unlike `Enum.group_by/2`, when a bucket does not already exist, `initial_fun` is called with
the new `key`, and must return a command, one of the following:
* `{:new, Collectable.t()}` – creates a new bucket with the given Collectable as the initial value
* `:discard` – drops the element and continues processing
* `:invalid` – stops processing and returns an error `{:invalid, element, key}`
For convenience, rather than an `initial_fun`, you may pass a tuple `{initial_map, not_found_command}`. Keys existing in `initial_map` will translate to `{:new, value}`. Other keys will return `not_found_command`.
The default behavior if `initial_fun` is not passed, is to imitate the behavior of `Enum.group_by/2`. This is equivalent to passing `{%{}, {:new, []}}` as an `initial_fun`.
## Examples
# imitate Enum.group_by/3 more explicitly
iex> CollectableUtils.into_by!(
...> 0..5,
...> fn i -> :erlang.rem(i, 3) end,
...> fn _ -> {:new, []} end
...> )
%{0 => [0, 3], 1 => [1, 4], 2 => [2, 5]}
# Enum.group_by/3, but with MapSets, and for only existing keys
iex> CollectableUtils.into_by!(
...> 0..5,
...> fn i -> :erlang.rem(i, 3) end,
...> {Map.new([0, 1], &{&1, MapSet.new()}), :discard}
...> )
%{
0 => %MapSet{map: %{0 => [], 3 => []}},
1 => %MapSet{map: %{1 => [], 4 => []}}
}
## Recipes
# Distribute lines to files by hash
CollectableUtils.into_by(
event_stream,
fn event_ln ->
:erlang.phash2(event_ln) |> :erlang.rem(256)
end,
fn shard ->
{:new, File.stream!("events-\#{shard}.events")}
end
)
# Hourly log rotation
CollectableUtils.into_by(
log_stream,
fn _ -> :erlang.system_time(:second) |> :erlang.div(3600) end,
fn period -> {:new, File.stream!("app-\#{period}.log")} end
)
"""
def into_by(enumerable, key_fun, initial_fun \\ {%{}, {:new, []}}) do
initial_fun =
case initial_fun do
f when is_function(f) ->
f
{initial_map, not_found_command} when is_map(initial_map) ->
fn k -> default_initial_fun(initial_map, k, not_found_command) end
end
try do
populated_collectors =
Enum.reduce(enumerable, %{}, fn element, collectors ->
key = key_fun.(element)
case Map.fetch(collectors, key) do
{:ok, {original, collector_fun}} ->
Map.put(collectors, key, {collector_fun.(original, {:cont, element}), collector_fun})
:error ->
case initial_fun.(key) do
{:new, new_collectable} ->
{new_original, collector_fun} = Collectable.into(new_collectable)
Map.put_new(
collectors,
key,
{collector_fun.(new_original, {:cont, element}), collector_fun}
)
:discard ->
collectors
:invalid ->
throw {:invalid, element, key}
end
end
end)
final_collectables =
Map.new(populated_collectors, fn {name, {updated, collector_fun}} ->
{name, collector_fun.(updated, :done)}
end)
{:ok, final_collectables}
catch {:invalid, element, key} ->
{:invalid, element, key}
end
end
@doc """
Routes an Enumerable into Collectables based on a `key_fun`, erroring out if
if a Collectable cannot be constructed for a key.
Like `into_by/3`, but raises an ArgumentError if `initial_fun` returns
`:invalid`.
"""
def into_by!(enumerable, key_fun, initial_fun \\ {%{}, {:new, []}}) do
case into_by(enumerable, key_fun, initial_fun) do
{:ok, final_collectables} ->
final_collectables
{:invalid, element, key} ->
raise ArgumentError, "invalid key #{inspect key} derived for element: #{inspect element}"
end
end
defp default_initial_fun(initial_map, key, not_found_command) do
case Map.fetch(initial_map, key) do
{:ok, value} -> {:new, value}
:error -> not_found_command
end
end
end
|
lib/collectable_utils.ex
| 0.857515 | 0.699139 |
collectable_utils.ex
|
starcoder
|
defmodule Moon do
# values for 2010 epoch
@sun_ecliptic_longitude 4.8791937
@sun_ecliptic_longitude_perigee 4.9412442
@sun_orbit_eccentricity 0.016_705
@mean_longitude_epoch 1.6044696 # radians
@mean_longitude_perigee 2.2714252 # radians
@mean_longitude_ascending_node_epoch 5.0908208 # radians
@inclination_orbit 0.0898041 # radians
@eccentricity_orbit 0.0549 # radians
@semi_major_axis 384_401 # km
@angular_diameter 0.5181 # degrees
@parallax 0.9507 # degrees
def get_position({{year, month, day}, {hour, minute, second}}) do
%Epoch{day: day} = Epoch.init({{year, month, day}, {hour, minute, second}})
# sun
sun_mean_anomaly = 2*:math.pi/365.242_191*day + @sun_ecliptic_longitude - @sun_ecliptic_longitude_perigee
sun_true_anomaly = sun_mean_anomaly + 2*@sun_orbit_eccentricity*:math.sin(sun_mean_anomaly)
sun_ecliptic_longitude = sun_true_anomaly + @sun_ecliptic_longitude_perigee
# moon
mean_longitude = 2*:math.pi / 360.0 * 13.1763966*day + @mean_longitude_epoch
mean_anomaly = mean_longitude - 2*:math.pi / 360.0 * 0.1114041 * day - @mean_longitude_perigee
ascending_node_mean_longitude = @mean_longitude_ascending_node_epoch - 2*:math.pi / 360.0 * 0.0529539 * day
evection_correction = 2*:math.pi / 360.0 * 1.2739 * :math.sin(2*(mean_longitude - sun_ecliptic_longitude) - mean_anomaly)
annual_equation = 2*:math.pi / 360.0 * 0.1858 * :math.sin(sun_mean_anomaly)
third_correction = 2*:math.pi / 360.0 * 0.37 * :math.sin(sun_mean_anomaly)
corrected_anomaly = mean_anomaly + evection_correction - annual_equation - third_correction
equation_centre = 2*:math.pi / 360.0 * 6.2886 * :math.sin(corrected_anomaly)
forth_correction = 2*:math.pi / 360.0 * 0.214 * :math.sin(2*corrected_anomaly)
corrected_longitude = mean_longitude + evection_correction + equation_centre - annual_equation + forth_correction
variation = 2*:math.pi / 360.0 * 0.6583 * :math.sin(2*(corrected_longitude - sun_ecliptic_longitude))
true_orbital_longitude = corrected_longitude + variation
ascending_node_corrected_longitude = ascending_node_mean_longitude - 2*:math.pi / 360.0 * 0.16*:math.sin(sun_mean_anomaly)
longitude = :math.atan2(:math.sin(true_orbital_longitude - ascending_node_corrected_longitude)*:math.cos(@inclination_orbit),
:math.cos(true_orbital_longitude - ascending_node_corrected_longitude)) + ascending_node_corrected_longitude
latitude = :math.asin(:math.sin(true_orbital_longitude - ascending_node_corrected_longitude)*:math.sin(@inclination_orbit))
longitude = Angle.normalize(radians: longitude)
latitude = Angle.normalize_90_90(radians: latitude)
%Coordinates.Ecliptic{latitude: %Angle{radians: latitude},
longitude: %Angle{radians: longitude}}
end
end
|
lib/moon.ex
| 0.620047 | 0.580055 |
moon.ex
|
starcoder
|
defmodule Crow.Plugin do
@moduledoc """
The behaviour all configured plugins should implement.
## Overview
Writing [Munin plugins](http://guide.munin-monitoring.org/en/latest/plugin/index.html)
is rather simple. A trivial plugin with the default
Munin node setup is a script with two main behaviours:
- When invoked with the command line argument `config`, print out configuration
of the plugin, such as graph setup (title, category, labels), field information
and more. A full description of all options can be found at the [Plugin reference](
http://guide.munin-monitoring.org/en/latest/reference/plugin.html) documentation.
- When not invoked with any command line argument, print out the values for fields
declared in the `config` command.
This is the foundation from which plugins are developed. Since our node runs in
the BEAM, we've taken a different approach here. Instead of being executable shell
scripts, crow plugins are modules which provide two main functions:
- `c:config/0`, which returns the configuration of the plugin, corresponding to
the first invocation form described above.
- `c:values/0`, which returns the values of the plugin, corresponding to the
second invocation form described above.
Instead of printing to standard output, these return a list of charlists which
is then sent to the peer via TCP.
An additional callback, `c:name/0`, specifies the name of the plugin shown to
Munin. This must be unique amongst all plugins configured on the node.
## Community plugins
Plugins for the crow node can be found in the
[`crow_plugins`](https://github.com/jchristgit/crow_plugins) repository.
"""
@doc """
Display the configuration for this plugin.
Each element in the output represents a single line in the output.
Adding newlines to each line is done by the worker.
For reference, see [Munin plugin config command](http://guide.munin-monitoring.org/en/latest/develop/plugins/howto-write-plugins.html#munin-plugin-config-command)
from the official documentation.
## Example
def config do
[
'graph_title Total processes',
'graph_category BEAM',
'graph_vlabel processes',
'processes.label processes'
]
end
"""
@callback config() :: [charlist()]
@doc """
Display values for this plugin.
## Example
def values do
[
'processes.value #\{length(:erlang.processes())\}'
]
end
"""
@callback values() :: [charlist()]
@doc """
Return the name of the plugin displayed to peers.
## Example
def name do
'my_plugin'
end
"""
@callback name() :: charlist()
end
|
lib/crow/plugin.ex
| 0.874252 | 0.571677 |
plugin.ex
|
starcoder
|
defmodule Tanks.Game.Cache.Position do
alias Tanks.Game.Components.Position
alias Tanks.Game.Components.Size
@component_types [Position, Size]
def component_types, do: @component_types
@initial_state []
def initial_state, do: @initial_state
@doc """
Rebuilds the cache.
"""
def update(game_id) do
ECS.Cache.clear(game_id, __MODULE__)
component_tuples(game_id)
|> Enum.map(&add_component_tuple(game_id, &1))
end
def update(game_id, entity) do
update_entity(game_id, entity)
end
@possible_places [
{1, 0},
{1, 1},
{0, 1},
{1, 1},
{-1, 0},
{-1, -1},
{0, -1},
{1, -1}
]
def closest_empty_place(game_id, x, y, {_shape_type, shape_size} = shape) do
if colliding_entities(game_id, x, y, shape, blocking: true) |> Enum.empty?() do
{x, y}
else
found_place =
@possible_places
|> Enum.shuffle()
|> Enum.find(fn {x_shift, y_shift} ->
x_shifted = x + x_shift * shape_size
y_shifted = y + y_shift * shape_size
colliding_entities(game_id, x_shifted, y_shifted, shape, blocking: true)
|> Enum.empty?()
end)
if found_place do
{x_shift, y_shift} = found_place
x_shifted = x + x_shift * shape_size
y_shifted = y + y_shift * shape_size
{:ok, {x_shifted, y_shifted}}
else
{:error, "Can't place"}
end
end
end
def colliding_entities(
game_id,
check_x,
check_y,
check_shape,
opts \\ []
) do
filter_id_not = Keyword.get(opts, :id_not, nil)
filter_type = Keyword.get(opts, :type, nil)
filter_blocking = Keyword.get(opts, :blocking, nil)
ECS.Cache.get(game_id, __MODULE__)
# Filters
|> Enum.filter(fn {_x, _y, _shape, _blocking, _entity_type, entity_id} ->
filter_id_not == nil or entity_id != filter_id_not
end)
|> Enum.filter(fn {_x, _y, _shape, _blocking, entity_type, _entity_id} ->
filter_type == nil or filter_type == entity_type
end)
|> Enum.filter(fn {_x, _y, _shape, blocking, _entity_type, _entity_id} ->
filter_blocking == nil or filter_blocking == blocking
end)
# Find collisions
|> Enum.filter(fn {x, y, shape, _blocking, _entity_type, _entity_id} ->
Utils.Math.collision?(x, y, shape, check_x, check_y, check_shape)
end)
# Add distance
|> Enum.map(fn {x, y, shape, blocking, entity_type, entity_id} ->
{x, y, shape, blocking, entity_type, entity_id, Utils.Math.distance(x, y, check_x, check_y)}
end)
# Sort by distance
|> Enum.sort_by(fn {_x, _y, _shape, _blocking, _entity_type, _entity_id, distance} ->
distance
end)
# Format result
|> Enum.map(fn {_x, _y, _shape, _blocking, entity_type, entity_id, _distance} ->
{entity_type, entity_id}
end)
end
defp update_entity(
game_id,
%{
__struct__: entity_type,
id: entity_id,
components: %{position: %{pid: position_pid}, size: %{pid: size_pid}}
} = _entity
) do
elem = build_cached_entity(entity_type, entity_id, position_pid, size_pid)
ECS.Cache.update(game_id, __MODULE__, fn state ->
filtered_state =
state
|> Enum.filter(fn {_x, _y, _shape, _blocking, _entity_type, state_entity_id} ->
state_entity_id != entity_id
end)
[elem | filtered_state]
end)
end
defp add_component_tuple(game_id, {entity_type, entity_id, {position_pid, size_pid}}) do
elem = build_cached_entity(entity_type, entity_id, position_pid, size_pid)
ECS.Cache.update(game_id, __MODULE__, fn state ->
[elem | state]
end)
end
defp build_cached_entity(entity_type, entity_id, position_pid, size_pid) do
%{x: x, y: y} = ECS.Component.get_state(position_pid)
%{shape: shape, blocking: blocking} = ECS.Component.get_state(size_pid)
{x, y, shape, blocking, entity_type, entity_id}
end
defp component_tuples(game_id) do
id = ECS.Registry.ComponentTuple.build_registry_id(@component_types)
ECS.Registry.ComponentTuple.get(game_id, id)
end
end
|
lib/tanks/game/cache/position.ex
| 0.609757 | 0.407746 |
position.ex
|
starcoder
|
defmodule Cast do
require IEx
defmodule Foo do
def head([h | _ ]) do
h
end
end
defmodule BadArgumentError do
defexception message: "Cast function couldn't process this argument tuple",
value: nil,
left_type: nil,
right_type: nil
def new(%{reason: reason, value: value, left_type: left_type, right_type: right_type} = params) do
message =
case reason do
"type_error" ->
"#{inspect(value)} is not of type #{inspect(left_type)}"
"inconsistent_types" ->
"#{inspect(left_type)} is not consistent with #{inspect(right_type)}"
end
message =
"Cast #{inspect(value)} from #{inspect(left_type)} into #{inspect(right_type)} is forbidden:\n #{message}"
struct(BadArgumentError, Map.put(params, :message, message))
end
end
defmodule CastError do
defexception message: "Cast error", expression: nil, left_type: nil, right_type: nil
def new(%{value: value, left_type: left_type, right_type: right_type} = params) do
message = "Couldn't cast #{inspect(value)} from type #{inspect(left_type)} into #{inspect(right_type)}"
struct(CastError, Map.put(params, :message, message))
end
end
defguard is_base(type)
when (is_atom(type) and type != :any) or
(is_tuple(type) and tuple_size(type) == 2 and elem(type, 0) == :atom and
is_atom(elem(type, 1)))
defguard is_base_value(value)
when is_atom(value) or is_boolean(value) or is_integer(value) or is_float(value)
def build_type_from_ast(type_ast) do
# IO.inspect(type_ast)
case type_ast do
{type_ast_1, type_ast_2} ->
{:tuple, [build_type_from_ast(type_ast_1), build_type_from_ast(type_ast_2)]}
{:{}, _, type_list_ast} ->
{:tuple, Enum.map(type_list_ast, &build_type_from_ast/1)}
[{:->, _, [type_list_ast, type_ast]}] ->
{:fun, Enum.map(type_list_ast, &build_type_from_ast/1), build_type_from_ast(type_ast)}
[] ->
{:elist, []}
_ when is_list(type_ast) and length(type_ast) == 1 ->
[item] = type_ast
{:list, build_type_from_ast(item)}
{:%{}, _, key_type_list} ->
aux = Enum.map(key_type_list, fn {key, type} -> {key, build_type_from_ast(type)} end)
{:map, Enum.into(aux, %{})}
{item, _, _} when is_atom(item) ->
item
item when is_atom(item) ->
{:atom, item}
end
end
def type_for_value(value) do
case value do
_ when is_boolean(value) -> {:atom, value}
_ when is_atom(value) -> {:atom, value}
_ when is_integer(value) -> :integer
_ when is_float(value) -> :float
end
end
def is_base_subtype(left_type, right_type) do
case {left_type, right_type} do
{type, type} -> true
{{:atom, _}, :atom} -> true
{{:atom, false}, :boolean} -> true
{{:atom, true}, :boolean} -> true
{:boolean, :atom} -> true
{:integer, :number} -> true
{:float, :number} -> true
_ -> false
end
end
def is_consistent_subtype(left_type, right_type) do
case {left_type, right_type} do
_ when is_base(left_type) and is_base(right_type) ->
is_base_subtype(left_type, right_type)
{:any, _} ->
true
{_, :any} ->
true
{{:elist, []}, {:elist, []}} ->
true
{{:elist, []}, {:list, _}} ->
true
{{:list, left_type}, {:list, right_type}} ->
is_consistent_subtype(left_type, right_type)
{{:tuple, left_type_list}, {:tuple, right_type_list}}
when length(left_type_list) == length(right_type_list) ->
Enum.zip(left_type_list, right_type_list)
|> Enum.all?(fn {type1, type2} -> is_consistent_subtype(type1, type2) end)
{{:map, left_type_map}, {:map, right_type_map}} ->
if Enum.all?(Map.keys(right_type_map), &Enum.member?(Map.keys(left_type_map), &1)) do
Enum.all?(right_type_map, fn {k, type} ->
is_consistent_subtype(left_type_map[k], type)
end)
else
false
end
{{:fun, left_type_list, left_type}, {:map, right_type_list, right_type}}
when length(left_type_list) == length(right_type_list) ->
if is_consistent_subtype(left_type, right_type) do
Enum.zip(left_type_list, right_type_list)
|> Enum.all?(fn {type1, type2} -> is_consistent_subtype(type1, type2) end)
else
false
end
_ ->
false
end
end
def ground(type) do
case type do
_ when is_base(type) ->
type
{:elist, []} ->
{:elist, []}
{:list, _} ->
{:list, :any}
{:tuple, type_list} ->
{:tuple, type_list |> Enum.map(fn _ -> :any end)}
{:map, type_map} ->
{:map, Enum.into(Enum.map(type_map, fn {k, _} -> {k, :any} end), %{})}
{:fun, type_list, _} ->
{:fun, type_list |> Enum.map(fn _ -> :any end), :any}
end
end
def cast(value, left_type, right_type) do
# IO.inspect({value, left_type, right_type})
result =
case {value, left_type, right_type} do
{value, :any, :any} ->
value
{value, type, :any} ->
if is_base(type) do
if is_consistent_subtype(type_for_value(value), type), do: value, else: :cast_error
else
cast(value, type, ground(type))
end
{value, :any, type} ->
if is_base_value(value) do
if is_consistent_subtype(type_for_value(value), type), do: value, else: :cast_error
else
cast(value, ground(type), type)
end
_ when is_base(left_type) ->
is_left_type_ok = is_consistent_subtype(type_for_value(value), left_type)
left_right_ground_types_consistent = is_base(right_type) and is_base_subtype(left_type, right_type)
case {is_left_type_ok, left_right_ground_types_consistent} do
{true, true} -> value
{false, _} -> :bad_argument_error
{_, false} -> :cast_error
end
{value, {:elist, []}, right_type} ->
is_left_type_ok = value == []
left_right_ground_types_consistent =
case right_type do
{:elist, []} -> true
{:list, _} -> true
_ -> false
end
case {is_left_type_ok, left_right_ground_types_consistent} do
{true, true} ->
[]
{false, _} ->
:bad_argument_error
{true, false} ->
:cast_error
end
{value, {:list, left_type}, right_type} ->
is_left_type_ok = is_list(value)
left_right_ground_types_consistent =
case right_type do
{:list, _} -> true
_ -> false
end
case {is_left_type_ok, left_right_ground_types_consistent} do
{true, true} ->
right_type = elem(right_type, 1)
if value == [] and not is_consistent_subtype(left_type, right_type) do
# since this will not be checked downwards
:cast_error
else
Enum.map(value, fn val -> cast(val, left_type, right_type) end)
end
{false, _} ->
:bad_argument_error
{true, false} ->
:cast_error
end
{value, {:tuple, left_type_list}, right_type} ->
is_left_type_ok = is_tuple(value) and tuple_size(value) == length(left_type_list)
left_right_ground_types_consistent =
case right_type do
{:tuple, right_type_list} -> length(left_type_list) == length(right_type_list)
_ -> false
end
case {is_left_type_ok, left_right_ground_types_consistent} do
{true, true} ->
right_type_list = elem(right_type, 1)
Enum.zip([Tuple.to_list(value), left_type_list, right_type_list])
|> Enum.map(fn {val, left_type, right_type} -> cast(val, left_type, right_type) end)
|> List.to_tuple()
{false, _} ->
:bad_argument_error
{true, false} ->
:cast_error
end
{value, {:map, left_type_map}, right_type} ->
is_left_type_ok = is_map(value) and Enum.all?(Map.keys(left_type_map), &Enum.member?(Map.keys(value), &1))
left_right_ground_types_consistent =
case right_type do
{:map, right_type_map} ->
Enum.sort(Map.keys(left_type_map)) === Enum.sort(Map.keys(right_type_map))
_ ->
false
end
case {is_left_type_ok, left_right_ground_types_consistent} do
{true, true} ->
right_type_map = elem(right_type, 1)
Enum.map(value, fn {k, v} -> {k, v, left_type_map[k], right_type_map[k]} end)
|> Enum.map(fn {k, v, type1, type2} -> {k, cast(v, type1, type2)} end)
|> Enum.into(%{})
{false, _} ->
:bad_argument_error
{true, false} ->
:cast_error
end
{value, {:fun, left_type_list, left_type}, right_type} ->
f = value
is_left_type_ok = is_function(f, length(left_type_list))
left_right_ground_types_consistent =
case right_type do
{:fun, _, _} -> true
_ -> false
end
case {is_left_type_ok, left_right_ground_types_consistent} do
{true, true} ->
{:fun, right_type_list, right_type} = right_type
left_type_tuple = left_type_list |> List.to_tuple()
right_type_tuple = right_type_list |> List.to_tuple()
case length(left_type_list) do
0 ->
fn ->
cast(f.(), left_type, right_type)
end
1 ->
fn val1 ->
casted_val1 = cast(val1, elem(right_type_tuple, 0), elem(left_type_tuple, 0))
cast(f.(casted_val1), left_type, right_type)
end
2 ->
fn val1, val2 ->
casted_val1 = cast(val1, elem(right_type_tuple, 0), elem(left_type_tuple, 0))
casted_val2 = cast(val2, elem(right_type_tuple, 1), elem(left_type_tuple, 1))
cast(f.(casted_val1, casted_val2), left_type, right_type)
end
3 ->
fn val1, val2, val3 ->
casted_val1 = cast(val1, elem(right_type_tuple, 0), elem(left_type_tuple, 0))
casted_val2 = cast(val2, elem(right_type_tuple, 1), elem(left_type_tuple, 1))
casted_val3 = cast(val3, elem(right_type_tuple, 2), elem(left_type_tuple, 2))
cast(f.(casted_val1, casted_val2, casted_val3), left_type, right_type)
end
# TODO make this general to support arbitrary function arity
# probably this is macro-doable by converting function args into tuple first
end
{false, _} ->
:bad_argument_error
{true, false} ->
:cast_error
end
end
case result do
:bad_argument_error ->
raise BadArgumentError.new(%{
reason: "type_error",
value: value,
left_type: left_type,
right_type: right_type
})
:cast_error ->
raise CastError.new(%{
value: value,
left_type: left_type,
right_type: right_type
})
value ->
value
end
end
end
defmodule UseCast do
defmacro __using__(_opts) do
quote do
alias Cast
defmacro value_ast | {:~>, _, [left_type_ast, right_type_ast]} do
context = [
left_type: Code.string_to_quoted(inspect(left_type_ast)),
right_type: Code.string_to_quoted(inspect(right_type_ast)),
value_ast: value_ast
]
quote bind_quoted: [context: context] do
{:ok, left_type} = Keyword.get(context, :left_type)
{:ok, right_type} = Keyword.get(context, :right_type)
value_ast = Keyword.get(context, :value_ast)
left_type = Cast.build_type_from_ast(left_type)
right_type = Cast.build_type_from_ast(right_type)
Cast.cast(value_ast, left_type, right_type)
end
end
defmacro value_ast | type_ast do
quote do
unquote(value_ast)
end
end
end
end
end
|
elixir_port/lib/cast.ex
| 0.594904 | 0.448064 |
cast.ex
|
starcoder
|
defmodule Surface do
@moduledoc """
Surface is component based library for **Phoenix LiveView**.
Built on top of the new `Phoenix.LiveComponent` API, Surface provides
a more declarative way to express and use components in Phoenix.
A work-in-progress live demo with more details can be found at [surface-demo.msaraiva.io](http://surface-demo.msaraiva.io)
This module defines the `~H` sigil that should be used to translate Surface
code into Phoenix templates.
In order to have `~H` available for any Phoenix view, add the following import to your web
file in `lib/my_app_web.ex`:
# lib/my_app_web.ex
...
def view do
quote do
...
import Surface
end
end
## Defining components
To create a component you need to define a module and `use` one of the available component types:
* `Surface.Component` - A stateless component.
* `Surface.LiveComponent` - A live stateful component.
* `Surface.LiveView` - A wrapper component around `Phoenix.LiveView`.
* `Surface.DataComponent` - A component that serves as a customizable data holder for the parent component.
* `Surface.MacroComponent` - A low-level component which is responsible for translating its own content at compile time.
### Example
# A functional stateless component
defmodule Button do
use Surface.Component
property click, :event
property kind, :string, default: "is-info"
def render(assigns) do
~H"\""
<button class="button {{ @kind }}" phx-click={{ @click }}>
{{ @inner_content.() }}
</button>
"\""
end
end
You can visit the documentation of each type of component for further explanation and examples.
## Directives
Directives are built-in attributes that can modify the translated code of a component
at compile time. Currently, the following directives are supported:
* `:for` - Iterates over a list (generator) and renders the content of the tag (or component)
for each item in the list.
* `:if` - Conditionally render a tag (or component). The code will be rendered if the expression
is evaluated to a truthy value.
* `:show` - Conditionally shows/hides an HTML tag, keeping the rendered alement in the DOM even
when the value is `false`.
* `:bindings` - Defines the name of the variables (bindings) in the current scope that represent
the values passed internally by the component when calling the `@content` function.
* `:on-[event]` - Sets a `phx` event binding defining the component itself as the
default handler (target). This is the prefered way to use `phx` events in **Surface** as it can
properly handle properties of type `:event`. Available directives are: `:on-phx-click`,
`:on-phx-blur`, `:on-phx-focus`, `:on-phx-change`, `:on-phx-submit`, `:on-phx-keydown`
and `:on-phx-keyup`.
### Example
<div>
<div class="header" :if={{ @showHeader }}>
The Header
</div>
<ul>
<li :for={{ item <- @items }}>
{{ item }}
</li>
</ul>
</div>
"""
@doc """
Translates Surface code into Phoenix templates.
"""
defmacro sigil_H({:<<>>, _, [string]}, _) do
line_offset = __CALLER__.line + 1
string
|> Surface.Translator.run(line_offset, __CALLER__, __CALLER__.file)
|> EEx.compile_string(engine: Phoenix.LiveView.Engine, line: line_offset, file: __CALLER__.file)
end
@doc false
def component(module, assigns) do
module.render(assigns)
end
def component(module, assigns, []) do
module.render(assigns)
end
@doc false
def put_default_props(props, mod) do
Enum.reduce(mod.__props__(), props, fn %{name: name, opts: opts}, acc ->
default = Keyword.get(opts, :default)
Map.put_new(acc, name, default)
end)
end
@doc false
def begin_context(props, current_context, mod) do
assigns = put_gets_into_assigns(props, current_context, mod.__context_gets__())
initialized_context_assigns =
with true <- function_exported?(mod, :init_context, 1),
{:ok, values} <- mod.init_context(assigns) do
Map.new(values)
else
false ->
[]
{:error, message} ->
runtime_error(message)
result ->
runtime_error(
"unexpected return value from init_context/1. " <>
"Expected {:ok, keyword()} | {:error, String.t()}, got: #{inspect(result)}"
)
end
{assigns, new_context} =
put_sets_into_assigns_and_context(
assigns,
current_context,
initialized_context_assigns,
mod.__context_sets__()
)
assigns = Map.put(assigns, :__surface_context__, new_context)
{assigns, new_context}
end
@doc false
def end_context(context, mod) do
Enum.reduce(mod.__context_sets__(), context, fn %{name: name, opts: opts}, acc ->
to = Keyword.fetch!(opts, :to)
context_entry = acc |> Map.get(to, %{}) |> Map.delete(name)
if context_entry == %{} do
Map.delete(acc, to)
else
Map.put(acc, to, context_entry)
end
end)
end
@doc false
def attr_value(attr, value) do
if String.Chars.impl_for(value) do
value
else
runtime_error "invalid value for attribute \"#{attr}\". Expected a type that implements " <>
"the String.Chars protocol (e.g. string, boolean, integer, atom, ...), " <>
"got: #{inspect(value)}"
end
end
@doc false
def style(value, show) when is_binary(value) do
if show do
quot(value)
else
semicolon = if String.ends_with?(value, ";") || value == "", do: "", else: ";"
quot([value, semicolon, "display: none;"])
end
end
def style(value, _show) do
runtime_error "invalid value for attribute \"style\". Expected a string " <>
"got: #{inspect(value)}"
end
@doc false
def css_class(list) when is_list(list) do
Enum.reduce(list, [], fn item, classes ->
case item do
{class, true} ->
[to_kebab_case(class) | classes]
class when is_binary(class) or is_atom(class) ->
[to_kebab_case(class) | classes]
_ ->
classes
end
end) |> Enum.reverse() |> Enum.join(" ")
end
def css_class(value) when is_binary(value) do
value
end
@doc false
def boolean_attr(name, value) do
if value do
name
else
""
end
end
@doc false
def event_value(key, [event], caller_cid) do
event_value(key, event, caller_cid)
end
def event_value(key, [name | opts], caller_cid) do
event = Map.new(opts) |> Map.put(:name, name)
event_value(key, event, caller_cid)
end
def event_value(_key, nil, _caller_cid) do
nil
end
def event_value(_key, name, nil) when is_binary(name) do
%{name: name, target: :live_view}
end
def event_value(_key, name, caller_cid) when is_binary(name) do
%{name: name, target: "[surface-cid=#{caller_cid}]"}
end
def event_value(_key, %{name: _, target: _} = event, _caller_cid) do
event
end
def event_value(key, event, _caller_cid) do
runtime_error "invalid value for event \"#{key}\". Expected an :event or :string, got: #{inspect(event)}"
end
@doc false
def on_phx_event(phx_event, [event], caller_cid) do
on_phx_event(phx_event, event, caller_cid)
end
def on_phx_event(phx_event, [event | opts], caller_cid) do
value = Map.new(opts) |> Map.put(:name, event)
on_phx_event(phx_event, value, caller_cid)
end
def on_phx_event(phx_event, %{name: name, target: :live_view}, _caller_cid) do
[phx_event, "=", quot(name)]
end
def on_phx_event(phx_event, %{name: name, target: target}, _caller_cid) do
[phx_event, "=", quot(name), " phx-target=", quot(target)]
end
# Stateless component or a liveview (no caller_id)
def on_phx_event(phx_event, event, nil) when is_binary(event) do
[phx_event, "=", quot(event)]
end
def on_phx_event(phx_event, event, caller_cid) when is_binary(event) do
[phx_event, "=", quot(event), " phx-target=", "[surface-cid=", caller_cid, "]"]
end
def on_phx_event(_phx_event, nil, _caller_cid) do
[]
end
def on_phx_event(phx_event, event, _caller_cid) do
runtime_error "invalid value for \":on-#{phx_event}\". " <>
"Expected a :string or :event, got: #{inspect(event)}"
end
@doc false
def phx_event(_phx_event, value) when is_binary(value) do
value
end
def phx_event(phx_event, value) do
runtime_error "invalid value for \"#{phx_event}\". LiveView bindings only accept values " <>
"of type :string. If you want to pass an :event, please use directive " <>
":on-#{phx_event} instead. Expected a :string, got: #{inspect(value)}"
end
defp quot(value) do
[{:safe, "\""}, value, {:safe, "\""}]
end
# TODO: Find a better way to do this
defp to_kebab_case(value) do
value
|> to_string()
|> Macro.underscore()
|> String.replace("_", "-")
end
defp runtime_error(message) do
stacktrace =
self()
|> Process.info(:current_stacktrace)
|> elem(1)
|> Enum.drop(2)
reraise(message, stacktrace)
end
defp put_gets_into_assigns(assigns, context, gets) do
Enum.reduce(gets, assigns, fn %{name: name, opts: opts}, acc ->
key = Keyword.get(opts, :as, name)
from = Keyword.fetch!(opts, :from)
# TODO: raise an error if it's required and it hasn't been set
value = context[from][name]
Map.put_new(acc, key, value)
end)
end
defp put_sets_into_assigns_and_context(assigns, context, values, sets) do
Enum.reduce(sets, {assigns, context}, fn %{name: name, opts: opts}, {assigns, context} ->
to = Keyword.fetch!(opts, :to)
scope = Keyword.get(opts, :scope)
case Map.fetch(values, name) do
{:ok, value} ->
new_context_entry =
context
|> Map.get(to, %{})
|> Map.put(name, value)
new_context = Map.put(context, to, new_context_entry)
new_assigns =
if scope == :only_children, do: assigns, else: Map.put(assigns, name, value)
{new_assigns, new_context}
:error ->
{assigns, context}
end
end)
end
end
|
lib/surface.ex
| 0.865437 | 0.622832 |
surface.ex
|
starcoder
|
defmodule Ecto.Adapter do
@moduledoc """
Specifies the API required from adapters.
"""
@type t :: module
@typedoc "The metadata returned by the adapter init/1"
@type adapter_meta :: term
@typedoc "Ecto.Query metadata fields (stored in cache)"
@type query_meta :: %{sources: tuple, preloads: term, select: map}
@typedoc "Ecto.Schema metadata fields"
@type schema_meta :: %{
source: source,
schema: atom,
context: term,
autogenerate_id: {atom, :id | :binary_id}
}
@type source :: {prefix :: binary | nil, table :: binary}
@type fields :: Keyword.t()
@type filters :: Keyword.t()
@type constraints :: Keyword.t()
@type returning :: [atom]
@type prepared :: term
@type cached :: term
@type on_conflict ::
{:raise, list(), []}
| {:nothing, list(), [atom]}
| {[atom], list(), [atom]}
| {Ecto.Query.t(), list(), [atom]}
@type options :: Keyword.t()
@doc """
The callback invoked in case the adapter needs to inject code.
"""
@macrocallback __before_compile__(env :: Macro.Env.t()) :: Macro.t()
@doc """
Ensure all applications necessary to run the adapter are started.
"""
@callback ensure_all_started(config :: Keyword.t(), type :: :application.restart_type()) ::
{:ok, [atom]} | {:error, atom}
@doc """
Initializes the adapter supervision tree by returning the children and adapter metadata.
"""
@callback init(config :: Keyword.t()) :: {:ok, :supervisor.child_spec(), adapter_meta}
## Types
@doc """
Returns the loaders for a given type.
It receives the primitive type and the Ecto type (which may be
primitive as well). It returns a list of loaders with the given
type usually at the end.
This allows developers to properly translate values coming from
the adapters into Ecto ones. For example, if the database does not
support booleans but instead returns 0 and 1 for them, you could
add:
def loaders(:boolean, type), do: [&bool_decode/1, type]
def loaders(_primitive, type), do: [type]
defp bool_decode(0), do: {:ok, false}
defp bool_decode(1), do: {:ok, true}
All adapters are required to implement a clause for `:binary_id` types,
since they are adapter specific. If your adapter does not provide binary
ids, you may simply use Ecto.UUID:
def loaders(:binary_id, type), do: [Ecto.UUID, type]
def loaders(_primitive, type), do: [type]
"""
@callback loaders(primitive_type :: Ecto.Type.primitive(), ecto_type :: Ecto.Type.t()) ::
[(term -> {:ok, term} | :error) | Ecto.Type.t()]
@doc """
Returns the dumpers for a given type.
It receives the primitive type and the Ecto type (which may be
primitive as well). It returns a list of dumpers with the given
type usually at the beginning.
This allows developers to properly translate values coming from
the Ecto into adapter ones. For example, if the database does not
support booleans but instead returns 0 and 1 for them, you could
add:
def dumpers(:boolean, type), do: [type, &bool_encode/1]
def dumpers(_primitive, type), do: [type]
defp bool_encode(false), do: {:ok, 0}
defp bool_encode(true), do: {:ok, 1}
All adapters are required to implement a clause or :binary_id types,
since they are adapter specific. If your adapter does not provide
binary ids, you may simply use Ecto.UUID:
def dumpers(:binary_id, type), do: [type, Ecto.UUID]
def dumpers(_primitive, type), do: [type]
"""
@callback dumpers(primitive_type :: Ecto.Type.primitive(), ecto_type :: Ecto.Type.t()) ::
[(term -> {:ok, term} | :error) | Ecto.Type.t()]
@doc """
Called to autogenerate a value for id/embed_id/binary_id.
Returns the autogenerated value, or nil if it must be
autogenerated inside the storage or raise if not supported.
"""
@callback autogenerate(field_type :: :id | :binary_id | :embed_id) :: term | nil
@doc """
Commands invoked to prepare a query for `all`, `update_all` and `delete_all`.
The returned result is given to `execute/6`.
"""
@callback prepare(atom :: :all | :update_all | :delete_all, query :: Ecto.Query.t()) ::
{:cache, prepared} | {:nocache, prepared}
@doc """
Executes a previously prepared query.
It must return a tuple containing the number of entries and
the result set as a list of lists. The result set may also be
`nil` if a particular operation does not support them.
The `meta` field is a map containing some of the fields found
in the `Ecto.Query` struct.
"""
@callback execute(adapter_meta, query_meta, query, params :: list(), options) :: result
when result: {integer, [[term]] | nil},
query:
{:nocache, prepared}
| {:cached, (prepared -> :ok), cached}
| {:cache, (cached -> :ok), prepared}
@doc """
Inserts multiple entries into the data store.
"""
@callback insert_all(
adapter_meta,
schema_meta,
header :: [atom],
[fields],
on_conflict,
returning,
options
) :: {integer, [[term]] | nil}
@doc """
Inserts a single new struct in the data store.
## Autogenerate
The primary key will be automatically included in `returning` if the
field has type `:id` or `:binary_id` and no value was set by the
developer or none was autogenerated by the adapter.
"""
@callback insert(adapter_meta, schema_meta, fields, on_conflict, returning, options) ::
{:ok, fields} | {:invalid, constraints}
@doc """
Updates a single struct with the given filters.
While `filters` can be any record column, it is expected that
at least the primary key (or any other key that uniquely
identifies an existing record) be given as a filter. Therefore,
in case there is no record matching the given filters,
`{:error, :stale}` is returned.
"""
@callback update(adapter_meta, schema_meta, fields, filters, returning, options) ::
{:ok, fields} | {:invalid, constraints} | {:error, :stale}
@doc """
Deletes a single struct with the given filters.
While `filters` can be any record column, it is expected that
at least the primary key (or any other key that uniquely
identifies an existing record) be given as a filter. Therefore,
in case there is no record matching the given filters,
`{:error, :stale}` is returned.
"""
@callback delete(adapter_meta, schema_meta, filters, options) ::
{:ok, fields} | {:invalid, constraints} | {:error, :stale}
@doc """
Returns the adapter metadata from the `init/2` callback.
It expects a name or a pid representing a repo.
"""
def lookup_meta(repo_name_or_pid) do
{_, _, meta} = Ecto.Repo.Registry.lookup(repo_name_or_pid)
meta
end
@doc """
Plans and prepares a query for the given repo, leveraging its query cache.
This operation uses the query cache if one is available.
"""
def prepare_query(operation, repo_name_or_pid, queryable) do
{adapter, cache, _meta} = Ecto.Repo.Registry.lookup(repo_name_or_pid)
{_meta, prepared, params} =
queryable
|> Ecto.Queryable.to_query()
|> Ecto.Query.Planner.ensure_select(operation == :all)
|> Ecto.Query.Planner.query(operation, cache, adapter, 0)
{prepared, params}
end
@doc """
Plans a query using the given adapter.
This does not expect the repository and therefore does not leverage the cache.
"""
def plan_query(operation, adapter, queryable) do
query = Ecto.Queryable.to_query(queryable)
{query, params, _key} = Ecto.Query.Planner.prepare(query, operation, adapter, 0)
{query, _} = Ecto.Query.Planner.normalize(query, operation, adapter, 0)
{query, params}
end
end
|
lib/ecto/adapter.ex
| 0.908092 | 0.400925 |
adapter.ex
|
starcoder
|
defprotocol Enumerable do
@moduledoc """
Enumerable protocol used by `Enum` and `Stream` modules.
When you invoke a function in the `Enum` module, the first argument
is usually a collection that must implement this protocol.
For example, the expression:
Enum.map([1, 2, 3], &(&1 * 2))
invokes `Enumerable.reduce/3` to perform the reducing operation that
builds a mapped list by calling the mapping function `&(&1 * 2)` on
every element in the collection and consuming the element with an
accumulated list.
Internally, `Enum.map/2` is implemented as follows:
def map(enumerable, fun) do
reducer = fn x, acc -> {:cont, [fun.(x) | acc]} end
Enumerable.reduce(enumerable, {:cont, []}, reducer) |> elem(1) |> :lists.reverse()
end
Notice the user-supplied function is wrapped into a `t:reducer/0` function.
The `t:reducer/0` function must return a tagged tuple after each step,
as described in the `t:acc/0` type. At the end, `Enumerable.reduce/3`
returns `t:result/0`.
This protocol uses tagged tuples to exchange information between the
reducer function and the data type that implements the protocol. This
allows enumeration of resources, such as files, to be done efficiently
while also guaranteeing the resource will be closed at the end of the
enumeration. This protocol also allows suspension of the enumeration,
which is useful when interleaving between many enumerables is required
(as in the `zip/1` and `zip/2` functions).
This protocol requires four functions to be implemented, `reduce/3`,
`count/1`, `member?/2`, and `slice/1`. The core of the protocol is the
`reduce/3` function. All other functions exist as optimizations paths
for data structures that can implement certain properties in better
than linear time.
"""
@typedoc """
The accumulator value for each step.
It must be a tagged tuple with one of the following "tags":
* `:cont` - the enumeration should continue
* `:halt` - the enumeration should halt immediately
* `:suspend` - the enumeration should be suspended immediately
Depending on the accumulator value, the result returned by
`Enumerable.reduce/3` will change. Please check the `t:result/0`
type documentation for more information.
In case a `t:reducer/0` function returns a `:suspend` accumulator,
it must be explicitly handled by the caller and never leak.
"""
@type acc :: {:cont, term} | {:halt, term} | {:suspend, term}
@typedoc """
The reducer function.
Should be called with the `enumerable` element and the
accumulator contents.
Returns the accumulator for the next enumeration step.
"""
@type reducer :: (term, term -> acc)
@typedoc """
The result of the reduce operation.
It may be *done* when the enumeration is finished by reaching
its end, or *halted*/*suspended* when the enumeration was halted
or suspended by the `t:reducer/0` function.
In case a `t:reducer/0` function returns the `:suspend` accumulator, the
`:suspended` tuple must be explicitly handled by the caller and
never leak. In practice, this means regular enumeration functions
just need to be concerned about `:done` and `:halted` results.
Furthermore, a `:suspend` call must always be followed by another call,
eventually halting or continuing until the end.
"""
@type result ::
{:done, term}
| {:halted, term}
| {:suspended, term, continuation}
@typedoc """
A partially applied reduce function.
The continuation is the closure returned as a result when
the enumeration is suspended. When invoked, it expects
a new accumulator and it returns the result.
A continuation can be trivially implemented as long as the reduce
function is defined in a tail recursive fashion. If the function
is tail recursive, all the state is passed as arguments, so
the continuation is the reducing function partially applied.
"""
@type continuation :: (acc -> result)
@typedoc """
A slicing function that receives the initial position and the
number of elements in the slice.
The `start` position is a number `>= 0` and guaranteed to
exist in the `enumerable`. The length is a number `>= 1` in a way
that `start + length <= count`, where `count` is the maximum
amount of elements in the enumerable.
The function should return a non empty list where
the amount of elements is equal to `length`.
"""
@type slicing_fun :: (start :: non_neg_integer, length :: pos_integer -> [term()])
@doc """
Reduces the `enumerable` into an element.
Most of the operations in `Enum` are implemented in terms of reduce.
This function should apply the given `t:reducer/0` function to each
element in the `enumerable` and proceed as expected by the returned
accumulator.
See the documentation of the types `t:result/0` and `t:acc/0` for
more information.
## Examples
As an example, here is the implementation of `reduce` for lists:
def reduce(_list, {:halt, acc}, _fun), do: {:halted, acc}
def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}
def reduce([], {:cont, acc}, _fun), do: {:done, acc}
def reduce([head | tail], {:cont, acc}, fun), do: reduce(tail, fun.(head, acc), fun)
"""
@spec reduce(t, acc, reducer) :: result
def reduce(enumerable, acc, fun)
@doc """
Retrieves the number of elements in the `enumerable`.
It should return `{:ok, count}` if you can count the number of elements
in the `enumerable`.
Otherwise it should return `{:error, __MODULE__}` and a default algorithm
built on top of `reduce/3` that runs in linear time will be used.
"""
@spec count(t) :: {:ok, non_neg_integer} | {:error, module}
def count(enumerable)
@doc """
Checks if an `element` exists within the `enumerable`.
It should return `{:ok, boolean}` if you can check the membership of a
given element in the `enumerable` with `===/2` without traversing the whole
enumerable.
Otherwise it should return `{:error, __MODULE__}` and a default algorithm
built on top of `reduce/3` that runs in linear time will be used.
The [`in`](`in/2`) and [`not in`](`in/2`) operators work by calling this
function.
"""
@spec member?(t, term) :: {:ok, boolean} | {:error, module}
def member?(enumerable, element)
@doc """
Returns a function that slices the data structure contiguously.
It should return `{:ok, size, slicing_fun}` if the `enumerable` has
a known bound and can access a position in the `enumerable` without
traversing all previous elements.
Otherwise it should return `{:error, __MODULE__}` and a default
algorithm built on top of `reduce/3` that runs in linear time will be
used.
## Differences to `count/1`
The `size` value returned by this function is used for boundary checks,
therefore it is extremely important that this function only returns `:ok`
if retrieving the `size` of the `enumerable` is cheap, fast and takes constant
time. Otherwise the simplest of operations, such as `Enum.at(enumerable, 0)`,
will become too expensive.
On the other hand, the `count/1` function in this protocol should be
implemented whenever you can count the number of elements in the collection.
"""
@spec slice(t) ::
{:ok, size :: non_neg_integer(), slicing_fun()}
| {:error, module()}
def slice(enumerable)
end
defmodule Enum do
import Kernel, except: [max: 2, min: 2]
@moduledoc """
Provides a set of algorithms to work with enumerables.
In Elixir, an enumerable is any data type that implements the
`Enumerable` protocol. `List`s (`[1, 2, 3]`), `Map`s (`%{foo: 1, bar: 2}`)
and `Range`s (`1..3`) are common data types used as enumerables:
iex> Enum.map([1, 2, 3], fn x -> x * 2 end)
[2, 4, 6]
iex> Enum.sum([1, 2, 3])
6
iex> Enum.map(1..3, fn x -> x * 2 end)
[2, 4, 6]
iex> Enum.sum(1..3)
6
iex> map = %{"a" => 1, "b" => 2}
iex> Enum.map(map, fn {k, v} -> {k, v * 2} end)
[{"a", 2}, {"b", 4}]
However, many other enumerables exist in the language, such as `MapSet`s
and the data type returned by `File.stream!/3` which allows a file to be
traversed as if it was an enumerable.
The functions in this module work in linear time. This means that, the
time it takes to perform an operation grows at the same rate as the length
of the enumerable. This is expected on operations such as `Enum.map/2`.
After all, if we want to traverse every element on a list, the longer the
list, the more elements we need to traverse, and the longer it will take.
This linear behaviour should also be expected on operations like `count/1`,
`member?/2`, `at/2` and similar. While Elixir does allow data types to
provide performant variants for such operations, you should not expect it
to always be available, since the `Enum` module is meant to work with a
large variety of data types and not all data types can provide optimized
behaviour.
Finally, note the functions in the `Enum` module are eager: they will
traverse the enumerable as soon as they are invoked. This is particularly
dangerous when working with infinite enumerables. In such cases, you should
use the `Stream` module, which allows you to lazily express computations,
without traversing collections, and work with possibly infinite collections.
See the `Stream` module for examples and documentation.
"""
@compile :inline_list_funcs
@type t :: Enumerable.t()
@type acc :: any
@type element :: any
@typedoc "Zero-based index. It can also be a negative integer."
@type index :: integer
@type default :: any
require Stream.Reducers, as: R
defmacrop skip(acc) do
acc
end
defmacrop next(_, entry, acc) do
quote(do: [unquote(entry) | unquote(acc)])
end
defmacrop acc(head, state, _) do
quote(do: {unquote(head), unquote(state)})
end
defmacrop next_with_acc(_, entry, head, state, _) do
quote do
{[unquote(entry) | unquote(head)], unquote(state)}
end
end
@doc """
Returns `true` if `fun.(element)` is truthy for all elements in `enumerable`.
Iterates over the `enumerable` and invokes `fun` on each element. When an invocation
of `fun` returns a falsy value (`false` or `nil`) iteration stops immediately and
`false` is returned. In all other cases `true` is returned.
## Examples
iex> Enum.all?([2, 4, 6], fn x -> rem(x, 2) == 0 end)
true
iex> Enum.all?([2, 3, 4], fn x -> rem(x, 2) == 0 end)
false
iex> Enum.all?([], fn x -> x > 0 end)
true
If no function is given, the truthiness of each element is checked during iteration.
When an element has a falsy value (`false` or `nil`) iteration stops immediately and
`false` is returned. In all other cases `true` is returned.
iex> Enum.all?([1, 2, 3])
true
iex> Enum.all?([1, nil, 3])
false
iex> Enum.all?([])
true
"""
@spec all?(t, (element -> as_boolean(term))) :: boolean
def all?(enumerable, fun \\ fn x -> x end)
def all?(enumerable, fun) when is_list(enumerable) do
all_list(enumerable, fun)
end
def all?(enumerable, fun) do
Enumerable.reduce(enumerable, {:cont, true}, fn entry, _ ->
if fun.(entry), do: {:cont, true}, else: {:halt, false}
end)
|> elem(1)
end
@doc """
Returns `true` if `fun.(element)` is truthy for at least one element in `enumerable`.
Iterates over the `enumerable` and invokes `fun` on each element. When an invocation
of `fun` returns a truthy value (neither `false` nor `nil`) iteration stops
immediately and `true` is returned. In all other cases `false` is returned.
## Examples
iex> Enum.any?([2, 4, 6], fn x -> rem(x, 2) == 1 end)
false
iex> Enum.any?([2, 3, 4], fn x -> rem(x, 2) == 1 end)
true
iex> Enum.any?([], fn x -> x > 0 end)
false
If no function is given, the truthiness of each element is checked during iteration.
When an element has a truthy value (neither `false` nor `nil`) iteration stops
immediately and `true` is returned. In all other cases `false` is returned.
iex> Enum.any?([false, false, false])
false
iex> Enum.any?([false, true, false])
true
iex> Enum.any?([])
false
"""
@spec any?(t, (element -> as_boolean(term))) :: boolean
def any?(enumerable, fun \\ fn x -> x end)
def any?(enumerable, fun) when is_list(enumerable) do
any_list(enumerable, fun)
end
def any?(enumerable, fun) do
Enumerable.reduce(enumerable, {:cont, false}, fn entry, _ ->
if fun.(entry), do: {:halt, true}, else: {:cont, false}
end)
|> elem(1)
end
@doc """
Finds the element at the given `index` (zero-based).
Returns `default` if `index` is out of bounds.
A negative `index` can be passed, which means the `enumerable` is
enumerated once and the `index` is counted from the end (for example,
`-1` finds the last element).
## Examples
iex> Enum.at([2, 4, 6], 0)
2
iex> Enum.at([2, 4, 6], 2)
6
iex> Enum.at([2, 4, 6], 4)
nil
iex> Enum.at([2, 4, 6], 4, :none)
:none
"""
@spec at(t, index, default) :: element | default
def at(enumerable, index, default \\ nil) when is_integer(index) do
case slice_any(enumerable, index, 1) do
[value] -> value
[] -> default
end
end
@doc false
@deprecated "Use Enum.chunk_every/2 instead"
def chunk(enumerable, count), do: chunk(enumerable, count, count, nil)
@doc false
@deprecated "Use Enum.chunk_every/3 instead"
def chunk(enum, n, step) do
chunk_every(enum, n, step, :discard)
end
@doc false
@deprecated "Use Enum.chunk_every/4 instead"
def chunk(enumerable, count, step, leftover) do
chunk_every(enumerable, count, step, leftover || :discard)
end
@doc """
Shortcut to `chunk_every(enumerable, count, count)`.
"""
@doc since: "1.5.0"
@spec chunk_every(t, pos_integer) :: [list]
def chunk_every(enumerable, count), do: chunk_every(enumerable, count, count, [])
@doc """
Returns list of lists containing `count` elements each, where
each new chunk starts `step` elements into the `enumerable`.
`step` is optional and, if not passed, defaults to `count`, i.e.
chunks do not overlap.
If the last chunk does not have `count` elements to fill the chunk,
elements are taken from `leftover` to fill in the chunk. If `leftover`
does not have enough elements to fill the chunk, then a partial chunk
is returned with less than `count` elements.
If `:discard` is given in `leftover`, the last chunk is discarded
unless it has exactly `count` elements.
## Examples
iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 2)
[[1, 2], [3, 4], [5, 6]]
iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, :discard)
[[1, 2, 3], [3, 4, 5]]
iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, [7])
[[1, 2, 3], [3, 4, 5], [5, 6, 7]]
iex> Enum.chunk_every([1, 2, 3, 4], 3, 3, [])
[[1, 2, 3], [4]]
iex> Enum.chunk_every([1, 2, 3, 4], 10)
[[1, 2, 3, 4]]
iex> Enum.chunk_every([1, 2, 3, 4, 5], 2, 3, [])
[[1, 2], [4, 5]]
"""
@doc since: "1.5.0"
@spec chunk_every(t, pos_integer, pos_integer, t | :discard) :: [list]
def chunk_every(enumerable, count, step, leftover \\ [])
when is_integer(count) and count > 0 and is_integer(step) and step > 0 do
R.chunk_every(&chunk_while/4, enumerable, count, step, leftover)
end
@doc """
Chunks the `enumerable` with fine grained control when every chunk is emitted.
`chunk_fun` receives the current element and the accumulator and
must return `{:cont, chunk, acc}` to emit the given chunk and
continue with accumulator or `{:cont, acc}` to not emit any chunk
and continue with the return accumulator.
`after_fun` is invoked when iteration is done and must also return
`{:cont, chunk, acc}` or `{:cont, acc}`.
Returns a list of lists.
## Examples
iex> chunk_fun = fn element, acc ->
...> if rem(element, 2) == 0 do
...> {:cont, Enum.reverse([element | acc]), []}
...> else
...> {:cont, [element | acc]}
...> end
...> end
iex> after_fun = fn
...> [] -> {:cont, []}
...> acc -> {:cont, Enum.reverse(acc), []}
...> end
iex> Enum.chunk_while(1..10, [], chunk_fun, after_fun)
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
"""
@doc since: "1.5.0"
@spec chunk_while(
t,
acc,
(element, acc -> {:cont, chunk, acc} | {:cont, acc} | {:halt, acc}),
(acc -> {:cont, chunk, acc} | {:cont, acc})
) :: Enumerable.t()
when chunk: any
def chunk_while(enumerable, acc, chunk_fun, after_fun) do
{_, {res, acc}} =
Enumerable.reduce(enumerable, {:cont, {[], acc}}, fn entry, {buffer, acc} ->
case chunk_fun.(entry, acc) do
{:cont, emit, acc} -> {:cont, {[emit | buffer], acc}}
{:cont, acc} -> {:cont, {buffer, acc}}
{:halt, acc} -> {:halt, {buffer, acc}}
end
end)
case after_fun.(acc) do
{:cont, _acc} -> :lists.reverse(res)
{:cont, elem, _acc} -> :lists.reverse([elem | res])
end
end
@doc """
Splits enumerable on every element for which `fun` returns a new
value.
Returns a list of lists.
## Examples
iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1))
[[1], [2, 2], [3], [4, 4, 6], [7, 7]]
"""
@spec chunk_by(t, (element -> any)) :: [list]
def chunk_by(enumerable, fun) do
R.chunk_by(&chunk_while/4, enumerable, fun)
end
@doc """
Given an enumerable of enumerables, concatenates the `enumerables` into
a single list.
## Examples
iex> Enum.concat([1..3, 4..6, 7..9])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
iex> Enum.concat([[1, [2], 3], [4], [5, 6]])
[1, [2], 3, 4, 5, 6]
"""
@spec concat(t) :: t
def concat(enumerables) do
fun = &[&1 | &2]
enumerables |> reduce([], &reduce(&1, &2, fun)) |> :lists.reverse()
end
@doc """
Concatenates the enumerable on the `right` with the enumerable on the
`left`.
This function produces the same result as the `Kernel.++/2` operator
for lists.
## Examples
iex> Enum.concat(1..3, 4..6)
[1, 2, 3, 4, 5, 6]
iex> Enum.concat([1, 2, 3], [4, 5, 6])
[1, 2, 3, 4, 5, 6]
"""
@spec concat(t, t) :: t
def concat(left, right) when is_list(left) and is_list(right) do
left ++ right
end
def concat(left, right) do
concat([left, right])
end
@doc """
Returns the size of the `enumerable`.
## Examples
iex> Enum.count([1, 2, 3])
3
"""
@spec count(t) :: non_neg_integer
def count(enumerable) when is_list(enumerable) do
length(enumerable)
end
def count(enumerable) do
case Enumerable.count(enumerable) do
{:ok, value} when is_integer(value) ->
value
{:error, module} ->
enumerable |> module.reduce({:cont, 0}, fn _, acc -> {:cont, acc + 1} end) |> elem(1)
end
end
@doc """
Returns the count of elements in the `enumerable` for which `fun` returns
a truthy value.
## Examples
iex> Enum.count([1, 2, 3, 4, 5], fn x -> rem(x, 2) == 0 end)
2
"""
@spec count(t, (element -> as_boolean(term))) :: non_neg_integer
def count(enumerable, fun) do
reduce(enumerable, 0, fn entry, acc ->
if(fun.(entry), do: acc + 1, else: acc)
end)
end
@doc """
Enumerates the `enumerable`, returning a list where all consecutive
duplicated elements are collapsed to a single element.
Elements are compared using `===/2`.
If you want to remove all duplicated elements, regardless of order,
see `uniq/1`.
## Examples
iex> Enum.dedup([1, 2, 3, 3, 2, 1])
[1, 2, 3, 2, 1]
iex> Enum.dedup([1, 1, 2, 2.0, :three, :three])
[1, 2, 2.0, :three]
"""
@spec dedup(t) :: list
def dedup(enumerable) do
dedup_by(enumerable, fn x -> x end)
end
@doc """
Enumerates the `enumerable`, returning a list where all consecutive
duplicated elements are collapsed to a single element.
The function `fun` maps every element to a term which is used to
determine if two elements are duplicates.
## Examples
iex> Enum.dedup_by([{1, :a}, {2, :b}, {2, :c}, {1, :a}], fn {x, _} -> x end)
[{1, :a}, {2, :b}, {1, :a}]
iex> Enum.dedup_by([5, 1, 2, 3, 2, 1], fn x -> x > 2 end)
[5, 1, 3, 2]
"""
@spec dedup_by(t, (element -> term)) :: list
def dedup_by(enumerable, fun) do
{list, _} = reduce(enumerable, {[], []}, R.dedup(fun))
:lists.reverse(list)
end
@doc """
Drops the `amount` of elements from the `enumerable`.
If a negative `amount` is given, the `amount` of last values will be dropped.
The `enumerable` will be enumerated once to retrieve the proper index and
the remaining calculation is performed from the end.
## Examples
iex> Enum.drop([1, 2, 3], 2)
[3]
iex> Enum.drop([1, 2, 3], 10)
[]
iex> Enum.drop([1, 2, 3], 0)
[1, 2, 3]
iex> Enum.drop([1, 2, 3], -1)
[1, 2]
"""
@spec drop(t, integer) :: list
def drop(enumerable, amount)
when is_list(enumerable) and is_integer(amount) and amount >= 0 do
drop_list(enumerable, amount)
end
def drop(enumerable, amount) when is_integer(amount) and amount >= 0 do
{result, _} = reduce(enumerable, {[], amount}, R.drop())
if is_list(result), do: :lists.reverse(result), else: []
end
def drop(enumerable, amount) when is_integer(amount) and amount < 0 do
{count, fun} = slice_count_and_fun(enumerable)
amount = Kernel.min(amount + count, count)
if amount > 0 do
fun.(0, amount)
else
[]
end
end
@doc """
Returns a list of every `nth` element in the `enumerable` dropped,
starting with the first element.
The first element is always dropped, unless `nth` is 0.
The second argument specifying every `nth` element must be a non-negative
integer.
## Examples
iex> Enum.drop_every(1..10, 2)
[2, 4, 6, 8, 10]
iex> Enum.drop_every(1..10, 0)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
iex> Enum.drop_every([1, 2, 3], 1)
[]
"""
@spec drop_every(t, non_neg_integer) :: list
def drop_every(enumerable, nth)
def drop_every(_enumerable, 1), do: []
def drop_every(enumerable, 0), do: to_list(enumerable)
def drop_every([], nth) when is_integer(nth), do: []
def drop_every(enumerable, nth) when is_integer(nth) and nth > 1 do
{res, _} = reduce(enumerable, {[], :first}, R.drop_every(nth))
:lists.reverse(res)
end
@doc """
Drops elements at the beginning of the `enumerable` while `fun` returns a
truthy value.
## Examples
iex> Enum.drop_while([1, 2, 3, 2, 1], fn x -> x < 3 end)
[3, 2, 1]
"""
@spec drop_while(t, (element -> as_boolean(term))) :: list
def drop_while(enumerable, fun) when is_list(enumerable) do
drop_while_list(enumerable, fun)
end
def drop_while(enumerable, fun) do
{res, _} = reduce(enumerable, {[], true}, R.drop_while(fun))
:lists.reverse(res)
end
@doc """
Invokes the given `fun` for each element in the `enumerable`.
Returns `:ok`.
## Examples
Enum.each(["some", "example"], fn x -> IO.puts(x) end)
"some"
"example"
#=> :ok
"""
@spec each(t, (element -> any)) :: :ok
def each(enumerable, fun) when is_list(enumerable) do
:lists.foreach(fun, enumerable)
:ok
end
def each(enumerable, fun) do
reduce(enumerable, nil, fn entry, _ ->
fun.(entry)
nil
end)
:ok
end
@doc """
Determines if the `enumerable` is empty.
Returns `true` if `enumerable` is empty, otherwise `false`.
## Examples
iex> Enum.empty?([])
true
iex> Enum.empty?([1, 2, 3])
false
"""
@spec empty?(t) :: boolean
def empty?(enumerable) when is_list(enumerable) do
enumerable == []
end
def empty?(enumerable) do
case Enumerable.slice(enumerable) do
{:ok, value, _} ->
value == 0
{:error, module} ->
enumerable
|> module.reduce({:cont, true}, fn _, _ -> {:halt, false} end)
|> elem(1)
end
end
@doc """
Finds the element at the given `index` (zero-based).
Returns `{:ok, element}` if found, otherwise `:error`.
A negative `index` can be passed, which means the `enumerable` is
enumerated once and the `index` is counted from the end (for example,
`-1` fetches the last element).
## Examples
iex> Enum.fetch([2, 4, 6], 0)
{:ok, 2}
iex> Enum.fetch([2, 4, 6], -3)
{:ok, 2}
iex> Enum.fetch([2, 4, 6], 2)
{:ok, 6}
iex> Enum.fetch([2, 4, 6], 4)
:error
"""
@spec fetch(t, index) :: {:ok, element} | :error
def fetch(enumerable, index) when is_integer(index) do
case slice_any(enumerable, index, 1) do
[value] -> {:ok, value}
[] -> :error
end
end
@doc """
Finds the element at the given `index` (zero-based).
Raises `OutOfBoundsError` if the given `index` is outside the range of
the `enumerable`.
## Examples
iex> Enum.fetch!([2, 4, 6], 0)
2
iex> Enum.fetch!([2, 4, 6], 2)
6
iex> Enum.fetch!([2, 4, 6], 4)
** (Enum.OutOfBoundsError) out of bounds error
"""
@spec fetch!(t, index) :: element
def fetch!(enumerable, index) when is_integer(index) do
case slice_any(enumerable, index, 1) do
[value] -> value
[] -> raise Enum.OutOfBoundsError
end
end
@doc """
Filters the `enumerable`, i.e. returns only those elements
for which `fun` returns a truthy value.
See also `reject/2` which discards all elements where the
function returns a truthy value.
## Examples
iex> Enum.filter([1, 2, 3], fn x -> rem(x, 2) == 0 end)
[2]
Keep in mind that `filter` is not capable of filtering and
transforming an element at the same time. If you would like
to do so, consider using `flat_map/2`. For example, if you
want to convert all strings that represent an integer and
discard the invalid one in one pass:
strings = ["1234", "abc", "12ab"]
Enum.flat_map(strings, fn string ->
case Integer.parse(string) do
# transform to integer
{int, _rest} -> [int]
# skip the value
:error -> []
end
end)
"""
@spec filter(t, (element -> as_boolean(term))) :: list
def filter(enumerable, fun) when is_list(enumerable) do
filter_list(enumerable, fun)
end
def filter(enumerable, fun) do
reduce(enumerable, [], R.filter(fun)) |> :lists.reverse()
end
@doc false
@deprecated "Use Enum.filter/2 + Enum.map/2 or for comprehensions instead"
def filter_map(enumerable, filter, mapper) when is_list(enumerable) do
for element <- enumerable, filter.(element), do: mapper.(element)
end
def filter_map(enumerable, filter, mapper) do
enumerable
|> reduce([], R.filter_map(filter, mapper))
|> :lists.reverse()
end
@doc """
Returns the first element for which `fun` returns a truthy value.
If no such element is found, returns `default`.
## Examples
iex> Enum.find([2, 3, 4], fn x -> rem(x, 2) == 1 end)
3
iex> Enum.find([2, 4, 6], fn x -> rem(x, 2) == 1 end)
nil
iex> Enum.find([2, 4, 6], 0, fn x -> rem(x, 2) == 1 end)
0
"""
@spec find(t, default, (element -> any)) :: element | default
def find(enumerable, default \\ nil, fun)
def find(enumerable, default, fun) when is_list(enumerable) do
find_list(enumerable, default, fun)
end
def find(enumerable, default, fun) do
Enumerable.reduce(enumerable, {:cont, default}, fn entry, default ->
if fun.(entry), do: {:halt, entry}, else: {:cont, default}
end)
|> elem(1)
end
@doc """
Similar to `find/3`, but returns the index (zero-based)
of the element instead of the element itself.
## Examples
iex> Enum.find_index([2, 4, 6], fn x -> rem(x, 2) == 1 end)
nil
iex> Enum.find_index([2, 3, 4], fn x -> rem(x, 2) == 1 end)
1
"""
@spec find_index(t, (element -> any)) :: non_neg_integer | nil
def find_index(enumerable, fun) when is_list(enumerable) do
find_index_list(enumerable, 0, fun)
end
def find_index(enumerable, fun) do
result =
Enumerable.reduce(enumerable, {:cont, {:not_found, 0}}, fn entry, {_, index} ->
if fun.(entry), do: {:halt, {:found, index}}, else: {:cont, {:not_found, index + 1}}
end)
case elem(result, 1) do
{:found, index} -> index
{:not_found, _} -> nil
end
end
@doc """
Similar to `find/3`, but returns the value of the function
invocation instead of the element itself.
The return value is considered to be found when the result is truthy
(neither `nil` nor `false`).
## Examples
iex> Enum.find_value([2, 3, 4], fn x ->
...> if x > 2, do: x * x
...> end)
9
iex> Enum.find_value([2, 4, 6], fn x -> rem(x, 2) == 1 end)
nil
iex> Enum.find_value([2, 3, 4], fn x -> rem(x, 2) == 1 end)
true
iex> Enum.find_value([1, 2, 3], "no bools!", &is_boolean/1)
"no bools!"
"""
@spec find_value(t, any, (element -> any)) :: any | nil
def find_value(enumerable, default \\ nil, fun)
def find_value(enumerable, default, fun) when is_list(enumerable) do
find_value_list(enumerable, default, fun)
end
def find_value(enumerable, default, fun) do
Enumerable.reduce(enumerable, {:cont, default}, fn entry, default ->
fun_entry = fun.(entry)
if fun_entry, do: {:halt, fun_entry}, else: {:cont, default}
end)
|> elem(1)
end
@doc """
Maps the given `fun` over `enumerable` and flattens the result.
This function returns a new enumerable built by appending the result of invoking `fun`
on each element of `enumerable` together; conceptually, this is similar to a
combination of `map/2` and `concat/1`.
## Examples
iex> Enum.flat_map([:a, :b, :c], fn x -> [x, x] end)
[:a, :a, :b, :b, :c, :c]
iex> Enum.flat_map([{1, 3}, {4, 6}], fn {x, y} -> x..y end)
[1, 2, 3, 4, 5, 6]
iex> Enum.flat_map([:a, :b, :c], fn x -> [[x]] end)
[[:a], [:b], [:c]]
"""
@spec flat_map(t, (element -> t)) :: list
def flat_map(enumerable, fun) when is_list(enumerable) do
flat_map_list(enumerable, fun)
end
def flat_map(enumerable, fun) do
reduce(enumerable, [], fn entry, acc ->
case fun.(entry) do
list when is_list(list) -> :lists.reverse(list, acc)
other -> reduce(other, acc, &[&1 | &2])
end
end)
|> :lists.reverse()
end
@doc """
Maps and reduces an `enumerable`, flattening the given results (only one level deep).
It expects an accumulator and a function that receives each enumerable
element, and must return a tuple containing a new enumerable (often a list)
with the new accumulator or a tuple with `:halt` as first element and
the accumulator as second.
## Examples
iex> enumerable = 1..100
iex> n = 3
iex> Enum.flat_map_reduce(enumerable, 0, fn x, acc ->
...> if acc < n, do: {[x], acc + 1}, else: {:halt, acc}
...> end)
{[1, 2, 3], 3}
iex> Enum.flat_map_reduce(1..5, 0, fn x, acc -> {[[x]], acc + x} end)
{[[1], [2], [3], [4], [5]], 15}
"""
@spec flat_map_reduce(t, acc, fun) :: {[any], acc}
when fun: (element, acc -> {t, acc} | {:halt, acc})
def flat_map_reduce(enumerable, acc, fun) do
{_, {list, acc}} =
Enumerable.reduce(enumerable, {:cont, {[], acc}}, fn entry, {list, acc} ->
case fun.(entry, acc) do
{:halt, acc} ->
{:halt, {list, acc}}
{[], acc} ->
{:cont, {list, acc}}
{[entry], acc} ->
{:cont, {[entry | list], acc}}
{entries, acc} ->
{:cont, {reduce(entries, list, &[&1 | &2]), acc}}
end
end)
{:lists.reverse(list), acc}
end
@doc """
Returns a map with keys as unique elements of `enumerable` and values
as the count of every element.
## Examples
iex> Enum.frequencies(~w{ant buffalo ant ant buffalo dingo})
%{"ant" => 3, "buffalo" => 2, "dingo" => 1}
"""
@doc since: "1.10.0"
@spec frequencies(t) :: map
def frequencies(enumerable) do
reduce(enumerable, %{}, fn key, acc ->
case acc do
%{^key => value} -> %{acc | key => value + 1}
%{} -> Map.put(acc, key, 1)
end
end)
end
@doc """
Returns a map with keys as unique elements given by `key_fun` and values
as the count of every element.
## Examples
iex> Enum.frequencies_by(~w{aa aA bb cc}, &String.downcase/1)
%{"aa" => 2, "bb" => 1, "cc" => 1}
iex> Enum.frequencies_by(~w{aaa aA bbb cc c}, &String.length/1)
%{3 => 2, 2 => 2, 1 => 1}
"""
@doc since: "1.10.0"
@spec frequencies_by(t, (element -> any)) :: map
def frequencies_by(enumerable, key_fun) when is_function(key_fun) do
reduce(enumerable, %{}, fn entry, acc ->
key = key_fun.(entry)
case acc do
%{^key => value} -> %{acc | key => value + 1}
%{} -> Map.put(acc, key, 1)
end
end)
end
@doc """
Splits the `enumerable` into groups based on `key_fun`.
The result is a map where each key is given by `key_fun`
and each value is a list of elements given by `value_fun`.
The order of elements within each list is preserved from the `enumerable`.
However, like all maps, the resulting map is unordered.
## Examples
iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length/1)
%{3 => ["ant", "cat"], 5 => ["dingo"], 7 => ["buffalo"]}
iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length/1, &String.first/1)
%{3 => ["a", "c"], 5 => ["d"], 7 => ["b"]}
"""
@spec group_by(t, (element -> any), (element -> any)) :: map
def group_by(enumerable, key_fun, value_fun \\ fn x -> x end)
def group_by(enumerable, key_fun, value_fun) when is_function(key_fun) do
reduce(reverse(enumerable), %{}, fn entry, acc ->
key = key_fun.(entry)
value = value_fun.(entry)
case acc do
%{^key => existing} -> Map.put(acc, key, [value | existing])
%{} -> Map.put(acc, key, [value])
end
end)
end
def group_by(enumerable, dict, fun) do
IO.warn(
"Enum.group_by/3 with a map/dictionary as second element is deprecated. " <>
"A map is used by default and it is no longer required to pass one to this function"
)
# Avoid warnings about Dict
dict_module = Dict
reduce(reverse(enumerable), dict, fn entry, categories ->
dict_module.update(categories, fun.(entry), [entry], &[entry | &1])
end)
end
@doc """
Intersperses `element` between each element of the enumeration.
## Examples
iex> Enum.intersperse([1, 2, 3], 0)
[1, 0, 2, 0, 3]
iex> Enum.intersperse([1], 0)
[1]
iex> Enum.intersperse([], 0)
[]
"""
@spec intersperse(t, element) :: list
def intersperse(enumerable, element) do
list =
enumerable
|> reduce([], fn x, acc -> [x, element | acc] end)
|> :lists.reverse()
# Head is a superfluous intersperser element
case list do
[] -> []
[_ | t] -> t
end
end
@doc """
Inserts the given `enumerable` into a `collectable`.
Note that passing a non-empty list as the `collectable` is deprecated. If you're collecting
into a non-empty keyword list, consider using `Keyword.merge/2`. If you're collecting into a
non-empty list, consider something like `to_list(enumerable) ++ collectable`.
## Examples
iex> Enum.into([1, 2], [])
[1, 2]
iex> Enum.into([a: 1, b: 2], %{})
%{a: 1, b: 2}
iex> Enum.into(%{a: 1}, %{b: 2})
%{a: 1, b: 2}
iex> Enum.into([a: 1, a: 2], %{})
%{a: 2}
"""
@spec into(Enumerable.t(), Collectable.t()) :: Collectable.t()
def into(enumerable, collectable)
def into(enumerable, []) do
to_list(enumerable)
end
def into(%_{} = enumerable, collectable) do
into_protocol(enumerable, collectable)
end
def into(enumerable, %_{} = collectable) do
into_protocol(enumerable, collectable)
end
def into(%{} = enumerable, %{} = collectable) do
Map.merge(collectable, enumerable)
end
def into(enumerable, %{} = collectable) when is_list(enumerable) do
Map.merge(collectable, :maps.from_list(enumerable))
end
def into(enumerable, %{} = collectable) do
reduce(enumerable, collectable, fn {key, val}, acc ->
Map.put(acc, key, val)
end)
end
def into(enumerable, collectable) do
into_protocol(enumerable, collectable)
end
defp into_protocol(enumerable, collectable) do
{initial, fun} = Collectable.into(collectable)
into(enumerable, initial, fun, fn entry, acc ->
fun.(acc, {:cont, entry})
end)
end
@doc """
Inserts the given `enumerable` into a `collectable` according to the
transformation function.
## Examples
iex> Enum.into([2, 3], [3], fn x -> x * 3 end)
[3, 6, 9]
iex> Enum.into(%{a: 1, b: 2}, %{c: 3}, fn {k, v} -> {k, v * 2} end)
%{a: 2, b: 4, c: 3}
"""
@spec into(Enumerable.t(), Collectable.t(), (term -> term)) :: Collectable.t()
def into(enumerable, collectable, transform) when is_list(collectable) do
collectable ++ map(enumerable, transform)
end
def into(enumerable, collectable, transform) do
{initial, fun} = Collectable.into(collectable)
into(enumerable, initial, fun, fn entry, acc ->
fun.(acc, {:cont, transform.(entry)})
end)
end
defp into(enumerable, initial, fun, callback) do
try do
reduce(enumerable, initial, callback)
catch
kind, reason ->
fun.(initial, :halt)
:erlang.raise(kind, reason, __STACKTRACE__)
else
acc -> fun.(acc, :done)
end
end
@doc """
Joins the given `enumerable` into a string using `joiner` as a
separator.
If `joiner` is not passed at all, it defaults to an empty string.
All elements in the `enumerable` must be convertible to a string,
otherwise an error is raised.
## Examples
iex> Enum.join([1, 2, 3])
"123"
iex> Enum.join([1, 2, 3], " = ")
"1 = 2 = 3"
"""
@spec join(t, String.t()) :: String.t()
def join(enumerable, joiner \\ "")
def join(enumerable, "") do
enumerable
|> map(&entry_to_string(&1))
|> IO.iodata_to_binary()
end
def join(enumerable, joiner) when is_binary(joiner) do
reduced =
reduce(enumerable, :first, fn
entry, :first -> entry_to_string(entry)
entry, acc -> [acc, joiner | entry_to_string(entry)]
end)
if reduced == :first do
""
else
IO.iodata_to_binary(reduced)
end
end
@doc """
Returns a list where each element is the result of invoking
`fun` on each corresponding element of `enumerable`.
For maps, the function expects a key-value tuple.
## Examples
iex> Enum.map([1, 2, 3], fn x -> x * 2 end)
[2, 4, 6]
iex> Enum.map([a: 1, b: 2], fn {k, v} -> {k, -v} end)
[a: -1, b: -2]
"""
@spec map(t, (element -> any)) :: list
def map(enumerable, fun)
def map(enumerable, fun) when is_list(enumerable) do
:lists.map(fun, enumerable)
end
def map(enumerable, fun) do
reduce(enumerable, [], R.map(fun)) |> :lists.reverse()
end
@doc """
Returns a list of results of invoking `fun` on every `nth`
element of `enumerable`, starting with the first element.
The first element is always passed to the given function, unless `nth` is `0`.
The second argument specifying every `nth` element must be a non-negative
integer.
If `nth` is `0`, then `enumerable` is directly converted to a list,
without `fun` being ever applied.
## Examples
iex> Enum.map_every(1..10, 2, fn x -> x + 1000 end)
[1001, 2, 1003, 4, 1005, 6, 1007, 8, 1009, 10]
iex> Enum.map_every(1..10, 3, fn x -> x + 1000 end)
[1001, 2, 3, 1004, 5, 6, 1007, 8, 9, 1010]
iex> Enum.map_every(1..5, 0, fn x -> x + 1000 end)
[1, 2, 3, 4, 5]
iex> Enum.map_every([1, 2, 3], 1, fn x -> x + 1000 end)
[1001, 1002, 1003]
"""
@doc since: "1.4.0"
@spec map_every(t, non_neg_integer, (element -> any)) :: list
def map_every(enumerable, nth, fun)
def map_every(enumerable, 1, fun), do: map(enumerable, fun)
def map_every(enumerable, 0, _fun), do: to_list(enumerable)
def map_every([], nth, _fun) when is_integer(nth) and nth > 1, do: []
def map_every(enumerable, nth, fun) when is_integer(nth) and nth > 1 do
{res, _} = reduce(enumerable, {[], :first}, R.map_every(nth, fun))
:lists.reverse(res)
end
@doc """
Maps and intersperses the given enumerable in one pass.
## Examples
iex> Enum.map_intersperse([1, 2, 3], :a, &(&1 * 2))
[2, :a, 4, :a, 6]
"""
@doc since: "1.10.0"
@spec map_intersperse(t, element(), (element -> any())) :: list()
def map_intersperse(enumerable, separator, mapper)
def map_intersperse(enumerable, separator, mapper) when is_list(enumerable) do
map_intersperse_list(enumerable, separator, mapper)
end
def map_intersperse(enumerable, separator, mapper) do
reduced =
reduce(enumerable, :first, fn
entry, :first -> [mapper.(entry)]
entry, acc -> [mapper.(entry), separator | acc]
end)
if reduced == :first do
[]
else
:lists.reverse(reduced)
end
end
@doc """
Maps and joins the given `enumerable` in one pass.
If `joiner` is not passed at all, it defaults to an empty string.
All elements returned from invoking the `mapper` must be convertible to
a string, otherwise an error is raised.
## Examples
iex> Enum.map_join([1, 2, 3], &(&1 * 2))
"246"
iex> Enum.map_join([1, 2, 3], " = ", &(&1 * 2))
"2 = 4 = 6"
"""
@spec map_join(t, String.t(), (element -> String.Chars.t())) :: String.t()
def map_join(enumerable, joiner \\ "", mapper) when is_binary(joiner) do
enumerable
|> map_intersperse(joiner, &entry_to_string(mapper.(&1)))
|> IO.iodata_to_binary()
end
@doc """
Invokes the given function to each element in the `enumerable` to reduce
it to a single element, while keeping an accumulator.
Returns a tuple where the first element is the mapped enumerable and
the second one is the final accumulator.
The function, `fun`, receives two arguments: the first one is the
element, and the second one is the accumulator. `fun` must return
a tuple with two elements in the form of `{result, accumulator}`.
For maps, the first tuple element must be a `{key, value}` tuple.
## Examples
iex> Enum.map_reduce([1, 2, 3], 0, fn x, acc -> {x * 2, x + acc} end)
{[2, 4, 6], 6}
"""
@spec map_reduce(t, acc, (element, acc -> {element, acc})) :: {list, acc}
def map_reduce(enumerable, acc, fun) when is_list(enumerable) do
:lists.mapfoldl(fun, acc, enumerable)
end
def map_reduce(enumerable, acc, fun) do
{list, acc} =
reduce(enumerable, {[], acc}, fn entry, {list, acc} ->
{new_entry, acc} = fun.(entry, acc)
{[new_entry | list], acc}
end)
{:lists.reverse(list), acc}
end
@doc false
@spec max(t, (() -> empty_result)) :: element | empty_result when empty_result: any
def max(enumerable, empty_fallback) when is_function(empty_fallback, 0) do
max(enumerable, &>=/2, empty_fallback)
end
@doc """
Returns the maximal element in the `enumerable` according
to Erlang's term ordering.
By default, the comparison is done with the `>=` sorter function.
If multiple elements are considered maximal, the first one that
was found is returned. If you want the last element considered
maximal to be returned, the sorter function should not return true
for equal elements.
If the enumerable is empty, the provided `empty_fallback` is called.
The default `empty_fallback` raises `Enum.EmptyError`.
## Examples
iex> Enum.max([1, 2, 3])
3
The fact this function uses Erlang's term ordering means that the comparison
is structural and not semantic. For example:
iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]])
~D[2017-03-31]
In the example above, `max/2` returned March 31st instead of April 1st
because the structural comparison compares the day before the year.
For this reason, most structs provide a "compare" function, such as
`Date.compare/2`, which receives two structs and returns `:lt` (less than),
`:eq` (equal), and `:gt` (greater than). If you pass a module as the
sorting function, Elixir will automatically use the `compare/2` function
of said module:
iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]], Date)
~D[2017-04-01]
Finally, if you don't want to raise on empty enumerables, you can pass
the empty fallback:
iex> Enum.max([], &>=/2, fn -> 0 end)
0
"""
@spec max(t, (element, element -> boolean) | module()) ::
element | empty_result
when empty_result: any
@spec max(t, (element, element -> boolean) | module(), (() -> empty_result)) ::
element | empty_result
when empty_result: any
def max(enumerable, sorter \\ &>=/2, empty_fallback \\ fn -> raise Enum.EmptyError end) do
aggregate(enumerable, max_sort_fun(sorter), empty_fallback)
end
defp max_sort_fun(sorter) when is_function(sorter, 2), do: sorter
defp max_sort_fun(module) when is_atom(module), do: &(module.compare(&1, &2) != :lt)
@doc false
@spec max_by(t, (element -> any), (() -> empty_result)) :: element | empty_result
when empty_result: any
def max_by(enumerable, fun, empty_fallback)
when is_function(fun, 1) and is_function(empty_fallback, 0) do
max_by(enumerable, fun, &>=/2, empty_fallback)
end
@doc """
Returns the maximal element in the `enumerable` as calculated
by the given `fun`.
By default, the comparison is done with the `>=` sorter function.
If multiple elements are considered maximal, the first one that
was found is returned. If you want the last element considered
maximal to be returned, the sorter function should not return true
for equal elements.
Calls the provided `empty_fallback` function and returns its value if
`enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.
## Examples
iex> Enum.max_by(["a", "aa", "aaa"], fn x -> String.length(x) end)
"aaa"
iex> Enum.max_by(["a", "aa", "aaa", "b", "bbb"], &String.length/1)
"aaa"
The fact this function uses Erlang's term ordering means that the
comparison is structural and not semantic. Therefore, if you want
to compare structs, most structs provide a "compare" function, such as
`Date.compare/2`, which receives two structs and returns `:lt` (less than),
`:eq` (equal), and `:gt` (greater than). If you pass a module as the
sorting function, Elixir will automatically use the `compare/2` function
of said module:
iex> users = [
...> %{name: "Ellis", birthday: ~D[1943-05-11]},
...> %{name: "Lovelace", birthday: ~D[1815-12-10]},
...> %{name: "Turing", birthday: ~D[1912-06-23]}
...> ]
iex> Enum.max_by(users, &(&1.birthday), Date)
%{name: "Ellis", birthday: ~D[1943-05-11]}
Finally, if you don't want to raise on empty enumerables, you can pass
the empty fallback:
iex> Enum.max_by([], &String.length/1, fn -> nil end)
nil
"""
@spec max_by(
t,
(element -> any),
(element, element -> boolean) | module()
) :: element | empty_result
when empty_result: any
@spec max_by(
t,
(element -> any),
(element, element -> boolean) | module(),
(() -> empty_result)
) :: element | empty_result
when empty_result: any
def max_by(enumerable, fun, sorter \\ &>=/2, empty_fallback \\ fn -> raise Enum.EmptyError end)
when is_function(fun, 1) do
aggregate_by(enumerable, fun, max_sort_fun(sorter), empty_fallback)
end
@doc """
Checks if `element` exists within the `enumerable`.
Membership is tested with the match (`===/2`) operator.
## Examples
iex> Enum.member?(1..10, 5)
true
iex> Enum.member?(1..10, 5.0)
false
iex> Enum.member?([1.0, 2.0, 3.0], 2)
false
iex> Enum.member?([1.0, 2.0, 3.0], 2.000)
true
iex> Enum.member?([:a, :b, :c], :d)
false
The [`in`](`in/2`) and [`not in`](`in/2`) operators work by calling this
function.
"""
@spec member?(t, element) :: boolean
def member?(enumerable, element) when is_list(enumerable) do
:lists.member(element, enumerable)
end
def member?(enumerable, element) do
case Enumerable.member?(enumerable, element) do
{:ok, element} when is_boolean(element) ->
element
{:error, module} ->
module.reduce(enumerable, {:cont, false}, fn
v, _ when v === element -> {:halt, true}
_, _ -> {:cont, false}
end)
|> elem(1)
end
end
@doc false
@spec min(t, (() -> empty_result)) :: element | empty_result when empty_result: any
def min(enumerable, empty_fallback) when is_function(empty_fallback, 0) do
min(enumerable, &<=/2, empty_fallback)
end
@doc """
Returns the minimal element in the `enumerable` according
to Erlang's term ordering.
By default, the comparison is done with the `<=` sorter function.
If multiple elements are considered minimal, the first one that
was found is returned. If you want the last element considered
minimal to be returned, the sorter function should not return true
for equal elements.
If the enumerable is empty, the provided `empty_fallback` is called.
The default `empty_fallback` raises `Enum.EmptyError`.
## Examples
iex> Enum.min([1, 2, 3])
1
The fact this function uses Erlang's term ordering means that the comparison
is structural and not semantic. For example:
iex> Enum.min([~D[2017-03-31], ~D[2017-04-01]])
~D[2017-04-01]
In the example above, `min/2` returned April 1st instead of March 31st
because the structural comparison compares the day before the year.
For this reason, most structs provide a "compare" function, such as
`Date.compare/2`, which receives two structs and returns `:lt` (less than),
`:eq` (equal), and `:gt` (greater than). If you pass a module as the
sorting function, Elixir will automatically use the `compare/2` function
of said module:
iex> Enum.min([~D[2017-03-31], ~D[2017-04-01]], Date)
~D[2017-03-31]
Finally, if you don't want to raise on empty enumerables, you can pass
the empty fallback:
iex> Enum.min([], fn -> 0 end)
0
"""
@spec min(t, (element, element -> boolean) | module()) ::
element | empty_result
when empty_result: any
@spec min(t, (element, element -> boolean) | module(), (() -> empty_result)) ::
element | empty_result
when empty_result: any
def min(enumerable, sorter \\ &<=/2, empty_fallback \\ fn -> raise Enum.EmptyError end) do
aggregate(enumerable, min_sort_fun(sorter), empty_fallback)
end
defp min_sort_fun(sorter) when is_function(sorter, 2), do: sorter
defp min_sort_fun(module) when is_atom(module), do: &(module.compare(&1, &2) != :gt)
@doc false
@spec min_by(t, (element -> any), (() -> empty_result)) :: element | empty_result
when empty_result: any
def min_by(enumerable, fun, empty_fallback)
when is_function(fun, 1) and is_function(empty_fallback, 0) do
min_by(enumerable, fun, &<=/2, empty_fallback)
end
@doc """
Returns the minimal element in the `enumerable` as calculated
by the given `fun`.
By default, the comparison is done with the `<=` sorter function.
If multiple elements are considered minimal, the first one that
was found is returned. If you want the last element considered
minimal to be returned, the sorter function should not return true
for equal elements.
Calls the provided `empty_fallback` function and returns its value if
`enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.
## Examples
iex> Enum.min_by(["a", "aa", "aaa"], fn x -> String.length(x) end)
"a"
iex> Enum.min_by(["a", "aa", "aaa", "b", "bbb"], &String.length/1)
"a"
The fact this function uses Erlang's term ordering means that the
comparison is structural and not semantic. Therefore, if you want
to compare structs, most structs provide a "compare" function, such as
`Date.compare/2`, which receives two structs and returns `:lt` (less than),
`:eq` (equal), and `:gt` (greater than). If you pass a module as the
sorting function, Elixir will automatically use the `compare/2` function
of said module:
iex> users = [
...> %{name: "Ellis", birthday: ~D[1943-05-11]},
...> %{name: "Lovelace", birthday: ~D[1815-12-10]},
...> %{name: "Turing", birthday: ~D[1912-06-23]}
...> ]
iex> Enum.min_by(users, &(&1.birthday), Date)
%{name: "Lovelace", birthday: ~D[1815-12-10]}
Finally, if you don't want to raise on empty enumerables, you can pass
the empty fallback:
iex> Enum.min_by([], &String.length/1, fn -> nil end)
nil
"""
@spec min_by(
t,
(element -> any),
(element, element -> boolean) | module()
) :: element | empty_result
when empty_result: any
@spec min_by(
t,
(element -> any),
(element, element -> boolean) | module(),
(() -> empty_result)
) :: element | empty_result
when empty_result: any
def min_by(enumerable, fun, sorter \\ &<=/2, empty_fallback \\ fn -> raise Enum.EmptyError end)
when is_function(fun, 1) do
aggregate_by(enumerable, fun, min_sort_fun(sorter), empty_fallback)
end
@doc """
Returns a tuple with the minimal and the maximal elements in the
enumerable according to Erlang's term ordering.
If multiple elements are considered maximal or minimal, the first one
that was found is returned.
Calls the provided `empty_fallback` function and returns its value if
`enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.
## Examples
iex> Enum.min_max([2, 3, 1])
{1, 3}
iex> Enum.min_max([], fn -> {nil, nil} end)
{nil, nil}
"""
@spec min_max(t, (() -> empty_result)) :: {element, element} | empty_result
when empty_result: any
def min_max(enumerable, empty_fallback \\ fn -> raise Enum.EmptyError end)
def min_max(first..last, empty_fallback) when is_function(empty_fallback, 0) do
{Kernel.min(first, last), Kernel.max(first, last)}
end
def min_max(enumerable, empty_fallback) when is_function(empty_fallback, 0) do
first_fun = &[&1 | &1]
reduce_fun = fn entry, [min | max] ->
[Kernel.min(min, entry) | Kernel.max(max, entry)]
end
case reduce_by(enumerable, first_fun, reduce_fun) do
:empty -> empty_fallback.()
[min | max] -> {min, max}
end
end
@doc false
@spec min_max_by(t, (element -> any), (() -> empty_result)) :: {element, element} | empty_result
when empty_result: any
def min_max_by(enumerable, fun, empty_fallback)
when is_function(fun, 1) and is_function(empty_fallback, 0) do
min_max_by(enumerable, fun, &</2, empty_fallback)
end
@doc """
Returns a tuple with the minimal and the maximal elements in the
enumerable as calculated by the given function.
If multiple elements are considered maximal or minimal, the first one
that was found is returned.
## Examples
iex> Enum.min_max_by(["aaa", "bb", "c"], fn x -> String.length(x) end)
{"c", "aaa"}
iex> Enum.min_max_by(["aaa", "a", "bb", "c", "ccc"], &String.length/1)
{"a", "aaa"}
iex> Enum.min_max_by([], &String.length/1, fn -> {nil, nil} end)
{nil, nil}
The fact this function uses Erlang's term ordering means that the
comparison is structural and not semantic. Therefore, if you want
to compare structs, most structs provide a "compare" function, such as
`Date.compare/2`, which receives two structs and returns `:lt` (less than),
`:eq` (equal), and `:gt` (greater than). If you pass a module as the
sorting function, Elixir will automatically use the `compare/2` function
of said module:
iex> users = [
...> %{name: "Ellis", birthday: ~D[1943-05-11]},
...> %{name: "Lovelace", birthday: ~D[1815-12-10]},
...> %{name: "Turing", birthday: ~D[1912-06-23]}
...> ]
iex> Enum.min_max_by(users, &(&1.birthday), Date)
{
%{name: "Lovelace", birthday: ~D[1815-12-10]},
%{name: "Ellis", birthday: ~D[1943-05-11]}
}
Finally, if you don't want to raise on empty enumerables, you can pass
the empty fallback:
iex> Enum.min_max_by([], &String.length/1, fn -> nil end)
nil
"""
@spec min_max_by(t, (element -> any), (element, element -> boolean) | module()) ::
{element, element} | empty_result
when empty_result: any
@spec min_max_by(
t,
(element -> any),
(element, element -> boolean) | module(),
(() -> empty_result)
) :: {element, element} | empty_result
when empty_result: any
def min_max_by(
enumerable,
fun,
sorter_or_empty_fallback \\ &</2,
empty_fallback \\ fn -> raise Enum.EmptyError end
)
def min_max_by(enumerable, fun, sorter, empty_fallback)
when is_function(fun, 1) and is_atom(sorter) and is_function(empty_fallback, 0) do
min_max_by(enumerable, fun, min_max_by_sort_fun(sorter), empty_fallback)
end
def min_max_by(enumerable, fun, sorter, empty_fallback)
when is_function(fun, 1) and is_function(sorter, 2) and is_function(empty_fallback, 0) do
first_fun = fn entry ->
fun_entry = fun.(entry)
{entry, entry, fun_entry, fun_entry}
end
reduce_fun = fn entry, {prev_min, prev_max, fun_min, fun_max} = acc ->
fun_entry = fun.(entry)
cond do
sorter.(fun_entry, fun_min) ->
{entry, prev_max, fun_entry, fun_max}
sorter.(fun_max, fun_entry) ->
{prev_min, entry, fun_min, fun_entry}
true ->
acc
end
end
case reduce_by(enumerable, first_fun, reduce_fun) do
:empty -> empty_fallback.()
{min, max, _, _} -> {min, max}
end
end
defp min_max_by_sort_fun(module) when is_atom(module), do: &(module.compare(&1, &2) == :lt)
@doc """
Splits the `enumerable` in two lists according to the given function `fun`.
Splits the given `enumerable` in two lists by calling `fun` with each element
in the `enumerable` as its only argument. Returns a tuple with the first list
containing all the elements in `enumerable` for which applying `fun` returned
a truthy value, and a second list with all the elements for which applying
`fun` returned a falsy value (`false` or `nil`).
The elements in both the returned lists are in the same relative order as they
were in the original enumerable (if such enumerable was ordered, like a
list). See the examples below.
## Examples
iex> Enum.split_with([5, 4, 3, 2, 1, 0], fn x -> rem(x, 2) == 0 end)
{[4, 2, 0], [5, 3, 1]}
iex> Enum.split_with(%{a: 1, b: -2, c: 1, d: -3}, fn {_k, v} -> v < 0 end)
{[b: -2, d: -3], [a: 1, c: 1]}
iex> Enum.split_with(%{a: 1, b: -2, c: 1, d: -3}, fn {_k, v} -> v > 50 end)
{[], [a: 1, b: -2, c: 1, d: -3]}
iex> Enum.split_with(%{}, fn {_k, v} -> v > 50 end)
{[], []}
"""
@doc since: "1.4.0"
@spec split_with(t, (element -> as_boolean(term))) :: {list, list}
def split_with(enumerable, fun) do
{acc1, acc2} =
reduce(enumerable, {[], []}, fn entry, {acc1, acc2} ->
if fun.(entry) do
{[entry | acc1], acc2}
else
{acc1, [entry | acc2]}
end
end)
{:lists.reverse(acc1), :lists.reverse(acc2)}
end
@doc false
@deprecated "Use Enum.split_with/2 instead"
def partition(enumerable, fun) do
split_with(enumerable, fun)
end
@doc """
Returns a random element of an `enumerable`.
Raises `Enum.EmptyError` if `enumerable` is empty.
This function uses Erlang's [`:rand` module](http://www.erlang.org/doc/man/rand.html) to calculate
the random value. Check its documentation for setting a
different random algorithm or a different seed.
The implementation is based on the
[reservoir sampling](https://en.wikipedia.org/wiki/Reservoir_sampling#Relation_to_Fisher-Yates_shuffle)
algorithm.
It assumes that the sample being returned can fit into memory;
the input `enumerable` doesn't have to, as it is traversed just once.
If a range is passed into the function, this function will pick a
random value between the range limits, without traversing the whole
range (thus executing in constant time and constant memory).
## Examples
The examples below use the `:exrop` pseudorandom algorithm since it's
the default from Erlang/OTP 20, however if you are using Erlang/OTP 22
or above then `:exsss` is the default algorithm. If you are using `:exsplus`,
then please update, as this algorithm is deprecated since Erlang/OTP 20.
# Although not necessary, let's seed the random algorithm
iex> :rand.seed(:exrop, {101, 102, 103})
iex> Enum.random([1, 2, 3])
3
iex> Enum.random([1, 2, 3])
2
iex> Enum.random(1..1_000)
846
"""
@spec random(t) :: element
def random(enumerable)
def random(enumerable) when is_list(enumerable) do
case length(enumerable) do
0 -> raise Enum.EmptyError
length -> enumerable |> drop_list(random_integer(0, length - 1)) |> hd()
end
end
def random(enumerable) do
result =
case Enumerable.slice(enumerable) do
{:ok, 0, _} ->
[]
{:ok, count, fun} when is_function(fun) ->
fun.(random_integer(0, count - 1), 1)
{:error, _} ->
take_random(enumerable, 1)
end
case result do
[] -> raise Enum.EmptyError
[elem] -> elem
end
end
@doc """
Invokes `fun` for each element in the `enumerable` with the
accumulator.
Raises `Enum.EmptyError` if `enumerable` is empty.
The first element of the `enumerable` is used as the initial value
of the accumulator. Then the function is invoked with the next
element and the accumulator. The result returned by the function
is used as the accumulator for the next iteration, recursively.
When the `enumerable` is done, the last accumulator is returned.
Since the first element of the enumerable is used as the initial
value of the accumulator, `fun` will only be executed `n - 1` times
where `n` is the length of the enumerable. This function won't call
the specified function for enumerables that are one-element long.
If you wish to use another value for the accumulator, use
`Enum.reduce/3`.
## Examples
iex> Enum.reduce([1, 2, 3, 4], fn x, acc -> x * acc end)
24
"""
@spec reduce(t, (element, acc -> acc)) :: acc
def reduce(enumerable, fun)
def reduce([h | t], fun) do
reduce(t, h, fun)
end
def reduce([], _fun) do
raise Enum.EmptyError
end
def reduce(enumerable, fun) do
Enumerable.reduce(enumerable, {:cont, :first}, fn
x, {:acc, acc} -> {:cont, {:acc, fun.(x, acc)}}
x, :first -> {:cont, {:acc, x}}
end)
|> elem(1)
|> case do
:first -> raise Enum.EmptyError
{:acc, acc} -> acc
end
end
@doc """
Invokes `fun` for each element in the `enumerable` with the accumulator.
The initial value of the accumulator is `acc`. The function is invoked for
each element in the enumerable with the accumulator. The result returned
by the function is used as the accumulator for the next iteration.
The function returns the last accumulator.
## Examples
iex> Enum.reduce([1, 2, 3], 0, fn x, acc -> x + acc end)
6
## Reduce as a building block
Reduce (sometimes called `fold`) is a basic building block in functional
programming. Almost all of the functions in the `Enum` module can be
implemented on top of reduce. Those functions often rely on other operations,
such as `Enum.reverse/1`, which are optimized by the runtime.
For example, we could implement `map/2` in terms of `reduce/3` as follows:
def my_map(enumerable, fun) do
enumerable
|> Enum.reduce([], fn x, acc -> [fun.(x) | acc] end)
|> Enum.reverse()
end
In the example above, `Enum.reduce/3` accumulates the result of each call
to `fun` into a list in reverse order, which is correctly ordered at the
end by calling `Enum.reverse/1`.
Implementing functions like `map/2`, `filter/2` and others are a good
exercise for understanding the power behind `Enum.reduce/3`. When an
operation cannot be expressed by any of the functions in the `Enum`
module, developers will most likely resort to `reduce/3`.
"""
@spec reduce(t, any, (element, acc -> acc)) :: acc
def reduce(enumerable, acc, fun) when is_list(enumerable) do
:lists.foldl(fun, acc, enumerable)
end
def reduce(first..last, acc, fun) do
if first <= last do
reduce_range_inc(first, last, acc, fun)
else
reduce_range_dec(first, last, acc, fun)
end
end
def reduce(%_{} = enumerable, acc, fun) do
reduce_enumerable(enumerable, acc, fun)
end
def reduce(%{} = enumerable, acc, fun) do
:maps.fold(fn k, v, acc -> fun.({k, v}, acc) end, acc, enumerable)
end
def reduce(enumerable, acc, fun) do
reduce_enumerable(enumerable, acc, fun)
end
@doc """
Reduces `enumerable` until `fun` returns `{:halt, term}`.
The return value for `fun` is expected to be
* `{:cont, acc}` to continue the reduction with `acc` as the new
accumulator or
* `{:halt, acc}` to halt the reduction
If `fun` returns `{:halt, acc}` the reduction is halted and the function
returns `acc`. Otherwise, if the enumerable is exhausted, the function returns
the accumulator of the last `{:cont, acc}`.
## Examples
iex> Enum.reduce_while(1..100, 0, fn x, acc ->
...> if x < 5, do: {:cont, acc + x}, else: {:halt, acc}
...> end)
10
iex> Enum.reduce_while(1..100, 0, fn x, acc ->
...> if x > 0, do: {:cont, acc + x}, else: {:halt, acc}
...> end)
5050
"""
@spec reduce_while(t, any, (element, any -> {:cont, any} | {:halt, any})) :: any
def reduce_while(enumerable, acc, fun) do
Enumerable.reduce(enumerable, {:cont, acc}, fun) |> elem(1)
end
@doc """
Returns a list of elements in `enumerable` excluding those for which the function `fun` returns
a truthy value.
See also `filter/2`.
## Examples
iex> Enum.reject([1, 2, 3], fn x -> rem(x, 2) == 0 end)
[1, 3]
"""
@spec reject(t, (element -> as_boolean(term))) :: list
def reject(enumerable, fun) when is_list(enumerable) do
reject_list(enumerable, fun)
end
def reject(enumerable, fun) do
reduce(enumerable, [], R.reject(fun)) |> :lists.reverse()
end
@doc """
Returns a list of elements in `enumerable` in reverse order.
## Examples
iex> Enum.reverse([1, 2, 3])
[3, 2, 1]
"""
@spec reverse(t) :: list
def reverse(enumerable)
def reverse([]), do: []
def reverse([_] = list), do: list
def reverse([element1, element2]), do: [element2, element1]
def reverse([element1, element2 | rest]), do: :lists.reverse(rest, [element2, element1])
def reverse(enumerable), do: reduce(enumerable, [], &[&1 | &2])
@doc """
Reverses the elements in `enumerable`, appends the `tail`, and returns
it as a list.
This is an optimization for
`enumerable |> Enum.reverse() |> Enum.concat(tail)`.
## Examples
iex> Enum.reverse([1, 2, 3], [4, 5, 6])
[3, 2, 1, 4, 5, 6]
"""
@spec reverse(t, t) :: list
def reverse(enumerable, tail) when is_list(enumerable) do
:lists.reverse(enumerable, to_list(tail))
end
def reverse(enumerable, tail) do
reduce(enumerable, to_list(tail), fn entry, acc ->
[entry | acc]
end)
end
@doc """
Reverses the `enumerable` in the range from initial `start_index`
through `count` elements.
If `count` is greater than the size of the rest of the `enumerable`,
then this function will reverse the rest of the enumerable.
## Examples
iex> Enum.reverse_slice([1, 2, 3, 4, 5, 6], 2, 4)
[1, 2, 6, 5, 4, 3]
"""
@spec reverse_slice(t, non_neg_integer, non_neg_integer) :: list
def reverse_slice(enumerable, start_index, count)
when is_integer(start_index) and start_index >= 0 and is_integer(count) and count >= 0 do
list = reverse(enumerable)
length = length(list)
count = Kernel.min(count, length - start_index)
if count > 0 do
reverse_slice(list, length, start_index + count, count, [])
else
:lists.reverse(list)
end
end
@doc """
Applies the given function to each element in the `enumerable`,
storing the result in a list and passing it as the accumulator
for the next computation. Uses the first element in the `enumerable`
as the starting value.
## Examples
iex> Enum.scan(1..5, &(&1 + &2))
[1, 3, 6, 10, 15]
"""
@spec scan(t, (element, any -> any)) :: list
def scan(enumerable, fun) do
{res, _} = reduce(enumerable, {[], :first}, R.scan2(fun))
:lists.reverse(res)
end
@doc """
Applies the given function to each element in the `enumerable`,
storing the result in a list and passing it as the accumulator
for the next computation. Uses the given `acc` as the starting value.
## Examples
iex> Enum.scan(1..5, 0, &(&1 + &2))
[1, 3, 6, 10, 15]
"""
@spec scan(t, any, (element, any -> any)) :: list
def scan(enumerable, acc, fun) do
{res, _} = reduce(enumerable, {[], acc}, R.scan3(fun))
:lists.reverse(res)
end
@doc """
Returns a list with the elements of `enumerable` shuffled.
This function uses Erlang's [`:rand` module](http://www.erlang.org/doc/man/rand.html) to calculate
the random value. Check its documentation for setting a
different random algorithm or a different seed.
## Examples
The examples below use the `:exrop` pseudorandom algorithm since it's
the default from Erlang/OTP 20, however if you are using Erlang/OTP 22
or above then `:exsss` is the default algorithm. If you are using `:exsplus`,
then please update, as this algorithm is deprecated since Erlang/OTP 20.
# Although not necessary, let's seed the random algorithm
iex> :rand.seed(:exrop, {1, 2, 3})
iex> Enum.shuffle([1, 2, 3])
[3, 1, 2]
iex> Enum.shuffle([1, 2, 3])
[1, 3, 2]
"""
@spec shuffle(t) :: list
def shuffle(enumerable) do
randomized =
reduce(enumerable, [], fn x, acc ->
[{:rand.uniform(), x} | acc]
end)
shuffle_unwrap(:lists.keysort(1, randomized), [])
end
@doc """
Returns a subset list of the given `enumerable` by `index_range`.
`index_range` must be a `Range`. Given an `enumerable`, it drops
elements before `index_range.first` (zero-base), then takes elements
until element `index_range.last` (inclusively).
Indexes are normalized, meaning that negative indexes will be counted
from the end (for example, `-1` means the last element of the `enumerable`).
If `index_range.last` is out of bounds, then it is assigned as the index
of the last element.
If the normalized `index_range.first` is out of bounds of the given
`enumerable`, or this one is greater than the normalized `index_range.last`,
then `[]` is returned.
## Examples
iex> Enum.slice(1..100, 5..10)
[6, 7, 8, 9, 10, 11]
iex> Enum.slice(1..10, 5..20)
[6, 7, 8, 9, 10]
# last five elements (negative indexes)
iex> Enum.slice(1..30, -5..-1)
[26, 27, 28, 29, 30]
# last five elements (mixed positive and negative indexes)
iex> Enum.slice(1..30, 25..-1)
[26, 27, 28, 29, 30]
# out of bounds
iex> Enum.slice(1..10, 11..20)
[]
# first is greater than last
iex> Enum.slice(1..10, 6..5)
[]
"""
@doc since: "1.6.0"
@spec slice(t, Range.t()) :: list
def slice(enumerable, index_range)
def slice(enumerable, first..last) when last >= first and last >= 0 do
slice_any(enumerable, first, last - first + 1)
end
def slice(enumerable, first..last) do
{count, fun} = slice_count_and_fun(enumerable)
first = if first >= 0, do: first, else: first + count
last = if last >= 0, do: last, else: last + count
amount = last - first + 1
if first >= 0 and first < count and amount > 0 do
fun.(first, Kernel.min(amount, count - first))
else
[]
end
end
@doc """
Returns a subset list of the given `enumerable`, from `start_index` (zero-based)
with `amount` number of elements if available.
Given an `enumerable`, it drops elements right before element `start_index`,
then takes `amount` of elements, returning as many elements as possible if
there are not enough elements.
A negative `start_index` can be passed, which means the `enumerable` is
enumerated once and the index is counted from the end (for example,
`-1` starts slicing from the last element).
It returns `[]` if `amount` is `0` or if `start_index` is out of bounds.
## Examples
iex> Enum.slice(1..100, 5, 10)
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
# amount to take is greater than the number of elements
iex> Enum.slice(1..10, 5, 100)
[6, 7, 8, 9, 10]
iex> Enum.slice(1..10, 5, 0)
[]
# using a negative start index
iex> Enum.slice(1..10, -6, 3)
[5, 6, 7]
# out of bound start index (positive)
iex> Enum.slice(1..10, 10, 5)
[]
# out of bound start index (negative)
iex> Enum.slice(1..10, -11, 5)
[]
"""
@spec slice(t, index, non_neg_integer) :: list
def slice(_enumerable, start_index, 0) when is_integer(start_index), do: []
def slice(enumerable, start_index, amount)
when is_integer(start_index) and is_integer(amount) and amount >= 0 do
slice_any(enumerable, start_index, amount)
end
@doc """
Sorts the `enumerable` according to Erlang's term ordering.
This function uses the merge sort algorithm. Do not use this
function to sort structs, see `sort/2` for more information.
## Examples
iex> Enum.sort([3, 2, 1])
[1, 2, 3]
"""
@spec sort(t) :: list
def sort(enumerable) when is_list(enumerable) do
:lists.sort(enumerable)
end
def sort(enumerable) do
sort(enumerable, &(&1 <= &2))
end
@doc """
Sorts the `enumerable` by the given function.
This function uses the merge sort algorithm. The given function should compare
two arguments, and return `true` if the first argument precedes or is in the
same place as the second one.
## Examples
iex> Enum.sort([1, 2, 3], &(&1 >= &2))
[3, 2, 1]
The sorting algorithm will be stable as long as the given function
returns `true` for values considered equal:
iex> Enum.sort(["some", "kind", "of", "monster"], &(byte_size(&1) <= byte_size(&2)))
["of", "some", "kind", "monster"]
If the function does not return `true` for equal values, the sorting
is not stable and the order of equal terms may be shuffled.
For example:
iex> Enum.sort(["some", "kind", "of", "monster"], &(byte_size(&1) < byte_size(&2)))
["of", "kind", "some", "monster"]
## Ascending and descending
`sort/2` allows a developer to pass `:asc` or `:desc` as the sorting
function, which is a convenience for `<=/2` and `>=/2` respectively.
iex> Enum.sort([2, 3, 1], :asc)
[1, 2, 3]
iex> Enum.sort([2, 3, 1], :desc)
[3, 2, 1]
## Sorting structs
Do not use `</2`, `<=/2`, `>/2`, `>=/2` and friends when sorting structs.
That's because the built-in operators above perform structural comparison
and not a semantic one. Imagine we sort the following list of dates:
iex> dates = [~D[2019-01-01], ~D[2020-03-02], ~D[2019-06-06]]
iex> Enum.sort(dates)
[~D[2019-01-01], ~D[2020-03-02], ~D[2019-06-06]]
Notice the returned result is incorrect, because `sort/1` by default uses
`<=/2`, which will compare their structure. When comparing structures, the
fields are compared in alphabetical order, which means the dates above will
be compared by `day`, `month` and then `year`, which is the opposite of what
we want.
For this reason, most structs provide a "compare" function, such as
`Date.compare/2`, which receives two structs and returns `:lt` (less than),
`:eq` (equal), and `:gt` (greather than). If you pass a module as the
sorting function, Elixir will automatically use the `compare/2` function
of said module:
iex> dates = [~D[2019-01-01], ~D[2020-03-02], ~D[2019-06-06]]
iex> Enum.sort(dates, Date)
[~D[2019-01-01], ~D[2019-06-06], ~D[2020-03-02]]
To retrieve all dates in descending order, you can wrap the module in
a tuple with `:asc` or `:desc` as first element:
iex> dates = [~D[2019-01-01], ~D[2020-03-02], ~D[2019-06-06]]
iex> Enum.sort(dates, {:asc, Date})
[~D[2019-01-01], ~D[2019-06-06], ~D[2020-03-02]]
iex> dates = [~D[2019-01-01], ~D[2020-03-02], ~D[2019-06-06]]
iex> Enum.sort(dates, {:desc, Date})
[~D[2020-03-02], ~D[2019-06-06], ~D[2019-01-01]]
"""
@spec sort(
t,
(element, element -> boolean) | :asc | :desc | module() | {:asc | :desc, module()}
) :: list
def sort(enumerable, fun) when is_list(enumerable) do
:lists.sort(to_sort_fun(fun), enumerable)
end
def sort(enumerable, fun) do
fun = to_sort_fun(fun)
reduce(enumerable, [], &sort_reducer(&1, &2, fun))
|> sort_terminator(fun)
end
defp to_sort_fun(sorter) when is_function(sorter, 2), do: sorter
defp to_sort_fun(:asc), do: &<=/2
defp to_sort_fun(:desc), do: &>=/2
defp to_sort_fun(module) when is_atom(module), do: &(module.compare(&1, &2) != :gt)
defp to_sort_fun({:asc, module}) when is_atom(module), do: &(module.compare(&1, &2) != :gt)
defp to_sort_fun({:desc, module}) when is_atom(module), do: &(module.compare(&1, &2) != :lt)
@doc """
Sorts the mapped results of the `enumerable` according to the provided `sorter`
function.
This function maps each element of the `enumerable` using the
provided `mapper` function. The enumerable is then sorted by
the mapped elements using the `sorter` function, which defaults
to `Kernel.<=/2`.
`sort_by/3` differs from `sort/2` in that it only calculates the
comparison value for each element in the enumerable once instead of
once for each element in each comparison. If the same function is
being called on both elements, it's more efficient to use `sort_by/3`.
## Examples
Using the default `sorter` of `<=/2`:
iex> Enum.sort_by(["some", "kind", "of", "monster"], &byte_size/1)
["of", "some", "kind", "monster"]
Sorting by multiple properties - first by size, then by first letter
(this takes advantage of the fact that tuples are compared element-by-element):
iex> Enum.sort_by(["some", "kind", "of", "monster"], &{byte_size(&1), String.first(&1)})
["of", "kind", "some", "monster"]
Similar to `sort/2`, you can pass a custom sorter:
iex> Enum.sort_by(["some", "kind", "of", "monster"], &byte_size/1, &>=/2)
["monster", "some", "kind", "of"]
Or use `:asc` and `:desc`:
iex> Enum.sort_by(["some", "kind", "of", "monster"], &byte_size/1, :desc)
["monster", "some", "kind", "of"]
As in `sort/2`, avoid using the default sorting function to sort structs, as by default
it performs structural comparison instead of a semantic one. In such cases,
you shall pass a sorting function as third element or any module that implements
a `compare/2` function. For example, to sort users by their birthday in both
ascending and descending order respectively:
iex> users = [
...> %{name: "Ellis", birthday: ~D[1943-05-11]},
...> %{name: "Lovelace", birthday: ~D[1815-12-10]},
...> %{name: "Turing", birthday: ~D[1912-06-23]}
...> ]
iex> Enum.sort_by(users, &(&1.birthday), Date)
[
%{name: "Lovelace", birthday: ~D[1815-12-10]},
%{name: "Turing", birthday: ~D[1912-06-23]},
%{name: "Ellis", birthday: ~D[1943-05-11]}
]
iex> Enum.sort_by(users, &(&1.birthday), {:desc, Date})
[
%{name: "Ellis", birthday: ~D[1943-05-11]},
%{name: "Turing", birthday: ~D[1912-06-23]},
%{name: "Lovelace", birthday: ~D[1815-12-10]}
]
"""
@spec sort_by(
t,
(element -> mapped_element),
(element, element -> boolean) | :asc | :desc | module() | {:asc | :desc, module()}
) ::
list
when mapped_element: element
def sort_by(enumerable, mapper, sorter \\ &<=/2) do
enumerable
|> map(&{&1, mapper.(&1)})
|> sort(to_sort_by_fun(sorter))
|> map(&elem(&1, 0))
end
defp to_sort_by_fun(sorter) when is_function(sorter, 2),
do: &sorter.(elem(&1, 1), elem(&2, 1))
defp to_sort_by_fun(:asc),
do: &(elem(&1, 1) <= elem(&2, 1))
defp to_sort_by_fun(:desc),
do: &(elem(&1, 1) >= elem(&2, 1))
defp to_sort_by_fun(module) when is_atom(module),
do: &(module.compare(elem(&1, 1), elem(&2, 1)) != :gt)
defp to_sort_by_fun({:asc, module}) when is_atom(module),
do: &(module.compare(elem(&1, 1), elem(&2, 1)) != :gt)
defp to_sort_by_fun({:desc, module}) when is_atom(module),
do: &(module.compare(elem(&1, 1), elem(&2, 1)) != :lt)
@doc """
Splits the `enumerable` into two enumerables, leaving `count`
elements in the first one.
If `count` is a negative number, it starts counting from the
back to the beginning of the `enumerable`.
Be aware that a negative `count` implies the `enumerable`
will be enumerated twice: once to calculate the position, and
a second time to do the actual splitting.
## Examples
iex> Enum.split([1, 2, 3], 2)
{[1, 2], [3]}
iex> Enum.split([1, 2, 3], 10)
{[1, 2, 3], []}
iex> Enum.split([1, 2, 3], 0)
{[], [1, 2, 3]}
iex> Enum.split([1, 2, 3], -1)
{[1, 2], [3]}
iex> Enum.split([1, 2, 3], -5)
{[], [1, 2, 3]}
"""
@spec split(t, integer) :: {list, list}
def split(enumerable, count) when is_list(enumerable) and is_integer(count) and count >= 0 do
split_list(enumerable, count, [])
end
def split(enumerable, count) when is_integer(count) and count >= 0 do
{_, list1, list2} =
reduce(enumerable, {count, [], []}, fn entry, {counter, acc1, acc2} ->
if counter > 0 do
{counter - 1, [entry | acc1], acc2}
else
{counter, acc1, [entry | acc2]}
end
end)
{:lists.reverse(list1), :lists.reverse(list2)}
end
def split(enumerable, count) when is_integer(count) and count < 0 do
split_reverse_list(reverse(enumerable), -count, [])
end
@doc """
Splits enumerable in two at the position of the element for which
`fun` returns a falsy value (`false` or `nil`) for the first time.
It returns a two-element tuple with two lists of elements.
The element that triggered the split is part of the second list.
## Examples
iex> Enum.split_while([1, 2, 3, 4], fn x -> x < 3 end)
{[1, 2], [3, 4]}
iex> Enum.split_while([1, 2, 3, 4], fn x -> x < 0 end)
{[], [1, 2, 3, 4]}
iex> Enum.split_while([1, 2, 3, 4], fn x -> x > 0 end)
{[1, 2, 3, 4], []}
"""
@spec split_while(t, (element -> as_boolean(term))) :: {list, list}
def split_while(enumerable, fun) when is_list(enumerable) do
split_while_list(enumerable, fun, [])
end
def split_while(enumerable, fun) do
{list1, list2} =
reduce(enumerable, {[], []}, fn
entry, {acc1, []} ->
if(fun.(entry), do: {[entry | acc1], []}, else: {acc1, [entry]})
entry, {acc1, acc2} ->
{acc1, [entry | acc2]}
end)
{:lists.reverse(list1), :lists.reverse(list2)}
end
@doc """
Returns the sum of all elements.
Raises `ArithmeticError` if `enumerable` contains a non-numeric value.
## Examples
iex> Enum.sum([1, 2, 3])
6
"""
@spec sum(t) :: number
def sum(enumerable)
def sum(first..last) do
div((last + first) * (abs(last - first) + 1), 2)
end
def sum(enumerable) do
reduce(enumerable, 0, &+/2)
end
@doc """
Takes an `amount` of elements from the beginning or the end of the `enumerable`.
If a positive `amount` is given, it takes the `amount` elements from the
beginning of the `enumerable`.
If a negative `amount` is given, the `amount` of elements will be taken from the end.
The `enumerable` will be enumerated once to retrieve the proper index and
the remaining calculation is performed from the end.
If amount is `0`, it returns `[]`.
## Examples
iex> Enum.take([1, 2, 3], 2)
[1, 2]
iex> Enum.take([1, 2, 3], 10)
[1, 2, 3]
iex> Enum.take([1, 2, 3], 0)
[]
iex> Enum.take([1, 2, 3], -1)
[3]
"""
@spec take(t, integer) :: list
def take(enumerable, amount)
def take(_enumerable, 0), do: []
def take(enumerable, amount)
when is_list(enumerable) and is_integer(amount) and amount > 0 do
take_list(enumerable, amount)
end
def take(enumerable, amount) when is_integer(amount) and amount > 0 do
{_, {res, _}} =
Enumerable.reduce(enumerable, {:cont, {[], amount}}, fn entry, {list, n} ->
case n do
1 -> {:halt, {[entry | list], n - 1}}
_ -> {:cont, {[entry | list], n - 1}}
end
end)
:lists.reverse(res)
end
def take(enumerable, amount) when is_integer(amount) and amount < 0 do
{count, fun} = slice_count_and_fun(enumerable)
first = Kernel.max(amount + count, 0)
fun.(first, count - first)
end
@doc """
Returns a list of every `nth` element in the `enumerable`,
starting with the first element.
The first element is always included, unless `nth` is 0.
The second argument specifying every `nth` element must be a non-negative
integer.
## Examples
iex> Enum.take_every(1..10, 2)
[1, 3, 5, 7, 9]
iex> Enum.take_every(1..10, 0)
[]
iex> Enum.take_every([1, 2, 3], 1)
[1, 2, 3]
"""
@spec take_every(t, non_neg_integer) :: list
def take_every(enumerable, nth)
def take_every(enumerable, 1), do: to_list(enumerable)
def take_every(_enumerable, 0), do: []
def take_every([], nth) when is_integer(nth) and nth > 1, do: []
def take_every(enumerable, nth) when is_integer(nth) and nth > 1 do
{res, _} = reduce(enumerable, {[], :first}, R.take_every(nth))
:lists.reverse(res)
end
@doc """
Takes `count` random elements from `enumerable`.
Notice this function will traverse the whole `enumerable` to
get the random sublist.
See `random/1` for notes on implementation and random seed.
## Examples
# Although not necessary, let's seed the random algorithm
iex> :rand.seed(:exrop, {1, 2, 3})
iex> Enum.take_random(1..10, 2)
[7, 2]
iex> Enum.take_random(?a..?z, 5)
'hypnt'
"""
@spec take_random(t, non_neg_integer) :: list
def take_random(enumerable, count)
def take_random(_enumerable, 0), do: []
def take_random([], _), do: []
def take_random([h | t], 1), do: take_random_list_one(t, h, 1)
def take_random(enumerable, 1) do
enumerable
|> reduce([], fn
x, [current | index] ->
if :rand.uniform(index + 1) == 1 do
[x | index + 1]
else
[current | index + 1]
end
x, [] ->
[x | 1]
end)
|> case do
[] -> []
[current | _index] -> [current]
end
end
def take_random(enumerable, count) when is_integer(count) and count in 0..128 do
sample = Tuple.duplicate(nil, count)
reducer = fn elem, {idx, sample} ->
jdx = random_integer(0, idx)
cond do
idx < count ->
value = elem(sample, jdx)
{idx + 1, put_elem(sample, idx, value) |> put_elem(jdx, elem)}
jdx < count ->
{idx + 1, put_elem(sample, jdx, elem)}
true ->
{idx + 1, sample}
end
end
{size, sample} = reduce(enumerable, {0, sample}, reducer)
sample |> Tuple.to_list() |> take(Kernel.min(count, size))
end
def take_random(enumerable, count) when is_integer(count) and count >= 0 do
reducer = fn elem, {idx, sample} ->
jdx = random_integer(0, idx)
cond do
idx < count ->
value = Map.get(sample, jdx)
{idx + 1, Map.put(sample, idx, value) |> Map.put(jdx, elem)}
jdx < count ->
{idx + 1, Map.put(sample, jdx, elem)}
true ->
{idx + 1, sample}
end
end
{size, sample} = reduce(enumerable, {0, %{}}, reducer)
take_random(sample, Kernel.min(count, size), [])
end
defp take_random(_sample, 0, acc), do: acc
defp take_random(sample, position, acc) do
position = position - 1
take_random(sample, position, [Map.get(sample, position) | acc])
end
defp take_random_list_one([h | t], current, index) do
if :rand.uniform(index + 1) == 1 do
take_random_list_one(t, h, index + 1)
else
take_random_list_one(t, current, index + 1)
end
end
defp take_random_list_one([], current, _), do: [current]
@doc """
Takes the elements from the beginning of the `enumerable` while `fun` returns
a truthy value.
## Examples
iex> Enum.take_while([1, 2, 3], fn x -> x < 3 end)
[1, 2]
"""
@spec take_while(t, (element -> as_boolean(term))) :: list
def take_while(enumerable, fun) when is_list(enumerable) do
take_while_list(enumerable, fun)
end
def take_while(enumerable, fun) do
{_, res} =
Enumerable.reduce(enumerable, {:cont, []}, fn entry, acc ->
if fun.(entry) do
{:cont, [entry | acc]}
else
{:halt, acc}
end
end)
:lists.reverse(res)
end
@doc """
Converts `enumerable` to a list.
## Examples
iex> Enum.to_list(1..3)
[1, 2, 3]
"""
@spec to_list(t) :: [element]
def to_list(enumerable) when is_list(enumerable), do: enumerable
def to_list(%_{} = enumerable), do: reverse(enumerable) |> :lists.reverse()
def to_list(%{} = enumerable), do: Map.to_list(enumerable)
def to_list(enumerable), do: reverse(enumerable) |> :lists.reverse()
@doc """
Enumerates the `enumerable`, removing all duplicated elements.
## Examples
iex> Enum.uniq([1, 2, 3, 3, 2, 1])
[1, 2, 3]
"""
@spec uniq(t) :: list
def uniq(enumerable) do
uniq_by(enumerable, fn x -> x end)
end
@doc false
@deprecated "Use Enum.uniq_by/2 instead"
def uniq(enumerable, fun) do
uniq_by(enumerable, fun)
end
@doc """
Enumerates the `enumerable`, by removing the elements for which
function `fun` returned duplicate elements.
The function `fun` maps every element to a term. Two elements are
considered duplicates if the return value of `fun` is equal for
both of them.
The first occurrence of each element is kept.
## Example
iex> Enum.uniq_by([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end)
[{1, :x}, {2, :y}]
iex> Enum.uniq_by([a: {:tea, 2}, b: {:tea, 2}, c: {:coffee, 1}], fn {_, y} -> y end)
[a: {:tea, 2}, c: {:coffee, 1}]
"""
@spec uniq_by(t, (element -> term)) :: list
def uniq_by(enumerable, fun) when is_list(enumerable) do
uniq_list(enumerable, %{}, fun)
end
def uniq_by(enumerable, fun) do
{list, _} = reduce(enumerable, {[], %{}}, R.uniq_by(fun))
:lists.reverse(list)
end
@doc """
Opposite of `zip/2`. Extracts two-element tuples from the
given `enumerable` and groups them together.
It takes an `enumerable` with elements being two-element tuples and returns
a tuple with two lists, each of which is formed by the first and
second element of each tuple, respectively.
This function fails unless `enumerable` is or can be converted into a
list of tuples with *exactly* two elements in each tuple.
## Examples
iex> Enum.unzip([{:a, 1}, {:b, 2}, {:c, 3}])
{[:a, :b, :c], [1, 2, 3]}
iex> Enum.unzip(%{a: 1, b: 2})
{[:a, :b], [1, 2]}
"""
@spec unzip(t) :: {[element], [element]}
def unzip(enumerable) do
{list1, list2} =
reduce(enumerable, {[], []}, fn {el1, el2}, {list1, list2} ->
{[el1 | list1], [el2 | list2]}
end)
{:lists.reverse(list1), :lists.reverse(list2)}
end
@doc """
Returns the `enumerable` with each element wrapped in a tuple
alongside its index.
If an `offset` is given, we will index from the given offset instead of from zero.
## Examples
iex> Enum.with_index([:a, :b, :c])
[a: 0, b: 1, c: 2]
iex> Enum.with_index([:a, :b, :c], 3)
[a: 3, b: 4, c: 5]
"""
@spec with_index(t, integer) :: [{element, index}]
def with_index(enumerable, offset \\ 0) do
enumerable
|> to_list()
|> do_with_index(offset)
end
@spec do_with_index(list, integer) :: [{element, index}]
defp do_with_index([], _) do
[]
end
defp do_with_index([head | tail], index) do
[{head, index} | do_with_index(tail, index + 1)]
end
@doc """
Zips corresponding elements from two enumerables into one list
of tuples.
The zipping finishes as soon as any enumerable completes.
## Examples
iex> Enum.zip([1, 2, 3], [:a, :b, :c])
[{1, :a}, {2, :b}, {3, :c}]
iex> Enum.zip([1, 2, 3, 4, 5], [:a, :b, :c])
[{1, :a}, {2, :b}, {3, :c}]
"""
@spec zip(t, t) :: [{any, any}]
def zip(enumerable1, enumerable2)
when is_list(enumerable1) and is_list(enumerable2) do
zip_list(enumerable1, enumerable2)
end
def zip(enumerable1, enumerable2) do
zip([enumerable1, enumerable2])
end
@doc """
Zips corresponding elements from a finite collection of enumerables
into one list of tuples.
The zipping finishes as soon as any enumerable in the given collection completes.
## Examples
iex> Enum.zip([[1, 2, 3], [:a, :b, :c], ["foo", "bar", "baz"]])
[{1, :a, "foo"}, {2, :b, "bar"}, {3, :c, "baz"}]
iex> Enum.zip([[1, 2, 3, 4, 5], [:a, :b, :c]])
[{1, :a}, {2, :b}, {3, :c}]
"""
@doc since: "1.4.0"
@spec zip(enumerables) :: [tuple()] when enumerables: [t()] | t()
def zip([]), do: []
def zip(enumerables) do
Stream.zip(enumerables).({:cont, []}, &{:cont, [&1 | &2]})
|> elem(1)
|> :lists.reverse()
end
## Helpers
@compile {:inline, entry_to_string: 1, reduce: 3, reduce_by: 3, reduce_enumerable: 3}
defp entry_to_string(entry) when is_binary(entry), do: entry
defp entry_to_string(entry), do: String.Chars.to_string(entry)
defp aggregate([head | tail], fun, _empty) do
aggregate_list(tail, head, fun)
end
defp aggregate([], _fun, empty) do
empty.()
end
defp aggregate(first..last, fun, _empty) do
case fun.(first, last) do
true -> first
false -> last
end
end
defp aggregate(enumerable, fun, empty) do
ref = make_ref()
enumerable
|> reduce(ref, fn
element, ^ref ->
element
element, acc ->
case fun.(acc, element) do
true -> acc
false -> element
end
end)
|> case do
^ref -> empty.()
result -> result
end
end
defp aggregate_list([head | tail], acc, fun) do
acc =
case fun.(acc, head) do
true -> acc
false -> head
end
aggregate_list(tail, acc, fun)
end
defp aggregate_list([], acc, _fun), do: acc
defp aggregate_by(enumerable, fun, sorter, empty_fallback) do
first_fun = &[&1 | fun.(&1)]
reduce_fun = fn entry, [_ | fun_ref] = old ->
fun_entry = fun.(entry)
case sorter.(fun_ref, fun_entry) do
true -> old
false -> [entry | fun_entry]
end
end
case reduce_by(enumerable, first_fun, reduce_fun) do
:empty -> empty_fallback.()
[entry | _] -> entry
end
end
defp reduce_by([head | tail], first, fun) do
:lists.foldl(fun, first.(head), tail)
end
defp reduce_by([], _first, _fun) do
:empty
end
defp reduce_by(enumerable, first, fun) do
reduce(enumerable, :empty, fn
element, :empty -> first.(element)
element, acc -> fun.(element, acc)
end)
end
defp random_integer(limit, limit) when is_integer(limit) do
limit
end
defp random_integer(lower_limit, upper_limit) when upper_limit < lower_limit do
random_integer(upper_limit, lower_limit)
end
defp random_integer(lower_limit, upper_limit) do
lower_limit + :rand.uniform(upper_limit - lower_limit + 1) - 1
end
## Implementations
## all?
defp all_list([h | t], fun) do
if fun.(h) do
all_list(t, fun)
else
false
end
end
defp all_list([], _) do
true
end
## any?
defp any_list([h | t], fun) do
if fun.(h) do
true
else
any_list(t, fun)
end
end
defp any_list([], _) do
false
end
## drop
defp drop_list(list, 0), do: list
defp drop_list([_ | tail], counter), do: drop_list(tail, counter - 1)
defp drop_list([], _), do: []
## drop_while
defp drop_while_list([head | tail], fun) do
if fun.(head) do
drop_while_list(tail, fun)
else
[head | tail]
end
end
defp drop_while_list([], _) do
[]
end
## filter
defp filter_list([head | tail], fun) do
if fun.(head) do
[head | filter_list(tail, fun)]
else
filter_list(tail, fun)
end
end
defp filter_list([], _fun) do
[]
end
## find
defp find_list([head | tail], default, fun) do
if fun.(head) do
head
else
find_list(tail, default, fun)
end
end
defp find_list([], default, _) do
default
end
## find_index
defp find_index_list([head | tail], counter, fun) do
if fun.(head) do
counter
else
find_index_list(tail, counter + 1, fun)
end
end
defp find_index_list([], _, _) do
nil
end
## find_value
defp find_value_list([head | tail], default, fun) do
fun.(head) || find_value_list(tail, default, fun)
end
defp find_value_list([], default, _) do
default
end
## flat_map
defp flat_map_list([head | tail], fun) do
case fun.(head) do
list when is_list(list) -> list ++ flat_map_list(tail, fun)
other -> to_list(other) ++ flat_map_list(tail, fun)
end
end
defp flat_map_list([], _fun) do
[]
end
## map_intersperse
defp map_intersperse_list([], _, _),
do: []
defp map_intersperse_list([last], _, mapper),
do: [mapper.(last)]
defp map_intersperse_list([head | rest], separator, mapper),
do: [mapper.(head), separator | map_intersperse_list(rest, separator, mapper)]
## reduce
defp reduce_range_inc(first, first, acc, fun) do
fun.(first, acc)
end
defp reduce_range_inc(first, last, acc, fun) do
reduce_range_inc(first + 1, last, fun.(first, acc), fun)
end
defp reduce_range_dec(first, first, acc, fun) do
fun.(first, acc)
end
defp reduce_range_dec(first, last, acc, fun) do
reduce_range_dec(first - 1, last, fun.(first, acc), fun)
end
defp reduce_enumerable(enumerable, acc, fun) do
Enumerable.reduce(enumerable, {:cont, acc}, fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1)
end
## reject
defp reject_list([head | tail], fun) do
if fun.(head) do
reject_list(tail, fun)
else
[head | reject_list(tail, fun)]
end
end
defp reject_list([], _fun) do
[]
end
## reverse_slice
defp reverse_slice(rest, idx, idx, count, acc) do
{slice, rest} = head_slice(rest, count, [])
:lists.reverse(rest, :lists.reverse(slice, acc))
end
defp reverse_slice([elem | rest], idx, start, count, acc) do
reverse_slice(rest, idx - 1, start, count, [elem | acc])
end
defp head_slice(rest, 0, acc), do: {acc, rest}
defp head_slice([elem | rest], count, acc) do
head_slice(rest, count - 1, [elem | acc])
end
## shuffle
defp shuffle_unwrap([{_, h} | enumerable], t) do
shuffle_unwrap(enumerable, [h | t])
end
defp shuffle_unwrap([], t), do: t
## slice
defp slice_any(enumerable, start, amount) when start < 0 do
{count, fun} = slice_count_and_fun(enumerable)
start = count + start
if start >= 0 do
fun.(start, Kernel.min(amount, count - start))
else
[]
end
end
defp slice_any(list, start, amount) when is_list(list) do
list |> drop_list(start) |> take_list(amount)
end
defp slice_any(enumerable, start, amount) do
case Enumerable.slice(enumerable) do
{:ok, count, _} when start >= count ->
[]
{:ok, count, fun} when is_function(fun) ->
fun.(start, Kernel.min(amount, count - start))
{:error, module} ->
slice_enum(enumerable, module, start, amount)
end
end
defp slice_enum(enumerable, module, start, amount) do
{_, {_, _, slice}} =
module.reduce(enumerable, {:cont, {start, amount, []}}, fn
_entry, {start, amount, _list} when start > 0 ->
{:cont, {start - 1, amount, []}}
entry, {start, amount, list} when amount > 1 ->
{:cont, {start, amount - 1, [entry | list]}}
entry, {start, amount, list} ->
{:halt, {start, amount, [entry | list]}}
end)
:lists.reverse(slice)
end
defp slice_count_and_fun(enumerable) when is_list(enumerable) do
length = length(enumerable)
{length, &Enumerable.List.slice(enumerable, &1, &2, length)}
end
defp slice_count_and_fun(enumerable) do
case Enumerable.slice(enumerable) do
{:ok, count, fun} when is_function(fun) ->
{count, fun}
{:error, module} ->
{_, {list, count}} =
module.reduce(enumerable, {:cont, {[], 0}}, fn elem, {acc, count} ->
{:cont, {[elem | acc], count + 1}}
end)
{count, &Enumerable.List.slice(:lists.reverse(list), &1, &2, count)}
end
end
## sort
defp sort_reducer(entry, {:split, y, x, r, rs, bool}, fun) do
cond do
fun.(y, entry) == bool ->
{:split, entry, y, [x | r], rs, bool}
fun.(x, entry) == bool ->
{:split, y, entry, [x | r], rs, bool}
r == [] ->
{:split, y, x, [entry], rs, bool}
true ->
{:pivot, y, x, r, rs, entry, bool}
end
end
defp sort_reducer(entry, {:pivot, y, x, r, rs, s, bool}, fun) do
cond do
fun.(y, entry) == bool ->
{:pivot, entry, y, [x | r], rs, s, bool}
fun.(x, entry) == bool ->
{:pivot, y, entry, [x | r], rs, s, bool}
fun.(s, entry) == bool ->
{:split, entry, s, [], [[y, x | r] | rs], bool}
true ->
{:split, s, entry, [], [[y, x | r] | rs], bool}
end
end
defp sort_reducer(entry, [x], fun) do
{:split, entry, x, [], [], fun.(x, entry)}
end
defp sort_reducer(entry, acc, _fun) do
[entry | acc]
end
defp sort_terminator({:split, y, x, r, rs, bool}, fun) do
sort_merge([[y, x | r] | rs], fun, bool)
end
defp sort_terminator({:pivot, y, x, r, rs, s, bool}, fun) do
sort_merge([[s], [y, x | r] | rs], fun, bool)
end
defp sort_terminator(acc, _fun) do
acc
end
defp sort_merge(list, fun, true), do: reverse_sort_merge(list, [], fun, true)
defp sort_merge(list, fun, false), do: sort_merge(list, [], fun, false)
defp sort_merge([t1, [h2 | t2] | l], acc, fun, true),
do: sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, false) | acc], fun, true)
defp sort_merge([[h2 | t2], t1 | l], acc, fun, false),
do: sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, false) | acc], fun, false)
defp sort_merge([l], [], _fun, _bool), do: l
defp sort_merge([l], acc, fun, bool),
do: reverse_sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)
defp sort_merge([], acc, fun, bool), do: reverse_sort_merge(acc, [], fun, bool)
defp reverse_sort_merge([[h2 | t2], t1 | l], acc, fun, true),
do: reverse_sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, true) | acc], fun, true)
defp reverse_sort_merge([t1, [h2 | t2] | l], acc, fun, false),
do: reverse_sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, true) | acc], fun, false)
defp reverse_sort_merge([l], acc, fun, bool),
do: sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)
defp reverse_sort_merge([], acc, fun, bool), do: sort_merge(acc, [], fun, bool)
defp sort_merge1([h1 | t1], h2, t2, m, fun, bool) do
if fun.(h1, h2) == bool do
sort_merge2(h1, t1, t2, [h2 | m], fun, bool)
else
sort_merge1(t1, h2, t2, [h1 | m], fun, bool)
end
end
defp sort_merge1([], h2, t2, m, _fun, _bool), do: :lists.reverse(t2, [h2 | m])
defp sort_merge2(h1, t1, [h2 | t2], m, fun, bool) do
if fun.(h1, h2) == bool do
sort_merge2(h1, t1, t2, [h2 | m], fun, bool)
else
sort_merge1(t1, h2, t2, [h1 | m], fun, bool)
end
end
defp sort_merge2(h1, t1, [], m, _fun, _bool), do: :lists.reverse(t1, [h1 | m])
## split
defp split_list([head | tail], counter, acc) when counter > 0 do
split_list(tail, counter - 1, [head | acc])
end
defp split_list(list, 0, acc) do
{:lists.reverse(acc), list}
end
defp split_list([], _, acc) do
{:lists.reverse(acc), []}
end
defp split_reverse_list([head | tail], counter, acc) when counter > 0 do
split_reverse_list(tail, counter - 1, [head | acc])
end
defp split_reverse_list(list, 0, acc) do
{:lists.reverse(list), acc}
end
defp split_reverse_list([], _, acc) do
{[], acc}
end
## split_while
defp split_while_list([head | tail], fun, acc) do
if fun.(head) do
split_while_list(tail, fun, [head | acc])
else
{:lists.reverse(acc), [head | tail]}
end
end
defp split_while_list([], _, acc) do
{:lists.reverse(acc), []}
end
## take
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: []
## take_while
defp take_while_list([head | tail], fun) do
if fun.(head) do
[head | take_while_list(tail, fun)]
else
[]
end
end
defp take_while_list([], _) do
[]
end
## uniq
defp uniq_list([head | tail], set, fun) do
value = fun.(head)
case set do
%{^value => true} -> uniq_list(tail, set, fun)
%{} -> [head | uniq_list(tail, Map.put(set, value, true), fun)]
end
end
defp uniq_list([], _set, _fun) do
[]
end
## zip
defp zip_list([h1 | next1], [h2 | next2]) do
[{h1, h2} | zip_list(next1, next2)]
end
defp zip_list(_, []), do: []
defp zip_list([], _), do: []
end
defimpl Enumerable, for: List do
def count(_list), do: {:error, __MODULE__}
def member?(_list, _value), do: {:error, __MODULE__}
def slice(_list), do: {:error, __MODULE__}
def reduce(_list, {:halt, acc}, _fun), do: {:halted, acc}
def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}
def reduce([], {:cont, acc}, _fun), do: {:done, acc}
def reduce([head | tail], {:cont, acc}, fun), do: reduce(tail, fun.(head, acc), fun)
@doc false
def slice(_list, _start, 0, _size), do: []
def slice(list, start, count, size) when start + count == size, do: list |> drop(start)
def slice(list, start, count, _size), do: list |> drop(start) |> take(count)
defp drop(list, 0), do: list
defp drop([_ | tail], count), do: drop(tail, count - 1)
defp take(_list, 0), do: []
defp take([head | tail], count), do: [head | take(tail, count - 1)]
end
defimpl Enumerable, for: Map do
def count(map) do
{:ok, map_size(map)}
end
def member?(map, {key, value}) do
{:ok, match?(%{^key => ^value}, map)}
end
def member?(_map, _other) do
{:ok, false}
end
def slice(map) do
size = map_size(map)
{:ok, size, &Enumerable.List.slice(:maps.to_list(map), &1, &2, size)}
end
def reduce(map, acc, fun) do
Enumerable.List.reduce(:maps.to_list(map), acc, fun)
end
end
defimpl Enumerable, for: Function do
def count(_function), do: {:error, __MODULE__}
def member?(_function, _value), do: {:error, __MODULE__}
def slice(_function), do: {:error, __MODULE__}
def reduce(function, acc, fun) when is_function(function, 2), do: function.(acc, fun)
def reduce(function, _acc, _fun) do
raise Protocol.UndefinedError,
protocol: @protocol,
value: function,
description: "only anonymous functions of arity 2 are enumerable"
end
end
|
lib/elixir/lib/enum.ex
| 0.947381 | 0.830285 |
enum.ex
|
starcoder
|
defmodule IVCU.Converter.CMD do
@moduledoc """
Provides a helper to generate a [converter](`IVCU.Converter`) that
uses any cmd converter for files (`convert` binary from
[imagemagick](https://imagemagick.org/) in example).
## Usage
To use the converter you need to define a module.
defmodule MyApp.ImageConverter do
use IVCU.Converter.CMD,
args: %{
thumb: [
"convert",
:input,
"-thumbnail",
"100x100^",
"-gravity",
"center",
"-extent",
"100x100",
:output
]
}
end
`:args` is a map where the commands for different versions are
provided.
`:input` and `:output` represent positions of input and output files
for the command.
Now you can use your storage module in your
[definition](`IVCU.Definition`).
"""
@doc false
defmacro __using__(opts) do
args = Keyword.get(opts, :args) || raise ":args key was expected"
quote do
@behaviour IVCU.Converter
@impl IVCU.Converter
defdelegate clean!(file), to: unquote(__MODULE__)
@impl IVCU.Converter
def convert(file, version, new_filename) do
unquote(__MODULE__).convert(unquote(args), file, version, new_filename)
end
end
end
@doc false
def clean!(%{path: path}) when is_binary(path) do
File.rm!(path)
end
defmodule UnknownVersionError do
@moduledoc """
An error raised when your definition provides a version that
was not specified in `IVCU.Converter.CMD` config.
"""
defexception [:version]
@impl Exception
def message(%{version: version}) do
"unknown version: #{version}"
end
end
defmodule InvalidFormatError do
@moduledoc """
An error raised when a command in `IVCU.Converter.CMD` config
has invalid format.
"""
defexception [:cmd]
@impl Exception
def message(%{cmd: cmd}) do
"invalid command format: #{inspect(cmd)}"
end
end
@doc false
def convert(args, file, version, new_filename)
def convert(_, file, :original, new_filename) do
output_path = Path.join("/tmp", new_filename)
File.touch!(output_path)
input_path = input_path(file)
File.cp!(input_path, output_path)
clean_input_file!(file, input_path)
file = %IVCU.File{path: output_path, filename: new_filename}
{:ok, file}
end
def convert(args, file, version, new_filename) do
case args do
%{^version => cmd} when is_list(cmd) ->
do_convert(cmd, file, new_filename)
%{^version => cmd} ->
raise InvalidFormatError, cmd: cmd
_ ->
raise UnknownVersionError, version: version
end
end
defp do_convert(cmd, file, new_filename) do
output_path = Path.join("/tmp", new_filename)
File.touch!(output_path)
input_path = input_path(file)
with :ok <- run_command(cmd, input_path, output_path) do
clean_input_file!(file, input_path)
file = %IVCU.File{path: output_path, filename: new_filename}
{:ok, file}
end
end
defp input_path(%{path: path, content: nil}) when is_binary(path) do
path
end
defp input_path(%{path: nil, content: content, filename: filename})
when is_binary(content) and is_binary(filename) do
input_path = Path.join("/tmp", filename)
File.write!(input_path, content)
input_path
end
defp run_command(cmd, input_file, output_file) do
[executable | args] =
Enum.map(cmd, fn
:input -> input_file
:output -> output_file
x -> x
end)
case System.cmd(executable, args, stderr_to_stdout: true) do
{_, 0} -> :ok
{output, _} -> {:error, output}
end
end
defp clean_input_file!(%{path: nil, content: content}, input_path)
when is_binary(content) do
File.rm!(input_path)
end
defp clean_input_file!(%{path: path}, _) when is_binary(path) do
:ok
end
end
|
lib/ivcu/converter/cmd.ex
| 0.829665 | 0.527377 |
cmd.ex
|
starcoder
|
defmodule ChatApi.SlackAuthorizations do
@moduledoc """
The SlackAuthorizations context.
"""
import Ecto.Query, warn: false
alias ChatApi.Repo
alias ChatApi.SlackAuthorizations.SlackAuthorization
@spec list_slack_authorizations(map()) :: [SlackAuthorization.t()]
def list_slack_authorizations(filters \\ %{}) do
SlackAuthorization
|> where(^filter_where(filters))
|> order_by(desc: :inserted_at)
|> Repo.all()
end
@spec list_slack_authorizations_by_account(binary(), map()) :: [SlackAuthorization.t()]
def list_slack_authorizations_by_account(account_id, filters \\ %{}) do
filters |> Map.merge(%{account_id: account_id}) |> list_slack_authorizations()
end
@spec get_slack_authorization!(binary()) :: SlackAuthorization.t()
def get_slack_authorization!(id), do: Repo.get!(SlackAuthorization, id)
@spec find_slack_authorization(map()) :: SlackAuthorization.t() | nil
def find_slack_authorization(filters \\ %{}) do
SlackAuthorization
|> where(^filter_where(filters))
|> order_by(desc: :inserted_at)
|> Repo.one()
end
@spec get_authorization_by_account(binary(), map()) :: SlackAuthorization.t() | nil
def get_authorization_by_account(account_id, filters \\ %{}) do
SlackAuthorization
|> where(account_id: ^account_id)
|> where(^filter_where(filters))
|> order_by(desc: :inserted_at)
|> Repo.one()
end
@spec create_or_update(binary(), map()) ::
{:ok, SlackAuthorization.t()} | {:error, Ecto.Changeset.t()}
def create_or_update(account_id, params) do
filters = Map.take(params, [:type])
existing = get_authorization_by_account(account_id, filters)
if existing do
update_slack_authorization(existing, params)
else
create_slack_authorization(params)
end
end
@spec create_slack_authorization(map()) ::
{:ok, SlackAuthorization.t()} | {:error, Ecto.Changeset.t()}
def create_slack_authorization(attrs \\ %{}) do
%SlackAuthorization{}
|> SlackAuthorization.changeset(attrs)
|> Repo.insert()
end
@spec update_slack_authorization(SlackAuthorization.t(), map()) ::
{:ok, SlackAuthorization.t()} | {:error, Ecto.Changeset.t()}
def update_slack_authorization(%SlackAuthorization{} = slack_authorization, attrs) do
slack_authorization
|> SlackAuthorization.changeset(attrs)
|> Repo.update()
end
@spec delete_slack_authorization(SlackAuthorization.t()) ::
{:ok, SlackAuthorization.t()} | {:error, Ecto.Changeset.t()}
def delete_slack_authorization(%SlackAuthorization{} = slack_authorization) do
Repo.delete(slack_authorization)
end
@spec change_slack_authorization(SlackAuthorization.t(), map()) :: Ecto.Changeset.t()
def change_slack_authorization(%SlackAuthorization{} = slack_authorization, attrs \\ %{}) do
SlackAuthorization.changeset(slack_authorization, attrs)
end
@spec has_authorization_scope?(SlackAuthorization.t(), binary()) :: boolean()
def has_authorization_scope?(%SlackAuthorization{scope: full_scope}, scope) do
String.contains?(full_scope, scope)
end
# Pulled from https://hexdocs.pm/ecto/dynamic-queries.html#building-dynamic-queries
defp filter_where(params) do
Enum.reduce(params, dynamic(true), fn
{:account_id, value}, dynamic ->
dynamic([r], ^dynamic and r.account_id == ^value)
{:channel_id, value}, dynamic ->
dynamic([r], ^dynamic and r.channel_id == ^value)
{:team_id, value}, dynamic ->
dynamic([r], ^dynamic and r.team_id == ^value)
{:bot_user_id, value}, dynamic ->
dynamic([r], ^dynamic and r.bot_user_id == ^value)
{:type, neq: value}, dynamic ->
dynamic([r], ^dynamic and r.type != ^value)
{:type, value}, dynamic ->
dynamic([r], ^dynamic and r.type == ^value)
{_, _}, dynamic ->
# Not a where parameter
dynamic
end)
end
end
|
lib/chat_api/slack_authorizations.ex
| 0.707708 | 0.4831 |
slack_authorizations.ex
|
starcoder
|
defmodule Nebulex.Adapter do
@moduledoc """
This module specifies the adapter API that a Cache adapter is required to
implement.
"""
@type t :: module
@typedoc """
The metadata returned by the adapter `c:init/1`.
It must be a map and Nebulex itself will always inject two keys into the meta:
* `:cache` - The cache module.
* `:name` - The name of the cache.
* `:pid` - The PID returned by the child spec returned in `c:init/1`
"""
@type adapter_meta :: %{optional(atom) => term}
@type cache :: Nebulex.Cache.t()
@type key :: Nebulex.Cache.key()
@type value :: Nebulex.Cache.value()
@type entry :: Nebulex.Entry.t()
@type opts :: Nebulex.Cache.opts()
@type entries :: Nebulex.Cache.entries()
@type ttl :: timeout
@type on_write :: :put | :put_new | :replace
@type child_spec :: :supervisor.child_spec() | {module(), term()} | module() | nil
@doc """
The callback invoked in case the adapter needs to inject code.
"""
@macrocallback __before_compile__(env :: Macro.Env.t()) :: Macro.t()
@doc """
Initializes the adapter supervision tree by returning the children.
"""
@callback init(opts) :: {:ok, child_spec, adapter_meta}
@doc """
Gets the value for a specific `key` in `cache`.
See `c:Nebulex.Cache.get/2`.
"""
@callback get(adapter_meta, key, opts) :: value
@doc """
Gets a collection of entries from the Cache, returning them as `Map.t()` of
the values associated with the set of keys requested.
For every key that does not hold a value or does not exist, that key is
simply ignored. Because of this, the operation never fails.
See `c:Nebulex.Cache.get_all/2`.
"""
@callback get_all(adapter_meta, [key], opts) :: map
@doc """
Puts the given `value` under `key` into the `cache`.
Returns `true` if the `value` with key `key` is successfully inserted;
otherwise `false` is returned.
The `ttl` argument sets the time-to-live for the stored entry. If it is not
set, it means the entry hasn't a time-to-live, then it shouldn't expire.
## OnWrite
The `on_write` argument supports the following values:
* `:put` - If the `key` already exists, it is overwritten. Any previous
time-to-live associated with the key is discarded on successful `write`
operation.
* `:put_new` - It only stores the entry if the `key` does not already exist,
otherwise, `false` is returned.
* `:replace` - Alters the value stored under the given `key`, but only
if the key already exists into the cache, otherwise, `false` is
returned.
See `c:Nebulex.Cache.put/3`, `c:Nebulex.Cache.put_new/3`, `c:Nebulex.Cache.replace/3`.
"""
@callback put(adapter_meta, key, value, ttl, on_write, opts) :: boolean
@doc """
Puts the given `entries` (key/value pairs) into the `cache`.
Returns `true` if all the keys were inserted. If no key was inserted
(at least one key already existed), `false` is returned.
The `ttl` argument sets the time-to-live for the stored entry. If it is not
set, it means the entry hasn't a time-to-live, then it shouldn't expire.
The given `ttl` is applied to all keys.
## OnWrite
The `on_write` argument supports the following values:
* `:put` - If the `key` already exists, it is overwritten. Any previous
time-to-live associated with the key is discarded on successful `write`
operation.
* `:put_new` - It only stores the entry if the `key` does not already exist,
otherwise, `false` is returned.
Ideally, this operation should be atomic, so all given keys are set at once.
But it depends purely on the adapter's implementation and the backend used
internally by the adapter. Hence, it is recommended to checkout the
adapter's documentation.
See `c:Nebulex.Cache.put_all/2`.
"""
@callback put_all(adapter_meta, entries, ttl, on_write, opts) :: boolean
@doc """
Deletes a single entry from cache.
See `c:Nebulex.Cache.delete/2`.
"""
@callback delete(adapter_meta, key, opts) :: :ok
@doc """
Returns and removes the entry with key `key` in the cache.
See `c:Nebulex.Cache.take/2`.
"""
@callback take(adapter_meta, key, opts) :: value
@doc """
Increments or decrements the counter mapped to the given `key`.
See `c:Nebulex.Cache.incr/3`.
"""
@callback incr(adapter_meta, key, incr :: integer, ttl, opts) :: integer
@doc """
Returns whether the given `key` exists in cache.
See `c:Nebulex.Cache.has_key?/1`.
"""
@callback has_key?(adapter_meta, key) :: boolean
@doc """
Returns the TTL (time-to-live) for the given `key`. If the `key` does not
exist, then `nil` is returned.
See `c:Nebulex.Cache.ttl/1`.
"""
@callback ttl(adapter_meta, key) :: ttl | nil
@doc """
Returns `true` if the given `key` exists and the new `ttl` was successfully
updated, otherwise, `false` is returned.
See `c:Nebulex.Cache.expire/2`.
"""
@callback expire(adapter_meta, key, ttl) :: boolean
@doc """
Returns `true` if the given `key` exists and the last access time was
successfully updated, otherwise, `false` is returned.
See `c:Nebulex.Cache.touch/1`.
"""
@callback touch(adapter_meta, key) :: boolean
@doc """
Returns the total number of cached entries.
See `c:Nebulex.Cache.size/0`.
"""
@callback size(adapter_meta) :: integer
@doc """
Flushes the cache and returns the number of evicted keys.
See `c:Nebulex.Cache.flush/0`.
"""
@callback flush(adapter_meta) :: integer
@doc """
RExecutes the function `fun` passing as parameters the adapter and metadata
(from the `c:init/1` callback) associated with the given cache `name_or_pid`.
It expects a name or a PID representing the cache.
"""
@spec with_meta(atom | pid, (module, adapter_meta -> term)) :: term
def with_meta(name_or_pid, fun) do
{adapter, adapter_meta} = Nebulex.Cache.Registry.lookup(name_or_pid)
fun.(adapter, adapter_meta)
end
end
|
lib/nebulex/adapter.ex
| 0.896654 | 0.521593 |
adapter.ex
|
starcoder
|
defmodule Tirexs.ElasticSearch do
@doc """
This module provides a simple convenience for connection options such as `port`, `uri`, `user`, `pass`
and functions for doing a `HTTP` request to `ElasticSearch` engine directly.
"""
require Record
Record.defrecord :record_config, [port: 9200, uri: "127.0.0.1", user: nil, pass: nil]
@doc false
def get(query_url, config) do
do_request(make_url(query_url, config), :get)
end
@doc false
def put(query_url, config), do: put(query_url, [], config)
def put(query_url, body, config) do
unless body == [], do: body = to_string(body)
do_request(make_url(query_url, config), :put, body)
end
@doc false
def delete(query_url, config), do: delete(query_url, [], config)
@doc false
def delete(query_url, _body, config) do
unless _body == [], do: _body = to_string(_body)
do_request(make_url(query_url, config), :delete)
end
@doc false
def head(query_url, config) do
do_request(make_url(query_url, config), :head)
end
@doc false
def post(query_url, config), do: post(query_url, [], config)
def post(query_url, body, config) do
unless body == [], do: body = to_string(body)
url = make_url(query_url, config)
do_request(url, :post, body)
end
@doc false
def exist?(url, settings) do
case head(url, settings) do
{:error, _, _} -> false
_ -> true
end
end
@doc false
def do_request(url, method, body \\ []) do
:inets.start()
{ url, content_type, options } = { String.to_char_list(url), 'application/json', [{:body_format, :binary}] }
case method do
:get -> response(:httpc.request(method, {url, []}, [], []))
:head -> response(:httpc.request(method, {url, []}, [], []))
:put -> response(:httpc.request(method, {url, make_headers, content_type, body}, [], options))
:post -> response(:httpc.request(method, {url, make_headers, content_type, body}, [], options))
:delete -> response(:httpc.request(method, {url, make_headers},[],[]))
end
end
defp response(req) do
case req do
{:ok, { {_, status, _}, _, body}} ->
if round(status / 100) == 4 || round(status / 100) == 5 do
{ :error, status, body }
else
case body do
[] -> { :ok, status, [] }
_ -> { :ok, status, get_body_json(body) }
end
end
_ -> :error
end
end
def get_body_json(body), do: JSEX.decode!(to_string(body), [{:labels, :atom}])
def make_url(query_url, config) do
if (config |> record_config(:port) == nil) || (config |> record_config(:port)) == 80 do
"http://#{config |> record_config(:uri)}/#{query_url}"
else
"http://#{config |> record_config(:uri)}:#{config |> record_config(:port)}/#{query_url}"
end
end
defp make_headers, do: [{'Content-Type', 'application/json'}]
end
|
lib/tirexs/elastic_search.ex
| 0.521959 | 0.401717 |
elastic_search.ex
|
starcoder
|
defmodule Swarm.IntervalTreeClock do
@moduledoc """
This is an implementation of an Interval Clock Tree, ported from
the implementation in Erlang written by <NAME> <<EMAIL>>
found [here](https://github.com/ricardobcl/Interval-Tree-Clocks/blob/master/erlang/itc.erl).
"""
use Bitwise
import Kernel, except: [max: 2, min: 2]
@compile {:inline, [min: 2, max: 2, drop: 2, lift: 2, base: 1, height: 1]}
@type int_tuple :: {non_neg_integer, non_neg_integer}
@type t ::
int_tuple
| {int_tuple, non_neg_integer}
| {non_neg_integer, int_tuple}
| {int_tuple, int_tuple}
@doc """
Creates a new interval tree clock
"""
@spec seed() :: __MODULE__.t()
def seed(), do: {1, 0}
@doc """
Joins two forked clocks into a single clock with both causal histories,
used for retiring a replica.
"""
@spec join(__MODULE__.t(), __MODULE__.t()) :: __MODULE__.t()
def join({i1, e1}, {i2, e2}), do: {sum(i1, i2), join_ev(e1, e2)}
@doc """
Forks a clock containing a shared causal history, used for creating new replicas.
"""
@spec fork(__MODULE__.t()) :: __MODULE__.t()
def fork({i, e}) do
{i1, i2} = split(i)
{{i1, e}, {i2, e}}
end
@doc """
Gets a snapshot of a clock without its identity. Useful for sending the clock with messages,
but cannot be used to track events.
"""
@spec peek(__MODULE__.t()) :: __MODULE__.t()
def peek({_i, e}), do: {0, e}
@doc """
Records an event on the given clock
"""
@spec event(__MODULE__.t()) :: __MODULE__.t()
def event({i, e}) do
case fill(i, e) do
^e ->
{_, e1} = grow(i, e)
{i, e1}
e1 ->
{i, e1}
end
end
@doc """
Determines if the left-hand clock is causally dominated by the right-hand clock.
If the left-hand clock is LEQ than the right-hand clock, and vice-versa, then they are
causally equivalent.
"""
@spec leq(__MODULE__.t(), __MODULE__.t()) :: boolean
def leq({_, e1}, {_, e2}), do: leq_ev(e1, e2)
@doc """
Compares two clocks.
If :eq is returned, the two clocks are causally equivalent
If :lt is returned, the first clock is causally dominated by the second
If :gt is returned, the second clock is causally dominated by the first
If :concurrent is returned, the two clocks are concurrent (conflicting)
"""
@spec compare(__MODULE__.t(), __MODULE__.t()) :: :lt | :gt | :eq | :concurrent
def compare(a, b) do
a_leq = leq(a, b)
b_leq = leq(b, a)
cond do
a_leq and b_leq -> :eq
a_leq -> :lt
b_leq -> :gt
:else -> :concurrent
end
end
@doc """
Encodes the clock as a binary
"""
@spec encode(__MODULE__.t()) :: binary
def encode({i, e}), do: :erlang.term_to_binary({i, e})
@doc """
Decodes the clock from a binary
"""
@spec decode(binary) :: {:ok, __MODULE__.t()} | {:error, {:invalid_clock, term}}
def decode(b) when is_binary(b) do
case :erlang.binary_to_term(b) do
{_i, _e} = clock ->
clock
other ->
{:error, {:invalid_clock, other}}
end
end
@doc """
Returns the length of the encoded binary representation of the clock
"""
@spec len(__MODULE__.t()) :: non_neg_integer
def len(d), do: :erlang.size(encode(d))
## Private API
defp leq_ev({n1, l1, r1}, {n2, l2, r2}) do
n1 <= n2 and leq_ev(lift(n1, l1), lift(n2, l2)) and leq_ev(lift(n1, r1), lift(n2, r2))
end
defp leq_ev({n1, l1, r1}, n2) do
n1 <= n2 and leq_ev(lift(n1, l1), n2) and leq_ev(lift(n1, r1), n2)
end
defp leq_ev(n1, {n2, _, _}), do: n1 <= n2
defp leq_ev(n1, n2), do: n1 <= n2
defp norm_id({0, 0}), do: 0
defp norm_id({1, 1}), do: 1
defp norm_id(x), do: x
defp norm_ev({n, m, m}) when is_integer(m), do: n + m
defp norm_ev({n, l, r}) do
m = min(base(l), base(r))
{n + m, drop(m, l), drop(m, r)}
end
defp sum(0, x), do: x
defp sum(x, 0), do: x
defp sum({l1, r1}, {l2, r2}), do: norm_id({sum(l1, l2), sum(r1, r2)})
defp split(0), do: {0, 0}
defp split(1), do: {{1, 0}, {0, 1}}
defp split({0, i}) do
{i1, i2} = split(i)
{{0, i1}, {0, i2}}
end
defp split({i, 0}) do
{i1, i2} = split(i)
{{i1, 0}, {i2, 0}}
end
defp split({i1, i2}), do: {{i1, 0}, {0, i2}}
defp join_ev({n1, _, _} = e1, {n2, _, _} = e2) when n1 > n2, do: join_ev(e2, e1)
defp join_ev({n1, l1, r1}, {n2, l2, r2}) when n1 <= n2 do
d = n2 - n1
norm_ev({n1, join_ev(l1, lift(d, l2)), join_ev(r1, lift(d, r2))})
end
defp join_ev(n1, {n2, l2, r2}), do: join_ev({n1, 0, 0}, {n2, l2, r2})
defp join_ev({n1, l1, r1}, n2), do: join_ev({n1, l1, r1}, {n2, 0, 0})
defp join_ev(n1, n2), do: max(n1, n2)
defp fill(0, e), do: e
defp fill(1, {_, _, _} = e), do: height(e)
defp fill(_, n) when is_integer(n), do: n
defp fill({1, r}, {n, el, er}) do
er1 = fill(r, er)
d = max(height(el), base(er1))
norm_ev({n, d, er1})
end
defp fill({l, 1}, {n, el, er}) do
el1 = fill(l, el)
d = max(height(er), base(el1))
norm_ev({n, el1, d})
end
defp fill({l, r}, {n, el, er}) do
norm_ev({n, fill(l, el), fill(r, er)})
end
defp grow(1, n) when is_integer(n), do: {0, n + 1}
defp grow({0, i}, {n, l, r}) do
{h, e1} = grow(i, r)
{h + 1, {n, l, e1}}
end
defp grow({i, 0}, {n, l, r}) do
{h, e1} = grow(i, l)
{h + 1, {n, e1, r}}
end
defp grow({il, ir}, {n, l, r}) do
{hl, el} = grow(il, l)
{hr, er} = grow(ir, r)
cond do
hl < hr -> {hl + 1, {n, el, r}}
:else -> {hr + 1, {n, l, er}}
end
end
defp grow(i, n) when is_integer(n) do
{h, e} = grow(i, {n, 0, 0})
{h + 100_000, e}
end
defp height({n, l, r}), do: n + max(height(l), height(r))
defp height(n), do: n
defp base({n, _, _}), do: n
defp base(n), do: n
defp lift(m, {n, l, r}), do: {n + m, l, r}
defp lift(m, n), do: n + m
defp drop(m, {n, l, r}) when m <= n, do: {n - m, l, r}
defp drop(m, n) when m <= n, do: n - m
defp max(x, y) when x <= y, do: y
defp max(x, _), do: x
defp min(x, y) when x <= y, do: x
defp min(_, y), do: y
def str({i, e}),
do: List.to_string(List.flatten([List.flatten(stri(i)), List.flatten(stre(e))]))
defp stri(0), do: '0'
defp stri(1), do: ''
defp stri({0, i}), do: 'R' ++ stri(i)
defp stri({i, 0}), do: 'L' ++ stri(i)
defp stri({l, r}), do: ['(L' ++ stri(l), '+', 'R' ++ stri(r), ')']
defp stre({n, l, 0}), do: [stre(n), 'L', stre(l)]
defp stre({n, 0, r}), do: [stre(n), 'R', stre(r)]
defp stre({n, l, r}), do: [stre(n), '(L', stre(l), '+R', stre(r), ')']
defp stre(n) when n > 0, do: :erlang.integer_to_list(n)
defp stre(_), do: ''
end
|
lib/swarm/tracker/crdt.ex
| 0.882124 | 0.671464 |
crdt.ex
|
starcoder
|
defmodule EmailEx.RFC2822 do
@moduledoc """
E-mail parser and validation according to rfc-2822.
"""
use Combine
@expected_address_error "Expected address."
@atext ~r/[\!\#\$\%\&\*\+\-\/\=\?\^\_\`\|\{\}\~\'x[:alpha:][:digit:]]/
defp no_ws_ctl(x),
do: (x >= 1 and x < 9) or (x > 10 and x < 13) or (x > 13 and x < 32) or x == 127
defp ctext(),
do: satisfy(bits(8), fn <<x>> ->
no_ws_ctl(x) or (x > 32 and x < 40) or (x > 41 and x < 92) or x > 93
end)
defp ccontent(),
do: choice([ctext(), quoted_pair()])
defp comment(),
do: pipe([
between(char("("), many(ccontent()), char(")"))
], fn x -> "(" <> Enum.join(x) <> ")" end)
defp atext(),
do: word_of(@atext)
defp dot_atom_text(),
do: pipe([
option(comment()),
many1(atext()),
option(comment())
], &Enum.join/1)
defp dot_part(),
do: pipe([
many(map(pair_both(
char("."),
dot_atom_text()
), fn {a, b} -> a <> b end))],
&Enum.join/1
)
defp dot_atom(),
do: pipe([
option(comment()),
dot_atom_text(),
option(dot_part()),
option(comment())
], &Enum.join/1)
defp text(),
do: satisfy(bits(8), fn <<x>> ->
(x > 1 and x < 9) or (x > 10 and x < 13) or x > 14
end)
defp quoted_pair(),
do: pipe([char("\\"), text()], &Enum.join/1)
defp qtext(),
do: satisfy(bits(8), fn <<x>> ->
x == 33 or (x > 34 and x < 92) or x > 92
end)
defp quoted_string(),
do: pipe([
between(
char("\""),
many1(choice([quoted_pair(), qtext()])),
char("\"")
)], fn x -> "\"" <> Enum.join(x) <> "\"" end)
defp dtext(),
do: satisfy(bits(8), fn <<x>> ->
no_ws_ctl(x) or (x > 32 and x < 91) or x > 93
end)
defp dcontent(),
do: choice([many1(dtext()), quoted_pair()])
defp domain_literal(),
do: between(char("["), dcontent(), char("]"))
defp obs_domain(),
do: dot_atom()
defp domain(stuff),
do: stuff |> choice([dot_atom(), domain_literal(), obs_domain()])
defp atom(),
do: pipe([
option(comment()),
many1(atext()),
option(comment())
], &Enum.join/1)
defp word_(),
do: choice([atom(), quoted_string()])
defp obs_local_part(),
do: pipe([
word_(),
option([many(map(pair_both(
char("."),
word_()
), fn {a, b} -> a <> b end))])
], &Enum.join/1)
defp local_part(),
do: pipe([
choice([dot_atom(),
quoted_string(),
obs_local_part()])
], &Enum.join/1)
@doc since: "0.2.1"
def parse(nil), do: {:error, @expected_address_error}
def parse(""), do: {:error, @expected_address_error}
def parse(str),
do: Combine.parse(
str,
local_part() |> char("@") |> domain
)
end
|
lib/email_rfc2822.ex
| 0.753648 | 0.448064 |
email_rfc2822.ex
|
starcoder
|
defmodule Uinta.Formatter do
@moduledoc """
The Uinta Formatter will wrap normal log statements in a JSON object. The log
level, timestamp, and metadata will all be attached to it as parts of the
object.
The formatter can also format stuctured log messages. When a JSON string is
received for formatting, it will be decoded and merged with the map to be
output. In this way any keys that are passed to it will be on the high level
object, so that they won't need to be extracted from a secondary object later
on.
JSON tends to be a great solution for making logs easily machine parseable,
while still being mostly human readable. However, it is recommended that if
you have separate configuration for development and production environments
that you only enable this in the production environment as it can still
decrease developer productivity to have to mentally parse JSON during
development.
## Installation
To use the formatter, you'll need to add it to your logger configuration. In
your (production) config file, see if you have a line that looks something
like this:
```
config :logger, :console, format: "[$level] $message\\n"
```
If you have it, you'll want to replace it with this:
```
config :logger, :console, format: {Uinta.Formatter, :format}
```
If you don't have it, you'll want to just add that line.
"""
@type level :: :debug | :info | :warn | :error
@type time :: {{1970..10000, 1..12, 1..31}, {0..23, 0..59, 0..59, 0..999}}
@doc """
This function takes in four arguments, as defined by
[Logger](https://hexdocs.pm/logger/Logger.html#module-custom-formatting):
- `level` is the log level, one of `:debug`, `:info`, `:warn`, and `:error`
- `message` is the message to be formatted. This should be iodata
(typically String or iolist)
- `timestamp` is a timestamp formatted according to
`t:Logger.Formatter.time/0`
- `metadata` is a keyword list containing metadata that will be included
with the log line
However, this line should not be called manually. Instead it should be called
by configuring the Elixir logger in your project to use it as a custom log
formatter. See [the installation instructions](#module-installation) for more
information.
"""
@spec format(level(), iodata(), time(), Keyword.t()) :: iodata()
def format(level, message, timestamp, metadata) do
message
|> to_map()
|> add_timestamp_and_level(level, timestamp)
|> add_metadata(metadata)
|> Jason.encode!()
|> Kernel.<>("\n")
rescue
_ -> "Could not format: #{inspect({level, message, metadata})}"
end
@spec to_map(iodata()) :: map()
defp to_map(message) when is_binary(message) do
case Jason.decode(message) do
{:ok, decoded} -> decoded
_ -> %{"message" => message}
end
end
defp to_map(message) when is_list(message) do
%{"message" => to_string(message)}
rescue
_e in ArgumentError -> to_map(inspect(message))
end
defp to_map(message), do: %{"message" => "#{inspect(message)}"}
@spec add_timestamp_and_level(map(), atom(), time()) :: map()
defp add_timestamp_and_level(log, level, timestamp) do
formatted_timestamp = format_timestamp(timestamp)
log
|> Map.put("log_level", level)
|> Map.put("timestamp", formatted_timestamp)
end
@spec add_metadata(map(), Keyword.t()) :: map()
defp add_metadata(log, metadata) do
metadata = for {k, v} <- metadata, s = serialize(v), into: %{}, do: {k, s}
Map.put(log, "metadata", metadata)
end
@spec format_timestamp(Logger.Formatter.time()) :: String.t()
defp format_timestamp({date, {hh, mm, ss, ms}}) do
with erl_time <- :calendar.local_time_to_universal_time({date, {hh, mm, ss}}),
{:ok, timestamp} <- NaiveDateTime.from_erl(erl_time, {ms * 1000, 3}),
{:ok, with_timezone} <- DateTime.from_naive(timestamp, "Etc/UTC"),
result <- DateTime.to_iso8601(with_timezone) do
result
end
end
@spec serialize(term()) :: String.t() | nil
defp serialize(value) do
cond do
String.Chars.impl_for(value) ->
to_string(value)
Inspect.impl_for(value) ->
inspect(value)
true ->
nil
end
end
end
|
lib/uinta/formatter.ex
| 0.756268 | 0.845305 |
formatter.ex
|
starcoder
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.