hexsha
stringlengths 40
40
| size
int64 2
991k
| ext
stringclasses 2
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
208
| max_stars_repo_name
stringlengths 6
106
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
33.5k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
208
| max_issues_repo_name
stringlengths 6
106
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
16.3k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
208
| max_forks_repo_name
stringlengths 6
106
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
6.91k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 2
991k
| avg_line_length
float64 1
36k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f73a5c79a77896887431df280650e3f9d4347f1b | 725 | ex | Elixir | lib/bs/test/agent.ex | andersjanmyr/battlesnake-server-2018 | 091b4d1201d144de232be08fd7fb6df8156c5ee2 | [
"MIT"
] | 3 | 2018-07-14T22:55:23.000Z | 2019-02-25T06:11:55.000Z | lib/bs/test/agent.ex | andersjanmyr/battlesnake-server-2018 | 091b4d1201d144de232be08fd7fb6df8156c5ee2 | [
"MIT"
] | 7 | 2020-02-12T03:22:59.000Z | 2022-02-10T20:23:52.000Z | lib/bs/test/agent.ex | andersjanmyr/battlesnake-server-2018 | 091b4d1201d144de232be08fd7fb6df8156c5ee2 | [
"MIT"
] | 12 | 2018-03-27T05:27:20.000Z | 2019-04-02T08:19:04.000Z | defmodule Bs.Test.Agent do
alias Bs.Test.Vector
alias Bs.Snake
use Ecto.Schema
embedded_schema do
embeds_many(:body, Vector)
end
defmacro agent(ast) do
body =
Macro.postwalk(ast, fn
{:*, _, [x, y]} ->
quote bind_quoted: [x: x, y: y], do: List.duplicate(x, y)
[x, y] when is_number(x) and is_number(y) ->
quote bind_quoted: [x: x, y: y], do: %Bs.Test.Vector{x: x, y: y}
x ->
x
end)
quote do
%Bs.Test.Agent{
body: List.flatten(unquote(body))
}
end
end
def to_snake(agent) do
coords = for x <- agent.body, do: Vector.to_point(x)
%Snake{
id: agent.id,
coords: coords
}
end
end
| 18.125 | 74 | 0.542069 |
f73a5cfd6414de9d9df69d2c86bd9da897ffdf01 | 711 | ex | Elixir | elixir/lib/com/spoonacular/client/model/inline_response_200_19.ex | ddsky/spoonacular-api-clients | 63f955ceb2c356fefdd48ec634deb3c3e16a6ae7 | [
"MIT"
] | 21 | 2019-08-09T18:53:26.000Z | 2022-03-14T22:10:10.000Z | elixir/lib/com/spoonacular/client/model/inline_response_200_19.ex | ddsky/spoonacular-api-clients | 63f955ceb2c356fefdd48ec634deb3c3e16a6ae7 | [
"MIT"
] | null | null | null | elixir/lib/com/spoonacular/client/model/inline_response_200_19.ex | ddsky/spoonacular-api-clients | 63f955ceb2c356fefdd48ec634deb3c3e16a6ae7 | [
"MIT"
] | 55 | 2019-08-13T17:52:47.000Z | 2022-03-27T04:29:34.000Z | # NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
# https://openapi-generator.tech
# Do not edit the class manually.
defmodule com.spoonacular.client.Model.InlineResponse20019 do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:"sourceAmount",
:"sourceUnit",
:"targetAmount",
:"targetUnit",
:"answer"
]
@type t :: %__MODULE__{
:"sourceAmount" => float(),
:"sourceUnit" => String.t,
:"targetAmount" => float(),
:"targetUnit" => String.t,
:"answer" => String.t
}
end
defimpl Poison.Decoder, for: com.spoonacular.client.Model.InlineResponse20019 do
def decode(value, _options) do
value
end
end
| 20.911765 | 91 | 0.655415 |
f73a6d2f0ff562aa907227d08526105b1aa762ff | 4,609 | ex | Elixir | lib/phoenix/endpoint/render_errors.ex | G3z/phoenix | f13fe2c7f7ec25e6a59204266cb8cbbe7ffbbded | [
"MIT"
] | 2 | 2016-11-01T15:01:48.000Z | 2016-11-01T15:07:20.000Z | lib/phoenix/endpoint/render_errors.ex | G3z/phoenix | f13fe2c7f7ec25e6a59204266cb8cbbe7ffbbded | [
"MIT"
] | null | null | null | lib/phoenix/endpoint/render_errors.ex | G3z/phoenix | f13fe2c7f7ec25e6a59204266cb8cbbe7ffbbded | [
"MIT"
] | null | null | null | defmodule Phoenix.Endpoint.RenderErrors do
# This module is used to catch failures and render them using a view.
#
# This module is automatically used in `Phoenix.Endpoint` where it
# overrides `call/2` to provide rendering. Once the error is
# rendered, the error is reraised unless it is a NoRouteError.
#
# ## Options
#
# * `:view` - the name of the view we render templates against
# * `:format` - the format to use when none is available from the request
#
@moduledoc false
import Plug.Conn
require Phoenix.Endpoint
require Logger
alias Phoenix.Router.NoRouteError
alias Phoenix.Controller
@already_sent {:plug_conn, :sent}
@doc false
defmacro __using__(opts) do
quote do
@before_compile Phoenix.Endpoint.RenderErrors
@phoenix_render_errors unquote(opts)
end
end
@doc false
defmacro __before_compile__(_) do
quote location: :keep do
defoverridable [call: 2]
def call(conn, opts) do
try do
super(conn, opts)
rescue
e in Plug.Conn.WrapperError ->
%{conn: conn, kind: kind, reason: reason, stack: stack} = e
unquote(__MODULE__).__catch__(conn, kind, reason, stack, @phoenix_render_errors)
catch
kind, reason ->
stack = System.stacktrace()
unquote(__MODULE__).__catch__(conn, kind, reason, stack, @phoenix_render_errors)
end
end
end
end
@doc false
def __catch__(conn, kind, reason, stack, opts) do
receive do
@already_sent ->
send(self(), @already_sent)
%Plug.Conn{conn | state: :sent}
after 0 ->
instrument_render_and_send(conn, kind, reason, stack, opts)
end
:erlang.raise(kind, reason, stack)
end
defp instrument_render_and_send(conn, kind, reason, stack, opts) do
level = Keyword.get(opts, :log_level, :debug)
status = status(kind, reason)
conn = error_conn(conn, kind, reason)
metadata = %{status: status, conn: conn, kind: kind, reason: reason, stacktrace: stack, log_level: level}
conn =
Phoenix.Endpoint.instrument(conn, :phoenix_error_render, metadata, fn ->
render(conn, status, kind, reason, stack, opts)
end)
send_resp(conn)
end
defp error_conn(_conn, :error, %NoRouteError{conn: conn}), do: conn
defp error_conn(conn, _kind, _reason), do: conn
## Rendering
@doc false
def __debugger_banner__(_conn, _status, _kind, %NoRouteError{router: router}, _stack) do
"""
<h3>Available routes</h3>
<pre>#{Phoenix.Router.ConsoleFormatter.format(router)}</pre>
"""
end
def __debugger_banner__(_conn, _status, _kind, _reason, _stack), do: nil
defp render(conn, status, kind, reason, stack, opts) do
view = Keyword.fetch!(opts, :view)
conn =
conn
|> maybe_fetch_query_params()
|> maybe_fetch_format(opts)
|> Plug.Conn.put_status(status)
|> Controller.put_layout(opts[:layout] || false)
|> Controller.put_view(view)
reason = Exception.normalize(kind, reason, stack)
format = Controller.get_format(conn)
template = "#{conn.status}.#{format}"
assigns = %{kind: kind, reason: reason, stack: stack}
Controller.__put_render__(conn, view, template, format, assigns)
end
defp maybe_fetch_query_params(conn) do
fetch_query_params(conn)
rescue
Plug.Conn.InvalidQueryError ->
case conn.params do
%Plug.Conn.Unfetched{} -> %Plug.Conn{conn | query_params: %{}, params: %{}}
params -> %Plug.Conn{conn | query_params: %{}, params: params}
end
end
defp maybe_fetch_format(conn, opts) do
# We ignore params["_format"] although we respect any already stored.
case conn.private do
%{phoenix_format: format} when is_binary(format) -> conn
_ -> Controller.accepts(conn, Keyword.fetch!(opts, :accepts))
end
rescue
e in Phoenix.NotAcceptableError ->
fallback_format = Keyword.fetch!(opts, :accepts) |> List.first()
Logger.debug("Could not render errors due to #{Exception.message(e)}. " <>
"Errors will be rendered using the first accepted format #{inspect fallback_format} as fallback. " <>
"Please customize the :accepts option under the :render_errors configuration " <>
"in your endpoint if you want to support other formats or choose another fallback")
Controller.put_format(conn, fallback_format)
end
defp status(:error, error), do: Plug.Exception.status(error)
defp status(:throw, _throw), do: 500
defp status(:exit, _exit), do: 500
end
| 32.006944 | 120 | 0.661532 |
f73a724985a4905fd138093f1442a13642b467da | 360 | ex | Elixir | lib/aws/client.ex | RAM9/aws-elixir | 2890ba722c977e03212df6a957a19d466c05cdf6 | [
"Apache-2.0"
] | 2 | 2019-11-17T02:31:18.000Z | 2019-11-20T22:00:29.000Z | lib/aws/client.ex | RAM9/aws-elixir | 2890ba722c977e03212df6a957a19d466c05cdf6 | [
"Apache-2.0"
] | null | null | null | lib/aws/client.ex | RAM9/aws-elixir | 2890ba722c977e03212df6a957a19d466c05cdf6 | [
"Apache-2.0"
] | 1 | 2019-11-16T18:08:18.000Z | 2019-11-16T18:08:18.000Z | defmodule AWS.Client do
@moduledoc """
Access and connections details needed when making requests to AWS services.
"""
defstruct access_key_id: nil,
secret_access_key: nil,
session_token: nil,
region: nil,
endpoint: nil,
service: nil,
proto: "https",
port: "443"
end
| 24 | 77 | 0.566667 |
f73a7511ae4202d7e0c450c4c9916eb4ba881195 | 937 | exs | Elixir | priv/repo/seeds.exs | ysaito8015/communitex | d469447a62029d59883d95df4df3c9b09e0022e2 | [
"Apache-2.0"
] | 7 | 2021-07-14T15:45:55.000Z | 2022-01-25T11:13:01.000Z | priv/repo/seeds.exs | ysaito8015/communitex | d469447a62029d59883d95df4df3c9b09e0022e2 | [
"Apache-2.0"
] | 10 | 2021-08-09T15:54:05.000Z | 2022-02-17T04:18:38.000Z | priv/repo/seeds.exs | ysaito8015/communitex | d469447a62029d59883d95df4df3c9b09e0022e2 | [
"Apache-2.0"
] | 5 | 2021-07-23T05:54:35.000Z | 2022-01-28T04:14:51.000Z | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Basic.Repo.insert!(%Basic.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
alias Basic.Repo
alias Basic.Accounts.User
alias Basic.Organizations.Organization
alias Basic.Members.Member
alias Basic.Grants.Grant
Repo.insert!(%User{email: "[email protected]", hashed_password: "$pbkdf2-sha512$160000$KV/lR7sJQx5BHK9aRCA8sA$EZs4nue1WlDhuA2kjZL80hRU4lLmFJXu8JNzl8PMiRlOmiJz9PizPUabBgnQSoKhVrQ7U58C1Ii3qi96LSIqdA", confirmed_at: NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)})
Repo.insert!(%Organization{name: "システム管理者グループ"})
Repo.insert!(%Member{user_id: 1, organization_id: 1})
Repo.insert!(%Grant{user_id: 1, organization_id: 1, role: "SystemAdmin"})
| 40.73913 | 276 | 0.774813 |
f73a75da0d2888c5f60969f54010e44ff0948bc1 | 4,352 | ex | Elixir | clients/service_control/lib/google_api/service_control/v1/model/auth.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/service_control/lib/google_api/service_control/v1/model/auth.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/service_control/lib/google_api/service_control/v1/model/auth.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.ServiceControl.V1.Model.Auth do
@moduledoc """
This message defines request authentication attributes. Terminology is
based on the JSON Web Token (JWT) standard, but the terms also
correlate to concepts in other standards.
## Attributes
* `accessLevels` (*type:* `list(String.t)`, *default:* `nil`) - A list of access level resource names that allow resources to be
accessed by authenticated requester. It is part of Secure GCP processing
for the incoming request. An access level string has the format:
"//{api_service_name}/accessPolicies/{policy_id}/accessLevels/{short_name}"
Example:
"//accesscontextmanager.googleapis.com/accessPolicies/MY_POLICY_ID/accessLevels/MY_LEVEL"
* `audiences` (*type:* `list(String.t)`, *default:* `nil`) - The intended audience(s) for this authentication information. Reflects
the audience (`aud`) claim within a JWT. The audience
value(s) depends on the `issuer`, but typically include one or more of
the following pieces of information:
* The services intended to receive the credential such as
["pubsub.googleapis.com", "storage.googleapis.com"]
* A set of service-based scopes. For example,
["https://www.googleapis.com/auth/cloud-platform"]
* The client id of an app, such as the Firebase project id for JWTs
from Firebase Auth.
Consult the documentation for the credential issuer to determine the
information provided.
* `claims` (*type:* `map()`, *default:* `nil`) - Structured claims presented with the credential. JWTs include
`{key: value}` pairs for standard and private claims. The following
is a subset of the standard required and optional claims that would
typically be presented for a Google-based JWT:
{'iss': 'accounts.google.com',
'sub': '113289723416554971153',
'aud': ['123456789012', 'pubsub.googleapis.com'],
'azp': '123456789012.apps.googleusercontent.com',
'email': '[email protected]',
'iat': 1353601026,
'exp': 1353604926}
SAML assertions are similarly specified, but with an identity provider
dependent structure.
* `presenter` (*type:* `String.t`, *default:* `nil`) - The authorized presenter of the credential. Reflects the optional
Authorized Presenter (`azp`) claim within a JWT or the
OAuth client id. For example, a Google Cloud Platform client id looks
as follows: "123456789012.apps.googleusercontent.com".
* `principal` (*type:* `String.t`, *default:* `nil`) - The authenticated principal. Reflects the issuer (`iss`) and subject
(`sub`) claims within a JWT. The issuer and subject should be `/`
delimited, with `/` percent-encoded within the subject fragment. For
Google accounts, the principal format is:
"https://accounts.google.com/{id}"
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:accessLevels => list(String.t()),
:audiences => list(String.t()),
:claims => map(),
:presenter => String.t(),
:principal => String.t()
}
field(:accessLevels, type: :list)
field(:audiences, type: :list)
field(:claims, type: :map)
field(:presenter)
field(:principal)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceControl.V1.Model.Auth do
def decode(value, options) do
GoogleApi.ServiceControl.V1.Model.Auth.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceControl.V1.Model.Auth do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.089109 | 135 | 0.694853 |
f73a8679873a1ec0acdbf3a887214f0de42463bc | 737 | ex | Elixir | phoenix_rest_example/web/gettext.ex | ErikMejerHansen/REST-service-examples | 88358f74b490f718b7c6882fc1265a2b360b8ef2 | [
"Unlicense"
] | 1 | 2019-04-22T13:39:19.000Z | 2019-04-22T13:39:19.000Z | phoenix_rest_example/web/gettext.ex | ErikMejerHansen/REST-service-examples | 88358f74b490f718b7c6882fc1265a2b360b8ef2 | [
"Unlicense"
] | 1 | 2017-10-06T11:54:24.000Z | 2017-10-09T09:29:04.000Z | phoenix_rest_example/web/gettext.ex | ErikMejerHansen/REST-service-examples | 88358f74b490f718b7c6882fc1265a2b360b8ef2 | [
"Unlicense"
] | null | null | null | defmodule PhoenixRestExample.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import PhoenixRestExample.Gettext
# Simple translation
gettext "Here is the string to translate"
# Plural translation
ngettext "Here is the string to translate",
"Here are the strings to translate",
3
# Domain-based translation
dgettext "errors", "Here is the error message to translate"
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :phoenix_rest_example
end
| 29.48 | 72 | 0.693351 |
f73a8e1c1da36ffcde2bc8f79f8093d7cada220c | 9,734 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/subnetwork.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/subnetwork.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/subnetwork.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Compute.V1.Model.Subnetwork do
@moduledoc """
Represents a Subnetwork resource. A subnetwork (also known as a subnet) is a logical partition of a Virtual Private Cloud network with one primary IP range and zero or more secondary IP ranges. For more information, read Virtual Private Cloud (VPC) Network.
## Attributes
* `creationTimestamp` (*type:* `String.t`, *default:* `nil`) - [Output Only] Creation timestamp in RFC3339 text format.
* `description` (*type:* `String.t`, *default:* `nil`) - An optional description of this resource. Provide this property when you create the resource. This field can be set only at resource creation time.
* `enableFlowLogs` (*type:* `boolean()`, *default:* `nil`) - Whether to enable flow logging for this subnetwork. If this field is not explicitly set, it will not appear in get listings. If not set the default behavior is to disable flow logging. This field isn't supported with the purpose field set to INTERNAL_HTTPS_LOAD_BALANCER.
* `externalIpv6Prefix` (*type:* `String.t`, *default:* `nil`) - [Output Only] The range of external IPv6 addresses that are owned by this subnetwork.
* `fingerprint` (*type:* `String.t`, *default:* `nil`) - Fingerprint of this resource. A hash of the contents stored in this object. This field is used in optimistic locking. This field will be ignored when inserting a Subnetwork. An up-to-date fingerprint must be provided in order to update the Subnetwork, otherwise the request will fail with error 412 conditionNotMet. To see the latest fingerprint, make a get() request to retrieve a Subnetwork.
* `gatewayAddress` (*type:* `String.t`, *default:* `nil`) - [Output Only] The gateway address for default routes to reach destination addresses outside this subnetwork.
* `id` (*type:* `String.t`, *default:* `nil`) - [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* `ipCidrRange` (*type:* `String.t`, *default:* `nil`) - The range of internal addresses that are owned by this subnetwork. Provide this property when you create the subnetwork. For example, 10.0.0.0/8 or 100.64.0.0/10. Ranges must be unique and non-overlapping within a network. Only IPv4 is supported. This field is set at resource creation time. The range can be any range listed in the Valid ranges list. The range can be expanded after creation using expandIpCidrRange.
* `ipv6AccessType` (*type:* `String.t`, *default:* `nil`) - The access type of IPv6 address this subnet holds. It's immutable and can only be specified during creation or the first time the subnet is updated into IPV4_IPV6 dual stack. If the ipv6_type is EXTERNAL then this subnet cannot enable direct path.
* `ipv6CidrRange` (*type:* `String.t`, *default:* `nil`) - [Output Only] The range of internal IPv6 addresses that are owned by this subnetwork.
* `kind` (*type:* `String.t`, *default:* `compute#subnetwork`) - [Output Only] Type of the resource. Always compute#subnetwork for Subnetwork resources.
* `logConfig` (*type:* `GoogleApi.Compute.V1.Model.SubnetworkLogConfig.t`, *default:* `nil`) - This field denotes the VPC flow logging options for this subnetwork. If logging is enabled, logs are exported to Cloud Logging.
* `name` (*type:* `String.t`, *default:* `nil`) - The name of the resource, provided by the client when initially creating the resource. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.
* `network` (*type:* `String.t`, *default:* `nil`) - The URL of the network to which this subnetwork belongs, provided by the client when initially creating the subnetwork. This field can be set only at resource creation time.
* `privateIpGoogleAccess` (*type:* `boolean()`, *default:* `nil`) - Whether the VMs in this subnet can access Google services without assigned external IP addresses. This field can be both set at resource creation time and updated using setPrivateIpGoogleAccess.
* `privateIpv6GoogleAccess` (*type:* `String.t`, *default:* `nil`) - The private IPv6 google access type for the VMs in this subnet. This is an expanded field of enablePrivateV6Access. If both fields are set, privateIpv6GoogleAccess will take priority. This field can be both set at resource creation time and updated using patch.
* `purpose` (*type:* `String.t`, *default:* `nil`) - The purpose of the resource. This field can be either PRIVATE_RFC_1918 or INTERNAL_HTTPS_LOAD_BALANCER. A subnetwork with purpose set to INTERNAL_HTTPS_LOAD_BALANCER is a user-created subnetwork that is reserved for Internal HTTP(S) Load Balancing. If unspecified, the purpose defaults to PRIVATE_RFC_1918. The enableFlowLogs field isn't supported with the purpose field set to INTERNAL_HTTPS_LOAD_BALANCER.
* `region` (*type:* `String.t`, *default:* `nil`) - URL of the region where the Subnetwork resides. This field can be set only at resource creation time.
* `role` (*type:* `String.t`, *default:* `nil`) - The role of subnetwork. Currently, this field is only used when purpose = INTERNAL_HTTPS_LOAD_BALANCER. The value can be set to ACTIVE or BACKUP. An ACTIVE subnetwork is one that is currently being used for Internal HTTP(S) Load Balancing. A BACKUP subnetwork is one that is ready to be promoted to ACTIVE or is currently draining. This field can be updated with a patch request.
* `secondaryIpRanges` (*type:* `list(GoogleApi.Compute.V1.Model.SubnetworkSecondaryRange.t)`, *default:* `nil`) - An array of configurations for secondary IP ranges for VM instances contained in this subnetwork. The primary IP of such VM must belong to the primary ipCidrRange of the subnetwork. The alias IPs may belong to either primary or secondary ranges. This field can be updated with a patch request.
* `selfLink` (*type:* `String.t`, *default:* `nil`) - [Output Only] Server-defined URL for the resource.
* `stackType` (*type:* `String.t`, *default:* `nil`) - The stack type for this subnet to identify whether the IPv6 feature is enabled or not. If not specified IPV4_ONLY will be used. This field can be both set at resource creation time and updated using patch.
* `state` (*type:* `String.t`, *default:* `nil`) - [Output Only] The state of the subnetwork, which can be one of the following values: READY: Subnetwork is created and ready to use DRAINING: only applicable to subnetworks that have the purpose set to INTERNAL_HTTPS_LOAD_BALANCER and indicates that connections to the load balancer are being drained. A subnetwork that is draining cannot be used or modified until it reaches a status of READY
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:creationTimestamp => String.t() | nil,
:description => String.t() | nil,
:enableFlowLogs => boolean() | nil,
:externalIpv6Prefix => String.t() | nil,
:fingerprint => String.t() | nil,
:gatewayAddress => String.t() | nil,
:id => String.t() | nil,
:ipCidrRange => String.t() | nil,
:ipv6AccessType => String.t() | nil,
:ipv6CidrRange => String.t() | nil,
:kind => String.t() | nil,
:logConfig => GoogleApi.Compute.V1.Model.SubnetworkLogConfig.t() | nil,
:name => String.t() | nil,
:network => String.t() | nil,
:privateIpGoogleAccess => boolean() | nil,
:privateIpv6GoogleAccess => String.t() | nil,
:purpose => String.t() | nil,
:region => String.t() | nil,
:role => String.t() | nil,
:secondaryIpRanges =>
list(GoogleApi.Compute.V1.Model.SubnetworkSecondaryRange.t()) | nil,
:selfLink => String.t() | nil,
:stackType => String.t() | nil,
:state => String.t() | nil
}
field(:creationTimestamp)
field(:description)
field(:enableFlowLogs)
field(:externalIpv6Prefix)
field(:fingerprint)
field(:gatewayAddress)
field(:id)
field(:ipCidrRange)
field(:ipv6AccessType)
field(:ipv6CidrRange)
field(:kind)
field(:logConfig, as: GoogleApi.Compute.V1.Model.SubnetworkLogConfig)
field(:name)
field(:network)
field(:privateIpGoogleAccess)
field(:privateIpv6GoogleAccess)
field(:purpose)
field(:region)
field(:role)
field(:secondaryIpRanges, as: GoogleApi.Compute.V1.Model.SubnetworkSecondaryRange, type: :list)
field(:selfLink)
field(:stackType)
field(:state)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.Subnetwork do
def decode(value, options) do
GoogleApi.Compute.V1.Model.Subnetwork.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.Subnetwork do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 85.385965 | 502 | 0.724163 |
f73a9171152fd9c56f760c0ccd8e4d7edf063247 | 1,469 | ex | Elixir | clients/redis/lib/google_api/redis/v1beta1/model/gcs_destination.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/redis/lib/google_api/redis/v1beta1/model/gcs_destination.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/redis/lib/google_api/redis/v1beta1/model/gcs_destination.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Redis.V1beta1.Model.GcsDestination do
@moduledoc """
The Cloud Storage location for the output content
## Attributes
* `uri` (*type:* `String.t`, *default:* `nil`) - Required. Data destination URI (e.g. 'gs://my_bucket/my_object'). Existing files will be overwritten.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:uri => String.t()
}
field(:uri)
end
defimpl Poison.Decoder, for: GoogleApi.Redis.V1beta1.Model.GcsDestination do
def decode(value, options) do
GoogleApi.Redis.V1beta1.Model.GcsDestination.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Redis.V1beta1.Model.GcsDestination do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.255319 | 154 | 0.735194 |
f73aada935f25800aaa7d5fbc9872ebb98ec559a | 2,048 | exs | Elixir | apps/astarte_pairing_api/config/dev.exs | matt-mazzucato/astarte | 34d84941a5019efc42321052f7f34b7d907a38f2 | [
"Apache-2.0"
] | 191 | 2018-03-30T13:23:08.000Z | 2022-03-02T12:05:32.000Z | apps/astarte_pairing_api/config/dev.exs | matt-mazzucato/astarte | 34d84941a5019efc42321052f7f34b7d907a38f2 | [
"Apache-2.0"
] | 402 | 2018-03-30T13:37:00.000Z | 2022-03-31T16:47:10.000Z | apps/astarte_pairing_api/config/dev.exs | matt-mazzucato/astarte | 34d84941a5019efc42321052f7f34b7d907a38f2 | [
"Apache-2.0"
] | 24 | 2018-03-30T13:29:48.000Z | 2022-02-28T11:10:26.000Z | #
# This file is part of Astarte.
#
# Copyright 2017 Ispirata Srl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :astarte_pairing_api, Astarte.Pairing.APIWeb.Endpoint,
http: [port: 4003],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: []
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# command from your terminal:
#
# openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem
#
# The `http:` config above can be replaced with:
#
# https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
config :logger, :console,
format: {PrettyLog.LogfmtFormatter, :format},
metadata: [
:method,
:request_path,
:status_code,
:elapsed,
:realm,
:hw_id,
:module,
:function,
:request_id,
:tag
]
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
| 30.117647 | 170 | 0.725098 |
f73ab540e3359f53db8cb2bc8dbaa6092cbdc05e | 71 | ex | Elixir | testData/org/elixir_lang/formatting/no_parentheses_call_do_not_wrap_unless_keywords_multiline_before.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 1,668 | 2015-01-03T05:54:27.000Z | 2022-03-25T08:01:20.000Z | testData/org/elixir_lang/formatting/no_parentheses_call_do_not_wrap_unless_keywords_multiline_before.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 2,018 | 2015-01-01T22:43:39.000Z | 2022-03-31T20:13:08.000Z | testData/org/elixir_lang/formatting/no_parentheses_call_do_not_wrap_unless_keywords_multiline_before.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | one two, three, four: five
one two, three,
four: five,
six: seven
| 11.833333 | 26 | 0.647887 |
f73ad03ec39fac0d16132afcf9613bff4de631a3 | 2,453 | exs | Elixir | mix.exs | omgnetwork/ex_plasma | 27c33206297a4d6832a9419c4e61e04b3c2c9f71 | [
"Apache-2.0"
] | 6 | 2020-08-13T08:14:34.000Z | 2021-08-19T11:08:17.000Z | mix.exs | omisego/ex_plasma | 27c33206297a4d6832a9419c4e61e04b3c2c9f71 | [
"Apache-2.0"
] | 34 | 2019-11-20T03:33:22.000Z | 2020-05-27T18:40:10.000Z | mix.exs | omisego/ex_plasma | 27c33206297a4d6832a9419c4e61e04b3c2c9f71 | [
"Apache-2.0"
] | 6 | 2020-06-02T19:00:36.000Z | 2021-08-19T11:06:33.000Z | defmodule ExPlasma.MixProject do
use Mix.Project
def project do
[
app: :ex_plasma,
version: "0.3.0",
elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
elixirc_paths: elixirc_paths(Mix.env()),
description: description(),
deps: deps(),
package: package(),
name: "ExPlasma",
docs: docs(),
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
dialyzer: dialyzer()
]
end
defp description do
"""
A library for encoding, decoding and validating transactions used for the OMG Network Plasma contracts.
"""
end
defp package do
[
name: :ex_plasma,
maintainers: ["OMG Network team"],
licenses: ["Apache-2.0 License"],
links: %{"GitHub" => "https://github.com/omgnetwork/ex_plasma"}
]
end
defp docs do
[
main: "readme",
extras: [
"README.md"
]
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
applications: [:ex_abi, :ex_rlp, :ex_keccak, :ex_secp256k1, :merkle_tree],
extra_applications: [:logger]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:credo, "~> 1.4", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 1.0", only: [:dev], runtime: false},
{:ethereumex, "~> 0.6.0", only: [:test]},
{:ex_abi, "~> 0.5.1"},
{:ex_rlp, "~> 0.5.3"},
{:excoveralls, "~> 0.10", only: [:test]},
{:ex_keccak, "~> 0.1.2"},
{:ex_secp256k1, "~> 0.1.1"},
{:merkle_tree, "~> 2.0.0"},
{:stream_data, "~>0.4.3", only: [:test]},
{:telemetry, "~> 0.4", only: [:test]},
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false}
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
defp dialyzer do
[
flags: [:error_handling, :race_conditions, :underspecs, :unknown, :unmatched_returns],
ignore_warnings: "dialyzer.ignore-warnings",
list_unused_filters: true,
plt_add_apps: plt_apps()
]
end
defp plt_apps,
do: [
:ex_abi,
:ex_rlp,
:merkle_tree
]
end
| 25.030612 | 107 | 0.554423 |
f73afcafbf8b7f0a634f38a4c91474c241322425 | 3,070 | ex | Elixir | lib/ramona/events/events.ex | sqdorte/ramona | 45ba8b17a8542c4451931b2049ba618be187ecfa | [
"Apache-2.0"
] | 1 | 2019-01-24T19:58:04.000Z | 2019-01-24T19:58:04.000Z | lib/ramona/events/events.ex | sqdorte/ramona | 45ba8b17a8542c4451931b2049ba618be187ecfa | [
"Apache-2.0"
] | null | null | null | lib/ramona/events/events.ex | sqdorte/ramona | 45ba8b17a8542c4451931b2049ba618be187ecfa | [
"Apache-2.0"
] | null | null | null | defmodule Ramona.Events do
@moduledoc false
use Alchemy.Events
alias Ramona.Utils
alias Alchemy.{Cache, Client}
require Logger
require Alchemy.Cogs, as: Cogs
@invite_log "430374864906354710"
@unleashed_gid "429110044525592578"
@moderation_cat "430410176328368150"
Events.on_ready(:ready)
Events.on_message(:everyone)
Events.on_message(:command_log)
Events.on_message(:block_invites)
def ready(_, _) do
me = "#{Cache.user().username}##{Cache.user().discriminator} (#{Cache.user().id})"
Logger.info("Logged in as #{me}")
Logger.info("Ramona is ready!")
end
def command_log(message) do
prefix = Application.fetch_env!(:ramona, :prefix)
if String.starts_with?(message.content, prefix) do
command =
with m <- message.content |> String.split() |> List.first() do
String.slice(m, String.length(prefix), String.length(m))
end
if command in Map.keys(Cogs.all_commands()) do
id = message.author.id
username = message.author.username
tag = message.author.discriminator
~s/Command "#{message.content}" called by <@#{id}> (#{username}##{tag})/
|> Logger.info()
end
end
end
def everyone(message) do
if message.author.id != Cache.user.id
and Utils.not_an_admin(message.author.id)
do
patt = :binary.compile_pattern(["@everyone", "@here"])
if String.contains?(message.content, patt) do
police = "lib/ramona/assets/polar_bear_police.gif"
Client.send_message(message.channel_id, "***STOP***", file: police)
end
end
end
def block_invites(message) do
if Utils.invite_match?(message.content)
and on_main_server?(message)
do
{:ok, channel} = Client.get_channel(message.channel_id)
if message.author.id != Cache.user.id
and Utils.not_a_mod(message.author.id)
and channel.parent_id != @moderation_cat
do
msg = message.content
author_username = message.author.username
author_discrim = message.author.discriminator
author_id = message.author.id
with {:ok, nil} <- Client.delete_message(message) do
patt1 = ~r{discord\.gg\/[a-zA-Z0-9]*}
patt2 = ~r{discordapp\.com\/invite\/[a-zA-Z0-9]*}
invites =
with inv1 <- Utils.catch_invites(patt1, msg),
inv2 <- Utils.catch_invites(patt2, msg)
do
inv1 ++ inv2
|> Enum.map(& " - `#{&1}`")
|> Enum.join("\n")
end
warning =
"Blocked invite in <##{channel.id}> from "
<> "`#{author_username}##{author_discrim}` "
<> "(#{author_id}):\n"
<> invites
Logger.warn(warning)
Client.send_message(@invite_log, warning)
else
{:error, reason} -> Logger.error(reason)
end
end
end
end
defp on_main_server?(message) do
{:ok, chans} = Client.get_channels(@unleashed_gid)
message.channel_id in Enum.map(chans, & &1.id)
end
end
| 28.962264 | 86 | 0.608795 |
f73affc4ee7f7ee41811b04f3538754077622436 | 3,000 | ex | Elixir | clients/civic_info/lib/google_api/civic_info/v2/model/representative_info_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/civic_info/lib/google_api/civic_info/v2/model/representative_info_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/civic_info/lib/google_api/civic_info/v2/model/representative_info_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.CivicInfo.V2.Model.RepresentativeInfoResponse do
@moduledoc """
The result of a representative info lookup query.
## Attributes
* `divisions` (*type:* `%{optional(String.t) => GoogleApi.CivicInfo.V2.Model.GeographicDivision.t}`, *default:* `nil`) - Political geographic divisions that contain the requested address.
* `kind` (*type:* `String.t`, *default:* `civicinfo#representativeInfoResponse`) - Identifies what kind of resource this is. Value: the fixed string "civicinfo#representativeInfoResponse".
* `normalizedInput` (*type:* `GoogleApi.CivicInfo.V2.Model.SimpleAddressType.t`, *default:* `nil`) - The normalized version of the requested address
* `offices` (*type:* `list(GoogleApi.CivicInfo.V2.Model.Office.t)`, *default:* `nil`) - Elected offices referenced by the divisions listed above. Will only be present if includeOffices was true in the request.
* `officials` (*type:* `list(GoogleApi.CivicInfo.V2.Model.Official.t)`, *default:* `nil`) - Officials holding the offices listed above. Will only be present if includeOffices was true in the request.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:divisions => %{
optional(String.t()) => GoogleApi.CivicInfo.V2.Model.GeographicDivision.t()
},
:kind => String.t(),
:normalizedInput => GoogleApi.CivicInfo.V2.Model.SimpleAddressType.t(),
:offices => list(GoogleApi.CivicInfo.V2.Model.Office.t()),
:officials => list(GoogleApi.CivicInfo.V2.Model.Official.t())
}
field(:divisions, as: GoogleApi.CivicInfo.V2.Model.GeographicDivision, type: :map)
field(:kind)
field(:normalizedInput, as: GoogleApi.CivicInfo.V2.Model.SimpleAddressType)
field(:offices, as: GoogleApi.CivicInfo.V2.Model.Office, type: :list)
field(:officials, as: GoogleApi.CivicInfo.V2.Model.Official, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.CivicInfo.V2.Model.RepresentativeInfoResponse do
def decode(value, options) do
GoogleApi.CivicInfo.V2.Model.RepresentativeInfoResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CivicInfo.V2.Model.RepresentativeInfoResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 49.180328 | 213 | 0.734 |
f73b01fd7f8f518b7f41d0c905eec7575c9420c6 | 4,467 | ex | Elixir | lib/mnemonix/features/expiry.ex | christhekeele/mnemonix | 41c81b00b89562250ea451035fd34bf775173e50 | [
"MIT"
] | 36 | 2016-10-30T21:40:19.000Z | 2021-05-03T10:51:50.000Z | lib/mnemonix/features/expiry.ex | christhekeele/mnemonix | 41c81b00b89562250ea451035fd34bf775173e50 | [
"MIT"
] | 52 | 2016-10-30T20:57:35.000Z | 2017-12-28T03:39:57.000Z | lib/mnemonix/features/expiry.ex | christhekeele/mnemonix | 41c81b00b89562250ea451035fd34bf775173e50 | [
"MIT"
] | 5 | 2017-01-25T22:02:58.000Z | 2018-01-30T14:27:55.000Z | defmodule Mnemonix.Features.Expiry do
@name Inspect.inspect(__MODULE__, %Inspect.Opts{})
@moduledoc """
Functions to manage the time-to-live of entries within a store.
Using this feature will define all of its Mnemonix client API functions on your module.
Refer to `Mnemonix.Builder` for documentation on options you can use when doing so.
"""
use Mnemonix.Behaviour
use Mnemonix.Singleton.Behaviour
@typedoc """
The number of milliseconds an entry will be allowed to be retrieved.
"""
@type ttl :: non_neg_integer | nil
@callback expire(Mnemonix.store, Mnemonix.key, ttl)
:: Mnemonix.store | no_return
@doc """
Sets the entry under `key` to expire in `ttl` milliseconds.
If the `key` does not exist, the contents of `store` will be unaffected.
If the entry under `key` was already set to expire, the new `ttl` will be used instead.
If the `ttl` is `nil` or not provided, it will defer to the `ttl` passed into the store's options.
If that was also `nil`, the entry will not be set to expire.
## Examples
iex> store = Mnemonix.new(%{a: 1})
iex> #{@name}.expire(store, :a, 1)
iex> :timer.sleep(200)
iex> Mnemonix.get(store, :a)
nil
iex> store = Mnemonix.new(%{a: 1})
iex> #{@name}.expire(store, :a, 24 * 60 * 60 * 1)
iex> #{@name}.expire(store, :a, 1)
iex> :timer.sleep(200)
iex> Mnemonix.get(store, :a)
nil
iex> store = Mnemonix.new(%{a: 1})
iex> #{@name}.expire(store, :a, 1)
iex> #{@name}.expire(store, :a, 24 * 60 * 60 * 1)
iex> :timer.sleep(200)
iex> Mnemonix.get(store, :a)
1
"""
@spec expire(Mnemonix.store, Mnemonix.key, ttl)
:: Mnemonix.store | no_return
def expire(store, key, ttl) do
case GenServer.call(store, {:expire, key, ttl}) do
:ok -> store
{:warn, message} -> with :ok <- IO.warn(message), do: store
{:raise, type, args} -> raise type, args
end
end
@callback persist(Mnemonix.store, Mnemonix.key)
:: Mnemonix.store | no_return
@doc """
Prevents the entry under `key` from expiring.
If the `key` does not exist or is not set to expire, the contents of `store` will be unaffected.
## Examples
iex> store = Mnemonix.new(%{a: 1})
iex> Mnemonix.expire(store, :a, 200)
iex> #{@name}.persist(store, :a)
iex> :timer.sleep(200)
iex> Mnemonix.get(store, :a)
1
"""
@spec persist(Mnemonix.store, Mnemonix.key)
:: Mnemonix.store | no_return
def persist(store, key) do
case GenServer.call(store, {:persist, key}) do
:ok -> store
{:warn, message} -> with :ok <- IO.warn(message), do: store
{:raise, type, args} -> raise type, args
end
end
@callback put_and_expire(Mnemonix.store, Mnemonix.key, Mnemonix.value)
:: Mnemonix.store | no_return
@doc """
Creates a new entry for `value` under `key` in `store`
and sets it to expire.
It will use the `ttl` passed into the store's options.
If that was not set, the entry will not be set to expire.
## Examples
iex> store = Mnemonix.new
iex> #{@name}.put_and_expire(store, :a, "bar", 1)
iex> Mnemonix.get(store, :a)
"bar"
iex> :timer.sleep(200)
iex> Mnemonix.get(store, :a)
nil
"""
@spec put_and_expire(Mnemonix.store, Mnemonix.key, Mnemonix.value)
:: Mnemonix.store | no_return
def put_and_expire(store, key, value), do: put_and_expire(store, key, value, nil)
@callback put_and_expire(Mnemonix.store, Mnemonix.key, Mnemonix.value, ttl)
:: Mnemonix.store | no_return
@doc """
Creates a new entry for `value` under `key` in `store`
and sets it to expire in `ttl` milliseconds.
If the `ttl` is `nil` or not provided, it will defer to the `ttl` passed into the store's options.
If that was also `nil`, the entry will not be set to expire.
## Examples
iex> store = Mnemonix.new
iex> #{@name}.put_and_expire(store, :a, "bar", 1)
iex> Mnemonix.get(store, :a)
"bar"
iex> :timer.sleep(200)
iex> Mnemonix.get(store, :a)
nil
"""
@spec put_and_expire(Mnemonix.store, Mnemonix.key, Mnemonix.value, ttl)
:: Mnemonix.store | no_return
def put_and_expire(store, key, value, ttl) do
case GenServer.call(store, {:put_and_expire, key, value, ttl}) do
:ok -> store
{:warn, message} -> with :ok <- IO.warn(message), do: store
{:raise, type, args} -> raise type, args
end
end
end
| 31.680851 | 100 | 0.634878 |
f73b02aa02bf8924e29397f300700826776f8b48 | 982 | ex | Elixir | test/support/channel_case.ex | Andorbal/phoenix_react | 0291d612ca710f80bd5ec87f052649f32c9e5847 | [
"MIT"
] | null | null | null | test/support/channel_case.ex | Andorbal/phoenix_react | 0291d612ca710f80bd5ec87f052649f32c9e5847 | [
"MIT"
] | null | null | null | test/support/channel_case.ex | Andorbal/phoenix_react | 0291d612ca710f80bd5ec87f052649f32c9e5847 | [
"MIT"
] | null | null | null | defmodule PhoenixReact.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
imports other functionality to make it easier
to build and query models.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
use Phoenix.ChannelTest
alias PhoenixReact.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query, only: [from: 1, from: 2]
# The default endpoint for testing
@endpoint PhoenixReact.Endpoint
end
end
setup tags do
unless tags[:async] do
Ecto.Adapters.SQL.restart_test_transaction(PhoenixReact.Repo, [])
end
:ok
end
end
| 23.380952 | 71 | 0.706721 |
f73b2b2bf222e3d88275bbef1748c269b2d032f9 | 11,532 | ex | Elixir | lib/phoenix/view.ex | DavidAlphaFox/phoenix | 560131ab3b48c6b6cf864a3d20b7667e40990237 | [
"MIT"
] | 1 | 2019-06-11T20:22:21.000Z | 2019-06-11T20:22:21.000Z | lib/phoenix/view.ex | DavidAlphaFox/phoenix | 560131ab3b48c6b6cf864a3d20b7667e40990237 | [
"MIT"
] | null | null | null | lib/phoenix/view.ex | DavidAlphaFox/phoenix | 560131ab3b48c6b6cf864a3d20b7667e40990237 | [
"MIT"
] | null | null | null | defmodule Phoenix.View do
@moduledoc """
Defines the view layer of a Phoenix application.
This module is used to define the application main view, which
serves as the base for all other views and templates in the
application.
The view layer also contains conveniences for rendering templates,
including support for layouts and encoders per format.
## Examples
Phoenix defines the view template at `web/web.ex`:
defmodule YourApp.Web do
def view do
quote do
use Phoenix.View, root: "web/templates"
# Import common functionality
import YourApp.Router.Helpers
# Use Phoenix.HTML to import all HTML functions (forms, tags, etc)
use Phoenix.HTML
end
end
# ...
end
We can use the definition above to define any view in your application:
defmodule YourApp.UserView do
use YourApp.Web, :view
end
Because we have defined the template root to be "web/template", `Phoenix.View`
will automatically load all templates at "web/template/user" and include them
in the `YourApp.UserView`. For example, imagine we have the template:
# web/templates/user/index.html.eex
Hello <%= @name %>
The `.eex` extension is called a template engine which tells Phoenix how
to compile the code in the file into actual Elixir source code. After it is
compiled, the template can be rendered as:
Phoenix.View.render(YourApp.UserView, "index.html", name: "John Doe")
#=> {:safe, "Hello John Doe"}
We will discuss rendering in detail next.
## Rendering
The main responsibility of a view is to render a template.
A template has a name, which also contains a format. For example,
in the previous section we have rendered the "index.html" template:
Phoenix.View.render(YourApp.UserView, "index.html", name: "John Doe")
#=> {:safe, "Hello John Doe"}
When a view renders a template, the result returned is an inner
representation specific to the template format. In the example above,
we got: `{:safe, "Hello John Doe"}`. The safe tuple annotates that our
template is safe and that we don't need to escape its contents because
all data was already encoded so far. Let's try to inject custom code:
Phoenix.View.render(YourApp.UserView, "index.html", name: "John<br />Doe")
#=> {:safe, "Hello John<br />Doe"}
This inner representation allows us to render and compose templates easily.
For example, if you want to render JSON data, we could do so by adding a
"show.json" entry to `render/2` in our view:
defmodule YourApp.UserView do
use YourApp.View
def render("show.json", %{user: user}) do
%{name: user.name, address: user.address}
end
end
Notice that in order to render JSON data, we don't need to explicitly
return a JSON string! Instead, we just return data that is encodable to
JSON.
Both JSON and HTML formats will be encoded only when passing the data
to the controller via the `render_to_iodata/3` function. The
`render_to_iodata/3` uses the notion of format encoders to convert a
particular format to its string/iodata representation.
Phoenix ships with some template engines and format encoders, which
can be further configured in the Phoenix application. You can read
more about format encoders in `Phoenix.Template` documentation.
"""
@doc """
When used, defines the current module as a main view module.
## Options
* `:root` - the template root to find templates
* `:namespace` - the namespace to consider when calculating view paths
The `:root` option is required while the `:namespace` defaults to the
first nesting in the module name. For instance, both `MyApp.UserView`
and `MyApp.Admin.UserView` have namespace `MyApp`.
The namespace is used to calculate paths. For example, if you are in
`MyApp.UserView` and the namespace is `MyApp`, templates are expected
at `Path.join(root, "user")`. On the other hand, if the view is
`MyApp.Admin.UserView`, the path will be `Path.join(root, "admin/user")`
and so on.
Setting the namespace to `MyApp.Admin` in the second example will force
the template to also be looked up at `Path.join(root, "user")`.
"""
defmacro __using__(options) do
# 的到模版的根目录
if root = Keyword.get(options, :root) do
namespace =
if given = Keyword.get(options, :namespace) do
given
else
## 得到调用者模块的名字空间
__CALLER__.module
|> Module.split()
|> Enum.take(1)
|> Module.concat()
end
quote do
import Phoenix.View
use Phoenix.Template, root:
Path.join(unquote(root),
Phoenix.Template.module_to_template_root(__MODULE__, unquote(namespace), "View"))
@view_resource String.to_atom(Phoenix.Naming.resource_name(__MODULE__, "View"))
@doc "The resource name, as an atom, for this view"
def __resource__, do: @view_resource
end
else
raise "expected :root to be given as an option"
end
end
@doc """
Renders a template.
It expects the view module, the template as a string, and a
set of assigns.
Notice this function returns the inner representation of a
template. If you want the encoded template as a result, use
`render_to_iodata/3` instead.
## Examples
Phoenix.View.render(YourApp.UserView, "index.html", name: "John Doe")
#=> {:safe, "Hello John Doe"}
## Assigns
Assigns are meant to be user data that will be available in templates.
However there are keys under assigns that are specially handled by
Phoenix, they are:
* `:layout` - tells Phoenix to wrap the rendered result in the
given layout. See next section.
The following assigns are reserved, and cannot be set directly:
* `@view_module` - The view module being rendered
* `@view_template` - The `@view_module`'s template being rendered
## Layouts
Templates can be rendered within other templates using the `:layout`
option. `:layout` accepts a tuple of the form
`{LayoutModule, "template.extension"}`.
To render the template within the layout, simply call `render/3`
using the `@view_module` and `@view_template` assign:
<%= render @view_module, @view_template, assigns %>
"""
def render(module, template, assigns) do
## 从assigns中取出layout
## Map.pop会返回值和相应的新的Map
## 结果就是{value,new_map}
assigns
|> to_map()
|> Map.pop(:layout, false)
|> render_within(module, template)
end
defp render_within({{layout_mod, layout_tpl}, assigns}, inner_mod, inner_tpl) do
assigns = Map.merge(assigns, %{view_module: inner_mod,
view_template: inner_tpl})
render_layout(layout_mod, layout_tpl, assigns)
end
defp render_within({false, assigns}, module, template) do
assigns = Map.merge(assigns, %{view_module: module,
view_template: template})
module.render(template, assigns)
end
defp render_layout(layout_mod, layout_tpl, assigns) do
layout_mod.render(layout_tpl, assigns)
end
@doc """
Renders a template only if it exists.
Same as `render/3`, but returns `nil` instead of raising.
Useful for dynamically rendering templates in the layout that may or
may not be implemented by the `@view_module` view.
## Examples
Consider the case where the application layout allows views to dynamically
render a section of script tags in the head of the document. Some views
may wish to inject certain scripts, while others will not.
<head>
<%= render_existing @view_module, "scripts.html", assigns %>
</head>
Then the module for the `@view_module` view can decide to provide scripts with
either a precompiled template, or by implementing the function directly, ie:
def render("scripts.html", _assigns) do
~E(<script src="file.js"></script>)
end
To use a precompiled template, create a `scripts.html.eex` file in the `templates`
directory for the corresponding view you want it to render for. For example,
for the `UserView`, create the `scripts.html.eex` file at `web/templates/user/`.
## Rendering based on controller template
In some cases, you might need to render based on the template.
For these cases, `@view_template` can pair with
`render_existing/3` for per-template based content, ie:
<head>
<%= render_existing @view_module, "scripts." <> @view_template, assigns %>
</head>
def render("scripts.show.html", _assigns) do
~E(<script src="file.js"></script>)
end
def render("scripts.index.html", _assigns) do
~E(<script src="file.js"></script>)
end
"""
def render_existing(module, template, assigns \\ []) do
render(module, template, Dict.put(assigns, :render_existing, {module, template}))
end
@doc """
Renders a collection.
A collection is any enumerable of structs. This function
returns the rendered collection in a list:
render_many users, UserView, "show.html"
is roughly equivalent to:
Enum.map(users, fn user ->
render(UserView, "show.html", user: user)
end)
The underlying user is passed to the view and template as `:user`,
which is inflected from the view name. The name of the key
in assigns can be customized with the `:as` option:
render_many users, UserView, "show.html", as: :data
is roughly equivalent to:
Enum.map(users, fn user ->
render(UserView, "show.html", data: user)
end)
"""
def render_many(collection, view, template, assigns \\ %{}) do
assigns = to_map(assigns)
Enum.map(collection, fn model ->
render view, template, assign_model(assigns, view, model)
end)
end
@doc """
Renders a single item if not nil.
The following:
render_one user, UserView, "show.html"
is roughly equivalent to:
if user != nil do
render(UserView, "show.html", user: user)
end
The underlying user is passed to the view and template as
`:user`, which is inflected from the view name. The name
of the key in assigns can be customized with the `:as` option:
render_one user, UserView, "show.html", as: :data
is roughly equivalent to:
if user != nil do
render(UserView, "show.html", data: user)
end
"""
def render_one(model, view, template, assigns \\ %{}) do
if model != nil do
assigns = to_map(assigns)
render view, template, assign_model(assigns, view, model)
end
end
defp to_map(assigns) when is_map(assigns), do: assigns
defp to_map(assigns) when is_list(assigns), do: :maps.from_list(assigns)
defp to_map(assigns), do: Dict.merge(%{}, assigns)
defp assign_model(assigns, view, model) do
as = Map.get(assigns, :as) || view.__resource__
Map.put(assigns, as, model)
end
@doc """
Renders the template and returns iodata.
"""
def render_to_iodata(module, template, assign) do
render(module, template, assign) |> encode(template)
end
@doc """
Renders the template and returns a string.
"""
def render_to_string(module, template, assign) do
render_to_iodata(module, template, assign) |> IO.iodata_to_binary
end
defp encode(content, template) do
if encoder = Phoenix.Template.format_encoder(template) do
encoder.encode_to_iodata!(content)
else
content
end
end
end
| 31.422343 | 101 | 0.67924 |
f73b2e81a37324b2ea52d10e6771a29ab5f5dbf2 | 20,800 | ex | Elixir | clients/logging/lib/google_api/logging/v2/api/sinks.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/logging/lib/google_api/logging/v2/api/sinks.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/logging/lib/google_api/logging/v2/api/sinks.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Logging.V2.Api.Sinks do
@moduledoc """
API calls for all endpoints tagged `Sinks`.
"""
alias GoogleApi.Logging.V2.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's writer_identity is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink.
## Parameters
* `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server
* `v2_id` (*type:* `String.t`) - Part of `parent`. Required. The resource in which to create the sink:
"projects/[PROJECT_ID]"
"organizations/[ORGANIZATION_ID]"
"billingAccounts/[BILLING_ACCOUNT_ID]"
"folders/[FOLDER_ID]"
Examples: "projects/my-logging-project", "organizations/123456789".
* `v2_id1` (*type:* `String.t`) - Part of `parent`. See documentation of `v2Id`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:uniqueWriterIdentity` (*type:* `boolean()`) - Optional. Determines the kind of IAM identity returned as writer_identity in the new sink. If this value is omitted or set to false, and if the sink's parent is a project, then the value returned as writer_identity is the same group or service account used by Logging before the addition of writer identities to this API. The sink's destination must be in the same project as the sink itself.If this field is set to true, or if the sink is owned by a non-project resource such as an organization, then the value of writer_identity will be a unique service account used only for exports from the new sink. For more information, see writer_identity in LogSink.
* `:body` (*type:* `GoogleApi.Logging.V2.Model.LogSink.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Logging.V2.Model.LogSink{}}` on success
* `{:error, info}` on failure
"""
@spec logging_sinks_create(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Logging.V2.Model.LogSink.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def logging_sinks_create(connection, v2_id, v2_id1, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:uniqueWriterIdentity => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v2/{v2Id}/{v2Id1}/sinks", %{
"v2Id" => URI.encode(v2_id, &URI.char_unreserved?/1),
"v2Id1" => URI.encode(v2_id1, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Logging.V2.Model.LogSink{}])
end
@doc """
Deletes a sink. If the sink has a unique writer_identity, then that service account is also deleted.
## Parameters
* `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server
* `v2_id` (*type:* `String.t`) - Part of `sinkName`. Required. The full resource name of the sink to delete, including the parent resource and the sink identifier:
"projects/[PROJECT_ID]/sinks/[SINK_ID]"
"organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
"billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
"folders/[FOLDER_ID]/sinks/[SINK_ID]"
Example: "projects/my-project-id/sinks/my-sink-id".
* `v2_id1` (*type:* `String.t`) - Part of `sinkName`. See documentation of `v2Id`.
* `sinks_id` (*type:* `String.t`) - Part of `sinkName`. See documentation of `v2Id`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Logging.V2.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec logging_sinks_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Logging.V2.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def logging_sinks_delete(connection, v2_id, v2_id1, sinks_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v2/{v2Id}/{v2Id1}/sinks/{sinksId}", %{
"v2Id" => URI.encode(v2_id, &URI.char_unreserved?/1),
"v2Id1" => URI.encode(v2_id1, &URI.char_unreserved?/1),
"sinksId" => URI.encode(sinks_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Logging.V2.Model.Empty{}])
end
@doc """
Gets a sink.
## Parameters
* `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server
* `v2_id` (*type:* `String.t`) - Part of `sinkName`. Required. The resource name of the sink:
"projects/[PROJECT_ID]/sinks/[SINK_ID]"
"organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
"billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
"folders/[FOLDER_ID]/sinks/[SINK_ID]"
Example: "projects/my-project-id/sinks/my-sink-id".
* `v2_id1` (*type:* `String.t`) - Part of `sinkName`. See documentation of `v2Id`.
* `sinks_id` (*type:* `String.t`) - Part of `sinkName`. See documentation of `v2Id`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Logging.V2.Model.LogSink{}}` on success
* `{:error, info}` on failure
"""
@spec logging_sinks_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Logging.V2.Model.LogSink.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def logging_sinks_get(connection, v2_id, v2_id1, sinks_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v2/{v2Id}/{v2Id1}/sinks/{sinksId}", %{
"v2Id" => URI.encode(v2_id, &URI.char_unreserved?/1),
"v2Id1" => URI.encode(v2_id1, &URI.char_unreserved?/1),
"sinksId" => URI.encode(sinks_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Logging.V2.Model.LogSink{}])
end
@doc """
Lists sinks.
## Parameters
* `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server
* `v2_id` (*type:* `String.t`) - Part of `parent`. Required. The parent resource whose sinks are to be listed:
"projects/[PROJECT_ID]"
"organizations/[ORGANIZATION_ID]"
"billingAccounts/[BILLING_ACCOUNT_ID]"
"folders/[FOLDER_ID]"
* `v2_id1` (*type:* `String.t`) - Part of `parent`. See documentation of `v2Id`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of nextPageToken in the response indicates that more results might be available.
* `:pageToken` (*type:* `String.t`) - Optional. If present, then retrieve the next batch of results from the preceding call to this method. pageToken must be the value of nextPageToken from the previous response. The values of other method parameters should be identical to those in the previous call.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Logging.V2.Model.ListSinksResponse{}}` on success
* `{:error, info}` on failure
"""
@spec logging_sinks_list(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Logging.V2.Model.ListSinksResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def logging_sinks_list(connection, v2_id, v2_id1, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v2/{v2Id}/{v2Id1}/sinks", %{
"v2Id" => URI.encode(v2_id, &URI.char_unreserved?/1),
"v2Id1" => URI.encode(v2_id1, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Logging.V2.Model.ListSinksResponse{}])
end
@doc """
Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: destination, and filter.The updated sink might also have a new writer_identity; see the unique_writer_identity field.
## Parameters
* `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server
* `v2_id` (*type:* `String.t`) - Part of `sinkName`. Required. The full resource name of the sink to update, including the parent resource and the sink identifier:
"projects/[PROJECT_ID]/sinks/[SINK_ID]"
"organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
"billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
"folders/[FOLDER_ID]/sinks/[SINK_ID]"
Example: "projects/my-project-id/sinks/my-sink-id".
* `v2_id1` (*type:* `String.t`) - Part of `sinkName`. See documentation of `v2Id`.
* `sinks_id` (*type:* `String.t`) - Part of `sinkName`. See documentation of `v2Id`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:uniqueWriterIdentity` (*type:* `boolean()`) - Optional. See sinks.create for a description of this field. When updating a sink, the effect of this field on the value of writer_identity in the updated sink depends on both the old and new values of this field:
If the old and new values of this field are both false or both true, then there is no change to the sink's writer_identity.
If the old value is false and the new value is true, then writer_identity is changed to a unique service account.
It is an error if the old value is true and the new value is set to false or defaulted to false.
* `:updateMask` (*type:* `String.t`) - Optional. Field mask that specifies the fields in sink that need an update. A sink field will be overwritten if, and only if, it is in the update mask. name and output only fields cannot be updated.An empty updateMask is temporarily treated as using the following mask for backwards compatibility purposes: destination,filter,includeChildren At some point in the future, behavior will be removed and specifying an empty updateMask will be an error.For a detailed FieldMask definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMaskExample: updateMask=filter.
* `:body` (*type:* `GoogleApi.Logging.V2.Model.LogSink.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Logging.V2.Model.LogSink{}}` on success
* `{:error, info}` on failure
"""
@spec logging_sinks_update(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Logging.V2.Model.LogSink.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def logging_sinks_update(connection, v2_id, v2_id1, sinks_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:uniqueWriterIdentity => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/v2/{v2Id}/{v2Id1}/sinks/{sinksId}", %{
"v2Id" => URI.encode(v2_id, &URI.char_unreserved?/1),
"v2Id1" => URI.encode(v2_id1, &URI.char_unreserved?/1),
"sinksId" => URI.encode(sinks_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Logging.V2.Model.LogSink{}])
end
end
| 52.926209 | 716 | 0.639712 |
f73b366e648b3758800b823f186b882dd01fbb6c | 934 | ex | Elixir | apps/ello_v2/web/controllers/manage/activity_count_controller.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 16 | 2017-06-21T21:31:20.000Z | 2021-05-09T03:23:26.000Z | apps/ello_v2/web/controllers/manage/activity_count_controller.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 25 | 2017-06-07T12:18:28.000Z | 2018-06-08T13:27:43.000Z | apps/ello_v2/web/controllers/manage/activity_count_controller.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 3 | 2018-06-14T15:34:07.000Z | 2022-02-28T21:06:13.000Z | defmodule Ello.V2.Manage.ActivityCountController do
use Ello.V2.Web, :controller
alias Ello.Core.Contest
plug Ello.Auth.RequireUser
plug Manage.OwnedArtistInvite
def all(%{assigns: %{artist_invite: inv}} = conn, _) do
comments = Task.async(Contest, :artist_invite_comment_count, [%{artist_invite: inv}])
loves = Task.async(Contest, :artist_invite_love_count, [%{artist_invite: inv}])
reposts = Task.async(Contest, :artist_invite_repost_count, [%{artist_invite: inv}])
mentions = Task.async(Contest, :artist_invite_mention_count, [%{artist_invite: inv}])
followers = Task.async(Contest, :artist_invite_follower_count, [%{artist_invite: inv}])
api_render(conn, artist_invite: inv, data: %{
comments: Task.await(comments),
loves: Task.await(loves),
reposts: Task.await(reposts),
followers: Task.await(followers),
mentions: Task.await(mentions),
})
end
end
| 38.916667 | 91 | 0.708779 |
f73b50b8818bdc750cdecfa3c1eea17094fab1a6 | 1,976 | exs | Elixir | poc_elixir/config/prod.exs | fcevado/minha-receita | ebd5cca95115d878934a0f762a8e92d3f8f5b495 | [
"MIT"
] | null | null | null | poc_elixir/config/prod.exs | fcevado/minha-receita | ebd5cca95115d878934a0f762a8e92d3f8f5b495 | [
"MIT"
] | null | null | null | poc_elixir/config/prod.exs | fcevado/minha-receita | ebd5cca95115d878934a0f762a8e92d3f8f5b495 | [
"MIT"
] | null | null | null | use Mix.Config
# For production, don't forget to configure the url host
# to something meaningful, Phoenix uses this information
# when generating URLs.
#
# Note we also include the path to a cache manifest
# containing the digested version of static files. This
# manifest is generated by the `mix phx.digest` task,
# which you should run after static files are built and
# before starting your production server.
config :receita, ReceitaWeb.Endpoint,
url: [host: "example.com", port: 80],
cache_static_manifest: "priv/static/cache_manifest.json"
# Do not print debug messages in production
config :logger, level: :info
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :receita, ReceitaWeb.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [
# :inet6,
# port: 443,
# cipher_suite: :strong,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")
# ]
#
# The `cipher_suite` is set to `:strong` to support only the
# latest and more secure SSL ciphers. This means old browsers
# and clients may not be supported. You can set it to
# `:compatible` for wider support.
#
# `:keyfile` and `:certfile` expect an absolute path to the key
# and cert in disk or a relative path inside priv, for example
# "priv/ssl/server.key". For all supported SSL configuration
# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1
#
# We also recommend setting `force_ssl` in your endpoint, ensuring
# no data is ever sent via http, always redirecting to https:
#
# config :receita, ReceitaWeb.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# Finally import the config/prod.secret.exs which loads secrets
# and configuration from environment variables.
import_config "prod.secret.exs"
| 35.285714 | 66 | 0.713563 |
f73b6fad6cd4fd500410a0bfa0daa9b29a1eba85 | 3,523 | ex | Elixir | lib/phoenix.ex | alexgriff/phoenix | 87244793035572d9b119a90b1294db8e34961f8b | [
"MIT"
] | 1 | 2019-04-24T09:28:15.000Z | 2019-04-24T09:28:15.000Z | lib/phoenix.ex | alexgriff/phoenix | 87244793035572d9b119a90b1294db8e34961f8b | [
"MIT"
] | null | null | null | lib/phoenix.ex | alexgriff/phoenix | 87244793035572d9b119a90b1294db8e34961f8b | [
"MIT"
] | null | null | null | defmodule Phoenix do
@moduledoc """
This is the documentation for the Phoenix project.
By default, Phoenix applications depend on the following packages:
* [Ecto](https://hexdocs.pm/ecto) - a language integrated query and
database wrapper
* [Phoenix](https://hexdocs.pm/phoenix) - the Phoenix web framework
(these docs)
* [Phoenix.js](js) - Phoenix Channels JavaScript client
* [Phoenix PubSub](https://hexdocs.pm/phoenix_pubsub) - a distributed
pub/sub system with presence support
* [Phoenix HTML](https://hexdocs.pm/phoenix_html) - conveniences for
working with HTML in Phoenix
* [Plug](https://hexdocs.pm/plug) - a specification and conveniences
for composable modules in between web applications
* [Gettext](https://hexdocs.pm/gettext) - Internationalization and
localization through [`gettext`](https://www.gnu.org/software/gettext/)
There are also optional packages depending on your configuration:
* [Phoenix PubSub Redis](https://hexdocs.pm/phoenix_pubsub_redis) - use
Redis to power the Phoenix PubSub system
"""
use Application
@doc false
def start(_type, _args) do
# Warm up caches
_ = Phoenix.Template.engines()
_ = Phoenix.Template.format_encoder("index.html")
warn_on_missing_json_library()
# Configure proper system flags from Phoenix only
if stacktrace_depth = Application.get_env(:phoenix, :stacktrace_depth) do
:erlang.system_flag(:backtrace_depth, stacktrace_depth)
end
# Start the supervision tree
import Supervisor.Spec
children = [
# Code reloading must be serial across all Phoenix apps
worker(Phoenix.CodeReloader.Server, []),
supervisor(Phoenix.Transports.LongPoll.Supervisor, [])
]
Supervisor.start_link(children, strategy: :one_for_one, name: Phoenix.Supervisor)
end
# TODO v2: swap Poison default with Jason
# From there we can ditch explicit config for new projects
@doc """
Returns the configured JSON encoding library for Phoenix.
To customize the JSON library, including the following
in your `config/config.exs`:
config :phoenix, :json_library, Jason
"""
def json_library do
Application.get_env(:phoenix, :json_library, Poison)
end
@doc false
# Returns the `:init_mode` to pass to `Plug.Builder.compile/3`.
def plug_init_mode do
Application.get_env(:phoenix, :plug_init_mode, :compile)
end
defp warn_on_missing_json_library do
configured_lib = Application.get_env(:phoenix, :json_library)
default_lib = json_library()
cond do
configured_lib && not Code.ensure_loaded?(configured_lib) ->
warn_json configured_lib, """
found #{inspect(configured_lib)} in your application configuration
for Phoenix JSON encoding, but failed to load the library.
"""
not Code.ensure_loaded?(default_lib) and Code.ensure_loaded?(Jason) ->
warn_json(Jason)
not Code.ensure_loaded?(default_lib) ->
warn_json(default_lib)
true -> :ok
end
end
defp warn_json(lib, preabmle \\ nil) do
IO.warn """
#{preabmle || "failed to load #{inspect(lib)} for Phoenix JSON encoding"}
(module #{inspect(lib)} is not available).
Ensure #{inspect(lib)} exists in your deps in mix.exs,
and you have configured Phoenix to use it for JSON encoding by
verifying the following exists in your config/config.exs:
config :phoenix, :json_library, #{inspect(lib)}
"""
end
end
| 30.634783 | 85 | 0.700255 |
f73b9eee4d07b0080dcb95f1f47fc099bdf367ef | 197 | exs | Elixir | examples/bloggy/test/bloggy_web/controllers/page_controller_test.exs | wojtekmach/resourceful | 8425140aa1e89dfababcb2faa7bc4e2f59722661 | [
"Apache-2.0"
] | 1 | 2020-01-06T00:38:43.000Z | 2020-01-06T00:38:43.000Z | examples/bloggy/test/bloggy_web/controllers/page_controller_test.exs | wojtekmach/resourceful | 8425140aa1e89dfababcb2faa7bc4e2f59722661 | [
"Apache-2.0"
] | null | null | null | examples/bloggy/test/bloggy_web/controllers/page_controller_test.exs | wojtekmach/resourceful | 8425140aa1e89dfababcb2faa7bc4e2f59722661 | [
"Apache-2.0"
] | null | null | null | defmodule BloggyWeb.PageControllerTest do
use BloggyWeb.ConnCase
test "GET /", %{conn: conn} do
conn = get conn, "/"
assert html_response(conn, 200) =~ "Welcome to Phoenix!"
end
end
| 21.888889 | 60 | 0.680203 |
f73bbbaf765a7837359d7b59dc209a95c1daf52f | 9,931 | ex | Elixir | lib/chroxy/chrome_server.ex | suddenrushofsushi/chroxy | 2c7d3fe9a376557801016243d77be382ae3a0de8 | [
"MIT"
] | null | null | null | lib/chroxy/chrome_server.ex | suddenrushofsushi/chroxy | 2c7d3fe9a376557801016243d77be382ae3a0de8 | [
"MIT"
] | null | null | null | lib/chroxy/chrome_server.ex | suddenrushofsushi/chroxy | 2c7d3fe9a376557801016243d77be382ae3a0de8 | [
"MIT"
] | null | null | null | defmodule Chroxy.ChromeServer.Supervisor do
@moduledoc """
`DynamicSupervisor` for `Chroxy.ChromeServer`
"""
@sup __MODULE__
@worker Chroxy.ChromeServer
def child_spec() do
{DynamicSupervisor, name: @sup, strategy: :one_for_one}
end
def start_child(args) do
DynamicSupervisor.start_child(@sup, @worker.child_spec(args))
end
def which_children() do
DynamicSupervisor.which_children(@sup)
end
end
defmodule Chroxy.ChromeServer do
@moduledoc """
`GenServer` process which manages a port connection to a Chrome
browser OS Process as well as a `ChromeRemoteInterface.Session` to
the browser instance providing command and control over the instance.
The `stdout` and `stderr` messages from the os process are captured
and are used to determine state transitions, namely when the browser
is ready to start accepting connections, and when the browser enters
a critical error state and must be terminated.
"""
use GenServer
require Logger
alias ChromeRemoteInterface.Session
@ready_check_ms 30_000
def child_spec(opts) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [opts]},
restart: :permanent,
shutdown: 5000,
type: :worker
}
end
@doc """
Spanws a `Chroxy.ChromeServer` process which in turn starts an underlying
chrome browser os process, which is managed by a shared lifetime allowing
for managing Chrome Browser within an OTP Supervision model.
"""
def start_link(args) do
GenServer.start_link(__MODULE__, args)
end
@doc """
Blocks and performs a poll of the underlying `Chroxy.ChromeServer` to determine when
the chrome browser instance is ready for interaction.
Keyword `opts`:
* `:retries` - number to times to poll for _ready_ state.
* `:wait_ms` - how long to _sleep_ between polling calls.
* `:crash_dumps_dir` - where chrome should write crash dumps.
"""
def ready(server, opts \\ []) do
retries = Keyword.get(opts, :retries, 5)
wait_ms = Keyword.get(opts, :wait_ms, 1000)
try do
case GenServer.call(server, :ready, 30_000) do
:not_ready ->
if retries > 0 do
Process.sleep(wait_ms)
ready(server, retries: retries - 1, wait_ms: wait_ms)
else
:timeout
end
:ready ->
:ready
end
catch
:exit, _ ->
Logger.error("ChromeServer #{inspect(server)} did not reply to ready request")
:timeout
end
end
@doc """
Lists page sessions currently open to the chrome instance.
"""
def list_pages(server) do
GenServer.call(server, :list_pages)
end
@doc """
Creates a new chrome page (tab) within the chrome instance.
"""
def new_page(server) do
GenServer.call(server, :new_page)
end
@doc """
Closes the page in the chrome instance.
"""
def close_page(server, page) do
GenServer.cast(server, {:close_page, page})
end
@doc """
Closes all open pages in the chrome instance.
"""
def close_all_pages(server) do
GenServer.cast(server, :close_all_pages)
end
##
# GenServer callbacks
@doc false
def terminate(reason, state) do
Logger.warn("ChromeServer terminating - #{inspect(state)} - reason: #{reason}")
:ok
end
@doc false
def init(args) do
config = Application.get_env(:chroxy, __MODULE__)
opts =
default_opts()
|> Keyword.merge(config)
|> Keyword.merge(args)
page_wait_ms = Keyword.get(config, :page_wait_ms) |> String.to_integer()
send(self(), :launch)
Process.send_after(self(), :stop_if_not_ready, @ready_check_ms)
{:ok, %{options: opts, session: nil, page_wait_ms: page_wait_ms}}
end
@doc false
def handle_call(_, _from, state = %{session: nil}) do
{:reply, :not_ready, state}
end
def handle_call(:ready, _from, state = %{session: _session}) do
{:reply, :ready, state}
end
def handle_call(:list_pages, _from, state = %{session: session}) do
{:ok, pages} = Session.list_pages(session)
{:reply, pages, state}
end
def handle_call(:new_page, _from, state = %{session: session, page_wait_ms: page_wait_ms}) do
{:ok, page} = Session.new_page(session)
Process.sleep(page_wait_ms)
{:reply, page, state}
end
@doc false
def handle_cast({:close_page, page}, state = %{session: session}) do
Session.close_page(session, page["id"])
{:noreply, state}
end
def handle_cast(:close_all_pages, state = %{session: session}) do
{:ok, pages} = Session.list_pages(session)
Enum.each(pages, fn page ->
Session.close_page(session, page["id"])
end)
{:noreply, state}
end
@doc false
def handle_info(:launch, state = %{options: opts}) do
value_flags = ~w(
--remote-debugging-port=#{opts[:chrome_port]}
--crash-dumps-dir=#{opts[:crash_dumps_dir]}
--v=#{opts[:verbose_logging]}
)
chrome_path = String.replace(opts[:chrome_path], " ", "\\ ")
command =
[chrome_path, opts[:chrome_flags], value_flags]
|> List.flatten()
|> Enum.join(" ")
{:ok, pid, os_pid} = Exexec.run_link(command, exec_options())
state = Map.merge(%{command: command, pid: pid, os_pid: os_pid}, state)
{:noreply, state}
end
def handle_info(:stop_if_not_ready, state = %{session: nil, os_pid: os_pid}) do
Logger.warn("Chrome failed to start within #{@ready_check_ms} ms, self terminating.")
Exexec.stop_and_wait(os_pid)
{:stop, :normal, state}
end
def handle_info(:stop_if_not_ready, state) do
{:noreply, state}
end
@log_head_size 19 * 8
def handle_info({:stdout, pid, <<_::size(@log_head_size), ":WARNING:", msg::binary>>}, state) do
msg = String.replace(msg, "\r\n", "")
Logger.warn("[CHROME: #{inspect(pid)}] #{inspect(msg)}")
{:noreply, state}
end
def handle_info(
{source, pid,
<<_::size(@log_head_size), ":ERROR:socket_posix.cc(143)] bind()", _msg::binary>>},
state
)
when source == :stdout or source == :stderr do
Logger.error("[CHROME: #{inspect(pid)}] Address / Port already in use. terminating")
Exexec.stop_and_wait(pid)
{:stop, :normal, state}
end
def handle_info(
{:stdout, pid,
<<_::size(@log_head_size), ":ERROR:crash_handler_host_linux.cc", _rest::binary>> = msg},
state
) do
Logger.error("[CHROME: #{inspect(pid)}] #{msg}")
Logger.error("[CHROME: #{inspect(pid)}] Critical State - Terminating.")
Exexec.stop_and_wait(pid)
{:stop, :normal, state}
end
def handle_info({:stdout, pid, <<_::size(@log_head_size), ":ERROR:", msg::binary>>}, state) do
msg = String.replace(msg, "\r\n", "")
Logger.error("[CHROME: #{inspect(pid)}] #{inspect(msg)}")
{:noreply, state}
end
def handle_info({device, pid, <<_::size(@log_head_size), ":VERBOSE1:", msg::binary>>}, state)
when device == :stdout or device == :stderr do
msg = String.replace(msg, "\r\n", "")
Logger.debug("[CHROME: #{inspect(pid)}] #{inspect(msg)}")
{:noreply, state}
end
# TODO refactor messages from logs to remove "\r\n" once / create module to
# handle log parsing
def handle_info(
{:stdout, pid, <<"\r\nDevTools listening on ", _rest::binary>> = msg},
state = %{options: opts}
) do
msg = String.replace(msg, "\r\n", "")
Logger.info("[CHROME: #{inspect(pid)}] #{inspect(msg)}")
chrome_port = Keyword.get(opts, :chrome_port)
session = Session.new(port: chrome_port)
{:noreply, %{state | session: session}}
end
def handle_info(
{:stdout, pid, <<"DevTools listening on ", _rest::binary>> = msg},
state = %{options: opts}
) do
msg = String.replace(msg, "\r\n", "")
Logger.info("[CHROME: #{inspect(pid)}] #{inspect(msg)}")
chrome_port = Keyword.get(opts, :chrome_port)
session = Session.new(port: chrome_port)
{:noreply, %{state | session: session}}
end
def handle_info({:stderr, pid, <<"crash_handler_host_linux.cc", _rest::binary>> = msg}, state) do
Logger.error("[CHROME: #{inspect(pid)}] #{msg}")
Logger.error("[CHROME: #{inspect(pid)}] Critical State - Terminating.")
Exexec.stop_and_wait(pid)
{:stop, :normal, state}
end
def handle_info({:stdout, pid, <<"Failed to generate minidump.", _rest::binary>> = msg}, state) do
Logger.error("[CHROME: #{inspect(pid)}] #{msg}")
Logger.error("[CHROME: #{inspect(pid)}] Critical State - Terminating.")
Exexec.stop_and_wait(pid)
{:stop, :normal, state}
end
##
# Catch all
def handle_info({:stdout, pid, msg}, state) do
msg = String.replace(msg, "\r\n", "")
unless msg == "" do
Logger.info("[CHROME: #{inspect(pid)}] stdout: #{inspect(msg)}")
end
{:noreply, state}
end
def handle_info({:stderr, pid, msg}, state) do
msg = String.replace(msg, "\r\n", "")
unless msg == "" do
Logger.error("[CHROME: #{inspect(pid)}] stderr: #{inspect(msg)}")
end
{:noreply, state}
end
##
# Internal
defp exec_options do
%{pty: true, stdin: true, stdout: true, stderr: true}
end
defp default_opts do
[
chrome_port: 9222,
chrome_path: chrome_path(),
chrome_flags: ~w(
--headless
--disable-gpu
--disable-translate
--disable-extensions
--disable-background-networking
--safebrowsing-disable-auto-update
--enable-logging
--disable-sync
--metrics-recording-only
--disable-default-apps
--mute-audio
--no-first-run
--no-sandbox
--incognito
--ignore-certificate-errors
),
verbose_logging: 0,
crash_dumps_dir: "/tmp"
]
end
defp chrome_path do
case :os.type() do
{:unix, :darwin} ->
"/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome"
{:unix, _} ->
"/usr/bin/google-chrome"
end
end
end
| 27.740223 | 100 | 0.632464 |
f73bceed6e96329b413b42c022581eff46af7459 | 1,662 | ex | Elixir | crawler_challenge/lib/crawler_challenge_web/controllers/search_controller.ex | tuliostarling/crawler-challenge | 1b948769db200d09ac0481b9fd71a175d876d20f | [
"Apache-2.0"
] | null | null | null | crawler_challenge/lib/crawler_challenge_web/controllers/search_controller.ex | tuliostarling/crawler-challenge | 1b948769db200d09ac0481b9fd71a175d876d20f | [
"Apache-2.0"
] | 3 | 2021-05-08T08:50:39.000Z | 2022-02-10T19:40:38.000Z | crawler_challenge/lib/crawler_challenge_web/controllers/search_controller.ex | tuliostarling/elixir-crawler | 1b948769db200d09ac0481b9fd71a175d876d20f | [
"Apache-2.0"
] | null | null | null | defmodule CrawlerChallengeWeb.SearchController do
use CrawlerChallengeWeb, :controller
alias CrawlerChallenge.{Courts, NebulexCache, Processes, Searches}
alias CrawlerChallenge.Courts.Court
def index(conn, %{"court" => court, "process_n" => process_n}) do
with %Court{} = court <- Courts.get_court_by_name(court),
{:ok, :valid_process_number} <- Processes.valid_process_number(process_n),
{:invalid, nil} <- Processes.validate_date(process_n) do
do_crawl(conn, court, process_n)
else
{:error, :invalid_process_number} ->
conn
|> put_status(401)
|> json(%{message: "Número do processo inválido"})
nil ->
conn
|> put_status(401)
|> json(%{message: "Preencha os dados do form: Campo 'Tribunal'"})
{:valid, process} ->
conn
|> put_status(:ok)
|> json(%{data: process})
end
end
def do_crawl(conn, court, process_n) do
with {:ok, show_url} <- Searches.return_show_url(process_n),
{:ok, body} <- Searches.get_html_body(show_url),
{:ok, crawled_data} <- Searches.get_crawled_data(body),
{:ok, %{process: process}} <-
Processes.insert_all_data(process_n, court, crawled_data) do
process =
Processes.get_process_by_id_and_preload(
process,
[:details, :movements, :parties, :court]
)
NebulexCache.set_cache(process.process_number, process.id)
conn
|> put_status(:ok)
|> json(%{data: process})
else
{:error, reason} ->
conn
|> put_status(401)
|> json(%{error: reason})
end
end
end
| 30.218182 | 83 | 0.611312 |
f73be581daa075d24778545810f59775bf5e5ac3 | 5,695 | ex | Elixir | lib/sanbase/timeline/filter.ex | santiment/sanbase2 | 9ef6e2dd1e377744a6d2bba570ea6bd477a1db31 | [
"MIT"
] | 81 | 2017-11-20T01:20:22.000Z | 2022-03-05T12:04:25.000Z | lib/sanbase/timeline/filter.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 359 | 2017-10-15T14:40:53.000Z | 2022-01-25T13:34:20.000Z | lib/sanbase/timeline/filter.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 16 | 2017-11-19T13:57:40.000Z | 2022-02-07T08:13:02.000Z | defmodule Sanbase.Timeline.Filter do
import Ecto.Query
alias Sanbase.Timeline.Query
alias Sanbase.UserList
alias Sanbase.Alert.UserTrigger
alias Sanbase.Insight.Post
alias Sanbase.Repo
def filter_by_query(query, filter_by) do
query
|> filter_by_type_query(filter_by)
end
def filter_by_query(query, filter_by, user_id) do
query
|> filter_by_not_seen(filter_by, user_id)
|> filter_by_author_query(filter_by, user_id)
|> filter_by_watchlists_query(filter_by)
|> filter_by_assets_query(filter_by, user_id)
|> filter_by_type_query(filter_by)
end
defp filter_by_not_seen(query, %{only_not_seen: true}, user_id) do
event_id = Sanbase.Timeline.SeenEvent.last_seen_for_user(user_id)
filter_by_last_seen_event(query, %{last_seen_event_id: event_id})
end
defp filter_by_not_seen(query, _, _), do: query
defp filter_by_last_seen_event(query, %{last_seen_event_id: last_seen_event_id})
when last_seen_event_id != nil do
from(event in query, where: event.id > ^last_seen_event_id)
end
defp filter_by_last_seen_event(query, _), do: query
defp filter_by_type_query(query, %{type: :insight}) do
from(event in query, join: p in assoc(event, :post), where: not p.is_pulse)
end
defp filter_by_type_query(query, %{type: :pulse}) do
from(event in query, join: p in assoc(event, :post), where: p.is_pulse)
end
defp filter_by_type_query(query, %{type: :alert}) do
from(event in query, join: p in assoc(event, :user_trigger))
end
defp filter_by_type_query(query, _), do: query
defp filter_by_author_query(query, %{author: :all}, user_id) do
Query.events_by_sanfamily_or_followed_users_or_own_query(query, user_id)
end
defp filter_by_author_query(query, %{author: :sanfam}, _) do
Query.events_by_sanfamily_query(query)
end
defp filter_by_author_query(query, %{author: :followed}, user_id) do
Query.events_by_followed_users_query(query, user_id)
end
defp filter_by_author_query(query, %{author: :own}, user_id) do
Query.events_by_current_user_query(query, user_id)
end
defp filter_by_author_query(query, _, user_id) do
Query.events_by_sanfamily_or_followed_users_or_own_query(query, user_id)
end
defp filter_by_watchlists_query(query, %{watchlists: watchlists})
when is_list(watchlists) and length(watchlists) > 0 do
from(event in query, where: event.user_list_id in ^watchlists)
end
defp filter_by_watchlists_query(query, _), do: query
defp filter_by_assets_query(query, %{assets: assets} = filter_by, user_id)
when is_list(assets) and length(assets) > 0 do
{slugs, tickers} = get_slugs_and_tickers_by_asset_list(assets)
watchlist_ids = get_watchlist_ids_by_asset_list(assets, filter_by, user_id)
insight_ids = get_insight_ids_by_asset_list({slugs, tickers}, filter_by, user_id)
trigger_ids = get_trigger_ids_by_asset_list({slugs, tickers}, filter_by, user_id)
from(event in query,
where:
event.user_list_id in ^watchlist_ids or
event.post_id in ^insight_ids or
event.user_trigger_id in ^trigger_ids
)
end
defp filter_by_assets_query(query, _, _), do: query
defp get_watchlist_ids_by_asset_list(assets, filter_by, user_id) do
from(
entity in UserList,
join: li in assoc(entity, :list_items),
where: li.project_id in ^assets,
select: entity.id
)
|> filter_by_author_query(filter_by, user_id)
|> Repo.all()
end
defp get_slugs_and_tickers_by_asset_list(assets) do
project_slugs_and_tickers =
from(p in Sanbase.Model.Project, where: p.id in ^assets, select: [p.slug, p.ticker])
|> Repo.all()
slugs = project_slugs_and_tickers |> Enum.map(fn [slug, _] -> slug end)
tickers = project_slugs_and_tickers |> Enum.map(fn [_, ticker] -> ticker end)
{slugs, tickers}
end
defp get_insight_ids_by_asset_list({slugs, tickers}, filter_by, user_id) do
tickers_lc = Enum.map(tickers, &String.downcase/1)
tickers_uc = Enum.map(tickers, &String.upcase/1)
from(
entity in Post,
join: t in assoc(entity, :tags),
where: t.name in ^slugs or t.name in ^tickers_uc or t.name in ^tickers_lc,
select: entity.id
)
|> filter_by_author_query(filter_by, user_id)
|> Repo.all()
end
defp get_trigger_ids_by_asset_list({slugs, tickers}, filter_by, user_id) do
triggers =
from(ut in UserTrigger, select: [ut.id, fragment("trigger->'settings'->'target'")])
|> filter_by_author_query(filter_by, user_id)
|> Repo.all()
triggers
|> Enum.filter(fn [_id, target] -> filter_by_trigger_target(target, {slugs, tickers}) end)
|> Enum.map(fn [id, _] -> id end)
end
defp filter_by_trigger_target(%{"slug" => slug}, {slugs, _tickers}) when is_binary(slug),
do: slug in slugs
defp filter_by_trigger_target(%{"slug" => target_slugs}, {slugs, _tickers})
when is_binary(target_slugs) do
has_intersection?(target_slugs, slugs)
end
defp filter_by_trigger_target(%{"word" => word}, {slugs, tickers}) when is_binary(word) do
word in slugs or word in tickers or String.upcase(word) in tickers
end
defp filter_by_trigger_target(%{"word" => words}, {slugs, tickers}) when is_list(words) do
tickers_lc = Enum.map(tickers, &String.downcase/1)
tickers_uc = Enum.map(tickers, &String.upcase/1)
has_intersection?(words, slugs) or has_intersection?(words, tickers_lc) or
has_intersection?(words, tickers_uc)
end
defp filter_by_trigger_target(_, _), do: false
defp has_intersection?(list1, list2) do
MapSet.intersection(MapSet.new(list1), MapSet.new(list2)) |> MapSet.size() > 0
end
end
| 33.5 | 94 | 0.718349 |
f73bf57fd55dbd2921949612c2707fe2e443f011 | 867 | exs | Elixir | test/controllers/contact_controller_test.exs | cncgl/phoenix-sample | 81b1c807a40e972df93ccc4063395ddf48bf4e2e | [
"MIT"
] | 1 | 2016-01-01T12:55:25.000Z | 2016-01-01T12:55:25.000Z | test/controllers/contact_controller_test.exs | cncgl/phoenix-todo | 81b1c807a40e972df93ccc4063395ddf48bf4e2e | [
"MIT"
] | 1 | 2015-09-10T13:41:51.000Z | 2015-09-10T13:41:51.000Z | test/controllers/contact_controller_test.exs | cncgl/phoenix-todo | 81b1c807a40e972df93ccc4063395ddf48bf4e2e | [
"MIT"
] | null | null | null | defmodule HelloPhoenix.ContactControllerTest do
# use ExUnit.Case, async: false
# use Plug.Test
alias HelloPhoenix.Contact
alias HelloPhoenix.Repo
# alias Ecto.Adapters.SQL
use HelloPhoenix.ConnCase
# setup do
# SQL.begin_test_transaction(Repo)
#
# on_exit fn ->
# SQL.rollback_test_transaction(Repo)
# end
# end
# test "/index returns a list of contacts" do
# IO.puts "test"
# contacts_as_json =
# %Contact{name: "Gumbo", phone: "(801) 555-5555"}
# Repo.insert contacts_as_json
# Poison.encode! contacts_as_json
# response = conn(:get, "/contacts")
# |> send_request
# assert response.status == 200
# assert response.resp_body == contacts_as_json
# end
defp send_request(conn) do
conn
|> put_private(:plug_skip_csrf_protection, true)
|> HelloPhoenix.Endpoint.call([])
end
end
| 22.815789 | 55 | 0.679354 |
f73c3096c9497cee967c98e6cb80009f73b06caa | 4,797 | ex | Elixir | lib/quantum/executor.ex | kianmeng/quantum-core | 24997fb649d778f654c1adad0006f7ad529a1184 | [
"Apache-2.0"
] | null | null | null | lib/quantum/executor.ex | kianmeng/quantum-core | 24997fb649d778f654c1adad0006f7ad529a1184 | [
"Apache-2.0"
] | null | null | null | lib/quantum/executor.ex | kianmeng/quantum-core | 24997fb649d778f654c1adad0006f7ad529a1184 | [
"Apache-2.0"
] | null | null | null | defmodule Quantum.Executor do
@moduledoc false
# Task to actually execute a Task
use Task
require Logger
alias Quantum.{
Job,
NodeSelectorBroadcaster.Event,
TaskRegistry
}
alias __MODULE__.StartOpts
@spec start_link(StartOpts.t(), Event.t()) :: {:ok, pid}
def start_link(opts, %Event{job: job, node: node}) do
Task.start_link(fn ->
execute(opts, job, node)
end)
end
@spec execute(StartOpts.t(), Job.t(), Node.t()) :: :ok
# Execute task on all given nodes without checking for overlap
defp execute(
%StartOpts{
task_supervisor_reference: task_supervisor,
debug_logging: debug_logging,
scheduler: scheduler
},
%Job{overlap: true} = job,
node
) do
run(node, job, task_supervisor, debug_logging, scheduler)
:ok
end
# Execute task on all given nodes with checking for overlap
defp execute(
%StartOpts{
task_supervisor_reference: task_supervisor,
task_registry_reference: task_registry,
debug_logging: debug_logging,
scheduler: scheduler
},
%Job{overlap: false, name: job_name} = job,
node
) do
debug_logging &&
Logger.debug(fn ->
{"Start execution of job", node: Node.self(), name: job_name}
end)
case TaskRegistry.mark_running(task_registry, job_name, node) do
:marked_running ->
%Task{ref: ref} = run(node, job, task_supervisor, debug_logging, scheduler)
receive do
{^ref, _} ->
TaskRegistry.mark_finished(task_registry, job_name, node)
{:DOWN, ^ref, _, _, _} ->
TaskRegistry.mark_finished(task_registry, job_name, node)
:ok
end
_ ->
:ok
end
end
# Ececute the given function on a given node via the task supervisor
@spec run(Node.t(), Job.t(), GenServer.server(), boolean(), atom()) :: Task.t()
defp run(
node,
%Job{name: job_name, task: task} = job,
task_supervisor,
debug_logging,
scheduler
) do
debug_logging &&
Logger.debug(fn ->
{"Task for job started on node", node: Node.self(), name: job_name, started_on: node}
end)
Task.Supervisor.async_nolink({task_supervisor, node}, fn ->
debug_logging &&
Logger.debug(fn ->
{"Execute started for job", node: Node.self(), name: job_name}
end)
# Note: we are intentionally mimicking the ":telemetry.span" here to keep current functionality
start_monotonic_time = :erlang.monotonic_time()
:telemetry.execute([:quantum, :job, :start], %{system_time: start_monotonic_time}, %{
job: job,
node: node,
scheduler: scheduler
})
try do
execute_task(task)
catch
type, value ->
debug_logging &&
Logger.debug(fn ->
{
"Execution failed for job",
node: Node.self(), name: job_name, type: type, value: value
}
end)
log_exception(type, value, __STACKTRACE__)
duration = :erlang.monotonic_time() - start_monotonic_time
:telemetry.execute([:quantum, :job, :exception], %{duration: duration}, %{
job: job,
node: node,
reason: value,
stacktrace: __STACKTRACE__,
scheduler: scheduler
})
else
result ->
debug_logging &&
Logger.debug(fn ->
{"Execution ended for job", node: Node.self(), name: job_name, result: result}
end)
duration = :erlang.monotonic_time() - start_monotonic_time
:telemetry.execute([:quantum, :job, :stop], %{duration: duration}, %{
job: job,
node: node,
scheduler: scheduler,
result: result
})
end
:ok
end)
end
# Run function
@spec execute_task(Quantum.Job.task()) :: any
defp execute_task({mod, fun, args}) do
:erlang.apply(mod, fun, args)
end
defp execute_task(fun) when is_function(fun, 0) do
fun.()
end
def log_exception(kind, reason, stacktrace) do
reason = Exception.normalize(kind, reason, stacktrace)
# TODO: Remove in a future version and make elixir 1.10 minimum requirement
if Version.match?(System.version(), "< 1.10.0") do
Logger.error(Exception.format(kind, reason, stacktrace))
else
crash_reason =
case kind do
:throw -> {{:nocatch, reason}, stacktrace}
_ -> {reason, stacktrace}
end
Logger.error(
Exception.format(kind, reason, stacktrace),
crash_reason: crash_reason
)
end
end
end
| 26.798883 | 101 | 0.580988 |
f73c345ba293f1a714449d7df849c22c45521a69 | 2,610 | exs | Elixir | mix.exs | smartrent/beamware | 504fb50805c66a2985ea9587b152978cd41dc552 | [
"Apache-2.0"
] | 10 | 2018-04-12T18:16:40.000Z | 2018-04-14T06:05:42.000Z | mix.exs | nerves-hub/nerveshub | 8421aca4e5a9584c60913279b1dfc9e7c241bb6c | [
"Apache-2.0"
] | 13 | 2018-05-25T19:31:49.000Z | 2018-05-31T14:27:43.000Z | mix.exs | smartrent/beamware | 504fb50805c66a2985ea9587b152978cd41dc552 | [
"Apache-2.0"
] | 2 | 2018-04-12T18:19:47.000Z | 2018-04-12T18:57:46.000Z | defmodule NervesHubUmbrella.MixProject do
use Mix.Project
def project do
[
version: "0.1.0",
apps_path: "apps",
start_permanent: Mix.env() == :prod,
deps: deps(),
test_coverage: [tool: ExCoveralls],
aliases: aliases(),
elixirc_paths: elixirc_paths(Mix.env()),
dialyzer: [
plt_add_apps: [:ex_unit, :mix],
ignore_warnings: "dialyzer.ignore-warnings"
],
releases: [
nerves_hub_www: [
steps: [:assemble],
include_executables_for: [:unix],
runtime_config_path: "apps/nerves_hub_www/config/release.exs",
reboot_system_after_config: true,
applications: [
nerves_hub_www: :permanent
]
],
nerves_hub_device: [
steps: [:assemble],
include_executables_for: [:unix],
runtime_config_path: "apps/nerves_hub_device/config/release.exs",
reboot_system_after_config: true,
applications: [
nerves_hub_device: :permanent
]
],
nerves_hub_api: [
steps: [:assemble],
include_executables_for: [:unix],
runtime_config_path: "apps/nerves_hub_api/config/release.exs",
reboot_system_after_config: true,
applications: [
nerves_hub_api: :permanent
]
]
]
]
end
# Dependencies listed here are available only for this
# project and cannot be accessed from applications inside
# the apps folder.
#
# Run "mix help deps" for examples and options.
defp deps do
[
# {:excoveralls, "~> 0.8", only: :test},
{:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false},
{:mix_test_watch, "~> 1.0", only: :test, runtime: false},
{:recon, "~> 2.5"},
{:base62, "~> 1.2"}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to create, migrate and run the seeds file at once:
#
# $ mix ecto.setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
"assets.setup": ["assets.install", "assets.build"],
"ecto.setup": [
"ecto.create",
"ecto.migrate",
"run apps/nerves_hub_web_core/priv/repo/seeds.exs"
],
"ecto.reset": ["ecto.drop", "ecto.setup"],
test: ["ecto.create --quiet", "ecto.migrate", "test"]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(env) when env in [:dev, :test],
do: [Path.expand("test/support")]
defp elixirc_paths(_),
do: ["lib"]
end
| 29 | 75 | 0.583908 |
f73c3716f5762170682049dc7a5c42ca5c4ecbf7 | 743 | exs | Elixir | test/acceptance/html/inline_ial_test.exs | manuel-rubio/earmark | d747d73d31e8b8fa39389b01fc67cc53d946b707 | [
"Apache-1.1"
] | 734 | 2015-01-05T19:08:00.000Z | 2022-03-28T14:04:21.000Z | test/acceptance/html/inline_ial_test.exs | manuel-rubio/earmark | d747d73d31e8b8fa39389b01fc67cc53d946b707 | [
"Apache-1.1"
] | 343 | 2015-01-01T04:56:57.000Z | 2022-02-15T11:00:57.000Z | test/acceptance/html/inline_ial_test.exs | manuel-rubio/earmark | d747d73d31e8b8fa39389b01fc67cc53d946b707 | [
"Apache-1.1"
] | 169 | 2015-02-26T15:18:05.000Z | 2022-03-18T08:00:42.000Z | defmodule Acceptance.Html.InlineIalTest do
use Support.AcceptanceTestCase
describe "IAL no errors" do
test "link with simple ial" do
markdown = "[link](url){: .classy}"
html ="<p>\n<a class=\"classy\" href=\"url\">link</a></p>\n"
messages = []
assert as_html(markdown) == {:ok, html, messages}
end
end
describe "Error Handling" do
test "illegal format line two" do
markdown = "a line\n[link](url) {:incorrect x=y}"
html = "<p>\na line\n<a href=\"url\" x=\"y\">link</a></p>\n"
messages = [{:warning, 2, "Illegal attributes [\"incorrect\"] ignored in IAL"}]
assert as_html(markdown) == {:error, html, messages}
end
end
end
# SPDX-License-Identifier: Apache-2.0
| 27.518519 | 85 | 0.608345 |
f73c3c82c6c696421cf60fa8a1f218f16b752a52 | 8,882 | ex | Elixir | lib/switchx/connection.ex | kalmik/switchx | 14d5197b0ed6ab46c307bdb1b928bbf84607bd56 | [
"MIT"
] | 8 | 2020-03-30T11:14:19.000Z | 2022-03-24T11:53:30.000Z | lib/switchx/connection.ex | kalmik/switchx | 14d5197b0ed6ab46c307bdb1b928bbf84607bd56 | [
"MIT"
] | 5 | 2020-03-27T00:00:54.000Z | 2020-04-23T00:30:08.000Z | lib/switchx/connection.ex | kalmik/switchx | 14d5197b0ed6ab46c307bdb1b928bbf84607bd56 | [
"MIT"
] | 1 | 2020-04-22T23:55:52.000Z | 2020-04-22T23:55:52.000Z | defmodule SwitchX.Connection do
@moduledoc false
@behaviour :gen_statem
require Logger
alias SwitchX.Connection.{
Socket
}
defstruct [
:host,
:port,
:password,
:owner,
:socket,
:connection_mode,
:api_response_buffer,
:session_module,
api_calls: :queue.new(),
commands_sent: :queue.new(),
applications_pending: Map.new()
]
def callback_mode() do
:handle_event_function
end
def start_link(owner, socket, :inbound) when is_port(socket) and is_pid(owner) do
:gen_statem.start_link(__MODULE__, [owner, socket, :inbound], [])
end
def start_link(session_module, socket, :outbound) do
:gen_statem.start_link(__MODULE__, [session_module, socket, :outbound], [])
end
def init([owner, socket, :inbound]) when is_port(socket) do
{:ok, {host, port}} = :inet.peername(socket)
data = %__MODULE__{
host: host,
port: port,
owner: owner,
socket: socket,
connection_mode: :inbound
}
:inet.setopts(socket, active: :once)
{:ok, :connecting, data}
end
def init([session_module, socket, :outbound]) when is_port(socket) do
{:ok, {host, port}} = :inet.peername(socket)
data = %__MODULE__{
host: host,
port: port,
owner: nil,
socket: socket,
connection_mode: :outbound,
session_module: session_module
}
send(self(), :read_data)
{:ok, :connecting, data}
end
## Handler events ##
def handle_event({:call, from}, message, state, data) do
apply(__MODULE__, state, [:call, message, from, data])
end
def handle_event(:info, {:tcp, _socket, "\n"}, _state, data) do
# Empty line discarding
{:keep_state, data}
end
def handle_event(:info, :read_data, :connecting, data) do
:gen_tcp.send(data.socket, "connect\n\n")
event = Socket.recv(data.socket)
{:ok, owner} = apply(data.session_module, :start_link, [self(), event])
data = put_in(data.owner, owner)
:inet.setopts(data.socket, active: :once)
{:next_state, :ready, data}
end
def handle_event(:info, {:tcp, socket, payload}, state, data) do
event = Socket.recv(socket, payload)
:inet.setopts(socket, active: :once)
apply(__MODULE__, state, [:event, event, data])
end
def handle_event(:info, _message, _state, data) do
{:keep_state, data}
end
## CALL STATE FUNCTIONS ##
def connecting(:call, {:auth, password}, from, data) do
data = put_in(data.password, password)
data = put_in(data.commands_sent, :queue.in(from, data.commands_sent))
{:keep_state, data}
end
def connecting(:call, any_kind, from, data) do
:gen_statem.reply(from, {:error, "Could not perform #{inspect(any_kind)}, not ready"})
{:keep_state, data}
end
def authenticating(:call, {:auth, password}, from, data) do
data = put_in(data.password, password)
data = put_in(data.commands_sent, :queue.in(from, data.commands_sent))
:gen_tcp.send(data.socket, "auth #{data.password}\n\n")
{:keep_state, data}
end
def authenticating(:call, any_kind, from, data) do
:gen_statem.reply(from, {:error, "Could not perform #{inspect(any_kind)}, not ready"})
{:keep_state, data}
end
def ready(:call, {:api, args}, from, data) do
data = put_in(data.api_calls, :queue.in(from, data.api_calls))
:gen_tcp.send(data.socket, "api #{args}\n\n")
{:keep_state, data}
end
def ready(:call, {:listen_event, event_name}, from, data) do
:gen_tcp.send(data.socket, "event plain #{event_name}\n\n")
:gen_statem.reply(from, {:ok, "Listening #{event_name}"})
{:keep_state, data}
end
def ready(:call, {:linger}, from, data) do
:gen_tcp.send(data.socket, "linger\n\n")
data = put_in(data.commands_sent, :queue.in(from, data.commands_sent))
{:keep_state, data}
end
def ready(:call, {:sendevent, event_name, event, event_uuid}, from, data) do
event =
case event_uuid do
nil -> event
uuid -> put_in(event.headers["unique-id"], uuid)
end
event = put_in(event.headers, Map.merge(event.headers, %{
"Event-Name" => event_name
}))
:gen_tcp.send(data.socket, "sendevent #{event_name}\n#{SwitchX.Event.dump(event)}\n\n")
data = put_in(data.commands_sent, :queue.in(from, data.commands_sent))
{:keep_state, data}
end
def ready(:call, {:sendmsg, nil, _event}, from, %{connection_mode: :inbound} = data) do
:gen_statem.reply(
from,
{:error, "UUID is required for inbound mode, see SwitchX.send_message/3."}
)
{:keep_state, data}
end
def ready(:call, {:sendmsg, uuid, event}, from, data) do
case uuid do
nil -> :gen_tcp.send(data.socket, "sendmsg\n#{SwitchX.Event.dump(event)}\n\n")
uuid -> :gen_tcp.send(data.socket, "sendmsg #{uuid}\n#{SwitchX.Event.dump(event)}\n\n")
end
event_uuid = Map.get(event.headers, "Event-UUID")
data =
if is_nil(event_uuid) do
put_in(data.commands_sent, :queue.in(from, data.commands_sent))
else
put_in(data.applications_pending, Map.put(data.applications_pending, event_uuid, from))
end
{:keep_state, data}
end
def ready(:call, {:myevents, nil}, from, %{connection_mode: :inbound} = data) do
:gen_statem.reply(
from,
{:error, "UUID is required for inbound mode, see SwitchX.my_events/2."}
)
{:keep_state, data}
end
def ready(:call, {:myevents, nil}, from, data) do
:gen_tcp.send(data.socket, "myevents\n\n")
data = put_in(data.commands_sent, :queue.in(from, data.commands_sent))
{:keep_state, data}
end
def ready(:call, {:myevents, uuid}, from, data) do
:gen_tcp.send(data.socket, "myevents #{uuid}\n\n")
data = put_in(data.commands_sent, :queue.in(from, data.commands_sent))
{:keep_state, data}
end
def ready(:call, {:exit}, from, data) do
:gen_tcp.send(data.socket, "exit\n\n")
data = put_in(data.commands_sent, :queue.in(from, data.commands_sent))
{:keep_state, data}
end
def ready(:call, {:bgapi, args}, from, data) do
job_uuid = UUID.uuid4()
:gen_tcp.send(data.socket, "bgapi #{args}\n\n")
data = put_in(data.commands_sent, :queue.in(from, data.commands_sent))
{:keep_state, data}
end
## Event STATE FUNCTIONS ##
def connecting(
:event,
%{headers: %{"Content-Type" => "auth/request"}},
%{password: password} = data
)
when is_binary(password) do
:gen_tcp.send(data.socket, "auth #{data.password}\n\n")
{:next_state, :authenticating, data}
end
def connecting(:event, %{headers: %{"Content-Type" => "auth/request"}}, data) do
{:next_state, :authenticating, data}
end
def authenticating(
:event,
%{headers: %{"Content-Type" => "command/reply", "Reply-Text" => "+OK accepted"}},
data
) do
# Subscribing CHANNEL_EXECUTE_COMPLETE in order to handle correctly application responses
:gen_tcp.send(data.socket, "event plain CHANNEL_EXECUTE_COMPLETE\n\n")
Logger.info("Connected")
{:next_state, :ready, reply_from_queue("commands_sent", {:ok, "Accepted"}, data)}
end
def authenticating(
:event,
%{headers: %{"Content-Type" => "command/reply", "Reply-Text" => "-ERR invalid"}},
data
) do
Logger.info("Fail to Connect")
{:next_state, :disconnected, reply_from_queue("commands_sent", {:error, "Denied"}, data)}
end
def disconnected(:event, %{headers: %{"Content-Type" => "text/disconnect-notice"}}, data) do
{:keep_state, data}
end
def ready(
:event,
%{headers: %{"Content-Type" => "command/reply", "Reply-Text" => "+OK will linger"}},
data
) do
{:keep_state, reply_from_queue("commands_sent", {:ok, "Lingering"}, data)}
end
def ready(:event, %{headers: %{"Content-Type" => "api/response"}} = event, data) do
{:keep_state, reply_from_queue("api_calls", {:ok, event}, data)}
end
def ready(:event, %{headers: %{"Content-Type" => "command/reply"}} = event, data) do
{:keep_state, reply_from_queue("commands_sent", {:ok, event}, data)}
end
def ready(
:event,
%{headers: %{"Event-Name" => "CHANNEL_EXECUTE_COMPLETE", "Application-UUID" => app_uuid}} =
event,
data
) do
reply_to = Map.get(data.applications_pending, app_uuid)
unless is_nil(reply_to),
do: :gen_statem.reply(reply_to, event)
{:keep_state, data}
end
def ready(:event, event, data) do
send(data.owner, {:switchx_event, event})
{:keep_state, data}
end
## HELPERS ##
defp reply_from_queue(queue_name, response, data) do
queue = Map.get(data, String.to_atom(queue_name))
case :queue.out(queue) do
{{_, reply_to}, q} ->
:gen_statem.reply(reply_to, response)
Map.put(data, String.to_atom(queue_name), q)
{:empty, _} ->
data
end
end
end
| 28.467949 | 99 | 0.635893 |
f73c567c120e8aacb6e42a6a75312ae6a7b0d3a8 | 2,164 | ex | Elixir | lib/elixirfm/track.ex | jrichocean/Elixirfm | 5595c08c3217500bbc3fe74fe1657fe0e7bfcda8 | [
"MIT"
] | 9 | 2016-10-04T10:09:17.000Z | 2020-10-20T10:34:47.000Z | lib/elixirfm/track.ex | jrichocean/Elixirfm | 5595c08c3217500bbc3fe74fe1657fe0e7bfcda8 | [
"MIT"
] | 4 | 2017-06-19T11:11:15.000Z | 2021-11-10T04:31:45.000Z | lib/elixirfm/track.ex | jrichocean/Elixirfm | 5595c08c3217500bbc3fe74fe1657fe0e7bfcda8 | [
"MIT"
] | 2 | 2018-10-12T09:53:36.000Z | 2019-09-29T13:19:41.000Z | defmodule Elixirfm.Track do
@moduledoc "Functions for Last.fm Track endpoints"
@method "track"
defp req(uri), do: Elixirfm.get_request(@method <> uri)
defp req(uri, args), do: Elixirfm.get_request(@method <> uri, args)
# @doc """
# Tag an album using a list of user supplied tags.
# *requires auth*
# """
# def add_tags() do
# end
@doc """
Use the last.fm corrections data to check whether the supplied track has a correction to a canonical track.
"""
@spec correction(String.t(), String.t()) :: Elixirfm.response
def correction(artist, track),
do: req(".getcorrection&artist=#{artist}&track=#{track}")
@doc """
Get the metadata for a track on Last.fm using the artist & track name.
"""
@spec info(String.t(), String.t(), [username: String.t()]) :: Elixirfm.response
def info(artist, track, args \\ [username: ""]),
do: req(".getInfo&artist=#{artist}&track=#{track}", args)
@doc """
Get the similar tracks for this track on Last.fm, based on listening data.
"""
@spec similar(String.t(), String.t(), [limit: non_neg_integer()]) :: Elixirfm.response
def similar(artist, track, args \\ [limit: 20]),
do: req(".getsimilar&artist=#{artist}&track=#{track}", args)
@doc """
Get the tags applied by an individual user to a track on Last.fm.
To retrieve the list of top tags applied to a track by all users use .getTopTags.
"""
@spec tags(String.t(), String.t(), [username: String.t()]) :: Elixirfm.response
def tags(artist, track, args \\ []),
do: req(".getTags&artist=#{artist}&track=#{track}", args)
@doc """
Get the top tags for this track on Last.fm, ordered by tag count.
"""
@spec top_tags(String.t(), String.t()) :: Elixirfm.response
def top_tags(artist, track),
do: req(".gettoptags&artist=#{artist}&track=#{track}")
@doc """
Search for track by track name, returns tracks sorted by relanvance.
Can be supplied with an artist to further narrow down search
"""
@spec search_track(String.t(), [artist: String.t()]) :: Elixirfm.response
def search_track(title, args \\ [artist: ""]),
do: req(".search&track=#{title}&artist=#{args[:artist]}")
end
| 35.47541 | 109 | 0.657116 |
f73c59423e4f56f1c88b3c27e63ffc9abb79f8f1 | 1,489 | exs | Elixir | config/runtime.exs | rushsteve1/RateTheDub | 89a8ad8ab42d2a55f1c522ba78dc4ac3a7f84081 | [
"Apache-2.0"
] | 4 | 2021-04-26T21:50:45.000Z | 2021-04-27T18:37:51.000Z | config/runtime.exs | rushsteve1/RateTheDub | 89a8ad8ab42d2a55f1c522ba78dc4ac3a7f84081 | [
"Apache-2.0"
] | 25 | 2021-04-26T21:39:21.000Z | 2021-09-07T13:59:14.000Z | config/runtime.exs | rushsteve1/RateTheDub | 89a8ad8ab42d2a55f1c522ba78dc4ac3a7f84081 | [
"Apache-2.0"
] | null | null | null | # In this file, we load production configuration and secrets
# from environment variables. You can also hardcode secrets,
# although such is generally not recommended and you have to
# remember to add this file to your .gitignore.
# Taken and adapted from
# https://fly.io/docs/getting-started/elixir/
import Config
if config_env() == :prod do
goatcounter_token = System.get_env("GOATCOUNTER_TOKEN")
config :ratethedub,
goatcounter_token: goatcounter_token
secret_key_base =
System.get_env("SECRET_KEY_BASE") ||
raise """
environment variable SECRET_KEY_BASE is missing.
You can generate one by calling: mix phx.gen.secret
"""
app_name =
System.get_env("FLY_APP_NAME") ||
raise "FLY_APP_NAME not available"
config :ratethedub, RateTheDubWeb.Endpoint,
server: true,
url: [host: "#{app_name}.fly.dev", port: 80],
http: [
port: String.to_integer(System.get_env("PORT") || "4000"),
# IMPORTANT: support IPv6 addresses
transport_options: [socket_opts: [:inet6]]
],
secret_key_base: secret_key_base
database_url =
System.get_env("DATABASE_URL") ||
raise """
environment variable DATABASE_URL is missing.
For example: ecto://USER:PASS@HOST/DATABASE
"""
config :ratethedub, RateTheDub.Repo,
url: database_url,
# IMPORTANT: Or it won't find the DB server
socket_options: [:inet6],
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")
end
| 29.196078 | 69 | 0.693083 |
f73caf4f1eeae99184ceb3be9a43779c6348091c | 14,010 | exs | Elixir | test/slax/github_test.exs | HoffsMH/slax | b91ee30b9fd71a4cb7826f50b605ce580b7c1651 | [
"MIT"
] | 11 | 2016-07-05T18:56:21.000Z | 2021-09-15T22:23:54.000Z | test/slax/github_test.exs | HoffsMH/slax | b91ee30b9fd71a4cb7826f50b605ce580b7c1651 | [
"MIT"
] | 181 | 2016-06-23T00:47:13.000Z | 2022-03-10T11:23:44.000Z | test/slax/github_test.exs | HoffsMH/slax | b91ee30b9fd71a4cb7826f50b605ce580b7c1651 | [
"MIT"
] | 7 | 2019-01-30T21:38:28.000Z | 2022-03-01T07:13:39.000Z | defmodule Slax.Github.Test do
use Slax.ModelCase, async: true
alias Slax.Github
import Mox
# Make sure mocks are verified when the test exits
setup :verify_on_exit!
test "authorize_url/1" do
assert Github.authorize_url(%{token: "token"}) =~ "token=token"
end
test "fetch_access_token/1" do
expect(Slax.HttpMock, :post, fn _, _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 200, body: ~s<{"access_token": "token"}>}}
end)
assert Github.fetch_access_token(%{}) == "token"
end
test "current_user_info/1" do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 200, body: ~s<{"username": "test"}>}}
end)
assert Github.current_user_info(%{}) == %{"username" => "test"}
end
def create_issue_setup(context) do
params = %{
repo: "test",
access_token: "token"
}
url = "/repos/#{params[:repo]}/issues"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "create_issue/1" do
setup [:create_issue_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :post, fn _, _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 201, body: ~s<{"html_url": "http://github.com"}>}}
end)
assert Github.create_issue(params) == {:ok, "http://github.com"}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :post, fn _, _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 400, body: ~s<{"message": "Something happened"}>}}
end)
assert Github.create_issue(params) == {:error, "Something happened"}
end
end
def create_comment_setup(context) do
params = %{
body: "comment",
org: "test",
repo: "test",
issue_number: 1,
access_token: "token"
}
url = "/repos/#{params[:org]}/#{params[:repo]}/issues/#{params[:issue_number]}/comments"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "create_comment/1" do
setup [:create_comment_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :post, fn _, _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 201, body: ~s<{"html_url": "http://github.com"}>}}
end)
assert Github.create_comment(params) == {:ok, "http://github.com"}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :post, fn _, _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 400, body: ~s<{"message": "Something happened"}>}}
end)
assert Github.create_comment(params) == {:error, "Something happened"}
end
end
def fetch_issues_setup(context) do
params = %{
username: "test",
repo: "test",
org: "test",
access_token: "token"
}
url = "/repos/#{params[:org]}/#{params[:repo]}/issues"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "fetch_issues/1" do
setup [:fetch_issues_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 201, body: ~s<[{"id": 1}]>}}
end)
assert Github.fetch_issues(params) == [%{"id" => 1, "org" => "test", "repo" => "test"}]
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 400, body: ~s<{"message": "Something happened"}>}}
end)
assert Github.fetch_issues(params) == %{"message" => "Something happened"}
end
end
def fetch_issue_setup(context) do
params = %{
username: "test",
repo: "test",
access_token: "token",
number: 1
}
url = "/repos/#{params[:repo]}/issues/1"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "fetch_issue/1" do
setup [:fetch_issue_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 201, body: ~s<{"id": 1}>}}
end)
assert Github.fetch_issue(params) == %{"id" => 1}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 400, body: ~s<{"message": "Something happened"}>}}
end)
assert Github.fetch_issue(params) == %{"message" => "Something happened"}
end
end
def fetch_milestones_setup(context) do
params = %{
repo: "test",
access_token: "token"
}
url = "/repos/#{params[:repo]}/milestones"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "fetch_milestones/1" do
setup [:fetch_milestones_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 201, body: ~s<[{"id": 1}]>}}
end)
assert Github.fetch_milestones(params) == {:ok, [%{"id" => 1}]}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 404, body: ~s<{"message": "Not Found"}>}}
end)
assert Github.fetch_milestones(params) == {:error, :not_found}
end
end
def create_milestone_setup(context) do
params = %{
repo: "test",
access_token: "token",
title: "Milestone",
description: "Something"
}
url = "/repos/#{params[:repo]}/milestones"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "create_milestone/1" do
setup [:create_milestone_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :post, fn _, _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 201, body: ~s<{"id": 1}>}}
end)
assert Github.create_milestone(params) == {:ok, %{"id" => 1}}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :post, fn _, _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 400, body: ~s<{"message": "Invalid"}>}}
end)
assert Github.create_milestone(params) == {:error, "Invalid"}
end
end
def add_issue_to_milestone_setup(context) do
params = %{
repo: "test",
access_token: "token",
milestone_number: 1,
issue_number: 2
}
url = "/repos/#{params[:repo]}/issues/#{params[:issue_number]}"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "add_issue_to_milestone/1" do
setup [:add_issue_to_milestone_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :patch, fn _, _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 201, body: ~s<{"id": 1}>}}
end)
assert Github.add_issue_to_milestone(params) == {:ok, %{"id" => 1}}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :patch, fn _, _, _, _ ->
{:ok, %HTTPoison.Response{status_code: 400, body: ~s<{"message": "Invalid"}>}}
end)
assert Github.add_issue_to_milestone(params) == {:error, "Invalid"}
end
end
def create_repo_setup(context) do
params = %{
name: "test",
org_name: "test",
access_token: "token"
}
url = "/orgs/#{params[:org_name]}/repos"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "create_repo/1" do
setup [:create_repo_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :post, fn _, _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 201,
body: ~s<{"html_url": "https://github.com/test/test"}>
}}
end)
assert Github.create_repo(params) == {:ok, "https://github.com/test/test"}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :post, fn _, _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 400,
body: ~s<{"message": "Invalid"}>
}}
end)
assert Github.create_repo(params) == {:error, "Invalid"}
end
end
def fetch_repo_setup(context) do
params = %{
name: "test",
org_name: "test",
access_token: "token"
}
url = "/repos/#{params[:org_name]}/#{params[:name]}"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "fetch_repo/1" do
setup [:fetch_repo_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 201,
body: ~s<{"html_url": "https://github.com/test/test"}>
}}
end)
assert Github.fetch_repo(params) == {:ok, "https://github.com/test/test"}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 400,
body: ~s<{"message": "Invalid"}>
}}
end)
assert Github.fetch_repo(params) == {:error, "Invalid"}
end
test "not found", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 404,
body: ~s<{}>
}}
end)
assert Github.fetch_repo(params) == :not_found
end
end
def create_webhook_setup(context) do
params = %{
repo: "test",
access_token: "token"
}
url = "/repos/#{params[:repo]}/hooks"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "create_webhook/1" do
setup [:create_webhook_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :post, fn _, _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 201,
body: ~s<{"id": 1}>
}}
end)
assert Github.create_webhook(params) == {:ok, 1}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :post, fn _, _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 400,
body: ~s<{"message": "Invalid"}>
}}
end)
assert Github.create_webhook(params) == {:error, "Invalid"}
end
end
def fetch_tree_setup(context) do
params = %{
repo: "test",
access_token: "token"
}
url = "/repos/#{params[:repo]}/git/trees/master"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "fetch_tree/1" do
setup [:fetch_tree_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 201,
body: ~s<{"html_url": "https://github.com/test/test"}>
}}
end)
assert Github.fetch_tree(params) == {:ok, %{"html_url" => "https://github.com/test/test"}}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 400,
body: ~s<{"message": "Invalid"}>
}}
end)
assert Github.fetch_tree(params) == {:error, "Invalid"}
end
end
def fetch_blob_setup(context) do
params = %{
repo: "test",
sha: "abcdef1234567890",
access_token: "token"
}
url = "/repos/#{params[:repo]}/git/blobs/#{params[:sha]}"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "fetch_blob/1" do
setup [:fetch_blob_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 201,
body: ~s<{"html_url": "https://github.com/test/test"}>
}}
end)
assert Github.fetch_blob(params) == {:ok, %{"html_url" => "https://github.com/test/test"}}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 400,
body: ~s<{"message": "Invalid"}>
}}
end)
assert Github.fetch_blob(params) == {:error, "Invalid"}
end
end
def list_teams_setup(context) do
params = %{
org: "test",
access_token: "token"
}
url = "/orgs/#{params[:org]}/teams"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "list_teams/1" do
setup [:list_teams_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 201,
body: ~s<[{"id": 1}]>
}}
end)
assert Github.list_teams(params) == {:ok, [%{"id" => 1}]}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :get, fn _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 400,
body: ~s<{"message": "Invalid"}>
}}
end)
assert Github.list_teams(params) == {:error, "Invalid"}
end
end
def add_team_to_repo_setup(context) do
params = %{
repo: "test",
team: "test",
access_token: "token"
}
url = "/teams/#{params[:team]}/repos/#{params[:repo]}"
{:ok, context |> Map.put(:params, params) |> Map.put(:url, url)}
end
describe "add_team_to_repo/1" do
setup [:add_team_to_repo_setup]
test "success", %{params: params} do
expect(Slax.HttpMock, :put, fn _, _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 201,
body: ~s<{"id": 1}>
}}
end)
assert Github.add_team_to_repo(params) == {:ok, "Created"}
end
test "failure", %{params: params} do
expect(Slax.HttpMock, :put, fn _, _, _, _ ->
{:ok,
%HTTPoison.Response{
status_code: 400,
body: ~s<{"message": "Invalid"}>
}}
end)
assert Github.add_team_to_repo(params) == {:error, "Invalid"}
end
end
end
| 25.612431 | 97 | 0.55853 |
f73cb207c90975f4b4311e8a05e347373c09d5e4 | 361 | exs | Elixir | back/priv/repo/migrations/20190910095238_create_clocks.exs | HugoLefebvre/Epitech_TM_MP03 | 0ed161c956f7a10aec245fe2e17eb5a9b55f6075 | [
"MIT"
] | null | null | null | back/priv/repo/migrations/20190910095238_create_clocks.exs | HugoLefebvre/Epitech_TM_MP03 | 0ed161c956f7a10aec245fe2e17eb5a9b55f6075 | [
"MIT"
] | null | null | null | back/priv/repo/migrations/20190910095238_create_clocks.exs | HugoLefebvre/Epitech_TM_MP03 | 0ed161c956f7a10aec245fe2e17eb5a9b55f6075 | [
"MIT"
] | null | null | null | defmodule Api.Repo.Migrations.CreateClocks do
use Ecto.Migration
def change do
create table(:clocks) do
add :time, :utc_datetime, null: false
add :status, :boolean, default: true, null: false
add :user_a, references(:users, on_delete: :nothing), null: false
timestamps()
end
create index(:clocks, [:user_a])
end
end
| 22.5625 | 71 | 0.66759 |
f73ccd090ccfb0c08b4b8efe3730b014d270e2b0 | 1,450 | ex | Elixir | clients/vault/lib/google_api/vault/v1/model/held_hangouts_chat_query.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/vault/lib/google_api/vault/v1/model/held_hangouts_chat_query.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/vault/lib/google_api/vault/v1/model/held_hangouts_chat_query.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Vault.V1.Model.HeldHangoutsChatQuery do
@moduledoc """
Query options for hangouts chat holds.
## Attributes
* `includeRooms` (*type:* `boolean()`, *default:* `nil`) - If true, include rooms the user has participated in.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:includeRooms => boolean() | nil
}
field(:includeRooms)
end
defimpl Poison.Decoder, for: GoogleApi.Vault.V1.Model.HeldHangoutsChatQuery do
def decode(value, options) do
GoogleApi.Vault.V1.Model.HeldHangoutsChatQuery.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Vault.V1.Model.HeldHangoutsChatQuery do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 30.851064 | 115 | 0.73931 |
f73cd1a03985bf5b448ba0b9ad9a19e7de7f3243 | 1,675 | exs | Elixir | test/drab/commander_test.exs | bdfinlayson/drab | ce11a643ec8fe7e7f622489af5792ef12e69a8c7 | [
"MIT"
] | null | null | null | test/drab/commander_test.exs | bdfinlayson/drab | ce11a643ec8fe7e7f622489af5792ef12e69a8c7 | [
"MIT"
] | null | null | null | test/drab/commander_test.exs | bdfinlayson/drab | ce11a643ec8fe7e7f622489af5792ef12e69a8c7 | [
"MIT"
] | null | null | null | defmodule Drab.CommanderTest do
use ExUnit.Case, ascync: true
doctest Drab.Commander
test "__drab__/0 should return the valid config for test commander" do
assert DrabTestApp.TestCommander.__drab__() == %Drab.Commander.Config{
commander: DrabTestApp.TestCommander,
controller: DrabTestApp.TestController,
view: nil, # because view does not exist
onload: :onload_function,
modules: [Drab.Query]
}
end
test "__drab__/0 should return the valid config for page commander" do
assert DrabTestApp.PageCommander.__drab__() == %Drab.Commander.Config{
access_session: [:test_session_value1],
after_handler: [after_all: [], after_most: [except: [:core3_click]]],
before_handler: [before_all: [], cancel_handler: [only: [:core3_click]]],
broadcasting: :same_path,
commander: DrabTestApp.PageCommander,
controller: DrabTestApp.PageController,
modules: [Drab.Waiter, Drab.Query, Drab.Element, Drab.Live],
onconnect: :page_connected,
ondisconnect: nil,
onload: :page_loaded,
public_handlers: [],
view: DrabTestApp.PageView
}
end
test "__drab__/0 should return the valid config for lone commander" do
%Drab.Commander.Config{
access_session: [],
after_handler: [],
before_handler: [check_permissions: []],
broadcasting: :same_path,
commander: DrabTestApp.LoneCommander,
controller: nil,
modules: [Drab.Live, Drab.Element],
public_handlers: [:lone_handler]
}
end
end
| 37.222222 | 86 | 0.63403 |
f73cd3ffc29180f27f0084127d5f59532719e320 | 2,014 | ex | Elixir | clients/content/lib/google_api/content/v21/model/account_user.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/content/lib/google_api/content/v21/model/account_user.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/content/lib/google_api/content/v21/model/account_user.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Content.V21.Model.AccountUser do
@moduledoc """
## Attributes
* `admin` (*type:* `boolean()`, *default:* `nil`) - Whether user is an admin.
* `emailAddress` (*type:* `String.t`, *default:* `nil`) - User's email address.
* `orderManager` (*type:* `boolean()`, *default:* `nil`) - Whether user is an order manager.
* `paymentsAnalyst` (*type:* `boolean()`, *default:* `nil`) - Whether user can access payment statements.
* `paymentsManager` (*type:* `boolean()`, *default:* `nil`) - Whether user can manage payment settings.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:admin => boolean() | nil,
:emailAddress => String.t() | nil,
:orderManager => boolean() | nil,
:paymentsAnalyst => boolean() | nil,
:paymentsManager => boolean() | nil
}
field(:admin)
field(:emailAddress)
field(:orderManager)
field(:paymentsAnalyst)
field(:paymentsManager)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.AccountUser do
def decode(value, options) do
GoogleApi.Content.V21.Model.AccountUser.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.AccountUser do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.135593 | 109 | 0.690665 |
f73cd9fada28a57e67da781394e2d58e65801eb4 | 8,846 | ex | Elixir | clients/deployment_manager/lib/google_api/deployment_manager/v2/api/resources.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/deployment_manager/lib/google_api/deployment_manager/v2/api/resources.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/deployment_manager/lib/google_api/deployment_manager/v2/api/resources.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DeploymentManager.V2.Api.Resources do
@moduledoc """
API calls for all endpoints tagged `Resources`.
"""
alias GoogleApi.DeploymentManager.V2.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets information about a single resource.
## Parameters
* `connection` (*type:* `GoogleApi.DeploymentManager.V2.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - The project ID for this request.
* `deployment` (*type:* `String.t`) - The name of the deployment for this request.
* `resource` (*type:* `String.t`) - The name of the resource for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DeploymentManager.V2.Model.Resource{}}` on success
* `{:error, info}` on failure
"""
@spec deploymentmanager_resources_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DeploymentManager.V2.Model.Resource.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def deploymentmanager_resources_get(
connection,
project,
deployment,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/deployments/{deployment}/resources/{resource}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"deployment" => URI.encode(deployment, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DeploymentManager.V2.Model.Resource{}])
end
@doc """
Lists all resources in a given deployment.
## Parameters
* `connection` (*type:* `GoogleApi.DeploymentManager.V2.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - The project ID for this request.
* `deployment` (*type:* `String.t`) - The name of the deployment for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <.
For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance.
You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true).
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by name or creationTimestamp desc is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DeploymentManager.V2.Model.ResourcesListResponse{}}` on success
* `{:error, info}` on failure
"""
@spec deploymentmanager_resources_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DeploymentManager.V2.Model.ResourcesListResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def deploymentmanager_resources_list(
connection,
project,
deployment,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/deployments/{deployment}/resources", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"deployment" => URI.encode(deployment, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DeploymentManager.V2.Model.ResourcesListResponse{}]
)
end
end
| 48.604396 | 414 | 0.661655 |
f73cdc98239d836fa36d58eb27ac93b5e0a4abe2 | 3,118 | exs | Elixir | test/mongo/url_parser_test.exs | Virtual-Repetitions/mongodb | eea06db138ae3b4824c7f208fda621075fbf28a7 | [
"Apache-2.0"
] | null | null | null | test/mongo/url_parser_test.exs | Virtual-Repetitions/mongodb | eea06db138ae3b4824c7f208fda621075fbf28a7 | [
"Apache-2.0"
] | 2 | 2021-07-10T18:53:51.000Z | 2021-08-06T15:36:58.000Z | test/mongo/url_parser_test.exs | Virtual-Repetitions/mongodb | eea06db138ae3b4824c7f208fda621075fbf28a7 | [
"Apache-2.0"
] | 3 | 2021-07-10T18:01:00.000Z | 2021-08-05T00:39:17.000Z | defmodule Mongo.UrlParserTest do
@moduledoc false
use ExUnit.Case, async: false
alias Mongo.UrlParser
describe ".parse_url" do
test "basic url" do
assert UrlParser.parse_url(url: "mongodb://localhost:27017") == [seeds: ["localhost:27017"]]
end
test "percent encoded password" do
url =
"mongodb://myusername:2yPK%7DBzj%7CqE%28%24%5E1JDdk4J42%2A%264lLgV%25C@mymongodbserver:27017/admin"
opts = UrlParser.parse_url(url: url)
password = Keyword.get(opts, :password)
assert password = "2yPK}Bzj|qE($^1JDdk4J42*&4lLgV%C"
end
test "cluster url" do
url =
"mongodb://user:[email protected]:27017,seed2.domain.com:27017,seed3.domain.com:27017/db_name?ssl=true&replicaSet=set-name&authSource=admin&maxPoolSize=5"
assert UrlParser.parse_url(url: url) == [
username: "user",
password: "password",
database: "db_name",
pool_size: 5,
auth_source: "admin",
set_name: "set-name",
ssl: true,
seeds: [
"seed1.domain.com:27017",
"seed2.domain.com:27017",
"seed3.domain.com:27017"
]
]
end
test "merge options" do
assert UrlParser.parse_url(url: "mongodb://localhost:27017", name: :test, seeds: ["1234"]) ==
[seeds: ["localhost:27017"], name: :test]
end
test "url srv" do
assert UrlParser.parse_url(url: "mongodb+srv://test5.test.build.10gen.cc") ==
[
ssl: true,
auth_source: "thisDB",
set_name: "repl0",
seeds: [
"localhost.test.build.10gen.cc:27017"
]
]
end
test "url srv with user" do
assert UrlParser.parse_url(url: "mongodb+srv://user:[email protected]") ==
[
username: "user",
password: "password",
ssl: true,
auth_source: "thisDB",
set_name: "repl0",
seeds: [
"localhost.test.build.10gen.cc:27017"
]
]
end
test "write concern" do
for w <- [2, "majority"] do
assert UrlParser.parse_url(
url: "mongodb://seed1.domain.com:27017,seed2.domain.com:27017/db_name?w=#{w}"
) == [
database: "db_name",
w: w,
seeds: [
"seed1.domain.com:27017",
"seed2.domain.com:27017"
]
]
end
end
test "appName option" do
url = "mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE?ssl=true&replicaSet=globaldb&appName=APP"
assert UrlParser.parse_url(url: url) == [
username: "USERNAME",
password: "PASSWORD",
database: "DATABASE",
app_name: "APP",
set_name: "globaldb",
ssl: true,
seeds: ["HOST:PORT"]
]
end
end
end
| 30.871287 | 170 | 0.513149 |
f73cfc7068bc3cfc379e88cb8871f83a8b593220 | 424 | ex | Elixir | lib/blog/posts/comment.ex | nlundkvist/blog | 8353b0619e7d88285bb233990dcf8ec4959d6ed8 | [
"MIT"
] | null | null | null | lib/blog/posts/comment.ex | nlundkvist/blog | 8353b0619e7d88285bb233990dcf8ec4959d6ed8 | [
"MIT"
] | null | null | null | lib/blog/posts/comment.ex | nlundkvist/blog | 8353b0619e7d88285bb233990dcf8ec4959d6ed8 | [
"MIT"
] | null | null | null | defmodule Blog.Posts.Comment do
use Ecto.Schema
import Ecto.Changeset
alias Blog.Posts.{Comment, Post}
schema "comments" do
field :content, :string
field :name, :string
belongs_to :post, Post
timestamps()
end
@doc false
def changeset(%Comment{} = comment, attrs) do
comment
|> cast(attrs, [:name, :content, :post_id])
|> validate_required([:name, :content, :post_id])
end
end
| 19.272727 | 53 | 0.660377 |
f73d02671be9d8789509dacc98eb251853e341c5 | 816 | ex | Elixir | lib/branch_cutter/schema/pull_request.ex | smaximov/branch_cutter | eb750db1fcc9715ab7bbecadd2ccd3368b41dc81 | [
"MIT"
] | null | null | null | lib/branch_cutter/schema/pull_request.ex | smaximov/branch_cutter | eb750db1fcc9715ab7bbecadd2ccd3368b41dc81 | [
"MIT"
] | null | null | null | lib/branch_cutter/schema/pull_request.ex | smaximov/branch_cutter | eb750db1fcc9715ab7bbecadd2ccd3368b41dc81 | [
"MIT"
] | null | null | null | defmodule BranchCutter.Schema.PullRequest do
use Ecto.Schema
import Ecto.Changeset
@type t() :: %__MODULE__{
repo: String.t() | nil,
branch: String.t() | nil,
number: integer() | nil,
inserted_at: NaiveDateTime.t() | nil,
updated_at: NaiveDateTime.t() | nil
}
@primary_key false
schema "pull_requests" do
field :repo, :string, primary_key: true
field :branch, :string, primary_key: true
field :number, :integer, primary_key: true
timestamps()
end
@spec changeset(t(), map()) :: Changeset.t()
def changeset(pull_request, params \\ %{}) do
pull_request
|> cast(params, ~w[repo branch number]a)
|> validate_required(~w[repo branch number]a)
|> unique_constraint(:number, name: :pull_requests_pkey)
end
end
| 26.322581 | 60 | 0.634804 |
f73d064dffd3d2c56c6e91434d19fbd6fc942542 | 973 | exs | Elixir | test/ffaker/en/color_test.exs | marocchino/ffaker | 5bb4420a8034db9f954a2464cd72039129ef2307 | [
"MIT"
] | 9 | 2016-11-09T15:50:05.000Z | 2021-02-02T05:45:06.000Z | test/ffaker/en/color_test.exs | marocchino/ffaker | 5bb4420a8034db9f954a2464cd72039129ef2307 | [
"MIT"
] | 3 | 2016-09-01T09:54:46.000Z | 2017-07-25T05:23:56.000Z | test/ffaker/en/color_test.exs | marocchino/ffaker | 5bb4420a8034db9f954a2464cd72039129ef2307 | [
"MIT"
] | 4 | 2016-11-22T17:51:48.000Z | 2021-02-02T05:45:01.000Z | defmodule Ffaker.En.ColorTest do
use ExUnit.Case, async: true
use Ffaker
import Ffaker.En.Color
import Ffaker.Matcher, only: [assert_match: 2]
test "name/0" do
assert name() in ~F(names)
end
test "hex_code/0" do
assert_match ~r/\A[0-9A-F]{6}\z/, hex_code()
end
test "rgb/0" do
assert Enum.all?(rgb(), &(&1 >= 0 and &1 <= 255))
end
test "hsl/0" do
[hue | sl] = hsl()
assert hue >= 0 and hue <= 360
assert Enum.all?(sl, &Regex.match?(~r/\A\d{1,3}%\z/, &1))
end
test "rgba/0" do
[r, g, b, a] = rgba()
assert r in 0..255
assert g in 0..255
assert b in 0..255
assert a >= 0.0 and a <= 1.0
end
test "hsla/0" do
[h, s, l, a] = hsla()
assert h in 0..360
assert_match ~r/\A\d{1,3}%\z/, s
assert_match ~r/\A\d{1,3}%\z/, l
assert a >= 0.0 and a <= 1.0, "#{a} is not in 0..1"
end
test "alpha/0" do
a = alpha()
assert a >= 0.0 and a <= 1.0, "#{a} is not in 0..1"
end
end
| 21.152174 | 61 | 0.539568 |
f73d251233b911c2fcf98c694de38efc81f02a0c | 396 | exs | Elixir | test/server_test.exs | madhuvishy/ex_messenger | a35d14a75adfa64baf2880364d43969363cc3b02 | [
"MIT"
] | 4 | 2015-06-22T22:16:03.000Z | 2017-09-30T02:45:30.000Z | test/server_test.exs | madhuvishy/ex_messenger | a35d14a75adfa64baf2880364d43969363cc3b02 | [
"MIT"
] | null | null | null | test/server_test.exs | madhuvishy/ex_messenger | a35d14a75adfa64baf2880364d43969363cc3b02 | [
"MIT"
] | null | null | null | defmodule ServerTest do
use ExUnit.Case
test "Check if server is created" do
pid = Process.whereis(:message_server)
assert pid != nil
end
test "Check if server connect and disconnect works" do
pid = Process.whereis(:message_server)
assert {:ok, "hello"} == GenServer.call(pid, {:connect, :hello})
assert :ok == GenServer.call(pid, {:disconnect, :hello})
end
end
| 26.4 | 68 | 0.679293 |
f73d48849fd6305e3684c6331af3c4c2da084609 | 60,337 | ex | Elixir | clients/data_fusion/lib/google_api/data_fusion/v1beta1/api/projects.ex | jamesvl/elixir-google-api | 6c87fb31d996f08fb42ce6066317e9d652a87acc | [
"Apache-2.0"
] | null | null | null | clients/data_fusion/lib/google_api/data_fusion/v1beta1/api/projects.ex | jamesvl/elixir-google-api | 6c87fb31d996f08fb42ce6066317e9d652a87acc | [
"Apache-2.0"
] | null | null | null | clients/data_fusion/lib/google_api/data_fusion/v1beta1/api/projects.ex | jamesvl/elixir-google-api | 6c87fb31d996f08fb42ce6066317e9d652a87acc | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DataFusion.V1beta1.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.DataFusion.V1beta1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets information about a location.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Resource name for the location.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.Location{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.Location.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_get(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1beta1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.Location{}])
end
@doc """
Lists information about the supported locations for this service.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The resource that owns the locations collection, if applicable.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - The standard list filter.
* `:includeUnrevealedLocations` (*type:* `boolean()`) - If true, the returned list will include locations which are not yet revealed.
* `:pageSize` (*type:* `integer()`) - The standard list page size.
* `:pageToken` (*type:* `String.t`) - The standard list page token.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.ListLocationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.ListLocationsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_list(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:includeUnrevealedLocations => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1beta1/{+name}/locations", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.ListLocationsResponse{}]
)
end
@doc """
Remove IAM policy that is currently set on the given resource.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - The resource on which IAM policy to be removed is attached to.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.DataFusion.V1beta1.Model.RemoveIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.RemoveIamPolicyResponse{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_remove_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.RemoveIamPolicyResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_remove_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1beta1/{+resource}:removeIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.RemoveIamPolicyResponse{}]
)
end
@doc """
Creates a new Data Fusion instance in the specified project and location.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - The instance's project and location in the format projects/{project}/locations/{location}.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:instanceId` (*type:* `String.t`) - The name of the instance to create.
* `:body` (*type:* `GoogleApi.DataFusion.V1beta1.Model.Instance.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_instances_create(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_instances_create(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:instanceId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1beta1/{+parent}/instances", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.Operation{}])
end
@doc """
Deletes a single Data Fusion instance.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The instance resource name in the format projects/{project}/locations/{location}/instances/{instance}
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_instances_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_instances_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1beta1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.Operation{}])
end
@doc """
Gets details of a single Data Fusion instance.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The instance resource name in the format projects/{project}/locations/{location}/instances/{instance}.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.Instance{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_instances_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.Instance.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_instances_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1beta1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.Instance{}])
end
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:"options.requestedPolicyVersion"` (*type:* `integer()`) - Optional. The policy format version to be returned. Valid values are 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with any conditional bindings must specify version 3. Policies without any conditional bindings may specify any valid value or leave the field unset. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_instances_get_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_instances_get_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:"options.requestedPolicyVersion" => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1beta1/{+resource}:getIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.Policy{}])
end
@doc """
Lists Data Fusion instances in the specified project and location.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - The project and location for which to retrieve instance information in the format projects/{project}/locations/{location}. If the location is specified as '-' (wildcard), then all regions available to the project are queried, and the results are aggregated.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - List filter.
* `:orderBy` (*type:* `String.t`) - Sort results. Supported values are "name", "name desc", or "" (unsorted).
* `:pageSize` (*type:* `integer()`) - The maximum number of items to return.
* `:pageToken` (*type:* `String.t`) - The next_page_token value to use if there are additional results to retrieve for this list request.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.ListInstancesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_instances_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.ListInstancesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_instances_list(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:orderBy => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1beta1/{+parent}/instances", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.ListInstancesResponse{}]
)
end
@doc """
Updates a single Data Fusion instance.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Output only. The name of this instance is in the form of projects/{project}/locations/{location}/instances/{instance}.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:updateMask` (*type:* `String.t`) - Field mask is used to specify the fields that the update will overwrite in an instance resource. The fields specified in the update_mask are relative to the resource, not the full request. A field will be overwritten if it is in the mask. If the user does not provide a mask, all the supported fields (labels and options currently) will be overwritten.
* `:body` (*type:* `GoogleApi.DataFusion.V1beta1.Model.Instance.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_instances_patch(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_instances_patch(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1beta1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.Operation{}])
end
@doc """
Restart a single Data Fusion instance. At the end of an operation instance is fully restarted.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Name of the Data Fusion instance which need to be restarted in the form of projects/{project}/locations/{location}/instances/{instance}
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.DataFusion.V1beta1.Model.RestartInstanceRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_instances_restart(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_instances_restart(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1beta1/{+name}:restart", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.Operation{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy. Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.DataFusion.V1beta1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_instances_set_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_instances_set_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1beta1/{+resource}:setIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.Policy{}])
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.DataFusion.V1beta1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_instances_test_iam_permissions(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.TestIamPermissionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_instances_test_iam_permissions(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1beta1/{+resource}:testIamPermissions", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Upgrade a single Data Fusion instance. At the end of an operation instance is fully upgraded.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Name of the Data Fusion instance which need to be upgraded in the form of projects/{project}/locations/{location}/instances/{instance} Instance will be upgraded with the latest stable version of the Data Fusion.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.DataFusion.V1beta1.Model.UpgradeInstanceRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_instances_upgrade(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_instances_upgrade(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1beta1/{+name}:upgrade", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.Operation{}])
end
@doc """
Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource to be cancelled.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.DataFusion.V1beta1.Model.CancelOperationRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_operations_cancel(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_operations_cancel(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1beta1/{+name}:cancel", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.Empty{}])
end
@doc """
Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource to be deleted.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_operations_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_operations_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1beta1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.Empty{}])
end
@doc """
Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_operations_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_operations_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1beta1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.Operation{}])
end
@doc """
Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation's parent resource.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - The standard list filter.
* `:pageSize` (*type:* `integer()`) - The standard list page size.
* `:pageToken` (*type:* `String.t`) - The standard list page token.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.ListOperationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_operations_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.ListOperationsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_operations_list(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1beta1/{+name}/operations", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.ListOperationsResponse{}]
)
end
@doc """
Lists possible versions for Data Fusion instances in the specified project and location.
## Parameters
* `connection` (*type:* `GoogleApi.DataFusion.V1beta1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The project and location for which to retrieve instance information in the format projects/{project}/locations/{location}.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:latestPatchOnly` (*type:* `boolean()`) - Whether or not to return the latest patch of every available minor version. If true, only the latest patch will be returned. Ex. if allowed versions is [6.1.1, 6.1.2, 6.2.0] then response will be [6.1.2, 6.2.0]
* `:pageSize` (*type:* `integer()`) - The maximum number of items to return.
* `:pageToken` (*type:* `String.t`) - The next_page_token value to use if there are additional results to retrieve for this list request.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DataFusion.V1beta1.Model.ListAvailableVersionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec datafusion_projects_locations_versions_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DataFusion.V1beta1.Model.ListAvailableVersionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def datafusion_projects_locations_versions_list(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:latestPatchOnly => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1beta1/{+parent}/versions", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DataFusion.V1beta1.Model.ListAvailableVersionsResponse{}]
)
end
end
| 45.988567 | 607 | 0.619852 |
f73d5cae12e9be7a50687f04e1189cf43edd0bbe | 13,614 | exs | Elixir | test/phoenix/test/conn_test.exs | jshahs/magiclogo | 5b18cb4efff04c3547d167bab194d2806ec20d8a | [
"MIT"
] | null | null | null | test/phoenix/test/conn_test.exs | jshahs/magiclogo | 5b18cb4efff04c3547d167bab194d2806ec20d8a | [
"MIT"
] | null | null | null | test/phoenix/test/conn_test.exs | jshahs/magiclogo | 5b18cb4efff04c3547d167bab194d2806ec20d8a | [
"MIT"
] | null | null | null | defmodule Phoenix.Test.ConnTest.CatchAll do
def init(opts), do: opts
def call(conn, :stat), do: conn.params["action"].(conn)
def call(conn, _opts), do: Plug.Conn.assign(conn, :catch_all, true)
end
defmodule Phoenix.Test.ConnTest.Router do
use Phoenix.Router
alias Phoenix.Test.ConnTest.CatchAll
pipeline :browser do
plug :put_bypass, :browser
end
pipeline :api do
plug :put_bypass, :api
end
get "/stat", CatchAll, :stat
forward "/", CatchAll
def put_bypass(conn, pipeline) do
bypassed = (conn.assigns[:bypassed] || []) ++ [pipeline]
Plug.Conn.assign(conn, :bypassed, bypassed)
end
end
defmodule Phoenix.Test.ConnTest do
use ExUnit.Case, async: true
use Phoenix.ConnTest
alias Phoenix.Test.ConnTest.Router
defmodule ConnError do
defexception [message: nil, plug_status: 500]
end
Application.put_env(:phoenix, Phoenix.Test.ConnTest.Endpoint, [])
defmodule Endpoint do
use Phoenix.Endpoint, otp_app: :phoenix
def init(opts), do: opts
def call(conn, :set), do: resp(conn, 200, "ok")
def call(conn, opts) do
put_in(super(conn, opts).private[:endpoint], opts)
|> Router.call(Router.init([]))
end
end
@endpoint Endpoint
setup_all do
Endpoint.start_link()
:ok
end
test "build_conn/0 returns a new connection" do
conn = build_conn()
assert conn.method == "GET"
assert conn.path_info == []
assert conn.private.plug_skip_csrf_protection
assert conn.private.phoenix_recycled
end
test "build_conn/2 returns a new connection" do
conn = build_conn(:post, "/hello")
assert conn.method == "POST"
assert conn.path_info == ["hello"]
assert conn.private.plug_skip_csrf_protection
assert conn.private.phoenix_recycled
end
test "dispatch/5 with path" do
conn = post build_conn(), "/hello", foo: "bar"
assert conn.method == "POST"
assert conn.path_info == ["hello"]
assert conn.params == %{"foo" => "bar"}
assert conn.private.endpoint == []
refute conn.private.phoenix_recycled
end
test "dispatch/5 with action" do
conn = post build_conn(), :hello, %{foo: "bar"}
assert conn.method == "POST"
assert conn.path_info == []
assert conn.params == %{"foo" => "bar"}
assert conn.private.endpoint == :hello
refute conn.private.phoenix_recycled
end
test "dispatch/5 with binary body" do
assert_raise ArgumentError, fn ->
post build_conn(), :hello, "foo=bar"
end
conn =
build_conn()
|> put_req_header("content-type", "application/json")
|> post(:hello, "[1, 2, 3]")
|> Plug.Parsers.call(Plug.Parsers.init(parsers: [:json], json_decoder: Poison))
assert conn.method == "POST"
assert conn.path_info == []
assert conn.params == %{"_json" => [1, 2, 3]}
end
test "dispatch/5 with recycling" do
conn =
build_conn()
|> put_req_header("hello", "world")
|> post(:hello)
assert get_req_header(conn, "hello") == ["world"]
conn =
conn
|> put_req_header("hello", "skipped")
|> post(:hello)
assert get_req_header(conn, "hello") == []
conn =
conn
|> recycle()
|> put_req_header("hello", "world")
|> post(:hello)
assert get_req_header(conn, "hello") == ["world"]
end
test "dispatch/5 with :set state automatically sends" do
conn = get build_conn(), :set
assert conn.state == :sent
assert conn.status == 200
assert conn.resp_body == "ok"
refute conn.private.phoenix_recycled
end
test "recycle/1" do
conn =
build_conn()
|> get("/")
|> put_req_header("hello", "world")
|> put_req_cookie("req_cookie", "req_cookie")
|> put_req_cookie("del_cookie", "del_cookie")
|> put_req_cookie("over_cookie", "pre_cookie")
|> put_resp_cookie("over_cookie", "pos_cookie")
|> put_resp_cookie("resp_cookie", "resp_cookie")
|> delete_resp_cookie("del_cookie")
conn = conn |> recycle() |> fetch_cookies()
assert get_req_header(conn, "hello") == []
assert conn.cookies == %{"req_cookie" => "req_cookie",
"over_cookie" => "pos_cookie",
"resp_cookie" => "resp_cookie"}
end
test "ensure_recycled/1" do
conn =
build_conn()
|> put_req_header("hello", "world")
|> ensure_recycled()
assert get_req_header(conn, "hello") == ["world"]
conn =
put_in(conn.private.phoenix_recycled, false)
|> ensure_recycled()
assert get_req_header(conn, "hello") == []
end
test "put_req_header/3 and delete_req_header/3" do
conn = build_conn(:get, "/")
assert get_req_header(conn, "foo") == []
conn = put_req_header(conn, "foo", "bar")
assert get_req_header(conn, "foo") == ["bar"]
conn = put_req_header(conn, "foo", "baz")
assert get_req_header(conn, "foo") == ["baz"]
conn = delete_req_header(conn, "foo")
assert get_req_header(conn, "foo") == []
end
test "put_req_cookie/3 and delete_req_cookie/2" do
conn = build_conn(:get, "/")
assert get_req_header(conn, "cookie") == []
conn = conn |> put_req_cookie("foo", "bar")
assert get_req_header(conn, "cookie") == ["foo=bar"]
conn = conn |> delete_req_cookie("foo")
assert get_req_header(conn, "cookie") == []
end
test "response/2" do
conn = build_conn(:get, "/")
assert conn |> resp(200, "ok") |> response(200) == "ok"
assert conn |> send_resp(200, "ok") |> response(200) == "ok"
assert conn |> send_resp(200, "ok") |> response(:ok) == "ok"
assert_raise RuntimeError,
~r"expected connection to have a response but no response was set/sent", fn ->
build_conn(:get, "/") |> response(200)
end
assert_raise RuntimeError,
"expected response with status 200, got: 404, with body:\noops", fn ->
build_conn(:get, "/") |> resp(404, "oops") |> response(200)
end
end
test "html_response/2" do
assert build_conn(:get, "/") |> put_resp_content_type("text/html")
|> resp(200, "ok") |> html_response(:ok) == "ok"
assert_raise RuntimeError,
"no content-type was set, expected a html response", fn ->
build_conn(:get, "/") |> resp(200, "ok") |> html_response(200)
end
end
test "json_response/2" do
assert build_conn(:get, "/") |> put_resp_content_type("application/json")
|> resp(200, "{}") |> json_response(:ok) == %{}
assert build_conn(:get, "/") |> put_resp_content_type("application/vnd.api+json")
|> resp(200, "{}") |> json_response(:ok) == %{}
assert build_conn(:get, "/") |> put_resp_content_type("application/vnd.collection+json")
|> resp(200, "{}") |> json_response(:ok) == %{}
assert build_conn(:get, "/") |> put_resp_content_type("application/vnd.hal+json")
|> resp(200, "{}") |> json_response(:ok) == %{}
assert build_conn(:get, "/") |> put_resp_content_type("application/ld+json")
|> resp(200, "{}") |> json_response(:ok) == %{}
assert_raise RuntimeError,
"no content-type was set, expected a json response", fn ->
build_conn(:get, "/") |> resp(200, "ok") |> json_response(200)
end
assert_raise RuntimeError,
"could not decode JSON body, invalid token \"o\" in body:\n\nok", fn ->
build_conn(:get, "/") |> put_resp_content_type("application/json")
|> resp(200, "ok") |> json_response(200)
end
assert_raise RuntimeError, "could not decode JSON body, body is empty", fn ->
build_conn(:get, "/")
|> put_resp_content_type("application/json")
|> resp(200, "")
|> json_response(200)
end
assert_raise RuntimeError, ~s(expected response with status 200, got: 400, with body:\n{"error": "oh oh"}), fn ->
build_conn(:get, "/")
|> put_resp_content_type("application/json")
|> resp(400, ~s({"error": "oh oh"}))
|> json_response(200)
end
end
test "text_response/2" do
assert build_conn(:get, "/") |> put_resp_content_type("text/plain")
|> resp(200, "ok") |> text_response(:ok) == "ok"
assert_raise RuntimeError,
"no content-type was set, expected a text response", fn ->
build_conn(:get, "/") |> resp(200, "ok") |> text_response(200)
end
end
test "response_content_type/2" do
conn = build_conn(:get, "/")
assert put_resp_content_type(conn, "text/html") |> response_content_type(:html) ==
"text/html; charset=utf-8"
assert put_resp_content_type(conn, "text/plain") |> response_content_type(:text) ==
"text/plain; charset=utf-8"
assert put_resp_content_type(conn, "application/json") |> response_content_type(:json) ==
"application/json; charset=utf-8"
assert_raise RuntimeError,
"no content-type was set, expected a html response", fn ->
conn |> response_content_type(:html)
end
assert_raise RuntimeError,
"expected content-type for html, got: \"text/plain; charset=utf-8\"", fn ->
put_resp_content_type(conn, "text/plain") |> response_content_type(:html)
end
end
test "redirected_to/1" do
conn =
build_conn(:get, "/")
|> put_resp_header("location", "new location")
|> send_resp(302, "foo")
assert redirected_to(conn) == "new location"
end
test "redirected_to/2" do
Enum.each 300..308, fn(status) ->
conn =
build_conn(:get, "/")
|> put_resp_header("location", "new location")
|> send_resp(status, "foo")
assert redirected_to(conn, status) == "new location"
end
end
test "redirected_to/2 without header" do
assert_raise RuntimeError,
"no location header was set on redirected_to", fn ->
assert build_conn(:get, "/")
|> send_resp(302, "ok")
|> redirected_to()
end
end
test "redirected_to/2 without redirection" do
assert_raise RuntimeError,
"expected redirection with status 302, got: 200", fn ->
build_conn(:get, "/")
|> put_resp_header("location", "new location")
|> send_resp(200, "ok")
|> redirected_to()
end
end
test "redirected_to/2 without response" do
assert_raise RuntimeError,
~r"expected connection to have redirected but no response was set/sent", fn ->
build_conn(:get, "/")
|> redirected_to()
end
end
test "bypass_through/3 bypasses route match and invokes pipeline" do
conn = get(build_conn(), "/")
assert conn.assigns[:catch_all]
conn =
build_conn()
|> bypass_through(Router, :browser)
|> get("/")
assert conn.assigns[:bypassed] == [:browser]
refute conn.assigns[:catch_all]
conn =
build_conn()
|> bypass_through(Router, [:api])
|> get("/")
assert conn.assigns[:bypassed] == [:api]
refute conn.assigns[:catch_all]
conn =
build_conn()
|> bypass_through(Router, [:browser, :api])
|> get("/")
assert conn.assigns[:bypassed] == [:browser, :api]
refute conn.assigns[:catch_all]
end
test "bypass_through/2 bypasses route match" do
conn =
build_conn()
|> bypass_through(Router, [])
|> get("/")
refute conn.assigns[:catch_all]
end
test "bypass_through/1 bypasses router" do
conn =
build_conn()
|> bypass_through()
|> get("/")
refute conn.assigns[:catch_all]
end
test "assert_error_sent/2 with expected error response" do
response = assert_error_sent :not_found, fn ->
get(build_conn(), "/stat", action: fn _ -> raise ConnError, plug_status: 404 end)
end
assert {404, [_h | _t], "404.html from Phoenix.ErrorView"} = response
response = assert_error_sent 400, fn ->
get(build_conn(), "/stat", action: fn _ -> raise ConnError, plug_status: 400 end)
end
assert {400, [_h | _t], "400.html from Phoenix.ErrorView"} = response
end
test "assert_error_sent/2 with status mismatch assertion" do
assert_raise ExUnit.AssertionError, ~r/expected error to be sent as 400 status, but got 500 from.*RuntimeError/s, fn ->
assert_error_sent 400, fn ->
get(build_conn(), "/stat", action: fn _conn -> raise RuntimeError end)
end
end
end
test "assert_error_sent/2 with no error" do
assert_raise ExUnit.AssertionError, ~r/expected error to be sent as 404 status, but no error happened/, fn ->
assert_error_sent 404, fn -> get(build_conn(), "/") end
end
end
test "assert_error_sent/2 with error but no response" do
assert_raise ExUnit.AssertionError, ~r/expected error to be sent as 404 status, but got an error with no response from.*RuntimeError/s, fn ->
assert_error_sent 404, fn -> raise "oops" end
end
end
test "assert_error_sent/2 with response but no error" do
assert_raise ExUnit.AssertionError, ~r/expected error to be sent as 400 status, but response sent 400 without error/, fn ->
assert_error_sent :bad_request, fn ->
get(build_conn(), "/stat", action: fn conn -> Plug.Conn.send_resp(conn, 400, "") end)
end
end
end
for method <- [:get, :post, :put, :delete] do
@method method
test "#{method} helper raises ArgumentError for mismatched conn" do
assert_raise ArgumentError, ~r/expected first argument to #{@method} to be/, fn ->
unquote(@method)("/foo/bar", %{baz: "baz"})
end
end
end
end
| 31.296552 | 145 | 0.61591 |
f73db57d2088c6f75d780ffa7b0430e1303ff921 | 153 | exs | Elixir | server/priv/repo/migrations/20201212135024_add_unique_username_index.exs | jeepers3327/prepply | 64b6be3b832fddf429faa31f5f7c1b93b842f821 | [
"MIT"
] | 2 | 2021-03-04T15:21:14.000Z | 2021-03-21T13:43:07.000Z | server/priv/repo/migrations/20201212135024_add_unique_username_index.exs | jeepers3327/prepply | 64b6be3b832fddf429faa31f5f7c1b93b842f821 | [
"MIT"
] | null | null | null | server/priv/repo/migrations/20201212135024_add_unique_username_index.exs | jeepers3327/prepply | 64b6be3b832fddf429faa31f5f7c1b93b842f821 | [
"MIT"
] | null | null | null | defmodule Prepply.Repo.Migrations.AddUniqueUsernameIndex do
use Ecto.Migration
def change do
create unique_index(:users, [:username])
end
end
| 19.125 | 59 | 0.771242 |
f73db71067413631aa16d53ee1a999ba0b5b2ae4 | 8,979 | exs | Elixir | test/oidc/id_token_test.exs | YuriiZdyrko/oidc | 5587586a3ce00d43aa9df38052e95e17d8536033 | [
"Apache-2.0"
] | null | null | null | test/oidc/id_token_test.exs | YuriiZdyrko/oidc | 5587586a3ce00d43aa9df38052e95e17d8536033 | [
"Apache-2.0"
] | 1 | 2021-09-22T13:25:07.000Z | 2021-09-22T13:25:07.000Z | test/oidc/id_token_test.exs | YuriiZdyrko/oidc | 5587586a3ce00d43aa9df38052e95e17d8536033 | [
"Apache-2.0"
] | null | null | null | defmodule OIDC.IDTokenTest do
use ExUnit.Case
alias OIDC.IDToken
setup_all do
[client: client_conf(), op: op_metadata()]
end
test "valid signed ID token is verified", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op
}
id_token = signed_id_token(op, client)
assert {:ok, _} = IDToken.verify(id_token, client, verification_data)
end
test "valid encrypted ID token is verified", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op
}
id_token = signed_id_token(op, client) |> encrypt(client)
assert {:ok, _} = IDToken.verify(id_token, client, verification_data)
end
test "valid signed ID token with mandatory acr and auth_time is verified", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op,
mandatory_acrs: ["loa2", "loa3"],
auth_time_required: true
}
id_token = signed_id_token(op, client, auth_time: now(), acr: "loa2")
assert {:ok, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token with invalid signature is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op
}
id_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token with invalid encryption is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op
}
id_token = " eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ.OKOawDo13gRp2ojaHV7LFpZcgV7T6DVZKTyKOMTYUmKoTCVJRgckCL9kiMT03JGeipsEdY3mx_etLbbWSrFr05kLzcSr4qKAq7YN7e9jwQRb23nfa6c9d-StnImGyFDbSv04uVuxIp5Zms1gNxKKK2Da14B8S4rzVRltdYwam_lDp5XnZAYpQdb76FdIKLaVmqgfwX7XWRxv2322i-vDxRfqNzo_tETKzpVLzfiwQyeyPGLBIO56YJ7eObdv0je81860ppamavo35UgoRdbYaBcoh9QcfylQr66oc6vFWXRcZ_ZT2LawVCWTIy3brGPi6UklfCpIMfIjf7iGdXKHzg.48V1_ALb6US04U3b.5eym8TW_c8SuK0ltJ3rpYIzOeDQz7TALvtu6UG9oMo4vpzs9tX_EFShS8iB7j6jiSdiwkIr3ajwQzaBtQD_A.XFBoMYUZodetZdvTiFvSkQ"
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token with missing issuer is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op
}
id_token = signed_id_token(op, client, iss: nil)
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token with missing sub is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op
}
id_token = signed_id_token(op, client, sub: nil)
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token with missing aud is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op
}
id_token = signed_id_token(op, client, aud: nil)
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token with missing exp is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op
}
id_token = signed_id_token(op, client, exp: nil)
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token with missing iat is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op
}
id_token = signed_id_token(op, client, iat: nil)
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token with invalid issuer is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op
}
id_token = signed_id_token(op, client, iss: "https://wrong.com")
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token with invalid audience is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op
}
id_token = signed_id_token(op, client, aud: "another_client")
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token is expired and is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op
}
id_token = signed_id_token(op, client, exp: now() - 1)
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token was issued to far in the past and is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op,
id_token_iat_max_time_gap: 30
}
id_token = signed_id_token(op, client, iat: now() - 31)
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token nonce doesn't match and is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op,
nonce: "some another nonce"
}
id_token = signed_id_token(op, client, nonce: "some nonce")
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token is absent althouth required, and is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op,
mandatory_acrs: ["loa2", "loa3"]
}
id_token = signed_id_token(op, client)
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token ACR is not acceptable and is rejected", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op,
mandatory_acrs: ["loa2", "loa3"]
}
id_token = signed_id_token(op, client, acr: "loa1")
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
test "ID token auth_time is absent although required", %{client: client, op: op} do
verification_data = %{
issuer: op["issuer"],
client_id: client["client_id"],
server_metadata: op,
auth_time_required: true
}
id_token = signed_id_token(op, client)
assert {:error, _} = IDToken.verify(id_token, client, verification_data)
end
defp signed_id_token(op_metadata, client_conf, claims \\ []) do
claims_serialized =
[
iss: op_metadata["issuer"],
sub: "user_1",
aud: client_conf["client_id"],
exp: now() + 30,
iat: now()
]
|> Keyword.merge(claims)
|> Enum.filter(fn {_k, v} -> v != nil end)
|> Enum.filter(fn {_k, v} -> v != [] end)
|> Enum.into(%{})
|> Jason.encode!()
jwk =
op_metadata["jwks"]["keys"]
|> List.first()
|> JOSE.JWK.from_map()
JOSE.JWS.sign(jwk, claims_serialized, %{"alg" => "ES256"})
|> JOSE.JWS.compact()
|> elem(1)
end
defp encrypt(signed_id_token, client_conf) do
jwk = client_conf["jwks"]["keys"] |> List.first() |> JOSE.JWK.from_map()
JOSE.JWE.block_encrypt(jwk, signed_id_token, %{"alg" => "dir", "enc" => "A128CBC-HS256"})
|> JOSE.JWE.compact()
|> elem(1)
end
def client_conf() do
%{
"client_id" => "client_1",
"id_token_signed_response_alg" => "ES256",
"id_token_encrypted_response_alg" => "dir",
"jwks" => %{
"keys" => [
%{"k" => "STlqtIOhWJjoVnYjUjxFLZ6oN1oB70QARGSTWQ_5XgM", "kty" => "oct"}
]
}
}
end
defp op_metadata() do
%{
"issuer" => "https://example.com",
"jwks" => %{
"keys" => [
%{
"crv" => "P-256",
"d" => "bZa5NEa3OuDAxNs5LvpwPsYHBj0Tmkhr_dzynwUsarI",
"kty" => "EC",
"x" => "OpLxw9HqCn50523Rg6s59yE089s7f89HpAgMe9bn6RU",
"y" => "nzMjJbOdAHQOVIT9KJXJCve_SVRC_3hIvmaX-fnze5g"
}
]
}
}
end
defp now() do
System.system_time(:second)
end
end
| 29.93 | 532 | 0.64907 |
f73dcd5837f9e02c6fd5d5acc43d2ff7b952c96d | 2,704 | ex | Elixir | lib/hui/encode.ex | bluedevelz/hui | e5f24a30ade504db3adbffab1aeec90d490ac6a0 | [
"Apache-2.0"
] | 13 | 2018-09-06T12:42:18.000Z | 2021-06-15T15:13:13.000Z | lib/hui/encode.ex | bluedevelz/hui | e5f24a30ade504db3adbffab1aeec90d490ac6a0 | [
"Apache-2.0"
] | 27 | 2019-08-22T07:02:27.000Z | 2022-02-05T05:27:30.000Z | lib/hui/encode.ex | bluedevelz/hui | e5f24a30ade504db3adbffab1aeec90d490ac6a0 | [
"Apache-2.0"
] | 7 | 2019-08-22T06:29:05.000Z | 2021-10-16T15:39:21.000Z | defmodule Hui.Encode do
@moduledoc """
Utilities for encoding Solr query and update data structures.
"""
@type options :: __MODULE__.Options.t()
@url_delimiters {?=, ?&}
@json_delimiters {?:, ?,}
defmodule Options do
@moduledoc false
defstruct [:per_field, :prefix, type: :url]
@type t :: %__MODULE__{
type: :url | :json,
per_field: binary,
prefix: binary
}
end
@doc """
Encodes keywords list into IO data.
"""
@spec encode(keyword() | map()) :: iodata()
def encode([]), do: []
def encode(query) when is_list(query), do: encode(query, %Options{})
def encode(query) when is_map(query), do: encode(query |> Map.to_list(), %Options{})
@doc """
Encodes keywords of Solr query structs that require special handling into IO data.
"""
@spec encode(keyword(), options) :: iodata()
def encode(query, options)
def encode([h | t], %{type: :url} = opts), do: transform({h, t}, opts, @url_delimiters)
def encode([h | t], %{type: :json} = opts), do: transform({h, t}, opts, @json_delimiters)
@doc false
def encode_json([], %{type: :json}), do: [?{, ?}]
def encode_json(query, %{type: :json} = opts), do: [?{, encode(query, opts), ?}]
# expands and transforms fq: [x, y, z] => "fq=x&fq=&fq=z"
defp transform({{k, v}, t}, %{type: :url} = opts, _delimiters) when is_list(v) do
encode(Enum.map(v, &{k, &1}) ++ t, opts)
end
defp transform({{_k, %{:__struct__ => _} = v}, t}, opts, {_eql, delimiter}) do
case t do
[] -> Hui.Encoder.encode(v)
_ -> [Hui.Encoder.encode(v), delimiter | [encode(t, opts)]]
end
end
defp transform({h, []}, opts, {eql, _delimiter}), do: [key(h, opts), eql, value(h, opts)]
defp transform({h, t}, opts, {eql, delimiter}) do
[key(h, opts), eql, value(h, opts), delimiter | [encode(t, opts)]]
end
defp key({k, _v}, %{prefix: nil, type: :url}), do: to_string(k)
defp key({k, _v}, %{prefix: nil, type: :json}), do: [?", to_string(k), ?"]
defp key({k, _v}, %{prefix: prefix, per_field: field}) do
key = to_string(k)
cond do
k in [:facet, :mlt, :spellcheck, :suggest] -> key
String.ends_with?(prefix, key) -> prefix
field != nil -> ["f", ".", field, ".", prefix, ".", key] |> to_string()
field == nil -> [prefix, ".", key] |> to_string()
end
end
defp value({_k, v}, %{type: :url}), do: URI.encode_www_form(to_string(v))
defp value({_k, v}, %{type: :json}), do: Jason.encode_to_iodata!(v)
@doc false
@spec sanitise(list()) :: list()
def sanitise(query) do
query
|> Enum.reject(fn {k, v} ->
v in ["", nil, []] or k == :__struct__ or k == :per_field
end)
end
end
| 30.727273 | 91 | 0.576553 |
f73de07f4deefd3640e64ff246bcc6511dc66950 | 2,742 | ex | Elixir | lib/cadet_web/admin_controllers/admin_achievements_controller.ex | chownces/cadet | 0d8b264e4fad1c9aaab7ef3f037ac4e07a4c9b22 | [
"Apache-2.0"
] | null | null | null | lib/cadet_web/admin_controllers/admin_achievements_controller.ex | chownces/cadet | 0d8b264e4fad1c9aaab7ef3f037ac4e07a4c9b22 | [
"Apache-2.0"
] | 10 | 2022-02-24T17:57:38.000Z | 2022-03-31T07:43:05.000Z | lib/cadet_web/admin_controllers/admin_achievements_controller.ex | chownces/cadet | 0d8b264e4fad1c9aaab7ef3f037ac4e07a4c9b22 | [
"Apache-2.0"
] | 1 | 2019-07-17T15:51:58.000Z | 2019-07-17T15:51:58.000Z | defmodule CadetWeb.AdminAchievementsController do
use CadetWeb, :controller
use PhoenixSwagger
alias Cadet.Incentives.Achievements
def bulk_update(conn, %{"achievements" => achievements}) do
achievements
|> Enum.map(&json_to_achievement(&1))
|> Achievements.upsert_many()
|> handle_standard_result(conn)
end
def update(conn, %{"uuid" => uuid, "achievement" => achievement}) do
achievement
|> json_to_achievement(uuid)
|> Achievements.upsert()
|> handle_standard_result(conn)
end
def delete(conn, %{"uuid" => uuid}) do
uuid
|> Achievements.delete()
|> handle_standard_result(conn)
end
defp json_to_achievement(json, uuid \\ nil) do
json =
json
|> snake_casify_string_keys_recursive()
|> rename_keys([
{"deadline", "close_at"},
{"release", "open_at"},
{"card_background", "card_tile_url"}
])
|> case do
map = %{"view" => view} ->
map
|> Map.delete("view")
|> Map.merge(
view
|> rename_keys([{"cover_image", "canvas_url"}])
|> Map.take(~w(canvas_url description completion_text))
)
map ->
map
end
if is_nil(uuid) do
json
else
Map.put(json, "uuid", uuid)
end
end
swagger_path :update do
put("/admin/achievements/{uuid}")
summary("Inserts or updates an achievement")
security([%{JWT: []}])
parameters do
uuid(:path, :string, "Achievement UUID; takes precendence over UUID in payload",
required: true,
format: :uuid
)
achievement(
:body,
Schema.ref(:Achievement),
"The achievement to insert, or properties to update",
required: true
)
end
response(204, "Success")
response(401, "Unauthorised")
response(403, "Forbidden")
end
swagger_path :bulk_update do
put("/admin/achievements")
summary("Inserts or updates achievements")
security([%{JWT: []}])
parameters do
achievement(
:body,
Schema.array(:Achievement),
"The achievements to insert or sets of properties to update",
required: true
)
end
response(204, "Success")
response(401, "Unauthorised")
response(403, "Forbidden")
end
swagger_path :delete do
PhoenixSwagger.Path.delete("/admin/achievements/{uuid}")
summary("Deletes an achievement")
security([%{JWT: []}])
parameters do
uuid(:path, :string, "Achievement UUID", required: true, format: :uuid)
end
response(204, "Success")
response(401, "Unauthorised")
response(403, "Forbidden")
response(404, "Achievement not found")
end
end
| 22.661157 | 86 | 0.602115 |
f73e2f4ecf7d562e4b64a8722107d082f8c7c666 | 794 | exs | Elixir | server/priv/repo/migrations/20210718165643_create_projects_auth_tables.exs | felixwolter/idai-field | 146ab8dbdedb23035a4ba19eac95f02a1fa2329f | [
"Apache-2.0"
] | null | null | null | server/priv/repo/migrations/20210718165643_create_projects_auth_tables.exs | felixwolter/idai-field | 146ab8dbdedb23035a4ba19eac95f02a1fa2329f | [
"Apache-2.0"
] | null | null | null | server/priv/repo/migrations/20210718165643_create_projects_auth_tables.exs | felixwolter/idai-field | 146ab8dbdedb23035a4ba19eac95f02a1fa2329f | [
"Apache-2.0"
] | null | null | null | defmodule IdaiFieldServer.Repo.Migrations.CreateProjectsAuthTables do
use Ecto.Migration
def change do
execute "CREATE EXTENSION IF NOT EXISTS citext", ""
create table(:projects) do
add :email, :citext, null: false
add :hashed_password, :string, null: false
add :confirmed_at, :naive_datetime
timestamps()
end
create unique_index(:projects, [:email])
create table(:projects_tokens) do
add :project_id, references(:projects, on_delete: :delete_all), null: false
add :token, :binary, null: false
add :context, :string, null: false
add :sent_to, :string
timestamps(updated_at: false)
end
create index(:projects_tokens, [:project_id])
create unique_index(:projects_tokens, [:context, :token])
end
end
| 28.357143 | 81 | 0.687657 |
f73e357d00009ad96897ac6196fef2920e59dd5a | 1,857 | ex | Elixir | clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/identitytoolkit_relyingparty_email_link_signin_request.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/identitytoolkit_relyingparty_email_link_signin_request.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/identitytoolkit_relyingparty_email_link_signin_request.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.IdentityToolkit.V3.Model.IdentitytoolkitRelyingpartyEmailLinkSigninRequest do
@moduledoc """
Request to sign in with email.
## Attributes
- email (String.t): The email address of the user. Defaults to: `null`.
- idToken (String.t): Token for linking flow. Defaults to: `null`.
- oobCode (String.t): The confirmation code. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:email => any(),
:idToken => any(),
:oobCode => any()
}
field(:email)
field(:idToken)
field(:oobCode)
end
defimpl Poison.Decoder,
for: GoogleApi.IdentityToolkit.V3.Model.IdentitytoolkitRelyingpartyEmailLinkSigninRequest do
def decode(value, options) do
GoogleApi.IdentityToolkit.V3.Model.IdentitytoolkitRelyingpartyEmailLinkSigninRequest.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.IdentityToolkit.V3.Model.IdentitytoolkitRelyingpartyEmailLinkSigninRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.474576 | 97 | 0.736134 |
f73e5e39e736a57f60726528562114a586de1364 | 1,513 | ex | Elixir | clients/classroom/lib/google_api/classroom/v1/model/course_work_changes_info.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/classroom/lib/google_api/classroom/v1/model/course_work_changes_info.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/classroom/lib/google_api/classroom/v1/model/course_work_changes_info.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Classroom.V1.Model.CourseWorkChangesInfo do
@moduledoc """
Information about a `Feed` with a `feed_type` of `COURSE_WORK_CHANGES`.
## Attributes
* `courseId` (*type:* `String.t`, *default:* `nil`) - The `course_id` of the course to subscribe to work changes for.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:courseId => String.t()
}
field(:courseId)
end
defimpl Poison.Decoder, for: GoogleApi.Classroom.V1.Model.CourseWorkChangesInfo do
def decode(value, options) do
GoogleApi.Classroom.V1.Model.CourseWorkChangesInfo.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Classroom.V1.Model.CourseWorkChangesInfo do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.191489 | 121 | 0.741573 |
f73e784805a317763a861c1f684054f26f8c25cf | 502 | ex | Elixir | lib/open_submissions/submissions/submission.ex | csfalcione/open-submissions-api | b7af153ebe9c1a9bd487f7fc30a25007bdf2b9c3 | [
"MIT"
] | 7 | 2019-02-11T14:31:24.000Z | 2021-12-28T08:15:00.000Z | lib/open_submissions/submissions/submission.ex | tblount/open-submissions-api | fb7395175e8079a659bc65ff7c5a7f1f4fc4b422 | [
"MIT"
] | null | null | null | lib/open_submissions/submissions/submission.ex | tblount/open-submissions-api | fb7395175e8079a659bc65ff7c5a7f1f4fc4b422 | [
"MIT"
] | 2 | 2019-02-11T14:31:37.000Z | 2021-12-28T08:15:01.000Z | defmodule OpenSubmissions.Submissions.Submission do
use Ecto.Schema
import Ecto.Changeset
schema "submissions" do
field :code, :string
field :language, :string
field :status, :string
field :problem_id, :id
timestamps()
end
@doc false
def changeset(submission, attrs) do
submission
|> cast(attrs, [:code, :language, :status, :problem_id])
|> foreign_key_constraint(:problem_id)
|> validate_required([:code, :language, :status, :problem_id])
end
end
| 21.826087 | 66 | 0.689243 |
f73e8fe6823f47440c2655a0eb2cc2906edb6cfe | 596 | exs | Elixir | test/void_elements_test.exs | aforward-oss/earmark | b44d4817aa2b4047b07f91d633ae83ed27c695ed | [
"Apache-2.0"
] | null | null | null | test/void_elements_test.exs | aforward-oss/earmark | b44d4817aa2b4047b07f91d633ae83ed27c695ed | [
"Apache-2.0"
] | null | null | null | test/void_elements_test.exs | aforward-oss/earmark | b44d4817aa2b4047b07f91d633ae83ed27c695ed | [
"Apache-2.0"
] | null | null | null | defmodule VoidElementsTest do
use ExUnit.Case
import ExUnit.CaptureIO
[
{~s[<img src="whatevs.png">], nil},
{~s[<area alt="alt" href="http://some.image.com/image">], nil},
{~s[<br>], nil},
{~s[<hr>], ~s[<hr>]},
{~s[<wbr>], nil},
] |> Enum.each( fn {inp, out} ->
test "#{inp} is transformed to #{out} without errors" do
stderr_out = capture_io(:stderr, fn ->
result = Earmark.to_html(unquote(inp))
expected = unquote(out||inp)
assert result == expected
end)
assert stderr_out == ""
end
end)
end
| 25.913043 | 67 | 0.540268 |
f73e9ad0f2e40ab1ca6c6e0d8573cb6d1e81ef73 | 383 | ex | Elixir | lib/list_supervisor.ex | rafaelmws/supervised_list_server | 112886580c70f53b21a7cd24065a7bbffa8fa764 | [
"MIT"
] | null | null | null | lib/list_supervisor.ex | rafaelmws/supervised_list_server | 112886580c70f53b21a7cd24065a7bbffa8fa764 | [
"MIT"
] | null | null | null | lib/list_supervisor.ex | rafaelmws/supervised_list_server | 112886580c70f53b21a7cd24065a7bbffa8fa764 | [
"MIT"
] | null | null | null | defmodule ListSupervisor do
use Supervisor
def start_link do
end
def init([]) do
end
def start_server(supervisor, name) do
IO.puts "ListSupervisor.start_server(#{name})"
Supervisor.start_child(supervisor, name)
end
def stop_server(supervisor, pid) do
Supervisor.delete_child(supervisor, pid)
Supervisor.terminate_child(supervisor, pid)
end
end
| 18.238095 | 50 | 0.733681 |
f73e9e0e7d6ff69cac9cee393543f9a4d7159db2 | 22,482 | exs | Elixir | test/phoenix/router/helpers_test.exs | JWKyle/phoenix-test | 87066b7335764f7c3c4d098fdc85bdad2ab2ef54 | [
"MIT"
] | null | null | null | test/phoenix/router/helpers_test.exs | JWKyle/phoenix-test | 87066b7335764f7c3c4d098fdc85bdad2ab2ef54 | [
"MIT"
] | null | null | null | test/phoenix/router/helpers_test.exs | JWKyle/phoenix-test | 87066b7335764f7c3c4d098fdc85bdad2ab2ef54 | [
"MIT"
] | null | null | null | defmodule Phoenix.Router.HelpersTest do
use ExUnit.Case, async: true
use RouterHelper
alias Phoenix.Router.Helpers
## Unit tests
test "defhelper with :identifiers" do
route = build(:match, :get, "/foo/:bar", nil, Hello, :world, "hello_world")
assert extract_defhelper(route, 0) == String.trim """
def(hello_world_path(conn_or_endpoint, :world, bar)) do
hello_world_path(conn_or_endpoint, :world, bar, [])
end
"""
assert extract_defhelper(route, 1) == String.trim """
def(hello_world_path(conn_or_endpoint, :world, bar, params)) do
path(conn_or_endpoint, segments(("" <> "/foo") <> "/" <> URI.encode(to_param(bar), &URI.char_unreserved?/1), params, ["bar"]))
end
"""
end
test "defhelper with *identifiers" do
route = build(:match, :get, "/foo/*bar", nil, Hello, :world, "hello_world")
assert extract_defhelper(route, 0) == String.trim """
def(hello_world_path(conn_or_endpoint, :world, bar)) do
hello_world_path(conn_or_endpoint, :world, bar, [])
end
"""
assert extract_defhelper(route, 1) == String.trim """
def(hello_world_path(conn_or_endpoint, :world, bar, params)) do
path(conn_or_endpoint, segments(("" <> "/foo") <> "/" <> Enum.map_join(bar, "/", fn s -> URI.encode(s, &URI.char_unreserved?/1) end), params, ["bar"]))
end
"""
end
defp build(kind, verb, path, host, controller, action, helper) do
Phoenix.Router.Route.build(1, kind, verb, path, host, controller, action, helper, [], %{}, %{})
end
defp extract_defhelper(route, pos) do
{:__block__, _, block} = Helpers.defhelper(route, Phoenix.Router.Route.exprs(route))
Enum.fetch!(block, pos) |> Macro.to_string()
end
## Integration tests
defmodule Router do
use Phoenix.Router
get "/posts/top", PostController, :top, as: :top
get "/posts/:id", PostController, :show
get "/posts/file/*file", PostController, :file
get "/posts/skip", PostController, :skip, as: nil
get "/chat*js_route", ChatController, :show
resources "/users", UserController do
resources "/comments", CommentController do
resources "/files", FileController
end
end
resources "/files", FileController
resources "/account", UserController, as: :account, singleton: true do
resources "/page", PagesController, as: :page, only: [:show], singleton: true
end
scope "/admin", alias: Admin do
resources "/messages", MessageController
end
scope "/admin/new", alias: Admin, as: "admin" do
resources "/messages", MessageController
end
get "/", PageController, :root, as: :page
end
# Emulate regular endpoint functions
def url do
"https://example.com"
end
def static_url do
"https://static.example.com"
end
def path(path) do
path
end
def static_path(path) do
path
end
alias Router.Helpers
test "defines a __helpers__ function" do
assert Router.__helpers__ == Router.Helpers
end
test "root helper" do
conn = conn(:get, "/") |> put_private(:phoenix_endpoint, __MODULE__)
assert Helpers.page_path(conn, :root) == "/"
assert Helpers.page_path(__MODULE__, :root) == "/"
end
test "url helper with query strings" do
assert Helpers.post_path(__MODULE__, :show, 5, id: 3) == "/posts/5"
assert Helpers.post_path(__MODULE__, :show, 5, foo: "bar") == "/posts/5?foo=bar"
assert Helpers.post_path(__MODULE__, :show, 5, foo: :bar) == "/posts/5?foo=bar"
assert Helpers.post_path(__MODULE__, :show, 5, foo: true) == "/posts/5?foo=true"
assert Helpers.post_path(__MODULE__, :show, 5, foo: false) == "/posts/5?foo=false"
assert Helpers.post_path(__MODULE__, :show, 5, foo: nil) == "/posts/5?foo="
assert Helpers.post_path(__MODULE__, :show, 5, foo: ~w(bar baz)) ==
"/posts/5?foo[]=bar&foo[]=baz"
assert Helpers.post_path(__MODULE__, :show, 5, foo: %{id: 5}) ==
"/posts/5?foo[id]=5"
assert Helpers.post_path(__MODULE__, :show, 5, foo: %{__struct__: Foo, id: 5}) ==
"/posts/5?foo=5"
end
test "url helper with param protocol" do
assert Helpers.post_path(__MODULE__, :show, %{__struct__: Foo, id: 5}) == "/posts/5"
assert_raise ArgumentError, fn ->
Helpers.post_path(__MODULE__, :show, nil)
end
end
test "top-level named route" do
assert Helpers.post_path(__MODULE__, :show, 5) == "/posts/5"
assert Helpers.post_path(__MODULE__, :show, 5, []) == "/posts/5"
assert Helpers.post_path(__MODULE__, :show, 5, id: 5) == "/posts/5"
assert Helpers.post_path(__MODULE__, :show, 5, %{"id" => 5}) == "/posts/5"
assert Helpers.post_path(__MODULE__, :show, "foo") == "/posts/foo"
assert Helpers.post_path(__MODULE__, :show, "foo bar") == "/posts/foo%20bar"
assert Helpers.post_path(__MODULE__, :file, ["foo", "bar/baz"]) == "/posts/file/foo/bar%2Fbaz"
assert Helpers.post_path(__MODULE__, :file, ["foo", "bar"], []) == "/posts/file/foo/bar"
assert Helpers.post_path(__MODULE__, :file, ["foo", "bar baz"], []) == "/posts/file/foo/bar%20baz"
assert Helpers.chat_path(__MODULE__, :show, ["chat"]) == "/chat"
assert Helpers.chat_path(__MODULE__, :show, ["chat", "foo"]) == "/chat/foo"
assert Helpers.chat_path(__MODULE__, :show, ["chat/foo"]) == "/chat%2Ffoo"
assert Helpers.chat_path(__MODULE__, :show, ["chat/foo", "bar/baz"]) == "/chat%2Ffoo/bar%2Fbaz"
assert Helpers.top_path(__MODULE__, :top) == "/posts/top"
assert Helpers.top_path(__MODULE__, :top, id: 5) == "/posts/top?id=5"
assert Helpers.top_path(__MODULE__, :top, %{"id" => 5}) == "/posts/top?id=5"
assert Helpers.top_path(__MODULE__, :top, %{"id" => "foo"}) == "/posts/top?id=foo"
assert Helpers.top_path(__MODULE__, :top, %{"id" => "foo bar"}) == "/posts/top?id=foo+bar"
error_message = fn helper, arity ->
"""
No function clause for #{inspect Helpers}.#{helper}/#{arity} and action :skip. The following actions/clauses are supported:
#{helper}(conn_or_endpoint, :file, file, opts \\\\ [])
#{helper}(conn_or_endpoint, :show, id, opts \\\\ [])
""" |> String.trim
end
assert_raise UndefinedFunctionError, fn ->
Helpers.post_path(__MODULE__, :skip)
end
assert_raise UndefinedFunctionError, fn ->
Helpers.post_url(__MODULE__, :skip)
end
assert_raise ArgumentError, error_message.("post_path", 3), fn ->
Helpers.post_path(__MODULE__, :skip, 5)
end
assert_raise ArgumentError, error_message.("post_url", 3), fn ->
Helpers.post_url(__MODULE__, :skip, 5)
end
assert_raise ArgumentError, error_message.("post_path", 4), fn ->
Helpers.post_path(__MODULE__, :skip, 5, foo: "bar", other: "param")
end
assert_raise ArgumentError, error_message.("post_url", 4), fn ->
Helpers.post_url(__MODULE__, :skip, 5, foo: "bar", other: "param")
end
assert_raise ArgumentError, ~r/when building url for Phoenix.Router.HelpersTest.Router/, fn ->
Helpers.post_url("oops", :skip, 5, foo: "bar", other: "param")
end
assert_raise ArgumentError, ~r/when building path for Phoenix.Router.HelpersTest.Router/, fn ->
Helpers.post_path("oops", :skip, 5, foo: "bar", other: "param")
end
end
test "top-level named routes with complex ids" do
assert Helpers.post_path(__MODULE__, :show, "==d--+") ==
"/posts/%3D%3Dd--%2B"
assert Helpers.post_path(__MODULE__, :show, "==d--+", []) ==
"/posts/%3D%3Dd--%2B"
assert Helpers.top_path(__MODULE__, :top, id: "==d--+") ==
"/posts/top?id=%3D%3Dd--%2B"
assert Helpers.post_path(__MODULE__, :file, ["==d--+", ":O.jpg"]) ==
"/posts/file/%3D%3Dd--%2B/%3AO.jpg"
assert Helpers.post_path(__MODULE__, :file, ["==d--+", ":O.jpg"], []) ==
"/posts/file/%3D%3Dd--%2B/%3AO.jpg"
assert Helpers.post_path(__MODULE__, :file, ["==d--+", ":O.jpg"], xx: "/=+/") ==
"/posts/file/%3D%3Dd--%2B/%3AO.jpg?xx=%2F%3D%2B%2F"
end
test "resources generates named routes for :index, :edit, :show, :new" do
assert Helpers.user_path(__MODULE__, :index, []) == "/users"
assert Helpers.user_path(__MODULE__, :index) == "/users"
assert Helpers.user_path(__MODULE__, :edit, 123, []) == "/users/123/edit"
assert Helpers.user_path(__MODULE__, :edit, 123) == "/users/123/edit"
assert Helpers.user_path(__MODULE__, :show, 123, []) == "/users/123"
assert Helpers.user_path(__MODULE__, :show, 123) == "/users/123"
assert Helpers.user_path(__MODULE__, :new, []) == "/users/new"
assert Helpers.user_path(__MODULE__, :new) == "/users/new"
end
test "resources generated named routes with complex ids" do
assert Helpers.user_path(__MODULE__, :edit, "1a+/31d", []) == "/users/1a%2B%2F31d/edit"
assert Helpers.user_path(__MODULE__, :edit, "1a+/31d") == "/users/1a%2B%2F31d/edit"
assert Helpers.user_path(__MODULE__, :show, "1a+/31d", []) == "/users/1a%2B%2F31d"
assert Helpers.user_path(__MODULE__, :show, "1a+/31d") == "/users/1a%2B%2F31d"
assert Helpers.message_path(__MODULE__, :update, "8=/=d", []) == "/admin/messages/8%3D%2F%3Dd"
assert Helpers.message_path(__MODULE__, :update, "8=/=d") == "/admin/messages/8%3D%2F%3Dd"
assert Helpers.message_path(__MODULE__, :delete, "8=/=d", []) == "/admin/messages/8%3D%2F%3Dd"
assert Helpers.message_path(__MODULE__, :delete, "8=/=d") == "/admin/messages/8%3D%2F%3Dd"
assert Helpers.user_path(__MODULE__, :show, "1a+/31d", [dog: "8d="]) == "/users/1a%2B%2F31d?dog=8d%3D"
assert Helpers.user_path(__MODULE__, :index, [cat: "=8+/&"]) == "/users?cat=%3D8%2B%2F%26"
end
test "resources generates named routes for :create, :update, :delete" do
assert Helpers.message_path(__MODULE__, :create, []) == "/admin/messages"
assert Helpers.message_path(__MODULE__, :create) == "/admin/messages"
assert Helpers.message_path(__MODULE__, :update, 1, []) == "/admin/messages/1"
assert Helpers.message_path(__MODULE__, :update, 1) == "/admin/messages/1"
assert Helpers.message_path(__MODULE__, :delete, 1, []) == "/admin/messages/1"
assert Helpers.message_path(__MODULE__, :delete, 1) == "/admin/messages/1"
end
test "1-Level nested resources generates nested named routes for :index, :edit, :show, :new" do
assert Helpers.user_comment_path(__MODULE__, :index, 99, []) == "/users/99/comments"
assert Helpers.user_comment_path(__MODULE__, :index, 99) == "/users/99/comments"
assert Helpers.user_comment_path(__MODULE__, :edit, 88, 2, []) == "/users/88/comments/2/edit"
assert Helpers.user_comment_path(__MODULE__, :edit, 88, 2) == "/users/88/comments/2/edit"
assert Helpers.user_comment_path(__MODULE__, :show, 123, 2, []) == "/users/123/comments/2"
assert Helpers.user_comment_path(__MODULE__, :show, 123, 2) == "/users/123/comments/2"
assert Helpers.user_comment_path(__MODULE__, :new, 88, []) == "/users/88/comments/new"
assert Helpers.user_comment_path(__MODULE__, :new, 88) == "/users/88/comments/new"
error_message = fn helper, arity ->
"""
No function clause for #{inspect Helpers}.#{helper}/#{arity} and action :skip. The following actions/clauses are supported:
user_comment_file_path(conn_or_endpoint, :create, user_id, comment_id, opts \\\\ [])
user_comment_file_path(conn_or_endpoint, :delete, user_id, comment_id, id, opts \\\\ [])
user_comment_file_path(conn_or_endpoint, :edit, user_id, comment_id, id, opts \\\\ [])
user_comment_file_path(conn_or_endpoint, :index, user_id, comment_id, opts \\\\ [])
user_comment_file_path(conn_or_endpoint, :new, user_id, comment_id, opts \\\\ [])
user_comment_file_path(conn_or_endpoint, :show, user_id, comment_id, id, opts \\\\ [])
user_comment_file_path(conn_or_endpoint, :update, user_id, comment_id, id, opts \\\\ [])
""" |> String.trim
end
assert_raise ArgumentError, error_message.("user_comment_file_path", 4), fn ->
Helpers.user_comment_file_path(__MODULE__, :skip, 123, 456)
end
assert_raise ArgumentError, error_message.("user_comment_file_path", 5), fn ->
Helpers.user_comment_file_path(__MODULE__, :skip, 123, 456, foo: "bar")
end
arity_error_message =
"""
No action :show for helper #{inspect Helpers}.user_comment_path/3. The following actions/clauses are supported:
user_comment_path(conn_or_endpoint, :create, user_id, opts \\\\ [])
user_comment_path(conn_or_endpoint, :delete, user_id, id, opts \\\\ [])
user_comment_path(conn_or_endpoint, :edit, user_id, id, opts \\\\ [])
user_comment_path(conn_or_endpoint, :index, user_id, opts \\\\ [])
user_comment_path(conn_or_endpoint, :new, user_id, opts \\\\ [])
user_comment_path(conn_or_endpoint, :show, user_id, id, opts \\\\ [])
user_comment_path(conn_or_endpoint, :update, user_id, id, opts \\\\ [])
""" |> String.trim
assert_raise ArgumentError, arity_error_message, fn ->
Helpers.user_comment_path(__MODULE__, :show, 123)
end
end
test "multi-level nested resources generated named routes with complex ids" do
assert Helpers.user_comment_path(__MODULE__, :index, "f4/d+~=", []) ==
"/users/f4%2Fd%2B~%3D/comments"
assert Helpers.user_comment_path(__MODULE__, :index, "f4/d+~=") ==
"/users/f4%2Fd%2B~%3D/comments"
assert Helpers.user_comment_path(__MODULE__, :edit, "f4/d+~=", "x-+=/", []) ==
"/users/f4%2Fd%2B~%3D/comments/x-%2B%3D%2F/edit"
assert Helpers.user_comment_path(__MODULE__, :edit, "f4/d+~=", "x-+=/") ==
"/users/f4%2Fd%2B~%3D/comments/x-%2B%3D%2F/edit"
assert Helpers.user_comment_path(__MODULE__, :show, "f4/d+~=", "x-+=/", []) ==
"/users/f4%2Fd%2B~%3D/comments/x-%2B%3D%2F"
assert Helpers.user_comment_path(__MODULE__, :show, "f4/d+~=", "x-+=/") ==
"/users/f4%2Fd%2B~%3D/comments/x-%2B%3D%2F"
assert Helpers.user_comment_path(__MODULE__, :new, "/==/", []) ==
"/users/%2F%3D%3D%2F/comments/new"
assert Helpers.user_comment_path(__MODULE__, :new, "/==/") ==
"/users/%2F%3D%3D%2F/comments/new"
assert Helpers.user_comment_file_path(__MODULE__, :show, "f4/d+~=", "/==/", "x-+=/", []) ==
"/users/f4%2Fd%2B~%3D/comments/%2F%3D%3D%2F/files/x-%2B%3D%2F"
assert Helpers.user_comment_file_path(__MODULE__, :show, "f4/d+~=", "/==/", "x-+=/") ==
"/users/f4%2Fd%2B~%3D/comments/%2F%3D%3D%2F/files/x-%2B%3D%2F"
end
test "2-Level nested resources generates nested named routes for :index, :edit, :show, :new" do
assert Helpers.user_comment_file_path(__MODULE__, :index, 99, 1, []) ==
"/users/99/comments/1/files"
assert Helpers.user_comment_file_path(__MODULE__, :index, 99, 1) ==
"/users/99/comments/1/files"
assert Helpers.user_comment_file_path(__MODULE__, :edit, 88, 1, 2, []) ==
"/users/88/comments/1/files/2/edit"
assert Helpers.user_comment_file_path(__MODULE__, :edit, 88, 1, 2) ==
"/users/88/comments/1/files/2/edit"
assert Helpers.user_comment_file_path(__MODULE__, :show, 123, 1, 2, []) ==
"/users/123/comments/1/files/2"
assert Helpers.user_comment_file_path(__MODULE__, :show, 123, 1, 2) ==
"/users/123/comments/1/files/2"
assert Helpers.user_comment_file_path(__MODULE__, :new, 88, 1, []) ==
"/users/88/comments/1/files/new"
assert Helpers.user_comment_file_path(__MODULE__, :new, 88, 1) ==
"/users/88/comments/1/files/new"
end
test "resources without block generates named routes for :index, :edit, :show, :new" do
assert Helpers.file_path(__MODULE__, :index, []) == "/files"
assert Helpers.file_path(__MODULE__, :index) == "/files"
assert Helpers.file_path(__MODULE__, :edit, 123, []) == "/files/123/edit"
assert Helpers.file_path(__MODULE__, :edit, 123) == "/files/123/edit"
assert Helpers.file_path(__MODULE__, :show, 123, []) == "/files/123"
assert Helpers.file_path(__MODULE__, :show, 123) == "/files/123"
assert Helpers.file_path(__MODULE__, :new, []) == "/files/new"
assert Helpers.file_path(__MODULE__, :new) == "/files/new"
end
test "resource generates named routes for :show, :edit, :new, :update, :delete" do
assert Helpers.account_path(__MODULE__, :show, []) == "/account"
assert Helpers.account_path(__MODULE__, :show) == "/account"
assert Helpers.account_path(__MODULE__, :edit, []) == "/account/edit"
assert Helpers.account_path(__MODULE__, :edit) == "/account/edit"
assert Helpers.account_path(__MODULE__, :new, []) == "/account/new"
assert Helpers.account_path(__MODULE__, :new) == "/account/new"
assert Helpers.account_path(__MODULE__, :update, []) == "/account"
assert Helpers.account_path(__MODULE__, :update) == "/account"
assert Helpers.account_path(__MODULE__, :delete, []) == "/account"
assert Helpers.account_path(__MODULE__, :delete) == "/account"
end
test "2-Level nested resource generates nested named routes for :show" do
assert Helpers.account_page_path(__MODULE__, :show, []) == "/account/page"
assert Helpers.account_page_path(__MODULE__, :show) == "/account/page"
end
test "scoped route helpers generated named routes with :path, and :alias options" do
assert Helpers.message_path(__MODULE__, :index, []) == "/admin/messages"
assert Helpers.message_path(__MODULE__, :index) == "/admin/messages"
assert Helpers.message_path(__MODULE__, :show, 1, []) == "/admin/messages/1"
assert Helpers.message_path(__MODULE__, :show, 1) == "/admin/messages/1"
end
test "scoped route helpers generated named routes with :path, :alias, and :helper options" do
assert Helpers.admin_message_path(__MODULE__, :index, []) == "/admin/new/messages"
assert Helpers.admin_message_path(__MODULE__, :index) == "/admin/new/messages"
assert Helpers.admin_message_path(__MODULE__, :show, 1, []) == "/admin/new/messages/1"
assert Helpers.admin_message_path(__MODULE__, :show, 1) == "/admin/new/messages/1"
end
## Others
defp conn_with_endpoint do
conn(:get, "/") |> put_private(:phoenix_endpoint, __MODULE__)
end
defp socket_with_endpoint do
%Phoenix.Socket{endpoint: __MODULE__}
end
defp uri do
%URI{scheme: "https", host: "example.com", port: 443}
end
test "helpers module generates a static_path helper" do
assert Helpers.static_path(__MODULE__, "/images/foo.png") == "/images/foo.png"
assert Helpers.static_path(conn_with_endpoint(), "/images/foo.png") == "/images/foo.png"
assert Helpers.static_path(socket_with_endpoint(), "/images/foo.png") == "/images/foo.png"
end
test "helpers module generates a static_url helper" do
url = "https://static.example.com/images/foo.png"
assert Helpers.static_url(__MODULE__, "/images/foo.png") == url
assert Helpers.static_url(conn_with_endpoint(), "/images/foo.png") == url
assert Helpers.static_url(socket_with_endpoint(), "/images/foo.png") == url
end
test "helpers module generates a url helper" do
assert Helpers.url(__MODULE__) == "https://example.com"
assert Helpers.url(conn_with_endpoint()) == "https://example.com"
assert Helpers.url(socket_with_endpoint()) == "https://example.com"
assert Helpers.url(uri()) == "https://example.com"
end
test "helpers module generates a path helper" do
assert Helpers.path(__MODULE__, "/") == "/"
assert Helpers.path(conn_with_endpoint(), "/") == "/"
assert Helpers.path(socket_with_endpoint(), "/") == "/"
assert Helpers.path(uri(), "/") == "/"
end
test "helpers module generates named routes url helpers" do
url = "https://example.com/admin/new/messages/1"
assert Helpers.admin_message_url(__MODULE__, :show, 1) == url
assert Helpers.admin_message_url(__MODULE__, :show, 1, []) == url
assert Helpers.admin_message_url(conn_with_endpoint(), :show, 1) == url
assert Helpers.admin_message_url(conn_with_endpoint(), :show, 1, []) == url
assert Helpers.admin_message_url(socket_with_endpoint(), :show, 1) == url
assert Helpers.admin_message_url(socket_with_endpoint(), :show, 1, []) == url
assert Helpers.admin_message_url(uri(), :show, 1) == url
assert Helpers.admin_message_url(uri(), :show, 1, []) == url
end
## Script name
defmodule ScriptName do
def url do
"https://example.com"
end
def static_url do
"https://static.example.com"
end
def path(path) do
"/api" <> path
end
def static_path(path) do
"/api" <> path
end
end
def conn_with_script_name(script_name \\ ~w(api)) do
conn = conn(:get, "/")
|> put_private(:phoenix_endpoint, ScriptName)
put_in conn.script_name, script_name
end
defp uri_with_script_name do
%URI{scheme: "https", host: "example.com", port: 123, path: "/api"}
end
test "paths use script name" do
assert Helpers.page_path(ScriptName, :root) == "/api/"
assert Helpers.page_path(conn_with_script_name(), :root) == "/api/"
assert Helpers.page_path(uri_with_script_name(), :root) == "/api/"
assert Helpers.post_path(ScriptName, :show, 5) == "/api/posts/5"
assert Helpers.post_path(conn_with_script_name(), :show, 5) == "/api/posts/5"
assert Helpers.post_path(uri_with_script_name(), :show, 5) == "/api/posts/5"
end
test "urls use script name" do
assert Helpers.page_url(ScriptName, :root) ==
"https://example.com/api/"
assert Helpers.page_url(conn_with_script_name(), :root) ==
"https://example.com/api/"
assert Helpers.page_url(uri_with_script_name(), :root) ==
"https://example.com:123/api/"
assert Helpers.post_url(ScriptName, :show, 5) ==
"https://example.com/api/posts/5"
assert Helpers.post_url(conn_with_script_name(), :show, 5) ==
"https://example.com/api/posts/5"
assert Helpers.post_url(uri_with_script_name(), :show, 5) ==
"https://example.com:123/api/posts/5"
end
test "static does not use script name" do
assert Helpers.static_path(conn_with_script_name(~w(foo)), "/images/foo.png") ==
"/api/images/foo.png"
assert Helpers.static_url(conn_with_script_name(~w(foo)), "/images/foo.png") ==
"https://static.example.com/api/images/foo.png"
end
test "helpers properly encode named and query string params" do
assert Router.Helpers.post_path(__MODULE__, :show, "my path", foo: "my param") ==
"/posts/my%20path?foo=my+param"
end
end
| 43.317919 | 157 | 0.65826 |
f73eccdf587307fd5b68b5a8d26a2fc77efc44ab | 178 | exs | Elixir | test/fexr_web/controllers/page_controller_test.exs | Schultzer/fexr | f64d67b78bc785ae967f4c1193491a1d9cf33279 | [
"MIT",
"Unlicense"
] | 4 | 2017-08-13T09:03:24.000Z | 2018-06-19T06:32:07.000Z | test/fexr_web/controllers/page_controller_test.exs | Schultzer/fexr | f64d67b78bc785ae967f4c1193491a1d9cf33279 | [
"MIT",
"Unlicense"
] | null | null | null | test/fexr_web/controllers/page_controller_test.exs | Schultzer/fexr | f64d67b78bc785ae967f4c1193491a1d9cf33279 | [
"MIT",
"Unlicense"
] | null | null | null | defmodule FexrWeb.PageControllerTest do
use FexrWeb.ConnCase
test "GET /", %{conn: conn} do
conn = get conn, "/"
assert html_response(conn, 200) =~ "Fexr"
end
end
| 19.777778 | 45 | 0.662921 |
f73edd716f9b09de7cff46c3df38c893a5786205 | 3,236 | ex | Elixir | clients/game_services/lib/google_api/game_services/v1/model/expr.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/game_services/lib/google_api/game_services/v1/model/expr.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/game_services/lib/google_api/game_services/v1/model/expr.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.GameServices.V1.Model.Expr do
@moduledoc """
Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars" expression: "document.summary.size() < 100" Example (Equality): title: "Requestor is owner" description: "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email" Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly visible" expression: "document.type != 'private' && document.type != 'internal'" Example (Data Manipulation): title: "Notification string" description: "Create a notification string with a timestamp." expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that may be referenced within an expression are determined by the service that evaluates it. See the service documentation for additional information.
## Attributes
* `description` (*type:* `String.t`, *default:* `nil`) - Optional. Description of the expression. This is a longer text which describes the expression, e.g. when hovered over it in a UI.
* `expression` (*type:* `String.t`, *default:* `nil`) - Textual representation of an expression in Common Expression Language syntax.
* `location` (*type:* `String.t`, *default:* `nil`) - Optional. String indicating the location of the expression for error reporting, e.g. a file name and a position in the file.
* `title` (*type:* `String.t`, *default:* `nil`) - Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs which allow to enter the expression.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:description => String.t() | nil,
:expression => String.t() | nil,
:location => String.t() | nil,
:title => String.t() | nil
}
field(:description)
field(:expression)
field(:location)
field(:title)
end
defimpl Poison.Decoder, for: GoogleApi.GameServices.V1.Model.Expr do
def decode(value, options) do
GoogleApi.GameServices.V1.Model.Expr.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.GameServices.V1.Model.Expr do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 57.785714 | 1,092 | 0.733931 |
f73ee1be025405bfb7ca2dcfcb4983a1af073927 | 341 | exs | Elixir | tests/resource/test.exs | pilotier/nimler | bc80503d9e300ba59889f533b79dc51962083ba7 | [
"MIT"
] | 83 | 2019-10-20T12:04:33.000Z | 2022-03-17T01:04:26.000Z | tests/resource/test.exs | pilotier/nimler | bc80503d9e300ba59889f533b79dc51962083ba7 | [
"MIT"
] | 18 | 2019-10-12T17:56:25.000Z | 2022-03-21T03:05:02.000Z | tests/resource/test.exs | pilotier/nimler | bc80503d9e300ba59889f533b79dc51962083ba7 | [
"MIT"
] | 6 | 2020-02-21T14:00:30.000Z | 2021-11-06T04:18:38.000Z |
ExUnit.start(trace: false, seed: 0)
defmodule NimlerTest do
use ExUnit.Case, async: false
test "resource" do
res = NimlerWrapper.create_resource()
assert(is_reference(res))
assert(is_reference(NimlerWrapper.update_resource(res)))
assert(is_reference(NimlerWrapper.check_resource(res)))
end
end
| 24.357143 | 64 | 0.70088 |
f73ee1d2eda1741db293e72a1e1bb7f5d3a6ff4f | 708 | exs | Elixir | mix.exs | defacedvr/deque | 49076ecb0ea6283577edcb008cdf185dfb4a3f54 | [
"MIT"
] | 61 | 2017-09-21T05:56:48.000Z | 2020-03-10T11:43:19.000Z | mix.exs | defacedvr/deque | 49076ecb0ea6283577edcb008cdf185dfb4a3f54 | [
"MIT"
] | 3 | 2018-05-26T07:02:33.000Z | 2019-06-21T19:48:00.000Z | mix.exs | defacedvr/deque | 49076ecb0ea6283577edcb008cdf185dfb4a3f54 | [
"MIT"
] | 11 | 2017-09-21T05:56:52.000Z | 2019-11-23T13:37:13.000Z | defmodule Deque.Mixfile do
use Mix.Project
def project do
[
app: :deque,
version: "1.2.0",
elixir: ">= 1.5.0",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
deps: deps(),
package: package()
]
end
def application do
[]
end
defp deps do
[
{:benchfella, "~> 0.3.5", only: :dev}
]
end
def package do
[
name: :deque,
description: "Fast bounded deque using two rotating lists.",
maintainers: [],
licenses: ["MIT"],
files: ["lib/*", "mix.exs", "README*", "LICENSE*"],
links: %{
"GitHub" => "https://github.com/discordapp/deque"
}
]
end
end
| 18.153846 | 66 | 0.515537 |
f73f033058e5fac9ac2badf4fff7dc45a561553f | 218 | ex | Elixir | lib/filey/application.ex | cjfreeze/filey | 84d674f31333875b487b9b2b67883d6286bfe315 | [
"MIT"
] | 2 | 2020-10-21T06:36:05.000Z | 2021-11-24T22:17:18.000Z | lib/filey/application.ex | cjfreeze/filey | 84d674f31333875b487b9b2b67883d6286bfe315 | [
"MIT"
] | null | null | null | lib/filey/application.ex | cjfreeze/filey | 84d674f31333875b487b9b2b67883d6286bfe315 | [
"MIT"
] | null | null | null | defmodule Filey.Application do
@moduledoc false
use Application
@impl true
def start(_type, _args) do
opts = [strategy: :one_for_one, name: Filey.Supervisor]
Supervisor.start_link([], opts)
end
end
| 18.166667 | 59 | 0.711009 |
f73f1a627cdf62c2a452310e5a31133b0c0cc85d | 6,083 | ex | Elixir | lib/dark_matter/naming.ex | dark-elixir/dark_matter | 3f70edf4220ad1c066489110ef30880a143522fd | [
"Apache-2.0"
] | 2 | 2020-12-01T21:33:44.000Z | 2021-05-29T14:51:18.000Z | lib/dark_matter/naming.ex | dark-elixir/dark_matter | 3f70edf4220ad1c066489110ef30880a143522fd | [
"Apache-2.0"
] | null | null | null | lib/dark_matter/naming.ex | dark-elixir/dark_matter | 3f70edf4220ad1c066489110ef30880a143522fd | [
"Apache-2.0"
] | 2 | 2020-09-02T14:36:58.000Z | 2021-04-22T11:20:43.000Z | defmodule DarkMatter.Naming do
@moduledoc """
DarkMatter naming conventions.
"""
@moduledoc since: "1.0.0"
alias DarkMatter.Inflections
defstruct [
:module,
:base_module,
:parent_module,
:alias,
:alias_plural,
:singular,
:plural,
:camel_plural,
:camel_singular,
:human_plural,
:human_singular,
:title_plural,
:title_singular,
:pascal_plural,
:pascal_singular
]
@type t() :: %__MODULE__{
module: module(),
base_module: module(),
parent_module: module(),
alias: String.t(),
alias_plural: String.t(),
singular: String.t(),
plural: String.t(),
camel_plural: String.t(),
camel_singular: String.t(),
human_plural: String.t(),
human_singular: String.t(),
title_plural: String.t(),
title_singular: String.t(),
pascal_plural: String.t(),
pascal_singular: String.t()
}
@doc """
Definition for reflected `DarkPhoenix.Schema`.
## Examples
iex> cast(DarkMatter)
%DarkMatter.Naming{
alias: "DarkMatter",
alias_plural: "DarkMatters",
base_module: DarkMatter,
camel_plural: "darkMatters",
camel_singular: "darkMatter",
human_plural: "Darkmatters",
human_singular: "Darkmatter",
title_plural: "Dark Matters",
title_singular: "Dark Matter",
module: DarkMatter,
parent_module: DarkMatter,
pascal_plural: "DarkMatters",
pascal_singular: "DarkMatter",
plural: "dark_matters",
singular: "dark_matter"
}
iex> cast(DarkMatter.Inflections)
%DarkMatter.Naming{
alias: "Inflections",
alias_plural: "Inflections",
base_module: DarkMatter,
camel_plural: "inflections",
camel_singular: "inflection",
human_plural: "Inflections",
human_singular: "Inflections",
module: DarkMatter.Inflections,
parent_module: DarkMatter,
pascal_plural: "Inflections",
pascal_singular: "Inflections",
plural: "inflections",
singular: "inflections",
title_plural: "Inflections",
title_singular: "Inflections"
}
iex> cast(Ecto.Changeset)
%DarkMatter.Naming{
alias: "Changeset",
alias_plural: "Changesets",
base_module: Ecto,
camel_plural: "changesets",
camel_singular: "changeset",
human_plural: "Changesets",
human_singular: "Changeset",
title_plural: "Changesets",
title_singular: "Changeset",
module: Ecto.Changeset,
parent_module: Ecto,
pascal_plural: "Changesets",
pascal_singular: "Changeset",
plural: "changesets",
singular: "changeset"
}
"""
@spec cast(module()) :: t()
def cast(module) when is_atom(module) do
module_alias = alias_for(module)
%__MODULE__{
module: module,
alias: alias_for(module),
base_module: base_module_for(module),
parent_module: parent_module_for(module),
alias_plural: Inflections.binary(module_alias, [:plural]),
singular: Inflections.binary(module_alias, [:underscore]),
plural: Inflections.binary(module_alias, [:underscore, :plural]),
camel_singular: Inflections.binary(module_alias, [:singular, :absinthe_camel]),
camel_plural: Inflections.binary(module_alias, [:plural, :absinthe_camel]),
human_singular: Inflections.binary(module_alias, [:human]),
human_plural: Inflections.binary(module_alias, [:plural, :human]),
title_singular: Inflections.binary(module_alias, [:title]),
title_plural: Inflections.binary(module_alias, [:plural, :title]),
pascal_singular: Inflections.binary(module_alias, [:underscore, :absinthe_pascal]),
pascal_plural: Inflections.binary(module_alias, [:underscore, :plural, :absinthe_pascal])
}
end
@doc """
Derives the ` de` matter for the given `module`.
## Examples
iex> base_module_for(DarkMatter)
DarkMatter
iex> base_module_for(DarkMatter.Inflections)
DarkMatter
iex> base_module_for(DarkMatter.Decimals.Arithmetic)
DarkMatter
"""
@spec base_module_for(module()) :: module()
def base_module_for(module) do
module
|> Module.split()
|> hd()
|> List.wrap()
|> Module.safe_concat()
end
@doc """
Derives the `parent_module` matter for the given `module`.
## Examples
iex> parent_module_for(DarkMatter)
DarkMatter
iex> parent_module_for(DarkMatter.Inflections)
DarkMatter
iex> parent_module_for(DarkMatter.Decimals.Arithmetic)
DarkMatter.Decimals
"""
@spec parent_module_for(module()) :: module()
def parent_module_for(module) do
case Module.split(module) do
[part] ->
Module.safe_concat([part])
[_hd | _tl] = parts ->
parts
|> Enum.reverse()
|> tl()
|> Enum.reverse()
|> Module.safe_concat()
end
end
@doc """
Derives the `alias` matter for the given `module`.
## Examples
iex> alias_for(DarkMatter)
"DarkMatter"
iex> alias_for(DarkMatter.Inflections)
"Inflections"
"""
@spec alias_for(module()) :: String.t()
def alias_for(module) do
module
|> Module.split()
|> Enum.reverse()
|> hd()
end
@doc """
Turn a `number` into a snake cased elixir numeric.
## Examples
iex> underscore_number(1)
"1"
iex> underscore_number(100)
"100"
iex> underscore_number(1000)
"1_000"
iex> underscore_number(100000)
"100_000"
iex> underscore_number(100000000)
"100_000_000"
"""
@spec underscore_number(number() | String.t()) :: String.t()
def underscore_number(number) when is_number(number) or is_binary(number) do
"#{number}"
|> String.reverse()
|> String.to_charlist()
|> Enum.chunk_every(3)
|> Enum.join("_")
|> String.reverse()
|> to_string()
end
end
| 26.219828 | 95 | 0.620089 |
f73f3d522c02ded96bdb9793e8507646932817fa | 2,469 | exs | Elixir | run-length-encoding/rle.exs | lpvm/exercism_elixir | b32981727c4aaec444680838db4014d70c983f5d | [
"MIT"
] | null | null | null | run-length-encoding/rle.exs | lpvm/exercism_elixir | b32981727c4aaec444680838db4014d70c983f5d | [
"MIT"
] | null | null | null | run-length-encoding/rle.exs | lpvm/exercism_elixir | b32981727c4aaec444680838db4014d70c983f5d | [
"MIT"
] | null | null | null | defmodule RunLengthEncoder do
@doc """
Generates a string where consecutive elements are represented as a data value and count.
"AABBBCCCC" => "2A3B4C"
For this example, assume all input are strings, that are all uppercase letters.
It should also be able to reconstruct the data into its original form.
"2A3B4C" => "AABBBCCCC"
"""
@spec encode(String.t()) :: String.t()
def encode(string) do
str_cp = string |> String.codepoints()
encode_aux(str_cp, "", 0, "")
end
defp encode_aux([hd | tl], encoded, count, last) do
cond do
# first character to be processed
encoded == "" and last == "" ->
encode_aux(tl, encoded, 1, hd)
# hd same as last character
hd == last ->
encode_aux(tl, encoded, count + 1, last)
# last char different of hd
true ->
cond do
# now: Y last: X
count == 1 ->
encode_aux(tl, encoded <> last, 1, hd)
true ->
encode_aux(tl, encoded <> to_string(count) <> last, 1, hd)
end
end
end
defp encode_aux([], encoded, count, last) do
cond do
# no initial string to encode
encoded == "" and last == "" ->
""
# initial string of same characters
encoded == "" ->
if count != 1, do: to_string(count) <> last, else: last
true ->
if count != 1 do
encoded <> to_string(count) <> last
else
encoded <> last
end
end
end
@spec decode(String.t()) :: String.t()
def decode(string) do
str_cp = String.codepoints(string)
decode_aux(str_cp, "", "0")
end
def decode_aux([hd | tl], decoded, count) do
case Integer.parse(hd) do
:error ->
# hd is letter and count == 0, single letter
if count == "0" do
decode_aux(tl, decoded <> hd, "0")
else
# hd is letter and count > 0, letter repeated `count` times
decode_aux(tl, decoded <> String.duplicate(hd, String.to_integer(count)), "0")
end
_ ->
if count == "0" do
# hd is a string of a number
# first number after letter or initial number
decode_aux(tl, decoded, hd)
else
# number followed by number, ex: 12 (1: count, 2: hd)
decode_aux(tl, decoded, count <> hd)
end
end
end
def decode_aux([], decoded, _) do
decoded
end
end
# RunLengthEncoder.encode("AABBBCCCC") == "2A3B4C"
| 26.836957 | 90 | 0.563791 |
f73f840e668a6dab2473b366bc63e091e092cd96 | 2,377 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/model/destination_table_properties.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | 1 | 2021-10-01T09:20:41.000Z | 2021-10-01T09:20:41.000Z | clients/big_query/lib/google_api/big_query/v2/model/destination_table_properties.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/model/destination_table_properties.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.BigQuery.V2.Model.DestinationTableProperties do
@moduledoc """
## Attributes
* `description` (*type:* `String.t`, *default:* `nil`) - [Optional] The description for the destination table. This will only be used if the destination table is newly created. If the table already exists and a value different than the current description is provided, the job will fail.
* `friendlyName` (*type:* `String.t`, *default:* `nil`) - [Optional] The friendly name for the destination table. This will only be used if the destination table is newly created. If the table already exists and a value different than the current friendly name is provided, the job will fail.
* `labels` (*type:* `map()`, *default:* `nil`) - [Optional] The labels associated with this table. You can use these to organize and group your tables. This will only be used if the destination table is newly created. If the table already exists and labels are different than the current labels are provided, the job will fail.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:description => String.t() | nil,
:friendlyName => String.t() | nil,
:labels => map() | nil
}
field(:description)
field(:friendlyName)
field(:labels, type: :map)
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.DestinationTableProperties do
def decode(value, options) do
GoogleApi.BigQuery.V2.Model.DestinationTableProperties.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.DestinationTableProperties do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.849057 | 331 | 0.737064 |
f73f92d884d7b1689c85dc66f29b78fb5a37ae7c | 1,644 | exs | Elixir | test/suite/draft4/not_test.exs | depressed-pho/xema | 56de4a5d3b3f37827c70f6052f895c59feb0bb51 | [
"MIT"
] | null | null | null | test/suite/draft4/not_test.exs | depressed-pho/xema | 56de4a5d3b3f37827c70f6052f895c59feb0bb51 | [
"MIT"
] | null | null | null | test/suite/draft4/not_test.exs | depressed-pho/xema | 56de4a5d3b3f37827c70f6052f895c59feb0bb51 | [
"MIT"
] | null | null | null | defmodule Draft4.NotTest do
use ExUnit.Case, async: true
import Xema, only: [valid?: 2]
describe "not" do
setup do
%{schema: Xema.new(not: :integer)}
end
test "allowed", %{schema: schema} do
data = "foo"
assert valid?(schema, data)
end
test "disallowed", %{schema: schema} do
data = 1
refute valid?(schema, data)
end
end
describe "not multiple types" do
setup do
%{schema: Xema.new(not: [:integer, :boolean])}
end
test "valid", %{schema: schema} do
data = "foo"
assert valid?(schema, data)
end
test "mismatch", %{schema: schema} do
data = 1
refute valid?(schema, data)
end
test "other mismatch", %{schema: schema} do
data = true
refute valid?(schema, data)
end
end
describe "not more complex schema" do
setup do
%{schema: Xema.new(not: {:map, [properties: %{foo: :string}]})}
end
test "match", %{schema: schema} do
data = 1
assert valid?(schema, data)
end
test "other match", %{schema: schema} do
data = %{foo: 1}
assert valid?(schema, data)
end
test "mismatch", %{schema: schema} do
data = %{foo: "bar"}
refute valid?(schema, data)
end
end
describe "forbidden property" do
setup do
%{schema: Xema.new(properties: %{foo: [not: :any]})}
end
test "property present", %{schema: schema} do
data = %{bar: 2, foo: 1}
refute valid?(schema, data)
end
test "property absent", %{schema: schema} do
data = %{bar: 1, baz: 2}
assert valid?(schema, data)
end
end
end
| 20.55 | 69 | 0.568127 |
f73f976a163b340a41dfea32ff0517f13aa4527a | 699 | ex | Elixir | lib/eview/changeset/validators/phone_number.ex | Contractbook/eview | 01166658910fd7c8c974874b116164873a382ac5 | [
"MIT"
] | 3 | 2018-11-11T22:43:04.000Z | 2020-03-11T12:17:11.000Z | lib/eview/changeset/validators/phone_number.ex | Contractbook/eview | 01166658910fd7c8c974874b116164873a382ac5 | [
"MIT"
] | 18 | 2016-10-28T16:10:22.000Z | 2018-09-11T11:35:28.000Z | lib/eview/changeset/validators/phone_number.ex | Contractbook/eview | 01166658910fd7c8c974874b116164873a382ac5 | [
"MIT"
] | 8 | 2017-01-11T16:14:46.000Z | 2022-03-21T13:06:10.000Z | if Code.ensure_loaded?(Ecto) do
defmodule EView.Changeset.Validators.PhoneNumber do
@moduledoc """
This helper validates phone numbers in international format (with `+:country_code`).
"""
import Ecto.Changeset
@phone_regex ~r/^\+[0-9]{9,16}$/
def validate_phone_number(changeset, field, opts \\ []) do
validate_change(changeset, field, {:phone_number, @phone_regex}, fn _, value ->
if value =~ @phone_regex,
do: [],
else: [{field, {message(opts, "is not a valid phone number"), [validation: :phone_number]}}]
end)
end
defp message(opts, key \\ :message, default) do
Keyword.get(opts, key, default)
end
end
end
| 30.391304 | 102 | 0.636624 |
f73fbc40f8772496166345c57834f7420b38f445 | 2,509 | ex | Elixir | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/callout_status_row.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/callout_status_row.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/callout_status_row.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.AdExchangeBuyer.V2beta1.Model.CalloutStatusRow do
@moduledoc """
The number of impressions with the specified dimension values where the
corresponding bid request or bid response was not successful, as described by
the specified callout status.
## Attributes
* `calloutStatusId` (*type:* `integer()`, *default:* `nil`) - The ID of the callout status.
See
[callout-status-codes](https://developers.google.com/authorized-buyers/rtb/downloads/callout-status-codes).
* `impressionCount` (*type:* `GoogleApi.AdExchangeBuyer.V2beta1.Model.MetricValue.t`, *default:* `nil`) - The number of impressions for which there was a bid request or bid response
with the specified callout status.
* `rowDimensions` (*type:* `GoogleApi.AdExchangeBuyer.V2beta1.Model.RowDimensions.t`, *default:* `nil`) - The values of all dimensions associated with metric values in this row.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:calloutStatusId => integer(),
:impressionCount => GoogleApi.AdExchangeBuyer.V2beta1.Model.MetricValue.t(),
:rowDimensions => GoogleApi.AdExchangeBuyer.V2beta1.Model.RowDimensions.t()
}
field(:calloutStatusId)
field(:impressionCount, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.MetricValue)
field(:rowDimensions, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.RowDimensions)
end
defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.CalloutStatusRow do
def decode(value, options) do
GoogleApi.AdExchangeBuyer.V2beta1.Model.CalloutStatusRow.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.CalloutStatusRow do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.258621 | 185 | 0.754882 |
f73fca8bb6fe26c1357d4f4ac538c665d94e9f14 | 1,009 | exs | Elixir | config/config.exs | code-mancers/resource-pool | 83610857b63ec3d0b5e215f6ac63e12ccb99c2f1 | [
"MIT"
] | null | null | null | config/config.exs | code-mancers/resource-pool | 83610857b63ec3d0b5e215f6ac63e12ccb99c2f1 | [
"MIT"
] | null | null | null | config/config.exs | code-mancers/resource-pool | 83610857b63ec3d0b5e215f6ac63e12ccb99c2f1 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
# General application configuration
config :resource_pool,
ecto_repos: [ResourcePool.Repo]
# Configures the endpoint
config :resource_pool, ResourcePoolWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "QUBDjkzVXS4aYdxFXwczslw5fEdWma+EFgVyTlU7SNvlYPtNJUUQFGGaQ/XbdxEV",
render_errors: [view: ResourcePoolWeb.ErrorView, accepts: ~w(html json)],
pubsub: [name: ResourcePool.PubSub,
adapter: Phoenix.PubSub.PG2]
config :resource_pool, :base_path, "/tmp/"
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:user_id]
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
| 33.633333 | 86 | 0.767096 |
f73fec618e6fc9a802c7d5868732c3e2d2cf7e17 | 940 | ex | Elixir | lib/shopix/admin/product.ex | gsarwate/shopix | 21d0e85294ee92cb7573d1b5a5746af6824b9355 | [
"MIT"
] | 196 | 2019-05-05T15:59:32.000Z | 2022-03-15T02:37:19.000Z | lib/shopix/admin/product.ex | gsarwate/shopix | 21d0e85294ee92cb7573d1b5a5746af6824b9355 | [
"MIT"
] | 105 | 2019-05-04T19:04:40.000Z | 2021-07-28T11:21:45.000Z | lib/shopix/admin/product.ex | gsarwate/shopix | 21d0e85294ee92cb7573d1b5a5746af6824b9355 | [
"MIT"
] | 26 | 2019-05-05T19:40:52.000Z | 2021-11-16T00:32:46.000Z | defmodule Shopix.Admin.Product do
import Ecto.{Changeset, Query}
use Shopix.TranslationFields, slug: :name, translated_fields: ~w(name description slug)
alias Shopix.Repo
alias Shopix.Schema.{Product, Group}
def changeset(%Product{} = product, attrs) do
product
|> cast(attrs, [:sku, :price, :images_group_url, :displayed] ++ localized_fields())
|> cast_assoc(:product_properties, with: &Shopix.Admin.ProductProperty.changeset/2)
|> change_slugs()
|> validate_required([:sku, :price])
|> update_groups(attrs)
|> unique_constraint(:sku, name: :products_lower_sku_index)
end
def update_groups(changeset, %{"group_ids" => ""}), do: put_assoc(changeset, :groups, [])
def update_groups(changeset, %{"group_ids" => group_ids}) do
groups = Repo.all(from g in Group, where: g.id in ^group_ids)
put_assoc(changeset, :groups, groups)
end
def update_groups(changeset, _), do: changeset
end
| 34.814815 | 91 | 0.704255 |
f7403c7ab511436128731cdadf912cc0a1fa10f4 | 401 | ex | Elixir | lib/quadquizaminos_web/controller/auth.ex | sFractal-Podii/quadquizaminos | 1693f2d1c6ffee33065dd2ba7d899ac4aa405762 | [
"MIT"
] | null | null | null | lib/quadquizaminos_web/controller/auth.ex | sFractal-Podii/quadquizaminos | 1693f2d1c6ffee33065dd2ba7d899ac4aa405762 | [
"MIT"
] | null | null | null | lib/quadquizaminos_web/controller/auth.ex | sFractal-Podii/quadquizaminos | 1693f2d1c6ffee33065dd2ba7d899ac4aa405762 | [
"MIT"
] | null | null | null | defmodule QuadquizaminosWeb.Auth do
@moduledoc """
Auth plug, checks for the current user and adds them to assigns.
"""
import Plug.Conn
use QuadquizaminosWeb, :controller
def init(opts), do: opts
def call(conn, _opts) do
if conn.assigns[:current_user] do
conn
else
user_id = get_session(conn, :user_id)
assign(conn, :current_user, user_id)
end
end
end
| 21.105263 | 66 | 0.680798 |
f7404f6424de9ad53b683f1d80613f6b949c82ae | 55 | exs | Elixir | config/test.exs | spencerdcarlson/prometheus_sidecar | fa81a6ba25e7dfa67c9e137f8f8c48c6b8d26036 | [
"MIT"
] | null | null | null | config/test.exs | spencerdcarlson/prometheus_sidecar | fa81a6ba25e7dfa67c9e137f8f8c48c6b8d26036 | [
"MIT"
] | null | null | null | config/test.exs | spencerdcarlson/prometheus_sidecar | fa81a6ba25e7dfa67c9e137f8f8c48c6b8d26036 | [
"MIT"
] | null | null | null | use Mix.Config
config :prometheus_sidecar, port: 2000
| 13.75 | 38 | 0.8 |
f74055d724ff9b372b4eeefe295a8b9d7cdc3d50 | 445 | exs | Elixir | test/day5_test.exs | erljef/adventofcode-2020 | fdae924b34eb9b324e529b02e2aed45a79078102 | [
"WTFPL"
] | null | null | null | test/day5_test.exs | erljef/adventofcode-2020 | fdae924b34eb9b324e529b02e2aed45a79078102 | [
"WTFPL"
] | null | null | null | test/day5_test.exs | erljef/adventofcode-2020 | fdae924b34eb9b324e529b02e2aed45a79078102 | [
"WTFPL"
] | null | null | null | defmodule Day5Test do
use ExUnit.Case
import Day5
test "calculates position" do
assert position("FBFBBFFRLR") == {44, 5}
assert position("BFFFBBFRRR") == {70, 7}
assert position("FFFBBBFRRR") == {14, 7}
assert position("BBFFBBFRLL") == {102, 4}
end
test "calculates seat id" do
assert seat({44, 5}) == 357
assert seat({70, 7}) == 567
assert seat({14, 7}) == 119
assert seat({102, 4}) == 820
end
end | 23.421053 | 45 | 0.608989 |
f7407a363153014ac76e3fc6ebb2d12debeb64c7 | 345 | ex | Elixir | lib/sbom_poc/posts/status.ex | TraceyOnim/SbomPoc-sFractal | bac895a7eda61c47c00b8bbe682a6fda4dd7255c | [
"MIT"
] | 2 | 2020-10-04T12:41:58.000Z | 2021-03-11T20:51:26.000Z | lib/sbom_poc/posts/status.ex | TraceyOnim/SbomPoc-sFractal | bac895a7eda61c47c00b8bbe682a6fda4dd7255c | [
"MIT"
] | 113 | 2020-07-25T02:29:33.000Z | 2022-03-01T01:07:23.000Z | lib/sbom_poc/posts/status.ex | TraceyOnim/SbomPoc-sFractal | bac895a7eda61c47c00b8bbe682a6fda4dd7255c | [
"MIT"
] | 5 | 2020-07-10T09:57:58.000Z | 2021-03-11T20:51:29.000Z | defmodule SbomPoc.Post.Status do
@moduledoc false
@enforce_keys [:id, :author, :body]
defstruct [:id, :author, :title, :body, :description, :tags]
def build(filename, attrs, body) do
[_, id] = filename |> Path.rootname() |> Path.split() |> Enum.take(-2)
struct!(__MODULE__, [body: body, id: id] ++ Map.to_list(attrs))
end
end
| 31.363636 | 74 | 0.649275 |
f7408798cb2f5207c9515483c92eb02cecd7fa13 | 320 | exs | Elixir | wabanex/priv/repo/migrations/20210623092157_create_users_table.exs | shonorio/nlwt_elixir | 029b731c747e4b4954bc0197881b325fb80b4ab6 | [
"MIT"
] | null | null | null | wabanex/priv/repo/migrations/20210623092157_create_users_table.exs | shonorio/nlwt_elixir | 029b731c747e4b4954bc0197881b325fb80b4ab6 | [
"MIT"
] | null | null | null | wabanex/priv/repo/migrations/20210623092157_create_users_table.exs | shonorio/nlwt_elixir | 029b731c747e4b4954bc0197881b325fb80b4ab6 | [
"MIT"
] | null | null | null | defmodule Wabanex.Repo.Migrations.CreateUsersTable do
use Ecto.Migration
def change do
create table(:users) do
add :email, :string, null: false
add :name, :string, null: false
add :password, :string, null: false
timestamps()
end
create unique_index(:users, [:email])
end
end
| 20 | 53 | 0.659375 |
f7408a1767ca3f5aef52cb21ff521574ec5c2aa9 | 18,531 | ex | Elixir | clients/compute/lib/google_api/compute/v1/api/zone_operations.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/zone_operations.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/zone_operations.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Compute.V1.Api.ZoneOperations do
@moduledoc """
API calls for all endpoints tagged `ZoneOperations`.
"""
alias GoogleApi.Compute.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Deletes the specified zone-specific Operations resource.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `zone` (*type:* `String.t`) - Name of the zone for this request.
* `operation` (*type:* `String.t`) - Name of the Operations resource to delete.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:userIp` (*type:* `String.t`) - Legacy name for parameter that has been superseded by `quotaUser`.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %{}}` on success
* `{:error, info}` on failure
"""
@spec compute_zone_operations_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()}
def compute_zone_operations_delete(
connection,
project,
zone,
operation,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/projects/{project}/zones/{zone}/operations/{operation}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"operation" => URI.encode(operation, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
@doc """
Retrieves the specified zone-specific Operations resource.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `zone` (*type:* `String.t`) - Name of the zone for this request.
* `operation` (*type:* `String.t`) - Name of the Operations resource to return.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:userIp` (*type:* `String.t`) - Legacy name for parameter that has been superseded by `quotaUser`.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_zone_operations_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_zone_operations_get(
connection,
project,
zone,
operation,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/projects/{project}/zones/{zone}/operations/{operation}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"operation" => URI.encode(operation, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Retrieves a list of Operation resources contained within the specified zone.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `zone` (*type:* `String.t`) - Name of the zone for request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:userIp` (*type:* `String.t`) - Legacy name for parameter that has been superseded by `quotaUser`.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. Most Compute resources support two types of filter expressions: expressions that support regular expressions and expressions that follow API improvement proposal AIP-160. If you want to use AIP-160, your expression must specify the field name, an operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The operator must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. The `:` operator can be used with string fields to match substrings. For non-string fields it is equivalent to the `=` operator. The `:*` comparison can be used to test whether a key has been defined. For example, to find all objects with `owner` label use: ``` labels.owner:* ``` You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` If you want to use a regular expression, use the `eq` (equal) or `ne` (not equal) operator against a single un-parenthesized expression with or without quotes or against multiple parenthesized expressions. Examples: `fieldname eq unquoted literal` `fieldname eq 'single quoted literal'` `fieldname eq "double quoted literal"` `(fieldname1 eq literal) (fieldname2 ne "literal")` The literal value is interpreted as a regular expression using Google RE2 library syntax. The literal value must match the entire field. For example, to filter for instances that do not end with name "instance", you would use `name ne .*instance`.
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by `name` or `creationTimestamp desc` is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results.
* `:returnPartialSuccess` (*type:* `boolean()`) - Opt-in for partial success behavior which provides partial results in case of failure. The default value is false.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.OperationList{}}` on success
* `{:error, info}` on failure
"""
@spec compute_zone_operations_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.OperationList.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_zone_operations_list(connection, project, zone, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query,
:returnPartialSuccess => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/projects/{project}/zones/{zone}/operations", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.OperationList{}])
end
@doc """
Waits for the specified Operation resource to return as `DONE` or for the request to approach the 2 minute deadline, and retrieves the specified Operation resource. This method waits for no more than the 2 minutes and then returns the current state of the operation, which might be `DONE` or still in progress. This method is called on a best-effort basis. Specifically: - In uncommon cases, when the server is overloaded, the request might return before the default deadline is reached, or might return after zero seconds. - If the default deadline is reached, there is no guarantee that the operation is actually done when the method returns. Be prepared to retry if the operation is not `DONE`.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `zone` (*type:* `String.t`) - Name of the zone for this request.
* `operation` (*type:* `String.t`) - Name of the Operations resource to return.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:userIp` (*type:* `String.t`) - Legacy name for parameter that has been superseded by `quotaUser`.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_zone_operations_wait(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_zone_operations_wait(
connection,
project,
zone,
operation,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/projects/{project}/zones/{zone}/operations/{operation}/wait", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"operation" => URI.encode(operation, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
end
| 53.869186 | 2,276 | 0.637904 |
f74093a01af9dc30f39daa59065bc3003a928533 | 3,312 | ex | Elixir | apps/local_ledger/lib/local_ledger/cached_balance.ex | vanmil/ewallet | 6c1aca95a83e0a9d93007670a40d8c45764a8122 | [
"Apache-2.0"
] | null | null | null | apps/local_ledger/lib/local_ledger/cached_balance.ex | vanmil/ewallet | 6c1aca95a83e0a9d93007670a40d8c45764a8122 | [
"Apache-2.0"
] | null | null | null | apps/local_ledger/lib/local_ledger/cached_balance.ex | vanmil/ewallet | 6c1aca95a83e0a9d93007670a40d8c45764a8122 | [
"Apache-2.0"
] | null | null | null | defmodule LocalLedger.CachedBalance do
@moduledoc """
This module is an interface to the abstract balances stored in DB. It is responsible for caching
wallets and serves as an interface to retrieve the current balances (which will either be
loaded from a cached balance or computed - or both).
"""
alias LocalLedgerDB.{Wallet, CachedBalance, Entry}
@doc """
Cache all the wallets balances using a batch stream mechanism for retrieval (1000 at a time). This
is meant to be used in some kind of schedulers, but can also be ran manually.
"""
@spec cache_all() :: :ok
def cache_all do
Wallet.stream_all(fn wallet ->
{:ok, calculate_with_strategy(wallet)}
end)
end
@doc """
Get all the balances for the given wallet.
"""
@spec all(%Wallet{}) :: {:ok, map()}
def all(wallet) do
{:ok, get_amounts(wallet)}
end
@doc """
Get the balance for the specified token (token_id) and
the given wallet.
"""
@spec get(%Wallet{}, String.t()) :: {:ok, map()}
def get(wallet, token_id) do
amounts = get_amounts(wallet)
{:ok, %{token_id => amounts[token_id] || 0}}
end
defp get_amounts(wallet) do
wallet.address
|> CachedBalance.get()
|> calculate_amounts(wallet)
end
defp calculate_amounts(nil, wallet), do: calculate_from_beginning_and_insert(wallet)
defp calculate_amounts(computed_balance, wallet) do
wallet.address
|> Entry.calculate_all_balances(%{
since: computed_balance.computed_at
})
|> add_amounts(computed_balance.amounts)
end
defp add_amounts(amounts_1, amounts_2) do
(Map.keys(amounts_1) ++ Map.keys(amounts_2))
|> Enum.map(fn token_id ->
{token_id, (amounts_1[token_id] || 0) + (amounts_2[token_id] || 0)}
end)
|> Enum.into(%{})
end
defp calculate_with_strategy(wallet) do
:local_ledger
|> Application.get_env(:balance_caching_strategy)
|> calculate_with_strategy(wallet)
end
defp calculate_with_strategy("since_last_cached", wallet) do
case CachedBalance.get(wallet.address) do
nil -> calculate_from_beginning_and_insert(wallet)
computed_balance -> calculate_from_cached_and_insert(wallet, computed_balance)
end
end
defp calculate_with_strategy("since_beginning", wallet) do
calculate_from_beginning_and_insert(wallet)
end
defp calculate_with_strategy(_, wallet) do
calculate_with_strategy("since_beginning", wallet)
end
defp calculate_from_beginning_and_insert(wallet) do
computed_at = NaiveDateTime.utc_now()
wallet.address
|> Entry.calculate_all_balances(%{upto: computed_at})
|> insert(wallet, computed_at)
end
defp calculate_from_cached_and_insert(wallet, computed_balance) do
computed_at = NaiveDateTime.utc_now()
wallet.address
|> Entry.calculate_all_balances(%{
since: computed_balance.computed_at,
upto: computed_at
})
|> add_amounts(computed_balance.amounts)
|> insert(wallet, computed_at)
end
defp insert(amounts, wallet, computed_at) do
_ =
if Enum.any?(amounts, fn {_token, amount} -> amount > 0 end) do
{:ok, _} =
CachedBalance.insert(%{
amounts: amounts,
wallet_address: wallet.address,
computed_at: computed_at
})
end
amounts
end
end
| 28.307692 | 100 | 0.692029 |
f7409659682ae05999f3a76e4ea21255b728ef20 | 12,013 | ex | Elixir | lib/real_world/datastore.ex | razuf/elixir-phoenix-liveview-realworld | 182eb845b2b56f146468d9a095a8d5d72fc44f17 | [
"MIT"
] | 10 | 2020-09-21T23:24:53.000Z | 2022-03-08T02:12:32.000Z | lib/real_world/datastore.ex | razuf/elixir-phoenix-liveview-realworld | 182eb845b2b56f146468d9a095a8d5d72fc44f17 | [
"MIT"
] | null | null | null | lib/real_world/datastore.ex | razuf/elixir-phoenix-liveview-realworld | 182eb845b2b56f146468d9a095a8d5d72fc44f17 | [
"MIT"
] | 1 | 2021-06-26T19:46:09.000Z | 2021-06-26T19:46:09.000Z | defmodule RealWorld.Datastore do
@moduledoc """
The Datastore.
"""
import Ecto.Query, warn: false
import Ecto.Changeset
alias RealWorld.Api
alias RealWorld.Repo
alias RealWorld.User
alias RealWorld.Article
alias RealWorld.Comment
alias RealWorld.Helpers
alias RealWorld.Backend
### Backend
def default_backend() do
%Backend{}
end
def change_backend() do
Backend.changeset(default_backend())
end
def validate_backend(form_params) do
changeset = Backend.changeset_from_form(default_backend(), form_params)
cond do
changeset.valid? ->
:ok
true ->
{:error, changeset}
end
end
### User
def default_user() do
%User{}
end
def change_user() do
User.changeset_login(default_user(), %{})
end
def change_user(%User{} = user, attrs) do
User.changeset(user, attrs)
end
def change_user(attrs) do
User.changeset(default_user(), attrs)
end
def get_user_by_session_id(session_id) do
Repo.get_by(User, %{:session_id => session_id})
end
def get_token_by_session_id(session_id) do
session_id = session_id || ""
user = Repo.get_by(User, %{:session_id => session_id})
(user && user.token) || nil
end
def auth_user(form_params) do
# POST /api/users/login
# Example request body:
# {
# "user":{
# "email": "[email protected]",
# "password": "jakejake"
# }
# }
changeset = User.changeset_auth(default_user(), form_params)
cond do
changeset.valid? ->
user_attrs = %{
email: changeset.changes.email,
password: changeset.changes.password
}
request_body = %{"user" => user_attrs}
result = Api.server_post("/users/login", request_body)
case result do
%{"user" => user} ->
{:ok, user}
%{"errors" => errors} ->
changeset =
changeset
|> Helpers.add_errors_to_changeset(errors)
{:error, changeset}
error ->
changeset =
changeset
|> Helpers.add_errors_to_changeset(inspect(error))
{:error, changeset}
end
true ->
{:error, changeset}
end
end
def login(user_attrs, session_id) do
user_attrs =
user_attrs
|> Map.merge(%{"session_id" => session_id})
|> Map.merge(%{"password" => "dummypassword"})
change_user(user_attrs)
|> Repo.insert()
end
def logout(current_user) do
frontend_user = get_user_by_session_id(current_user.session_id)
Repo.delete(frontend_user)
end
def register_user(user_attrs, session_id) do
# POST /api/users
# Example request body:
# {
# "user":{
# "username": "Jacob",
# "email": "[email protected]",
# "password": "jakejake"
# }
# }
changeset = change_user(user_attrs)
if changeset.valid? do
request_body = %{"user" => changeset.changes}
result = Api.server_post("/users", request_body, session_id)
case result do
%{"user" => server_user} ->
{:ok, server_user}
%{"errors" => errors} ->
changeset =
changeset
|> Helpers.add_errors_to_changeset(errors)
{:error, changeset}
_ ->
changeset =
changeset
|> add_error(:user, "register error")
{:error, changeset}
end
else
{:error, changeset}
end
end
def update_user(user_attrs, session_id) do
# PUT /api/user
# Example request body:
# {
# "user":{
# "email": "[email protected]",
# "bio": "I like to skateboard",
# "image": "https://i.stack.imgur.com/xHWG8.jpg"
# }
# }
changeset = change_user(user_attrs)
if changeset.valid? do
request_body = %{"user" => changeset.changes}
result = Api.server_put("/user", request_body, session_id)
case result do
%{"user" => backend_user} ->
frontend_user = Map.merge(backend_user, %{"password" => "dummypassword"})
session_id
|> get_user_by_session_id()
|> change_user(frontend_user)
|> Repo.update()
%{"errors" => errors} ->
changeset =
changeset
|> Helpers.add_errors_to_changeset(errors)
{:error, changeset}
_ ->
changeset =
changeset
|> add_error(:user, "update error")
{:error, changeset}
end
else
{:error, changeset}
end
end
def toggle_following_user(:unfollowing, username, session_id) do
# DELETE /api/profiles/:username/follow
result = Api.server_delete("/profiles/#{username}/follow", session_id)
case result do
%{"profile" => profile} ->
profile
_ ->
:error
end
end
def toggle_following_user(:follow, username, session_id) do
# POST /api/profiles/:username/follow
result = Api.server_post("/profiles/#{username}/follow", "", session_id)
case result do
%{"profile" => profile} ->
profile
_ ->
:error
end
end
### Article
def default_article() do
%Article{}
end
def change_article(attrs) do
Article.changeset_from_article(default_article(), attrs)
end
def change_new_article() do
Article.changeset(%Article{})
end
def get_article_by_slug(slug, session_id) do
result = Api.server_get("/articles/#{slug}", session_id)
case result do
%{"article" => article} ->
article
_ ->
nil
end
end
def create_article(form_params, session_id) do
# POST /api/articles
# Example request body:
# {
# "article": {
# "title": "How to train your dragon",
# "description": "Ever wonder how?",
# "body": "You have to believe",
# "tagList": ["reactjs", "angularjs", "dragons"]
# }
# }
changeset = Article.changeset_from_form(default_article(), form_params)
if changeset.valid? do
request_body = %{"article" => changeset.changes}
result = Api.server_post("/articles", request_body, session_id)
case result do
%{"article" => article} ->
{:ok, article}
%{"error" => error} ->
changeset =
changeset
|> add_error(:article, "update error: #{error}")
{:error, changeset}
_ ->
changeset =
changeset
|> add_error(:article, "update error")
{:error, changeset}
end
else
{:error, changeset}
end
end
def update_article(form_params, session_id) do
# PUT /api/articles/:slug
# Example request body:
# {
# "article": {
# "title": "Did you train your dragon?"
# }
# }
changeset = Article.changeset_from_form(default_article(), form_params)
if changeset.valid? do
slug = form_params["slug"]
request_body = %{"article" => changeset.changes}
result = Api.server_put("/articles/#{slug}", request_body, session_id)
case result do
%{"article" => article} ->
{:ok, article}
%{"error" => error} ->
changeset =
changeset
|> add_error(:article, "update error: #{error}")
{:error, changeset}
_ ->
changeset =
changeset
|> add_error(:article, "update error")
{:error, changeset}
end
else
{:error, changeset}
end
end
def delete_article(article, session_id) do
# DELETE /api/articles/:slug
slug = article["slug"]
result = Api.server_delete("/articles/#{slug}", session_id)
case result do
%{"error" => _error} ->
:error
_empty_result ->
:ok
end
end
### favorited_article
def toggle_favorited_article(:unfavorite, slug, session_id) do
# DELETE /api/articles/:slug/favorite
result = Api.server_delete("/articles/#{slug}/favorite", session_id)
case result do
%{"article" => article} ->
{:ok, article}
%{"error" => error} ->
{:error, error}
end
end
def toggle_favorited_article(:favorite, slug, session_id) do
# POST /api/articles/:slug/favorite
result = Api.server_post("/articles/#{slug}/favorite", "", session_id)
case result do
%{"article" => article} ->
{:ok, article}
%{"error" => error} ->
{:error, error}
end
end
### articles
def list_articles(offset, limit_per_page, session_id) do
result = Api.server_get("/articles?limit=#{limit_per_page}&offset=#{offset}", session_id)
result_handler_articles(result)
end
def feed_articles(offset, limit_per_page, session_id) do
result = Api.server_get("/articles/feed?limit=#{limit_per_page}&offset=#{offset}", session_id)
result_handler_articles(result)
end
def get_articles_by_tag(tag, offset, limit_per_page, session_id) do
result =
Api.server_get(
"/articles?tag=#{tag}&limit=#{limit_per_page}&offset=#{offset}",
session_id
)
result_handler_articles(result)
end
def get_articles_by_username(username, offset, limit_per_page, session_id) do
result =
Api.server_get(
"/articles?author=#{username}&limit=#{limit_per_page}&offset=#{offset}",
session_id
)
result_handler_articles(result)
end
def get_articles_favorited_by_username(username, offset, limit_per_page, session_id) do
result =
Api.server_get(
"/articles?favorited=#{username}&limit=#{limit_per_page}&offset=#{offset}",
session_id
)
result_handler_articles(result)
end
defp result_handler_articles(result) do
case result do
%{"articles" => articles, "articlesCount" => articlesCount} ->
%{"articles" => articles, "articlesCount" => articlesCount}
result ->
%{"articles" => [], "articlesCount" => 0}
end
end
### Comment
def default_comment() do
%Comment{}
end
def change_new_comment() do
Comment.changeset(default_comment())
end
def get_comments_from_one_article(slug, session_id) do
result = Api.server_get("/articles/#{slug}/comments", session_id)
case result do
%{"comments" => comments} ->
comments
_ ->
[]
end
end
def create_comment_for_slug(slug, form_params, session_id) do
# POST /api/articles/:slug/comments
changeset = Comment.changeset_from_form(default_comment(), form_params)
if changeset.valid? do
request_body = %{"comment" => form_params}
result = Api.server_post("/articles/#{slug}/comments", request_body, session_id)
case result do
%{"comment" => comment} ->
{:ok, comment}
%{"errors" => errors} ->
changeset =
changeset
|> Helpers.add_errors_to_changeset(errors)
{:error, changeset}
_ ->
changeset =
changeset
|> add_error(:comment, "create error")
{:error, changeset}
end
else
{:error, changeset}
end
end
def delete_comment_by_id(article, id, session_id) do
# DELETE /api/articles/:slug/comments/:id
slug = article["slug"]
result = Api.server_delete("/articles/#{slug}/comments/#{id}", session_id)
case result do
%{"error" => _error} ->
:error
%{"errors" => _errors} ->
:error
_result ->
:ok
end
end
### profile
def get_profile_by_username(username, session_id) do
result = Api.server_get("/profiles/#{username}", session_id)
case result do
%{"profile" => profile} ->
profile
_ ->
nil
end
end
### tags
def list_tags(session_id \\ "") do
result = Api.server_get("/tags", session_id)
case result do
%{"tags" => tags} ->
tags
_ ->
[]
end
end
end
| 22.082721 | 98 | 0.582785 |
f740c74ea86a72b44ff3700032a441bb3e5fa764 | 203 | exs | Elixir | apps/app/test/seed_sets/blog.exs | votiakov/petal | ec03551da6dadc0c3482b25a5f5dcd400c36db43 | [
"MIT"
] | null | null | null | apps/app/test/seed_sets/blog.exs | votiakov/petal | ec03551da6dadc0c3482b25a5f5dcd400c36db43 | [
"MIT"
] | null | null | null | apps/app/test/seed_sets/blog.exs | votiakov/petal | ec03551da6dadc0c3482b25a5f5dcd400c36db43 | [
"MIT"
] | null | null | null | alias Legendary.Content.Post
alias Legendary.Content.Repo
%Post{
title: "Public post",
name: "public-post",
status: "publish",
type: "post",
date: ~N[2020-01-01T00:00:00],
}
|> Repo.insert!()
| 16.916667 | 32 | 0.660099 |
f740ec8e5256b08d1051ef510143a685364b945e | 1,307 | exs | Elixir | anagrams-phx/config/dev.exs | mcdickenson/anagrams | 3132a98d5ac8b6175e134109386ce1d6a7270d94 | [
"MIT"
] | null | null | null | anagrams-phx/config/dev.exs | mcdickenson/anagrams | 3132a98d5ac8b6175e134109386ce1d6a7270d94 | [
"MIT"
] | null | null | null | anagrams-phx/config/dev.exs | mcdickenson/anagrams | 3132a98d5ac8b6175e134109386ce1d6a7270d94 | [
"MIT"
] | null | null | null | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :anagrams, Anagrams.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin",
cd: Path.expand("../", __DIR__)]]
# Watch static and templates for browser reloading.
config :anagrams, Anagrams.Endpoint,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{priv/gettext/.*(po)$},
~r{web/views/.*(ex)$},
~r{web/templates/.*(eex)$}
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Configure your database
config :anagrams, Anagrams.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
database: "anagrams_dev",
hostname: "localhost",
pool_size: 10
| 29.704545 | 73 | 0.695486 |
f740ee2d6e3ce5b50fa1b466d25cf09b87e76d3c | 381 | exs | Elixir | apps/temporario/config/config.exs | achedeuzot/temporar.io | acbec140732614070996924633f254b56e56131f | [
"MIT"
] | 2 | 2019-04-16T18:46:36.000Z | 2020-09-18T12:58:57.000Z | apps/temporario/config/config.exs | achedeuzot/temporar.io | acbec140732614070996924633f254b56e56131f | [
"MIT"
] | 6 | 2019-01-06T11:13:39.000Z | 2022-02-10T15:15:24.000Z | apps/temporario/config/config.exs | achedeuzot/temporar.io | acbec140732614070996924633f254b56e56131f | [
"MIT"
] | null | null | null | # Since configuration is shared in umbrella projects, this file
# should only configure the :temporario application itself
# and only for organization purposes. All other config goes to
# the umbrella root.
use Mix.Config
# config :temporario,
# ecto_repos: [Temporario.Repo]
config :temporario, :pastes,
save_path: "/tmp/temporario/pastes"
import_config "#{Mix.env()}.exs"
| 27.214286 | 63 | 0.761155 |
f740f13c49c6f1e227f3b85b77dd9794c69f5ce1 | 1,043 | ex | Elixir | test/support/conn_case.ex | Galanda/ectoproj | 9dadeb27cc7b54034ab19363bc569d0fc4be671b | [
"MIT"
] | null | null | null | test/support/conn_case.ex | Galanda/ectoproj | 9dadeb27cc7b54034ab19363bc569d0fc4be671b | [
"MIT"
] | null | null | null | test/support/conn_case.ex | Galanda/ectoproj | 9dadeb27cc7b54034ab19363bc569d0fc4be671b | [
"MIT"
] | null | null | null | defmodule EctoprojWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common datastructures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
import EctoprojWeb.Router.Helpers
# The default endpoint for testing
@endpoint EctoprojWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Ectoproj.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Ectoproj.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 26.74359 | 70 | 0.720997 |
f74112dc9eae17fa27167c13d9c7cb27d24de22a | 69 | exs | Elixir | test/pbf_parser_test.exs | mpraski/pbf-parser | 627cdf6518bec79724392afd4a7ec095a1998cbd | [
"MIT"
] | 5 | 2019-02-11T14:25:57.000Z | 2021-10-30T01:26:33.000Z | test/pbf_parser_test.exs | mpraski/pbf-parser | 627cdf6518bec79724392afd4a7ec095a1998cbd | [
"MIT"
] | null | null | null | test/pbf_parser_test.exs | mpraski/pbf-parser | 627cdf6518bec79724392afd4a7ec095a1998cbd | [
"MIT"
] | 1 | 2019-08-30T14:09:36.000Z | 2019-08-30T14:09:36.000Z | defmodule PBFParserTest do
use ExUnit.Case
doctest PBFParser
end
| 13.8 | 26 | 0.811594 |
f741300a3880c572ca5aaff44b2bd75d28c1774c | 11,473 | ex | Elixir | lib/chronos.ex | nurugger07/chronos | be8fcbee7330d938dff87532cf108125bf952d05 | [
"Apache-2.0"
] | 72 | 2015-01-28T16:30:45.000Z | 2021-05-21T03:33:16.000Z | lib/chronos.ex | nurugger07/chronos | be8fcbee7330d938dff87532cf108125bf952d05 | [
"Apache-2.0"
] | 9 | 2015-01-20T21:08:43.000Z | 2018-04-04T02:57:05.000Z | lib/chronos.ex | nurugger07/chronos | be8fcbee7330d938dff87532cf108125bf952d05 | [
"Apache-2.0"
] | 15 | 2015-01-20T04:34:06.000Z | 2019-02-10T22:42:12.000Z | defmodule Chronos do
import Chronos.Validation
@datetime1970 {{1970, 1, 1}, {0, 0, 0}}
@doc """
Chronos is an Elixir library for working with dates and times.
iex(1)> Chronos.today
{2013, 8, 21}
"""
def today, do: :erlang.date
def now, do: :calendar.now_to_datetime(:erlang.timestamp)
@doc """
The epoch_time/1 function returns the number of seconds since January 1, 1970 00:00:00.
If the date is prior to January 1, the integer will be negative.
iex(1)> Chronos.epoch_time({2012, 12, 21}, {12, 30, 55}}
"""
def epoch_time({y, m, d}), do: epoch_time({{y, m, d}, {0,0,0}})
def epoch_time(datetime) do
datetime_to_seconds(datetime) - datetime_to_seconds(@datetime1970)
end
def datetime_to_seconds(datetime), do: :calendar.datetime_to_gregorian_seconds(datetime)
@doc """
The from_epoch_time/1 function converts from epoch time to datetime tuple.
iex(1)> Chronos.from_epoch_time(1356048000)
"""
def from_epoch_time(timestamp) do
timestamp
|> Kernel.+(datetime_to_seconds(@datetime1970))
|> :calendar.gregorian_seconds_to_datetime
end
@doc """
The year function allows you to extract the year from a date tuple
iex(1)> Chronos.year({2013, 8, 21})
2013
iex(2)> {2012, 12, 21} |> Chronos.year
2012
"""
def year(date \\ today()) do
date
|> validate()
|> _extract_seg(:year)
end
@doc """
The month function allows you to extract the month from a date tuple
iex(1)> Chronos.month({2013, 8, 21})
8
iex(2)> {2012, 12, 21} |> Chronos.month
8
"""
def month(date \\ today()) do
date
|> validate()
|> _extract_seg(:month)
end
@doc """
The day function allows you to extract the day from a date tuple
iex(1)> Chronos.day({2013, 8, 21})
21
iex(2)> {2012, 12, 21} |> Chronos.day
21
"""
def day(date \\ today()) do
date
|> validate()
|> _extract_seg(:day)
end
@doc """
The hour function allows you to extract the hour from a date/time tuple
iex> Chronos.hour({{2013, 8, 21}, {13, 34, 45}})
13
iex> {{2013, 8, 21}, {13, 34, 45}} |> Chronos.hour
13
"""
def hour(datetime \\ now()) do
datetime
|> validate()
|> _extract_seg(:hour)
end
@doc """
The min function allows you to extract the minutes from a date/time tuple
iex> Chronos.min({{2013, 8, 21}, {13, 34, 45}})
34
iex> {{2013, 8, 21}, {13, 34, 45}} |> Chronos.min
34
"""
def min(datetime \\ now()) do
datetime
|> validate()
|> _extract_seg(:min)
end
@doc """
The sec function allows you to extract the seconds from a date/time tuple
iex> Chronos.sec({{2013, 8, 21}, {13, 34, 45}})
45
iex> {{2013, 8, 21}, {13, 34, 45}} |> Chronos.sec
45
"""
def sec(datetime \\ now()) do
datetime
|> validate()
|> _extract_seg(:sec)
end
@doc """
Returns an integer representing the day of the week, 1..7, with Monday == 1.
iex(1)> Chronos.wday({2013, 8, 21})
3
"""
def wday(date \\ today()), do: :calendar.day_of_the_week(date)
def sunday?(date \\ today()), do: wday(date) == 7
def monday?(date \\ today()), do: wday(date) == 1
def tuesday?(date \\ today()), do: wday(date) == 2
def wednesday?(date \\ today()), do: wday(date) == 3
def thursday?(date \\ today()), do: wday(date) == 4
def friday?(date \\ today()), do: wday(date) == 5
def saturday?(date \\ today()), do: wday(date) == 6
@doc """
The yday function allows you to extract the day of the year (1-366) from a
date tuple
iex(1)> Chronos.yday({2013, 8, 21})
233
iex(2)> {2012, 12, 21} |> Chronos.day
356
"""
def yday(date \\ today()) do
yd =
date
|> validate()
|> _extract_seg(:year)
|> :calendar.date_to_gregorian_days(1,1)
:calendar.date_to_gregorian_days(date) - yd + 1
end
@doc """
The yesterday function is based on the current date
iex(1)> Chronos.yesterday
{2013, 8, 20}
or you can pass it a date:
iex(2)> {2012, 12, 21} |> Chronos.yesterday
{2012, 12, 20}
"""
def yesterday(date \\ today()), do: calculate_date_for_days(date, -1)
@doc """
The tomorrow function is based on the current date
iex(1)> Chronos.tomorrow
{2013, 8, 22}
or you can pass it a date:
iex(2)> {2012, 12, 21} |> Chronos.tomorrow
{2012, 12, 22}
"""
def tomorrow(date \\ today()), do: calculate_date_for_days(date, 1)
@doc """
#beginning_of_week/2 function returns the date of starting day of the week for given date.
It defaults to today for given date and Monday(1) for starting day of the week.
Mon = 1, Tue = 2, Wed =3 , Thu = 4 , Fri = 5 , Sat = 6 , Sun = 7
If today is {2012,12,21}
iex(1)> Chronos.beginning_of_week
{2012,12,17}
iex(2)> Chronos.beginning_of_week({2015,1,20})
{2015,1,19}
iex(3)> Chronos.beginning_of_week({2015,1,20},3)
{2015,1,14}
"""
def beginning_of_week(date \\ today(), start_day \\ 1) do
days = [1,2,3,4,5,6,7]
offset = start_day - 1
days = (days |> Enum.reverse |> Enum.take(7-offset) |> Enum.reverse)
++ (days |> Enum.take(offset)) #list rotation hack
Enum.find_index(days,&(&1 == wday(date))) |> days_ago(date)
end
@doc """
#end_of_week/2 function returns the date of starting day of the week for given date.
It defaults to today for given date and Sunday(7) for ending day of the week.
Mon = 1, Tue = 2, Wed =3 , Thu = 4 , Fri = 5 , Sat = 6 , Sun = 7
If today is {2012,12,21}
iex(1)> Chronos.end_of_week
{2012,12,23}
iex(2)> Chronos.end_of_week({2015,1,20})
{2015,1,25}
iex(3)> Chronos.end_of_week({2015,1,20},3)
{2015,1,21}
"""
def end_of_week(date \\ today(), end_day \\ 7) do
days = [1,2,3,4,5,6,7]
offset = wday(date)- 1
days = (days |> Enum.reverse |> Enum.take(7-offset) |> Enum.reverse)
++ (days |> Enum.take(offset)) #list rotation hack
Enum.find_index(days,&(&1 == end_day)) |> days_from(date)
end
@doc """
The following functions all have similar behavior. The days_ago/2 and weeks_ago/2
functions take a integer representing the number of days or weeks in the past and
return the corresponding date. There is a optional argument for a date to base the
calculation on but if no date is provided then the current date is used.
iex(1)> Chronos.days_ago(5)
{2013, 8, 16}
iex(2)> Chronos.weeks_ago(3)
{2013, 3, 31}
The days_from/2 and weeks_from/2 return a future date calculated by the number
of days or weeks. There is a optional argument for a date to base the
calculation on but if no date is provided then the current date is used.
iex(1)> Chronos.days_from(5)
{2013, 8, 26}
iex(2)> Chronos.weeks_from(3)
{2013, 9, 11}
"""
def days_ago(days, date \\ today())
def days_ago(days, date) when days >= 0 do
calculate_date_for_days(date, -days)
end
def days_ago(days, _) when days < 0 do
raise ArgumentError, message: "Number of days must be zero or greater"
end
def days_from(days, date \\ today())
def days_from(days, date) when days >= 0 do
calculate_date_for_days(date, days)
end
def days_from(_, _) do
raise ArgumentError, message: "Number of days must be zero or greater"
end
def weeks_ago(weeks, date \\ today())
def weeks_ago(weeks, date) when weeks >= 0 do
calculate_date_for_weeks(date, -weeks)
end
def weeks_ago(_, _) do
raise ArgumentError, message: "Number of weeks must be zero or greater"
end
def weeks_from(weeks, date \\ today())
def weeks_from(weeks, date) when weeks >= 0 do
calculate_date_for_weeks(date, weeks)
end
def weeks_from(_, _) do
raise ArgumentError, message: "Number of weeks must be zero or greater"
end
defp calculate_date_for_days(date, days) do
date
|> covert_date_to_days()
|> date_for_days(days)
end
defp calculate_date_for_weeks(date, weeks) do
date
|> covert_date_to_days()
|> date_for_weeks(weeks)
end
defp covert_date_to_days(date) do
date
|> validate()
|> days_for_date()
end
defp days_for_date(date), do: :calendar.date_to_gregorian_days(date)
defp date_for_days(days, offset) when is_integer(days) do
:calendar.gregorian_days_to_date(days + offset)
end
defp date_for_weeks(days, weeks) when is_integer(days) do
date_for_days(days, weeks * 7)
end
defp _extract_seg({ year, _, _ }, :year), do: year
defp _extract_seg({ _, month, _ }, :month), do: month
defp _extract_seg({ _, _, day }, :day), do: day
defp _extract_seg({ _date, {hour, _, _}}, :hour), do: hour
defp _extract_seg({ _date, {_, min, _}}, :min), do: min
defp _extract_seg({ _date, {_, _, sec}}, :sec), do: sec
defp _opts_date({ :ok, date }), do: date
@doc """
There is an option to supply a date. This is handy for testing.
defmodule YourModule do
use Chronos, date: {2012, 12, 21}
end
iex(1)> YourModule.today
{2012, 12, 21}
"""
defmacro __using__(opts \\ []) do
date = fn() -> cond do
opts[:date] ->
opts
|> Keyword.values()
|> Enum.fetch(0)
|> _opts_date
:else ->
:erlang.date
end
end
quote do
def today, do: unquote(date.())
def now, do: unquote(__MODULE__).now
def epoch_time(datetime), do: unquote(__MODULE__).epoch_time(datetime)
def from_epoch_time(timestamp), do: unquote(__MODULE__).from_epoch_time(timestamp)
def year(date), do: unquote(__MODULE__).year(date)
def month(date), do: unquote(__MODULE__).month(date)
def day(date), do: unquote(__MODULE__).day(date)
def hour(datetime), do: unquote(__MODULE__).hour(datetime)
def min(datetime), do: unquote(__MODULE__).min(datetime)
def sec(datetime), do: unquote(__MODULE__).sec(datetime)
def wday(date), do: unquote(__MODULE__).wday(date)
def sunday?(date), do: unquote(__MODULE__).sunday?(date)
def monday?(date), do: unquote(__MODULE__).monday?(date)
def tuesday?(date), do: unquote(__MODULE__).tuesday?(date)
def wednesday?(date), do: unquote(__MODULE__).wednesday?(date)
def thursday?(date), do: unquote(__MODULE__).thursday?(date)
def friday?(date), do: unquote(__MODULE__).friday?(date)
def saturday?(date), do: unquote(__MODULE__).saturday?(date)
def yday(date), do: unquote(__MODULE__).yday(date)
def yesterday(date \\ unquote(date.())) do
unquote(__MODULE__).yesterday(date)
end
def tomorrow(date \\ unquote(date.())) do
unquote(__MODULE__).tomorrow(date)
end
def days_ago(days, date \\ unquote(date.())) do
unquote(__MODULE__).days_ago(days, date)
end
def days_from(days, date \\ unquote(date.())) do
unquote(__MODULE__).days_from(days, date)
end
def weeks_ago(weeks, date \\ unquote(date.())) do
unquote(__MODULE__).weeks_ago(weeks, date)
end
def weeks_from(weeks, date \\ unquote(date.())) do
unquote(__MODULE__).weeks_from(weeks, date)
end
def beginning_of_week(date \\ unquote(date.()),start_day \\ 1) do
unquote(__MODULE__).beginning_of_week(date, start_day)
end
def end_of_week(date \\ unquote(date.()),end_day \\ 7) do
unquote(__MODULE__).end_of_week(date, end_day)
end
end
end
end
| 27.982927 | 94 | 0.626166 |
f7418bf1e48b82350cf47117cf42b5d573800918 | 814 | exs | Elixir | test/faker/internet/user_agent_test.exs | pharosproduction/faker | 91deca51b3dc4bf8de75f81480e9f8880aa93886 | [
"MIT"
] | null | null | null | test/faker/internet/user_agent_test.exs | pharosproduction/faker | 91deca51b3dc4bf8de75f81480e9f8880aa93886 | [
"MIT"
] | null | null | null | test/faker/internet/user_agent_test.exs | pharosproduction/faker | 91deca51b3dc4bf8de75f81480e9f8880aa93886 | [
"MIT"
] | null | null | null | defmodule InternetUserAgentTest do
use ExUnit.Case, async: true
alias Faker.Internet.UserAgent
test "user_agent/0" do
assert is_binary(UserAgent.user_agent)
end
test "bot_user_agent/0" do
assert is_binary(UserAgent.bot_user_agent)
end
test "desktop_user_agent/0" do
assert is_binary(UserAgent.desktop_user_agent)
end
test "ereader_user_agent/0" do
assert is_binary(UserAgent.ereader_user_agent)
end
test "game_console_user_agent/0" do
assert is_binary(UserAgent.game_console_user_agent)
end
test "set_top_user_agent/0" do
assert is_binary(UserAgent.set_top_user_agent)
end
test "tablet_user_agent/0" do
assert is_binary(UserAgent.tablet_user_agent)
end
test "mobile_user_agent/0" do
assert is_binary(UserAgent.mobile_user_agent)
end
end
| 21.421053 | 55 | 0.769042 |
f741aaabbc6ec36ef1b17a6faf4ebe2474b95245 | 3,424 | exs | Elixir | test/plowman/git_cli_test.exs | azukiapp/plowman | 38bbab040eb691f8402e3073329bb19a1f0b7b9a | [
"MIT"
] | 11 | 2015-06-04T20:03:48.000Z | 2019-12-09T13:19:09.000Z | test/plowman/git_cli_test.exs | azukiapp/plowman | 38bbab040eb691f8402e3073329bb19a1f0b7b9a | [
"MIT"
] | null | null | null | test/plowman/git_cli_test.exs | azukiapp/plowman | 38bbab040eb691f8402e3073329bb19a1f0b7b9a | [
"MIT"
] | 1 | 2021-03-24T19:29:18.000Z | 2021-03-24T19:29:18.000Z | Code.require_file "../../test_helper.exs", __FILE__
defmodule PlowmanGitCliTest do
use Plowman.Test, async: false
@target Plowman.GitCli
@state @target.CliState
setup_all do
{:ok, [
state: @state.new(cm: 'cm', group: 'gp', channel: 'cl'),
connect: Mock.new(Plowman.Connection),
cmds: Mock.new(Plowman.GitCmds),
]}
end
teardown meta do
meta[:cmds].reset!
end
teardown_all meta do
meta[:connect].destroy
meta[:cmds].destroy
end
test "set new state to init" do
assert @target.init([]) === {:ok, @state.new()}
end
test "return new state for ssh_channel_up" do
{:ok, r} = @target.handle_msg({:ssh_channel_up, :channelId, :connectionManager}, nil)
assert r === @state.new(channel: :channelId, cm: :connectionManager)
end
test "return channelId and state for EXIT msg" do
state = @state.new(group: :group, channel: :channel)
{:ok, rchannel, rstate} = @target.handle_msg({'EXIT', :group, nil}, state)
assert rchannel == :channel
assert rstate == state
end
test "return any state for outher handle_msgs" do
state = @state.new(cm: :any_way)
assert {:ok, state} === @target.handle_msg({}, state)
end
test "return ok for call terminate" do
assert :ok === @target.terminate(:reason, @state.new())
end
test "handle invalid msgs", meta do
state = meta[:state]
meta[:connect].stubs(:reply_failure, [:_, :_, state.channel], :ok)
msgs = [
{:env, state.channel, true, :var, :value},
{:pty, state.channel, true, []},
{:shell, state.channel, true},
{:eof, state.channel}
]
Enum.each msgs, fn(msg, i) ->
{cm, wantReply} = {'cm#{i}', element(msg, 2, false)}
assert {:ok, state} === @target.handle_ssh_msg({:ssh_cm, cm, msg}, state)
assert 1 == meta[:connect].nc(:reply_failure, [cm, wantReply, state.channel])
end
end
test "send msg and failure to connection with invalid command", meta do
[state, connect, cmds] = [meta[:state], meta[:connect], meta[:cmds]]
cmds.stubs(:run, ['fail'], {:error, :invalid_path, "msg"})
connect.stubs(:reply_failure, [state.cm, false, state.channel, :_], :ok)
msg = {:ssh_cm, state.cm, {:exec, state.channel, false, 'fail'}}
assert {:ok, state} == @target.handle_ssh_msg(msg, state)
assert 1 == cmds.nc(:run, ['fail'])
assert 1 == connect.nc(:reply_failure, [state.cm, false, state.channel, "\nmsg\n\n"])
end
test "connect in dynohost and authentication for valid command", meta do
Mock.run Plowman.GenServer, [stub_all: {:ok, :dyno}], fn(server) ->
[state, cmds] = [meta[:state], meta[:cmds]]
msg = {:ssh_cm, state.cm, {:exec, state.channel, false, 'cmd'}}
cmds.stubs(:run, ['cmd'], {:ok, "localhost", 'authkey'})
assert {:ok, state.dyno(:dyno)} === @target.handle_ssh_msg(msg, state)
assert 1 == server.nc(:start_link, [Plowman.Dynohost, ["localhost", state], []])
assert 1 == server.nc(:cast, [:dyno, {:send, 'authkey'}])
end
end
test "forward data msgs to dynohost", meta do
Mock.run Plowman.GenServer, [stub_all: :ok], fn(server) ->
state = meta[:state]
msg = {:ssh_cm, state.cm, {:data, state.channel, :type, 'foobar'}}
state = state.dyno(:dyno)
assert {:ok, state} === @target.handle_ssh_msg(msg, state)
assert 1 === server.nc(:cast, [:dyno, {:send, 'foobar'}])
end
end
end
| 32.609524 | 89 | 0.618867 |
f741aed3b03ced3bdb82f332be2e9af9153280ed | 868 | ex | Elixir | sequence/lib/sequence/server.ex | douchuan/elixir_intro | 3c841405740c5842e868e99514ba271dbf6fd95f | [
"MIT"
] | 1 | 2021-09-16T03:32:39.000Z | 2021-09-16T03:32:39.000Z | sequence/lib/sequence/server.ex | douchuan/elixir_intro | 3c841405740c5842e868e99514ba271dbf6fd95f | [
"MIT"
] | null | null | null | sequence/lib/sequence/server.ex | douchuan/elixir_intro | 3c841405740c5842e868e99514ba271dbf6fd95f | [
"MIT"
] | null | null | null | defmodule Sequence.Server do
use GenServer
######
# External API
def start_link(_) do
{:ok, _pid} = GenServer.start_link(__MODULE__, nil, name: __MODULE__)
end
def next_number do
GenServer.call(__MODULE__, :next_number)
end
def increment_number(delta) do
GenServer.cast(__MODULE__, {:increment_number, delta})
end
######
# GenServer implementation
def init(_) do
# restore "current_number"
current_number = Sequence.Stash.get_value()
{:ok, current_number}
end
def handle_call(:next_number, _from, current_number) do
{:reply, current_number, current_number + 1}
end
def handle_cast({:increment_number, delta}, current_number) do
{:noreply, current_number + delta}
end
# save "current_number"
def terminate(_reason, current_number) do
Sequence.Stash.save_value(current_number)
end
end
| 21.170732 | 73 | 0.706221 |
f741c1b270d96e30f73d38bac06240151c040cd2 | 433 | exs | Elixir | mix.exs | aforward-oss/ex_doc | ed9ad6db2945d758c9afb321376df27dd9aa6bd2 | [
"Apache-2.0"
] | null | null | null | mix.exs | aforward-oss/ex_doc | ed9ad6db2945d758c9afb321376df27dd9aa6bd2 | [
"Apache-2.0"
] | null | null | null | mix.exs | aforward-oss/ex_doc | ed9ad6db2945d758c9afb321376df27dd9aa6bd2 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Compile.Sundown do
@shortdoc "Compiles sundown that ships with ExDoc"
def run(_) do
Mix.shell.info System.cmd("make share/markdown.so")
end
end
defmodule ExDoc.Mixfile do
use Mix.Project
def project do
[ app: :ex_doc,
version: "0.1.0",
elixir: "~> 0.10.3-dev",
compilers: [:sundown, :elixir, :app],
source_url: "https://github.com/elixir-lang/ex_doc/"
]
end
end
| 20.619048 | 58 | 0.646651 |
f74200b5da2e822dda5f0a4e68d43478acbbc549 | 2,208 | ex | Elixir | lib/ex_hl7/segment/default/msh.ex | eyrmedical/ex_hl7 | 430897ab791eb8f5127f6a0ddc443d01df9b33e1 | [
"Apache-2.0"
] | 38 | 2015-06-21T17:44:44.000Z | 2021-10-03T08:46:08.000Z | lib/ex_hl7/segment/default/msh.ex | eyrmedical/ex_hl7 | 430897ab791eb8f5127f6a0ddc443d01df9b33e1 | [
"Apache-2.0"
] | 2 | 2019-08-27T17:27:37.000Z | 2021-02-05T14:27:28.000Z | lib/ex_hl7/segment/default/msh.ex | eyrmedical/ex_hl7 | 430897ab791eb8f5127f6a0ddc443d01df9b33e1 | [
"Apache-2.0"
] | 14 | 2016-02-04T15:11:55.000Z | 2021-11-13T20:28:19.000Z | defmodule HL7.Segment.Default.MSH do
@moduledoc "2.16.9 MSH - message header segment"
use HL7.Segment.Spec
require HL7.Composite.Default.CM_MSH_9, as: CM_MSH_9
require HL7.Composite.Default.HD, as: HD
segment "MSH" do
field :field_separator, seq: 1, type: :string, len: 1
field :encoding_chars, seq: 2, type: :string, len: 4
field :sending_app_id, seq: 3, type: {HD, :namespace_id}, len: 12
field :sending_facility_id, seq: 4, type: {HD, :namespace_id}, len: 12
field :sending_facility_universal_id, seq: 4, type: {HD, :universal_id}, len: 20
field :sending_facility_universal_id_type, seq: 4, type: {HD, :universal_id_type}, len: 20
field :receiving_app_id, seq: 5, type: {HD, :namespace_id}, len: 12
field :receiving_facility_id, seq: 6, type: {HD, :namespace_id}, len: 12
field :receiving_facility_universal_id, seq: 6, type: {HD, :universal_id}, len: 20
field :receiving_facility_universal_id_type, seq: 6, type: {HD, :universal_id_type}, len: 20
field :message_datetime, seq: 7, type: :datetime, len: 14
field :security, seq: 8, type: :string, len: 40
field :message_type, seq: 9, type: {CM_MSH_9, :id}, len: 3
field :trigger_event, seq: 9, type: {CM_MSH_9, :trigger_event}, len: 3
field :message_structure, seq: 9, type: {CM_MSH_9, :structure}, len: 7
field :message_control_id, seq: 10, type: :string, len: 20
field :processing_id, seq: 11, type: :string, len: 3, default: "P"
field :version, seq: 12, type: :string, len: 8, default: "2.4"
field :accept_ack_type, seq: 15, type: :string, len: 2
field :app_ack_type, seq: 16, type: :string, len: 2
field :country_code, seq: 17, type: :string, len: 3, default: "ARG"
field :char_set, seq: 18, type: :string, len: 10
end
end
| 66.909091 | 98 | 0.550725 |
f7421195de258813bb977e5a9fae6e654ec2ad42 | 2,318 | ex | Elixir | clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/identitytoolkit_relyingparty_download_account_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/identitytoolkit_relyingparty_download_account_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/identitytoolkit_relyingparty_download_account_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.IdentityToolkit.V3.Model.IdentitytoolkitRelyingpartyDownloadAccountRequest do
@moduledoc """
Request to download user account in batch.
## Attributes
* `delegatedProjectNumber` (*type:* `String.t`, *default:* `nil`) - GCP project number of the requesting delegated app. Currently only intended for Firebase V1 migration.
* `maxResults` (*type:* `integer()`, *default:* `nil`) - The max number of results to return in the response.
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - The token for the next page. This should be taken from the previous response.
* `targetProjectId` (*type:* `String.t`, *default:* `nil`) - Specify which project (field value is actually project id) to operate. Only used when provided credential.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:delegatedProjectNumber => String.t(),
:maxResults => integer(),
:nextPageToken => String.t(),
:targetProjectId => String.t()
}
field(:delegatedProjectNumber)
field(:maxResults)
field(:nextPageToken)
field(:targetProjectId)
end
defimpl Poison.Decoder,
for: GoogleApi.IdentityToolkit.V3.Model.IdentitytoolkitRelyingpartyDownloadAccountRequest do
def decode(value, options) do
GoogleApi.IdentityToolkit.V3.Model.IdentitytoolkitRelyingpartyDownloadAccountRequest.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.IdentityToolkit.V3.Model.IdentitytoolkitRelyingpartyDownloadAccountRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38 | 174 | 0.734254 |
f74253dcf3b44fad24bc77574894e7976cafa6e3 | 415 | exs | Elixir | backend/priv/repo/migrations/20211112111450_add_serial_and_part_number_to_devices.exs | bejolithic/honeyland | 8c4a0d3b56543648d3acb96cc6906df86526743b | [
"Apache-2.0"
] | null | null | null | backend/priv/repo/migrations/20211112111450_add_serial_and_part_number_to_devices.exs | bejolithic/honeyland | 8c4a0d3b56543648d3acb96cc6906df86526743b | [
"Apache-2.0"
] | null | null | null | backend/priv/repo/migrations/20211112111450_add_serial_and_part_number_to_devices.exs | bejolithic/honeyland | 8c4a0d3b56543648d3acb96cc6906df86526743b | [
"Apache-2.0"
] | null | null | null | defmodule Honeyland.Repo.Migrations.AddSerialAndPartNumberToDevices do
use Ecto.Migration
def change do
alter table(:devices) do
add :serial_number, :string
add :part_number,
references(:appliance_model_part_numbers,
column: :part_number,
type: :string,
with: [tenant_id: :tenant_id],
on_delete: :nothing
)
end
end
end
| 23.055556 | 70 | 0.624096 |
f74258d20c47318da38be3cdf3f4c6edad0b59e4 | 8,272 | exs | Elixir | test/typelixir/functions_extractor_test.exs | damif94/typelixir | 73ca7cfdb79f57f8d39823f43cdf4322eba1b3e5 | [
"MIT"
] | null | null | null | test/typelixir/functions_extractor_test.exs | damif94/typelixir | 73ca7cfdb79f57f8d39823f43cdf4322eba1b3e5 | [
"MIT"
] | null | null | null | test/typelixir/functions_extractor_test.exs | damif94/typelixir | 73ca7cfdb79f57f8d39823f43cdf4322eba1b3e5 | [
"MIT"
] | null | null | null | # defmodule Typelixir.FunctionsExtractorTest do
# use ExUnit.Case
# alias Typelixir.FunctionsExtractor
# describe "extract_functions_file" do
# @test_dir "test/tmp"
# @env %{
# :functions => %{
# "ModuleA.ModuleB" => %{
# {:test, 2} => {{:tuple, [{:list, :integer}, :string]}, [{:list, :integer}, :string]},
# {:test2, 0} => {:any, []},
# {:test3, 1} => {:any, [:integer]},
# {:test3, 2} => {:string, [:integer, :string]}
# },
# "ModuleThree" => %{
# {:test, 2} => {:string, [:integer, :string]}
# }
# },
# :prefix => nil,
# :state => :ok,
# :error_data => %{},
# :data => %{},
# :vars => %{},
# }
# setup do
# File.mkdir(@test_dir)
# on_exit fn ->
# File.rm_rf @test_dir
# end
# end
# test "returns empty when there is no module or code defined on the file" do
# File.write("test/tmp/example.ex", "")
# assert FunctionsExtractor.extract_functions_file("#{@test_dir}/example.ex", @env) === @env
# end
# test "returns the module name with the functions defined" do
# File.write("test/tmp/example.ex", "
# defmodule Example do
# end
# ")
# assert FunctionsExtractor.extract_functions_file("#{@test_dir}/example.ex", @env)
# === %{
# error_data: %{},
# functions: %{
# "Example" => %{},
# "ModuleA.ModuleB" => %{{:test, 2} => {{:tuple, [{:list, :integer}, :string]}, [{:list, :integer}, :string]}, {:test2, 0} => {:any, []}, {:test3, 1} => {:any, [:integer]}, {:test3, 2} => {:string, [:integer, :string]}},
# "ModuleThree" => %{{:test, 2} => {:string, [:integer, :string]}}
# },
# prefix: nil,
# state: :ok,
# data: %{},
# vars: %{}
# }
# File.write("test/tmp/example.ex", "
# defmodule Example do
# @spec example(integer, boolean) :: float
# end
# defmodule Example2 do
# @spec example(integer, integer) :: boolean
# end
# ")
# assert FunctionsExtractor.extract_functions_file("#{@test_dir}/example.ex", @env)
# === %{
# error_data: %{},
# functions: %{
# "Example" => %{{:example, 2} => {:float, [:integer, :boolean]}},
# "Example2" => %{{:example, 2} => {:boolean, [:integer, :integer]}},
# "ModuleA.ModuleB" => %{{:test, 2} => {{:tuple, [{:list, :integer}, :string]}, [{:list, :integer}, :string]}, {:test2, 0} => {:any, []}, {:test3, 1} => {:any, [:integer]}, {:test3, 2} => {:string, [:integer, :string]}},
# "ModuleThree" => %{{:test, 2} => {:string, [:integer, :string]}}
# },
# prefix: nil,
# state: :ok,
# data: %{},
# vars: %{}
# }
# File.write("test/tmp/example.ex", "
# defmodule Example do
# @spec example(integer, boolean) :: float
# @spec example2() :: integer
# @spec example3(integer) :: any
# @spec example4([integer], {float, string}, %{none => float}) :: {float, string}
# @spec example5 :: integer
# end
# ")
# assert FunctionsExtractor.extract_functions_file("#{@test_dir}/example.ex", @env)
# === %{
# error_data: %{},
# functions: %{
# "Example" => %{{:example, 2} => {:float, [:integer, :boolean]}, {:example2, 0} => {:integer, []}, {:example3, 1} => {:any, [:integer]}, {:example4, 3} => {{:tuple, [:float, :string]}, [list: :integer, tuple: [:float, :string], map: {:none, [:float]}]}, {:example5, 0} => {:integer, []}},
# "ModuleA.ModuleB" => %{{:test, 2} => {{:tuple, [{:list, :integer}, :string]}, [{:list, :integer}, :string]}, {:test2, 0} => {:any, []}, {:test3, 1} => {:any, [:integer]}, {:test3, 2} => {:string, [:integer, :string]}},
# "ModuleThree" => %{{:test, 2} => {:string, [:integer, :string]}}
# },
# prefix: nil,
# state: :ok,
# data: %{},
# vars: %{}
# }
# end
# test "returns error when there are repeated function specifications" do
# File.write("test/tmp/example.ex", "
# defmodule Example do
# @spec example(integer) :: float
# @spec example(boolean) :: float
# end
# ")
# assert FunctionsExtractor.extract_functions_file("#{@test_dir}/example.ex", @env)
# === %{
# prefix: nil,
# error_data: %{4 => "example/1 already has a defined type"},
# functions: %{
# "ModuleA.ModuleB" => %{{:test, 2} => {{:tuple, [{:list, :integer}, :string]}, [{:list, :integer}, :string]}, {:test2, 0} => {:any, []}, {:test3, 1} => {:any, [:integer]}, {:test3, 2} => {:string, [:integer, :string]}},
# "ModuleThree" => %{{:test, 2} => {:string, [:integer, :string]}},
# "Example" => %{{:example, 1} => {:float, [:integer]}}
# },
# state: :error,
# data: {4, "example/1 already has a defined type"},
# vars: %{}
# }
# File.write("test/tmp/example.ex", "
# defmodule Example do
# @spec example(integer) :: float
# defmodule Example2 do
# @spec example(integer) :: float
# @spec example2(boolean) :: float
# @spec example2(atom) :: float
# end
# end
# ")
# assert FunctionsExtractor.extract_functions_file("#{@test_dir}/example.ex", @env)
# === %{
# prefix: nil,
# error_data: %{7 => "example2/1 already has a defined type"},
# functions: %{
# "ModuleA.ModuleB" => %{{:test, 2} => {{:tuple, [{:list, :integer}, :string]}, [{:list, :integer}, :string]}, {:test2, 0} => {:any, []}, {:test3, 1} => {:any, [:integer]}, {:test3, 2} => {:string, [:integer, :string]}},
# "ModuleThree" => %{{:test, 2} => {:string, [:integer, :string]}},
# "Example" => %{{:example, 1} => {:float, [:integer]}},
# "Example.Example2" => %{{:example2, 1} => {:float, [:boolean]}, {:example, 1} => {:float, [:integer]}}
# },
# state: :error,
# data: {7, "example2/1 already has a defined type"},
# vars: %{}
# }
# end
# test "returns error when there are malformed type specs" do
# File.write("test/tmp/example.ex", "
# defmodule Example do
# @spec example(%{integer => atom, boolean => integer}) :: float
# end
# ")
# assert FunctionsExtractor.extract_functions_file("#{@test_dir}/example.ex", @env)
# === %{
# prefix: nil,
# error_data: %{3 => "Malformed type spec on example/1 parameters"},
# functions: %{
# "ModuleA.ModuleB" => %{{:test, 2} => {{:tuple, [{:list, :integer}, :string]}, [{:list, :integer}, :string]}, {:test2, 0} => {:any, []}, {:test3, 1} => {:any, [:integer]}, {:test3, 2} => {:string, [:integer, :string]}},
# "ModuleThree" => %{{:test, 2} => {:string, [:integer, :string]}},
# "Example" => %{}
# },
# state: :error,
# data: {3, "Malformed type spec on example/1 parameters"},
# vars: %{}
# }
# File.write("test/tmp/example.ex", "
# defmodule Example do
# @spec example(float) :: [integer, string]
# end
# ")
# assert FunctionsExtractor.extract_functions_file("#{@test_dir}/example.ex", @env)
# === %{
# prefix: nil,
# error_data: %{3 => "Malformed type spec on example/1 return"},
# functions: %{
# "ModuleA.ModuleB" => %{{:test, 2} => {{:tuple, [{:list, :integer}, :string]}, [{:list, :integer}, :string]}, {:test2, 0} => {:any, []}, {:test3, 1} => {:any, [:integer]}, {:test3, 2} => {:string, [:integer, :string]}},
# "ModuleThree" => %{{:test, 2} => {:string, [:integer, :string]}},
# "Example" => %{}
# },
# state: :error,
# data: {3, "Malformed type spec on example/1 return"},
# vars: %{}
# }
# end
# end
# end
| 42.639175 | 301 | 0.468931 |
f7426c3bd798e681c60ec6b972b26f99aac3da50 | 2,761 | exs | Elixir | kousa/test/broth/_calls/get_current_room_users_test.exs | MrDogeBro/dogehouse | f36024ab161745825054be5d1f7835afc9fc12ec | [
"MIT"
] | 1 | 2021-05-18T15:21:25.000Z | 2021-05-18T15:21:25.000Z | kousa/test/broth/_calls/get_current_room_users_test.exs | MrDogeBro/dogehouse | f36024ab161745825054be5d1f7835afc9fc12ec | [
"MIT"
] | null | null | null | kousa/test/broth/_calls/get_current_room_users_test.exs | MrDogeBro/dogehouse | f36024ab161745825054be5d1f7835afc9fc12ec | [
"MIT"
] | null | null | null | defmodule BrothTest.GetCurrentRoomUsersTest do
use ExUnit.Case, async: true
use KousaTest.Support.EctoSandbox
alias Beef.Schemas.User
alias Beef.Users
alias BrothTest.WsClient
alias BrothTest.WsClientFactory
alias KousaTest.Support.Factory
require WsClient
setup do
user = Factory.create(User)
client_ws = WsClientFactory.create_client_for(user)
{:ok, user: user, client_ws: client_ws}
end
describe "the websocket get_current_room_users operation" do
test "returns one user if you are in the room", t do
user_id = t.user.id
# first, create a room owned by the primary user.
{:ok, %{room: %{id: room_id}}} = Kousa.Room.create_room(user_id, "foo room", "foo", false)
# make sure the user is in there.
assert %{currentRoomId: ^room_id} = Users.get_by_id(user_id)
ref =
WsClient.send_call_legacy(
t.client_ws,
"get_current_room_users",
%{"roomId" => room_id}
)
WsClient.assert_reply_legacy(
ref,
%{
"users" => [%{"id" => ^user_id}]
},
t.client_ws
)
end
test "returns two users if another is in the room", t do
user_id = t.user.id
# first, create a room owned by the primary user.
{:ok, %{room: %{id: room_id}}} = Kousa.Room.create_room(user_id, "foo room", "foo", false)
# make sure the user is in there.
assert %{currentRoomId: ^room_id} = Users.get_by_id(user_id)
# create a user that is logged in.
other = %{id: other_id} = Factory.create(User)
_other_ws = WsClientFactory.create_client_for(other)
Kousa.Room.join_room(other_id, room_id)
ref =
WsClient.send_call_legacy(
t.client_ws,
"get_current_room_users",
%{"roomId" => room_id}
)
WsClient.assert_reply_legacy(
ref,
%{
"users" => users = [_, _]
},
t.client_ws
)
assert Enum.any?(users, &match?(%{"id" => ^user_id}, &1))
assert Enum.any?(users, &match?(%{"id" => ^other_id}, &1))
end
@tag :skip
test "returns what if the room doesn't exist"
test "returns what if you're not in a room", t do
user_id = t.user.id
# first, create a room owned by the primary user.
{:ok, %{room: %{id: room_id}}} = Kousa.Room.create_room(user_id, "foo room", "foo", false)
# create a user that is logged in.
other = Factory.create(User)
other_ws = WsClientFactory.create_client_for(other)
ref =
WsClient.send_call_legacy(
other_ws,
"get_current_room_users",
%{"roomId" => room_id}
)
WsClient.assert_reply_legacy(ref, _, other_ws)
end
end
end
| 27.888889 | 96 | 0.605578 |
f7426cc6687ecfe6492c5ab82acdb35fd82df153 | 22,627 | ex | Elixir | lib/google_api/compute/v1/api/http_health_checks.ex | greg-rychlewski/google_api_compute | 08061de03f1e9688d6ab69df08501485ecd3f97e | [
"Apache-2.0"
] | null | null | null | lib/google_api/compute/v1/api/http_health_checks.ex | greg-rychlewski/google_api_compute | 08061de03f1e9688d6ab69df08501485ecd3f97e | [
"Apache-2.0"
] | null | null | null | lib/google_api/compute/v1/api/http_health_checks.ex | greg-rychlewski/google_api_compute | 08061de03f1e9688d6ab69df08501485ecd3f97e | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Compute.V1.Api.HttpHealthChecks do
@moduledoc """
API calls for all endpoints tagged `HttpHealthChecks`.
"""
alias GoogleApi.Compute.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Deletes the specified HttpHealthCheck resource.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `http_health_check` (*type:* `String.t`) - Name of the HttpHealthCheck resource to delete.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_http_health_checks_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_http_health_checks_delete(
connection,
project,
http_health_check,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/projects/{project}/global/httpHealthChecks/{httpHealthCheck}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"httpHealthCheck" =>
URI.encode(http_health_check, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Returns the specified HttpHealthCheck resource. Gets a list of available HTTP health checks by making a list() request.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `http_health_check` (*type:* `String.t`) - Name of the HttpHealthCheck resource to return.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.HttpHealthCheck{}}` on success
* `{:error, info}` on failure
"""
@spec compute_http_health_checks_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.HttpHealthCheckLegacy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_http_health_checks_get(
connection,
project,
http_health_check,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/projects/{project}/global/httpHealthChecks/{httpHealthCheck}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"httpHealthCheck" =>
URI.encode(http_health_check, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.HttpHealthCheckLegacy{}])
end
@doc """
Creates a HttpHealthCheck resource in the specified project using the data included in the request.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.Compute.V1.Model.HttpHealthCheckLegacy.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_http_health_checks_insert(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_http_health_checks_insert(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/projects/{project}/global/httpHealthChecks", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Retrieves the list of HttpHealthCheck resources available to the specified project.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`.
For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`.
You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ```
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by `name` or `creationTimestamp desc` is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results.
* `:returnPartialSuccess` (*type:* `boolean()`) - Opt-in for partial success behavior which provides partial results in case of failure. The default value is false.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.HttpHealthCheckList{}}` on success
* `{:error, info}` on failure
"""
@spec compute_http_health_checks_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.HttpHealthCheckList.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_http_health_checks_list(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query,
:returnPartialSuccess => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/projects/{project}/global/httpHealthChecks", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.HttpHealthCheckList{}])
end
@doc """
Updates a HttpHealthCheck resource in the specified project using the data included in the request. This method supports PATCH semantics and uses the JSON merge patch format and processing rules.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `http_health_check` (*type:* `String.t`) - Name of the HttpHealthCheck resource to patch.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.Compute.V1.Model.HttpHealthCheckLegacy.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_http_health_checks_patch(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_http_health_checks_patch(
connection,
project,
http_health_check,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/projects/{project}/global/httpHealthChecks/{httpHealthCheck}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"httpHealthCheck" =>
URI.encode(http_health_check, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Updates a HttpHealthCheck resource in the specified project using the data included in the request.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `http_health_check` (*type:* `String.t`) - Name of the HttpHealthCheck resource to update.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.Compute.V1.Model.HttpHealthCheckLegacy.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_http_health_checks_update(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_http_health_checks_update(
connection,
project,
http_health_check,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/projects/{project}/global/httpHealthChecks/{httpHealthCheck}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"httpHealthCheck" =>
URI.encode(http_health_check, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
end
| 50.282222 | 434 | 0.650639 |
f7426fcf754e744a133201c709c6574c6bef678f | 2,536 | ex | Elixir | lib/hexpm/store/gcs.ex | Benjamin-Philip/hexpm | 6f38244f81bbabd234c660f46ea973849ba77a7f | [
"Apache-2.0"
] | 691 | 2017-03-08T09:15:45.000Z | 2022-03-23T22:04:47.000Z | lib/hexpm/store/gcs.ex | Benjamin-Philip/hexpm | 6f38244f81bbabd234c660f46ea973849ba77a7f | [
"Apache-2.0"
] | 491 | 2017-03-07T12:58:42.000Z | 2022-03-29T23:32:54.000Z | lib/hexpm/store/gcs.ex | Benjamin-Philip/hexpm | 6f38244f81bbabd234c660f46ea973849ba77a7f | [
"Apache-2.0"
] | 200 | 2017-03-12T23:03:39.000Z | 2022-03-05T17:55:52.000Z | defmodule Hexpm.Store.GCS do
import SweetXml, only: [sigil_x: 2]
require Logger
@behaviour Hexpm.Store
@gs_xml_url "https://storage.googleapis.com"
def list(bucket, prefix) do
list_stream(bucket, prefix)
end
def get(bucket, key, _opts) do
url = url(bucket, key)
case Hexpm.HTTP.retry(fn -> Hexpm.HTTP.get(url, headers()) end, "gcs") do
{:ok, 200, _headers, body} -> body
_ -> nil
end
end
def put(bucket, key, blob, opts) do
headers =
headers() ++
meta_headers(Keyword.fetch!(opts, :meta)) ++
[
{"cache-control", Keyword.fetch!(opts, :cache_control)},
{"content-type", Keyword.get(opts, :content_type)}
]
url = url(bucket, key)
headers = filter_nil_values(headers)
{:ok, 200, _headers, _body} =
Hexpm.HTTP.retry(fn -> Hexpm.HTTP.put(url, headers, blob) end, "gcs")
:ok
end
def delete_many(bucket, keys) do
keys
|> Task.async_stream(
&delete(bucket, &1),
max_concurrency: 10,
timeout: 10_000
)
|> Stream.run()
end
def delete(bucket, key) do
url = url(bucket, key)
{:ok, 204, _headers, _body} =
Hexpm.HTTP.retry(fn -> Hexpm.HTTP.delete(url, headers()) end, "gcs")
:ok
end
defp list_stream(bucket, prefix) do
start_fun = fn -> nil end
after_fun = fn _ -> nil end
next_fun = fn
:halt ->
{:halt, nil}
marker ->
{items, marker} = do_list(bucket, prefix, marker)
{items, marker || :halt}
end
Stream.resource(start_fun, next_fun, after_fun)
end
defp do_list(bucket, prefix, marker) do
url = url(bucket) <> "?prefix=#{prefix}&marker=#{marker}"
{:ok, 200, _headers, body} = Hexpm.HTTP.retry(fn -> Hexpm.HTTP.get(url, headers()) end, "gcs")
doc = SweetXml.parse(body)
marker = SweetXml.xpath(doc, ~x"/ListBucketResult/NextMarker/text()"s)
items = SweetXml.xpath(doc, ~x"/ListBucketResult/Contents/Key/text()"ls)
marker = if marker != "", do: marker
{items, marker}
end
defp filter_nil_values(keyword) do
Enum.reject(keyword, fn {_key, value} -> is_nil(value) end)
end
defp headers() do
{:ok, token} = Goth.fetch(Hexpm.Goth)
[{"authorization", "#{token.type} #{token.token}"}]
end
defp meta_headers(meta) do
Enum.map(meta, fn {key, value} ->
{"x-goog-meta-#{key}", value}
end)
end
defp url(bucket) do
@gs_xml_url <> "/" <> bucket
end
defp url(bucket, key) do
url(bucket) <> "/" <> key
end
end
| 22.846847 | 98 | 0.598975 |
f74295b2fe96533c5570b75e845a2d5f02b8894c | 8,662 | ex | Elixir | lib/credo/check/design/duplicated_code.ex | egze/credo | 59ee836e9ee07c478421df3078a56230a86c3860 | [
"MIT"
] | 1 | 2019-11-11T21:48:20.000Z | 2019-11-11T21:48:20.000Z | deps/credo/lib/credo/check/design/duplicated_code.ex | rwtrecs/rocketseat-nlw5-inmana | 8ce8bc32e0bdd005c423394bb163945747b557e2 | [
"MIT"
] | 3 | 2021-06-20T14:51:14.000Z | 2021-06-25T00:56:11.000Z | deps/credo/lib/credo/check/design/duplicated_code.ex | rwtrecs/rocketseat-nlw5-inmana | 8ce8bc32e0bdd005c423394bb163945747b557e2 | [
"MIT"
] | 1 | 2020-06-28T00:36:07.000Z | 2020-06-28T00:36:07.000Z | defmodule Credo.Check.Design.DuplicatedCode do
use Credo.Check,
run_on_all: true,
base_priority: :higher,
tags: [:controversial],
param_defaults: [
mass_threshold: 40,
nodes_threshold: 2,
excluded_macros: []
],
explanations: [
check: """
Code should not be copy-pasted in a codebase when there is room to abstract
the copied functionality in a meaningful way.
That said, you should by no means "ABSTRACT ALL THE THINGS!".
Sometimes it can serve a purpose to have code be explicit in two places, even
if it means the snippets are nearly identical. A good example for this are
Database Adapters in a project like Ecto, where you might have nearly
identical functions for things like `order_by` or `limit` in both the
Postgres and MySQL adapters.
In this case, introducing an `AbstractAdapter` just to avoid code duplication
might cause more trouble down the line than having a bit of duplicated code.
Like all `Software Design` issues, this is just advice and might not be
applicable to your project/situation.
""",
params: [
mass_threshold:
"The minimum mass which a part of code has to have to qualify for this check.",
nodes_threshold: "The number of nodes that need to be found to raise an issue.",
excluded_macros: "List of macros to be excluded for this check."
]
]
alias Credo.SourceFile
@doc false
@impl true
def run_on_all_source_files(exec, source_files, params) do
mass_threshold = Params.get(params, :mass_threshold, __MODULE__)
nodes_threshold = Params.get(params, :nodes_threshold, __MODULE__)
source_files
|> duplicate_nodes(mass_threshold)
|> append_issues_via_issue_service(source_files, nodes_threshold, params, exec)
:ok
end
defp append_issues_via_issue_service(found_hashes, source_files, nodes_threshold, params, exec)
when is_map(found_hashes) do
found_hashes
|> Enum.map(
&Task.async(fn ->
do_append_issues_via_issue_service(
&1,
source_files,
nodes_threshold,
params,
exec
)
end)
)
|> Enum.map(&Task.await(&1, :infinity))
end
defp do_append_issues_via_issue_service(
{_hash, nodes},
source_files,
nodes_threshold,
params,
exec
) do
filename_map = nodes |> Enum.map(&{&1.filename, true}) |> Enum.into(%{})
source_files
|> Enum.filter(fn source_file -> filename_map[source_file.filename] end)
|> Enum.each(&new_issue_for_members(&1, nodes_threshold, nodes, params, exec))
end
defp new_issue_for_members(source_file, nodes_threshold, nodes, params, exec) do
this_node = Enum.find(nodes, &(&1.filename == source_file.filename))
other_nodes = List.delete(nodes, this_node)
issue_meta = IssueMeta.for(source_file, params)
issue = issue_for(issue_meta, this_node, other_nodes, nodes_threshold, params)
if issue do
Credo.Execution.ExecutionIssues.append(exec, source_file, issue)
end
end
defp duplicate_nodes(source_files, mass_threshold) do
chunked_nodes =
source_files
|> Enum.chunk_every(30)
|> Enum.map(&Task.async(fn -> calculate_hashes_for_chunk(&1, mass_threshold) end))
|> Enum.map(&Task.await(&1, :infinity))
nodes =
Enum.reduce(chunked_nodes, %{}, fn current_hashes, existing_hashes ->
Map.merge(existing_hashes, current_hashes, fn _hash, node_items1, node_items2 ->
node_items1 ++ node_items2
end)
end)
nodes
|> prune_hashes
|> add_masses
end
defp calculate_hashes_for_chunk(source_files, mass_threshold) do
Enum.reduce(source_files, %{}, fn source_file, acc ->
ast = SourceFile.ast(source_file)
calculate_hashes(ast, acc, source_file.filename, mass_threshold)
end)
end
def add_masses(found_hashes) do
Enum.into(found_hashes, %{}, &add_mass_to_subnode/1)
end
defp add_mass_to_subnode({hash, node_items}) do
node_items =
Enum.map(node_items, fn node_item ->
%{node_item | mass: mass(node_item.node)}
end)
{hash, node_items}
end
@doc """
Takes a map of hashes to nodes and prunes those nodes that are just
subnodes of others in the same set.
Returns the resulting map.
"""
def prune_hashes(
given_hashes,
mass_threshold \\ param_defaults()[:mass_threshold]
) do
# remove entries containing a single node
hashes_with_multiple_nodes =
given_hashes
|> Enum.filter(fn {_hash, node_items} -> Enum.count(node_items) > 1 end)
|> Enum.into(%{})
hashes_to_prune =
Enum.flat_map(
hashes_with_multiple_nodes,
&collect_subhashes(&1, mass_threshold)
)
delete_keys(hashes_to_prune, hashes_with_multiple_nodes)
end
defp delete_keys([], acc), do: acc
defp delete_keys([head | tail], acc) do
delete_keys(tail, Map.delete(acc, head))
end
defp collect_subhashes({_hash, node_items}, mass_threshold) do
%{node: first_node, filename: filename} = Enum.at(node_items, 0)
my_hash = first_node |> Credo.Code.remove_metadata() |> to_hash
# don't count self
subhashes =
first_node
|> calculate_hashes(%{}, filename, mass_threshold)
|> Map.keys()
|> List.delete(my_hash)
subhashes
end
@doc """
Calculates hash values for all sub nodes in a given +ast+.
Returns a map with the hashes as keys and the nodes as values.
"""
def calculate_hashes(
ast,
existing_hashes \\ %{},
filename \\ "foo.ex",
mass_threshold \\ param_defaults()[:mass_threshold]
)
when is_map(existing_hashes) do
Credo.Code.prewalk(
ast,
&collect_hashes(&1, &2, filename, mass_threshold),
existing_hashes
)
end
defp collect_hashes(ast, existing_hashes, filename, mass_threshold) do
if mass(ast) < mass_threshold do
{ast, existing_hashes}
else
hash = ast |> Credo.Code.remove_metadata() |> to_hash
node_item = %{node: ast, filename: filename, mass: nil}
node_items = Map.get(existing_hashes, hash, [])
updated_hashes = Map.put(existing_hashes, hash, node_items ++ [node_item])
{ast, updated_hashes}
end
end
@doc """
Returns a hash-value for a given +ast+.
"""
def to_hash(ast) do
string =
ast
|> Inspect.Algebra.to_doc(%Inspect.Opts{})
|> Inspect.Algebra.format(80)
|> Enum.join("")
:sha256
|> :crypto.hash(string)
|> Base.encode16()
end
@doc """
Returns the mass (count of instructions) for an AST.
"""
def mass(ast) do
Credo.Code.prewalk(ast, &calc_mass/2, 0)
end
defp calc_mass(ast, acc) when is_tuple(ast) do
{ast, acc + 1}
end
defp calc_mass(ast, acc) do
{ast, acc}
end
defp issue_for(issue_meta, this_node, other_nodes, nodes_threshold, params) do
if Enum.count(other_nodes) >= nodes_threshold - 1 do
filenames =
other_nodes
|> Enum.map(fn other_node ->
"#{other_node.filename}:#{line_no_for(other_node.node)}"
end)
|> Enum.join(", ")
node_mass = this_node.mass
line_no = line_no_for(this_node.node)
excluded_macros = params[:excluded_macros] || []
if create_issue?(this_node.node, excluded_macros) do
format_issue(
issue_meta,
message: "Duplicate code found in #{filenames} (mass: #{node_mass}).",
line_no: line_no,
severity: Severity.compute(1 + Enum.count(other_nodes), 1)
)
end
end
end
# ignore similar module attributes, no matter how complex
def create_issue?({:@, _, _}, _), do: false
def create_issue?([do: {atom, _, arguments}], excluded_macros)
when is_atom(atom) and is_list(arguments) do
!Enum.member?(excluded_macros, atom)
end
def create_issue?({atom, _, arguments}, excluded_macros)
when is_atom(atom) and is_list(arguments) do
!Enum.member?(excluded_macros, atom)
end
def create_issue?(_ast, _), do: true
# TODO: Put in AST helper
def line_no_for({:__block__, _meta, arguments}) do
line_no_for(arguments)
end
def line_no_for({:do, arguments}) do
line_no_for(arguments)
end
def line_no_for({atom, meta, _}) when is_atom(atom) do
meta[:line]
end
def line_no_for(list) when is_list(list) do
Enum.find_value(list, &line_no_for/1)
end
def line_no_for(nil), do: nil
def line_no_for(block) do
block
|> Credo.Code.Block.do_block_for!()
|> line_no_for
end
end
| 28.123377 | 97 | 0.658393 |
f742c291c342fd91ff525b81d2dfda5f7f7441d2 | 284 | ex | Elixir | lib/sutur/shops.ex | ab-zu/sutur | f314ed29b344fbe0139bd87ac01caf577b1d592e | [
"MIT"
] | 1 | 2021-11-16T02:18:31.000Z | 2021-11-16T02:18:31.000Z | lib/sutur/shops.ex | ab-zu/sutur | f314ed29b344fbe0139bd87ac01caf577b1d592e | [
"MIT"
] | null | null | null | lib/sutur/shops.ex | ab-zu/sutur | f314ed29b344fbe0139bd87ac01caf577b1d592e | [
"MIT"
] | null | null | null | defmodule Sutur.Shops do
@spec products(Shop.t()) :: [map()]
def products(%{url: url, access_token: access_token} = _shop) do
{:ok, %Shopify.Response{code: 200, data: products}} =
Shopify.session(url, access_token)
|> Shopify.Product.all()
products
end
end
| 25.818182 | 66 | 0.651408 |
f742d32e76f45cf8cfa4b999bf1839d93e9dca4a | 1,468 | ex | Elixir | lib/exshome_web/endpoint.ex | exshome/exshome | ef6b7a89f11dcd2016856dd49517b74aeebb6513 | [
"MIT"
] | 2 | 2021-12-21T16:32:56.000Z | 2022-02-22T17:06:39.000Z | lib/exshome_web/endpoint.ex | exshome/exshome | ef6b7a89f11dcd2016856dd49517b74aeebb6513 | [
"MIT"
] | null | null | null | lib/exshome_web/endpoint.ex | exshome/exshome | ef6b7a89f11dcd2016856dd49517b74aeebb6513 | [
"MIT"
] | null | null | null | defmodule ExshomeWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :exshome
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_exshome_key",
signing_salt: "2XdfCLmT"
]
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :exshome,
gzip: false,
only: ~w(assets fonts images favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug ExshomeWeb.Router
end
| 29.36 | 97 | 0.719346 |
f742f184a064882b348a2abe413986a9c4c80321 | 383 | ex | Elixir | elixir/elixir-sips/samples/twitter_playground/web/router.ex | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | 2 | 2015-12-09T02:16:51.000Z | 2021-07-26T22:53:43.000Z | elixir/elixir-sips/samples/twitter_playground/web/router.ex | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | null | null | null | elixir/elixir-sips/samples/twitter_playground/web/router.ex | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | 1 | 2016-05-08T18:40:31.000Z | 2016-05-08T18:40:31.000Z | defmodule TwitterPlayground.Router do
use Phoenix.Router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
end
scope "/", TwitterPlayground do
pipe_through :browser
get "/", PageController, :index
end
socket "/ws", TwitterPlayground.Channels do
channel "tweets", Tweets
end
end
| 19.15 | 45 | 0.70235 |
f743145622c523080a48334560980928d259b4cf | 364 | ex | Elixir | apps/asf_web/lib/asf_web/live/top_menu.ex | LazarRistic/asf | 2c557f06839a129b35174142c91f60696be2fa89 | [
"MIT"
] | null | null | null | apps/asf_web/lib/asf_web/live/top_menu.ex | LazarRistic/asf | 2c557f06839a129b35174142c91f60696be2fa89 | [
"MIT"
] | null | null | null | apps/asf_web/lib/asf_web/live/top_menu.ex | LazarRistic/asf | 2c557f06839a129b35174142c91f60696be2fa89 | [
"MIT"
] | null | null | null | defmodule AsfWeb.Live.TopMenu do
use AsfWeb, :live_view
def mount(_params, session, socket) do
socket =
assign(socket,
current_user: session["current_user"],
is_open?: false
)
{:ok, socket}
end
def handle_event("toggle_menu", _, socket) do
{:noreply, assign(socket, is_open?: !socket.assigns.is_open?)}
end
end
| 20.222222 | 66 | 0.645604 |
f7431864661f59f2df024f729da47ce359696f77 | 1,123 | ex | Elixir | portfolio/test/support/channel_case.ex | JackMaarek/portfolio | 4423e67df870b14228edbc9e4ce3f3cdf1bccc2d | [
"MIT"
] | null | null | null | portfolio/test/support/channel_case.ex | JackMaarek/portfolio | 4423e67df870b14228edbc9e4ce3f3cdf1bccc2d | [
"MIT"
] | 11 | 2020-04-29T10:28:20.000Z | 2020-04-29T11:03:13.000Z | portfolio/test/support/channel_case.ex | JackMaarek/portfolio | 4423e67df870b14228edbc9e4ce3f3cdf1bccc2d | [
"MIT"
] | null | null | null | defmodule PortfolioWeb.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use PortfolioWeb.ChannelCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
import Phoenix.ChannelTest
import PortfolioWeb.ChannelCase
# The default endpoint for testing
@endpoint PortfolioWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Portfolio.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Portfolio.Repo, {:shared, self()})
end
:ok
end
end
| 27.390244 | 71 | 0.730187 |