hexsha
stringlengths 40
40
| size
int64 2
991k
| ext
stringclasses 2
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
208
| max_stars_repo_name
stringlengths 6
106
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
list | max_stars_count
int64 1
33.5k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
208
| max_issues_repo_name
stringlengths 6
106
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
list | max_issues_count
int64 1
16.3k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
208
| max_forks_repo_name
stringlengths 6
106
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
list | max_forks_count
int64 1
6.91k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 2
991k
| avg_line_length
float64 1
36k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
03a218a701b944f5124e54140efc58d1ea8b9931
| 968
|
exs
|
Elixir
|
test/ecto_label_tree/postgrex_test.exs
|
RomanKotov/ecto_ltree
|
b2863fd31a3304ec07b9c43e09f5c985d8652deb
|
[
"MIT"
] | 24
|
2018-04-03T11:36:54.000Z
|
2021-09-21T09:37:15.000Z
|
test/ecto_label_tree/postgrex_test.exs
|
RomanKotov/ecto_ltree
|
b2863fd31a3304ec07b9c43e09f5c985d8652deb
|
[
"MIT"
] | 8
|
2019-06-01T13:49:37.000Z
|
2022-03-29T04:18:39.000Z
|
test/ecto_label_tree/postgrex_test.exs
|
RomanKotov/ecto_ltree
|
b2863fd31a3304ec07b9c43e09f5c985d8652deb
|
[
"MIT"
] | 10
|
2019-02-01T16:52:48.000Z
|
2022-02-23T03:46:09.000Z
|
defmodule EctoLtree.PostgrexTest do
use ExUnit.Case
setup do
{:ok, pid} = Postgrex.start_link(EctoLtree.TestRepo.config_postgrex())
{:ok, [pid: pid]}
end
test "insert item", context do
pid = context[:pid]
path = "this.is.the.path"
{:ok, _} = Postgrex.query(pid, "INSERT INTO items (path) VALUES ($1)", [path])
{:ok, result} = Postgrex.query(pid, "SELECT * FROM items", [])
[[_, result_path]] = result.rows
assert(path == result_path)
{:ok, _} = Postgrex.query(pid, "TRUNCATE TABLE items", [])
end
test "query item", context do
pid = context[:pid]
root = "this.is"
path = root <> ".the.path"
{:ok, _} = Postgrex.query(pid, "INSERT INTO items (path) VALUES ($1)", [path])
{:ok, result} = Postgrex.query(pid, "SELECT * FROM items WHERE path <@ $1;", [root])
[[_, result_path]] = result.rows
assert(path == result_path)
{:ok, _} = Postgrex.query(pid, "TRUNCATE TABLE items", [])
end
end
| 32.266667
| 88
| 0.609504
|
03a21b2121118aeabea0e974ce909ed612be3519
| 2,015
|
ex
|
Elixir
|
clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_v1_workload_fedramp_moderate_settings.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_v1_workload_fedramp_moderate_settings.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_v1_workload_fedramp_moderate_settings.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.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadFedrampModerateSettings do
@moduledoc """
Settings specific to resources needed for FedRAMP Moderate.
## Attributes
* `kmsSettings` (*type:* `GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadKMSSettings.t`, *default:* `nil`) - Required. Input only. Immutable. Settings used to create a CMEK crypto key.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kmsSettings =>
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadKMSSettings.t()
}
field(:kmsSettings,
as: GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadKMSSettings
)
end
defimpl Poison.Decoder,
for:
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadFedrampModerateSettings do
def decode(value, options) do
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadFedrampModerateSettings.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadFedrampModerateSettings do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.350877
| 219
| 0.778164
|
03a21e38956f759201d1929e098d8a9df8f44a7e
| 3,493
|
ex
|
Elixir
|
bench/lib/datasets/google_message3/benchmark_message3_7.pb.ex
|
redink/protobuf
|
9f3e443ba2f0e808aae8ae075ffb7abeeca75483
|
[
"MIT"
] | 4
|
2021-01-16T02:21:44.000Z
|
2022-03-04T18:42:18.000Z
|
bench/lib/datasets/google_message3/benchmark_message3_7.pb.ex
|
redink/protobuf
|
9f3e443ba2f0e808aae8ae075ffb7abeeca75483
|
[
"MIT"
] | 5
|
2020-04-07T20:22:38.000Z
|
2020-09-23T02:28:36.000Z
|
bench/lib/datasets/google_message3/benchmark_message3_7.pb.ex
|
redink/protobuf
|
9f3e443ba2f0e808aae8ae075ffb7abeeca75483
|
[
"MIT"
] | 4
|
2020-07-22T23:38:34.000Z
|
2021-03-26T18:52:54.000Z
|
defmodule Benchmarks.GoogleMessage3.Message11018 do
@moduledoc false
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{}
defstruct []
end
defmodule Benchmarks.GoogleMessage3.Message10800 do
@moduledoc false
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
field10808: String.t(),
field10809: integer,
field10810: boolean,
field10811: float | :infinity | :negative_infinity | :nan
}
defstruct [:field10808, :field10809, :field10810, :field10811]
field :field10808, 1, optional: true, type: :string
field :field10809, 2, optional: true, type: :int64
field :field10810, 3, optional: true, type: :bool
field :field10811, 4, optional: true, type: :float
end
defmodule Benchmarks.GoogleMessage3.Message10802 do
@moduledoc false
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{}
defstruct []
end
defmodule Benchmarks.GoogleMessage3.Message10748 do
@moduledoc false
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
field10750: String.t(),
field10751: integer,
field10752: integer,
field10753: integer
}
defstruct [:field10750, :field10751, :field10752, :field10753]
field :field10750, 1, optional: true, type: :string
field :field10751, 2, optional: true, type: :int32
field :field10752, 3, optional: true, type: :int32
field :field10753, 4, optional: true, type: :int32
end
defmodule Benchmarks.GoogleMessage3.Message7966 do
@moduledoc false
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
field7969: String.t(),
field7970: boolean
}
defstruct [:field7969, :field7970]
field :field7969, 1, optional: true, type: :string
field :field7970, 2, optional: true, type: :bool
end
defmodule Benchmarks.GoogleMessage3.Message708 do
@moduledoc false
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
field823: Benchmarks.GoogleMessage3.Message741.t() | nil,
field824: [String.t()],
field825: String.t(),
field826: String.t(),
field827: [String.t()],
field828: [String.t()]
}
defstruct [:field823, :field824, :field825, :field826, :field827, :field828]
field :field823, 1, optional: true, type: Benchmarks.GoogleMessage3.Message741
field :field824, 6, repeated: true, type: :string
field :field825, 2, optional: true, type: :string
field :field826, 3, optional: true, type: :string
field :field827, 4, repeated: true, type: :string
field :field828, 5, repeated: true, type: :string
end
defmodule Benchmarks.GoogleMessage3.Message8942 do
@moduledoc false
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{}
defstruct []
end
defmodule Benchmarks.GoogleMessage3.Message11011 do
@moduledoc false
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
field11752: binary,
field11753: binary
}
defstruct [:field11752, :field11753]
field :field11752, 1, required: true, type: :bytes
field :field11753, 2, required: true, type: :bytes
end
defmodule Benchmarks.GoogleMessage3.UnusedEmptyMessage do
@moduledoc false
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{}
defstruct []
end
defmodule Benchmarks.GoogleMessage3.Message741 do
@moduledoc false
use Protobuf, syntax: :proto2
@type t :: %__MODULE__{
field936: [String.t()]
}
defstruct [:field936]
field :field936, 1, repeated: true, type: :string
end
| 26.869231
| 80
| 0.678214
|
03a24cd36186c11f47e14b2946ab50b1b3830e99
| 1,674
|
ex
|
Elixir
|
lib/screens/route_patterns/route_pattern.ex
|
mbta/screens
|
4b586970f8844b19543bb2ffd4b032a89f6fa40a
|
[
"MIT"
] | 3
|
2021-07-27T14:11:00.000Z
|
2022-01-03T14:16:43.000Z
|
lib/screens/route_patterns/route_pattern.ex
|
mbta/screens
|
4b586970f8844b19543bb2ffd4b032a89f6fa40a
|
[
"MIT"
] | 444
|
2021-03-10T20:57:17.000Z
|
2022-03-31T16:00:35.000Z
|
lib/screens/route_patterns/route_pattern.ex
|
mbta/screens
|
4b586970f8844b19543bb2ffd4b032a89f6fa40a
|
[
"MIT"
] | null | null | null |
defmodule Screens.RoutePatterns.RoutePattern do
@moduledoc false
alias Screens.RoutePatterns
alias Screens.Routes.Route
alias Screens.Stops.Stop
alias Screens.Trips.Trip
alias Screens.V3Api
defstruct id: nil,
direction_id: nil,
typicality: nil,
route_id: nil,
representative_trip_id: nil
@type id :: String.t()
@type t :: %__MODULE__{
id: id,
direction_id: 0 | 1,
typicality: 1 | 2 | 3 | 4,
route_id: Route.id(),
representative_trip_id: Trip.id()
}
def stops_by_route_and_direction(route_id, direction_id) do
case V3Api.get_json("route_patterns", %{
"filter[route]" => route_id,
"filter[direction_id]" => direction_id,
"sort" => "typicality",
"include" => "representative_trip.stops"
}) do
{:ok, result} -> {:ok, RoutePatterns.Parser.parse_result(result, route_id)}
_ -> :error
end
end
@spec fetch_stop_sequences_through_stop(Stop.id()) :: {:ok, list(list(Stop.id()))} | :error
def fetch_stop_sequences_through_stop(stop_id, get_json_fn \\ &V3Api.get_json/2) do
case get_json_fn.("route_patterns", %{
"include" => "representative_trip.stops",
"filter[stop]" => stop_id
}) do
{:ok, result} ->
stop_sequences =
get_in(result, [
"included",
Access.filter(&(&1["type"] == "trip")),
"relationships",
"stops",
"data",
Access.all(),
"id"
])
{:ok, stop_sequences}
_ ->
:error
end
end
end
| 26.571429
| 93
| 0.55675
|
03a2553644e1270b02a8975946687f1b9c4cc03f
| 205
|
exs
|
Elixir
|
priv/repo/migrations/20180825231845_remove_education_company_in_users.exs
|
coderplanets/coderplanets_server
|
3663e56340d6d050e974c91f7e499d8424fc25e9
|
[
"Apache-2.0"
] | 240
|
2018-11-06T09:36:54.000Z
|
2022-02-20T07:12:36.000Z
|
priv/repo/migrations/20180825231845_remove_education_company_in_users.exs
|
coderplanets/coderplanets_server
|
3663e56340d6d050e974c91f7e499d8424fc25e9
|
[
"Apache-2.0"
] | 363
|
2018-07-11T03:38:14.000Z
|
2021-12-14T01:42:40.000Z
|
priv/repo/migrations/20180825231845_remove_education_company_in_users.exs
|
mydearxym/mastani_server
|
f24034a4a5449200165cf4a547964a0961793eab
|
[
"Apache-2.0"
] | 22
|
2019-01-27T11:47:56.000Z
|
2021-02-28T13:17:52.000Z
|
defmodule GroupherServer.Repo.Migrations.RemoveEducationCompanyInUsers do
use Ecto.Migration
def change do
alter table(:users) do
remove(:company)
remove(:education)
end
end
end
| 18.636364
| 73
| 0.726829
|
03a2823397397434dc257f51aaad900f19370312
| 417
|
ex
|
Elixir
|
lib/glimesh_web/live/user_live/index.ex
|
Darkhax-Forked/glimesh.tv
|
9566f0ec6909ecc5151f0e092f3e08b63d911fa8
|
[
"MIT"
] | 1
|
2020-08-02T00:12:28.000Z
|
2020-08-02T00:12:28.000Z
|
lib/glimesh_web/live/user_live/index.ex
|
Darkhax-Forked/glimesh.tv
|
9566f0ec6909ecc5151f0e092f3e08b63d911fa8
|
[
"MIT"
] | null | null | null |
lib/glimesh_web/live/user_live/index.ex
|
Darkhax-Forked/glimesh.tv
|
9566f0ec6909ecc5151f0e092f3e08b63d911fa8
|
[
"MIT"
] | null | null | null |
defmodule GlimeshWeb.UserLive.Index do
use GlimeshWeb, :live_view
alias Glimesh.Accounts
def mount(_, session, socket) do
users = Accounts.list_users()
# If the viewer is logged in set their locale, otherwise it defaults to English
if session["locale"], do: Gettext.put_locale(session["locale"])
{:ok,
socket
|> assign(:page_title, "Users")
|> assign(:users, users)}
end
end
| 24.529412
| 83
| 0.681055
|
03a2a2bef442792231729a9a1705818636953707
| 562
|
ex
|
Elixir
|
elixir/roman-numerals/lib/roman_numerals.ex
|
quatauta/exercism
|
8c8a477a83719cbe57630c6a2884d40cc1808149
|
[
"MIT"
] | 1
|
2022-01-23T20:34:27.000Z
|
2022-01-23T20:34:27.000Z
|
elixir/roman-numerals/lib/roman_numerals.ex
|
quatauta/exercism
|
8c8a477a83719cbe57630c6a2884d40cc1808149
|
[
"MIT"
] | null | null | null |
elixir/roman-numerals/lib/roman_numerals.ex
|
quatauta/exercism
|
8c8a477a83719cbe57630c6a2884d40cc1808149
|
[
"MIT"
] | null | null | null |
defmodule RomanNumerals do
@symbols [
[1000, "M"],
[900, "CM"],
[500, "D"],
[400, "CD"],
[100, "C"],
[90, "XC"],
[50, "L"],
[40, "XL"],
[10, "X"],
[9, "IX"],
[5, "V"],
[4, "IV"],
[1, "I"]
]
@moduledoc """
Convert the number to a roman number.
"""
@spec numeral(pos_integer) :: String.t()
def numeral(number) when number <= 0, do: ""
def numeral(number) do
[value, symbol] = Enum.find(@symbols, 1, fn pair -> Enum.at(pair, 0) <= number end)
symbol <> numeral(number - value)
end
end
| 19.37931
| 87
| 0.491103
|
03a2ad9ab90d93b68d88dbe9468cb691198c7d82
| 2,071
|
ex
|
Elixir
|
lib/ex_binance/public.ex
|
buurzx/ex_binance
|
95c273bc2b04c8c22eda26b5905f81ae9646577c
|
[
"MIT"
] | null | null | null |
lib/ex_binance/public.ex
|
buurzx/ex_binance
|
95c273bc2b04c8c22eda26b5905f81ae9646577c
|
[
"MIT"
] | null | null | null |
lib/ex_binance/public.ex
|
buurzx/ex_binance
|
95c273bc2b04c8c22eda26b5905f81ae9646577c
|
[
"MIT"
] | null | null | null |
defmodule ExBinance.Public do
import ExBinance.Rest.HTTPClient, only: [get: 2]
def ping, do: get("/api/v1/ping", %{})
def server_time do
with {:ok, %{"serverTime" => time}} <- get("/api/v1/time", %{}) do
{:ok, time}
end
end
def exchange_info do
with {:ok, data} <- get("/fapi/v1/exchangeInfo", %{}) do
{:ok, ExBinance.ExchangeInfo.new(data)}
end
end
def all_prices do
with {:ok, data} <- get("/api/v1/ticker/allPrices", %{}) do
{:ok, Enum.map(data, &ExBinance.SymbolPrice.new(&1))}
end
end
def depth(symbol, limit) do
with {:ok, data} <- get("/api/v1/depth", %{symbol: symbol, limit: limit}) do
{:ok, ExBinance.OrderBook.new(data)}
end
end
def recent_trades(symbol, limit) do
with {:ok, data} <- get("/fapi/v1/trades", %{symbol: symbol, limit: limit}) do
{:ok, Enum.map(data, &ExBinance.TradesBook.new/1)}
end
end
def historical_trades(symbol, limit, from_id) do
with {:ok, data} <-
get("/fapi/v1/historicalTrades", %{symbol: symbol, limit: limit, from_id: from_id}) do
{:ok, Enum.map(data, &ExBinance.TradesBook.new/1)}
end
end
def open_interest(symbol) do
with {:ok, data} <-
get("/fapi/v1/openInterest", %{symbol: symbol}) do
{:ok, ExBinance.OpenInterest.new(data)}
end
end
def long_short_position_ratio(symbol, period, limit) do
with {:ok, data} <-
get("/futures/data/globalLongShortAccountRatio", %{
symbol: symbol,
period: period,
limit: limit
}) do
{:ok, Enum.map(data, &ExBinance.LongShortPositionsRaito.new/1)}
end
end
def candlesticks(symbol, interval, limit \\ 500, start_time \\ nil, end_time \\ nil) do
with {:ok, data} <-
get("/fapi/v1/klines", %{
symbol: symbol,
interval: interval,
start_time: start_time,
end_time: end_time,
limit: limit
}) do
{:ok, Enum.map(data, &ExBinance.Candlestick.new/1)}
end
end
end
| 27.986486
| 97
| 0.582327
|
03a2c6c528d8ebeec1d05243d31ea77ff980927a
| 412
|
ex
|
Elixir
|
apps/glayu_core/lib/glayu/url.ex
|
pmartinezalvarez/glayu
|
8dc30eea4d04c38f5c7999b593c066828423a3dc
|
[
"MIT"
] | 51
|
2017-05-21T07:27:34.000Z
|
2017-11-30T04:34:17.000Z
|
apps/glayu_core/lib/glayu/url.ex
|
doc22940/glayu
|
8dc30eea4d04c38f5c7999b593c066828423a3dc
|
[
"MIT"
] | 17
|
2017-06-14T18:40:44.000Z
|
2017-08-20T16:14:58.000Z
|
apps/glayu_core/lib/glayu/url.ex
|
doc22940/glayu
|
8dc30eea4d04c38f5c7999b593c066828423a3dc
|
[
"MIT"
] | 5
|
2017-06-04T19:55:56.000Z
|
2017-07-29T16:18:58.000Z
|
defmodule Glayu.URL do
@root "/"
@index "index"
@html_ext ".html"
def root() do
@root
end
def home() do
Path.join(@root, @index <> @html_ext)
end
def path(:category, keys) do
Path.join([@root] ++ keys ++ [@index <> @html_ext])
end
def path(_, premalink) do
{file, partial} = List.pop_at(premalink, -1)
Path.join([@root] ++ partial ++ [file <> @html_ext])
end
end
| 17.166667
| 56
| 0.57767
|
03a30ed47e95b9268c6066a47158016982dbd4db
| 1,807
|
ex
|
Elixir
|
lib/exploring_mars.ex
|
pcstl/swap-challenge
|
bc0a84773cd3cb0b48eb23d5dbda47e9d99b4c2c
|
[
"BSD-3-Clause"
] | null | null | null |
lib/exploring_mars.ex
|
pcstl/swap-challenge
|
bc0a84773cd3cb0b48eb23d5dbda47e9d99b4c2c
|
[
"BSD-3-Clause"
] | null | null | null |
lib/exploring_mars.ex
|
pcstl/swap-challenge
|
bc0a84773cd3cb0b48eb23d5dbda47e9d99b4c2c
|
[
"BSD-3-Clause"
] | null | null | null |
defmodule ExploringMars do
@moduledoc """
Start reading here.
The program defined in this project can be ran in three ways:
* It can be used as a CLI application
* It can be used interactively, reading the problem statement
from files and running the program specification
* Or it can be used interactively, passing the problem statement
to the relevant functions as an already-parsed data structure.
There is a module encapsulating each of these ways of running the program:
* `ExploringMars.CLI` defines the CLI application. Running the command
`mix escript.build` at the top-level of this project will generate a
binary file named `exploring_mars` which can be ran on any computer which
has an Erlang runtime available. For more information on this CLI
app, check the documentation for the `ExploringMars.CLI` module.
* `ExploringMars.MissionRunner` defines the functions which read the
input and write the output to files (or to standard input/output).
Calling `ExploringMars.MissionRunner.get_bounds_and_run/2` passing in
input and output files (or `:stdio` in any of the arguments) will
attempt to read in bounds followed by a series of mission specifications
(each mission specification consists of an initial position and a series
of instructions), outputting the results to the specified output device.
Note that this function reads from the input device until it finds EOF, so
press Ctrl+D to end the input if reading from `:stdio`.
* `ExploringMars.Mission` defines the functions which take the already-parsed
data for a mission and return the result of the mission as an Elixir data
structure. Check the module doc for more details. This is probably the module
you should use if you want to use this from `iex`.
"""
end
| 48.837838
| 79
| 0.768124
|
03a323e791a5af36e45563d705360291713e6e37
| 61
|
ex
|
Elixir
|
web/views/page_view.ex
|
cdegroot/clueless
|
c7f575159a42f55eb843df0e37802e778826c845
|
[
"MIT"
] | null | null | null |
web/views/page_view.ex
|
cdegroot/clueless
|
c7f575159a42f55eb843df0e37802e778826c845
|
[
"MIT"
] | 4
|
2015-12-18T20:35:49.000Z
|
2015-12-18T20:36:43.000Z
|
web/views/page_view.ex
|
cdegroot/clueless
|
c7f575159a42f55eb843df0e37802e778826c845
|
[
"MIT"
] | null | null | null |
defmodule Clueless.PageView do
use Clueless.Web, :view
end
| 15.25
| 30
| 0.786885
|
03a3397be6df8ca248e6a9be7e8eab8810d42a2a
| 772
|
ex
|
Elixir
|
lib/data/color.ex
|
NatTuck/ex_venture
|
7a74d33025a580f1e3e93d3755f22258eb3e9127
|
[
"MIT"
] | null | null | null |
lib/data/color.ex
|
NatTuck/ex_venture
|
7a74d33025a580f1e3e93d3755f22258eb3e9127
|
[
"MIT"
] | null | null | null |
lib/data/color.ex
|
NatTuck/ex_venture
|
7a74d33025a580f1e3e93d3755f22258eb3e9127
|
[
"MIT"
] | null | null | null |
defmodule Data.Color do
@moduledoc """
Static color data
"""
@doc """
Valid color codes
"""
def options() do
[
"black",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white"
]
end
@doc """
Valid map color codes
"""
def map_colors() do
[
"blue",
"brown",
"dark-green",
"green",
"grey",
"light-grey"
]
end
@doc """
Color "tags" or semantic colors for things in the game like an NPC
"""
def color_tags() do
[
"command",
"exit",
"error",
"hint",
"item",
"link",
"npc",
"player",
"quest",
"room",
"say",
"shop",
"skill",
"zone",
]
end
end
| 13.310345
| 68
| 0.426166
|
03a350d61ea2142999775dcf4b287d647d256c49
| 933
|
exs
|
Elixir
|
priv/repo/migrations/20180310145608_create_posts.exs
|
saycel/Litelist
|
2a1f67385523e5388c431c307b4052a6f8778818
|
[
"MIT"
] | 1
|
2021-01-13T15:46:49.000Z
|
2021-01-13T15:46:49.000Z
|
priv/repo/migrations/20180310145608_create_posts.exs
|
saycel/Litelist
|
2a1f67385523e5388c431c307b4052a6f8778818
|
[
"MIT"
] | 1
|
2021-01-13T16:42:24.000Z
|
2021-01-13T16:42:24.000Z
|
priv/repo/migrations/20180310145608_create_posts.exs
|
saycel/Litelist
|
2a1f67385523e5388c431c307b4052a6f8778818
|
[
"MIT"
] | null | null | null |
defmodule Litelist.Repo.Migrations.CreatePosts do
use Ecto.Migration
def change do
create table(:posts) do
add :type, :string
add :title, :string
add :description, :text
add :price, :float
add :slug, :string
add :url, :string
add :location, :string
add :contact_info, :string
add :salary, :string
add :position_name, :string
add :company_name, :string
add :neighbor_id, references(:neighbors, on_delete: :delete_all)
add :start_date, :date
add :end_date, :date
add :start_time, :utc_datetime
add :end_time, :utc_datetime
add :organization_name, :string
timestamps()
end
create index(:posts, [:neighbor_id])
create index(:posts, [:title])
create index(:posts, [:type])
create unique_index(:posts, [:url])
create index(:posts, [:start_date])
create index(:posts, [:start_time])
end
end
| 26.657143
| 70
| 0.633441
|
03a357ad705182b810bf3b24efc77344f9d21391
| 279
|
ex
|
Elixir
|
lib/live_beats/repo.ex
|
dsdshcym/live_beats
|
554c97fde490b75cf1868e152a73f4066d8470b6
|
[
"MIT"
] | 547
|
2022-02-02T14:11:31.000Z
|
2022-03-31T12:34:03.000Z
|
lib/live_beats/repo.ex
|
dsdshcym/live_beats
|
554c97fde490b75cf1868e152a73f4066d8470b6
|
[
"MIT"
] | 24
|
2022-02-02T14:11:36.000Z
|
2022-02-23T20:14:43.000Z
|
lib/live_beats/repo.ex
|
dsdshcym/live_beats
|
554c97fde490b75cf1868e152a73f4066d8470b6
|
[
"MIT"
] | 63
|
2022-02-02T15:59:36.000Z
|
2022-03-23T05:30:43.000Z
|
defmodule LiveBeats.Repo do
use Ecto.Repo,
otp_app: :live_beats,
adapter: Ecto.Adapters.Postgres
def replica, do: LiveBeats.config([:replica])
end
defmodule LiveBeats.ReplicaRepo do
use Ecto.Repo,
otp_app: :live_beats,
adapter: Ecto.Adapters.Postgres
end
| 19.928571
| 47
| 0.734767
|
03a357d12362106d2a0cb704603f3955216578d4
| 1,442
|
ex
|
Elixir
|
lib/ellsberg_paradox_simple/participant.ex
|
xeejp/xee_ellsberg_paradox_simple
|
81bc0c37146e8d04c6c9c2bbb40aec41c9d77ef0
|
[
"MIT"
] | null | null | null |
lib/ellsberg_paradox_simple/participant.ex
|
xeejp/xee_ellsberg_paradox_simple
|
81bc0c37146e8d04c6c9c2bbb40aec41c9d77ef0
|
[
"MIT"
] | null | null | null |
lib/ellsberg_paradox_simple/participant.ex
|
xeejp/xee_ellsberg_paradox_simple
|
81bc0c37146e8d04c6c9c2bbb40aec41c9d77ef0
|
[
"MIT"
] | null | null | null |
defmodule EllsbergParadoxSimple.Participant do
alias EllsbergParadoxSimple.Actions
require Logger
# Actions
def fetch_contents(data, id) do
# if data.page == "waiting", do: data = data |> put_in([:participants, id, :active], true)
Actions.update_participant_contents(data, id)
end
def next_question(data, id, selected) do
data = data |> put_in([:participants, id, :sequence], selected["next"])
if selected["next"] == "question2" do
data = data |> put_in([:participants, id, :question1], selected["selected"])
else
data = data |> put_in([:participants, id, :question2], selected["selected"])
|> Map.put(:answered, data.answered + 1)
|> put_in([:participants, id, :bingo], case data.participants[id].question1 do
1 -> :rand.uniform(2) == selected["selected"]
2 -> :rand.uniform(100) <= :rand.uniform(100) && selected["selected"] == 1
_ -> false
end)
end
Actions.next_question(data, id, selected)
end
# Utilities
def format_participant(participant), do: participant
def format_data(data) do
%{
page: data.page,
}
end
def format_contents(data, id) do
%{participants: participants} = data
participant = Map.get(participants, id)
format_participant(participant)
|> Map.merge(format_data(data))
end
end
| 32.772727
| 101
| 0.608183
|
03a3725f9598b7339fea347ab2fda60572b046f4
| 1,024
|
exs
|
Elixir
|
test/asciinema/vt_test.exs
|
zubairshokh/asciinema-server
|
b882f285a84054e94e70def8f9777cc2fc3551b1
|
[
"Apache-2.0"
] | null | null | null |
test/asciinema/vt_test.exs
|
zubairshokh/asciinema-server
|
b882f285a84054e94e70def8f9777cc2fc3551b1
|
[
"Apache-2.0"
] | null | null | null |
test/asciinema/vt_test.exs
|
zubairshokh/asciinema-server
|
b882f285a84054e94e70def8f9777cc2fc3551b1
|
[
"Apache-2.0"
] | null | null | null |
defmodule Asciinema.VtTest do
use ExUnit.Case
alias Asciinema.Vt
@moduletag :vt
test "Vt.Worker" do
{:ok, pid} = Vt.Worker.start_link(nil)
assert Vt.Worker.new(pid, 8, 3) == :ok
assert Vt.Worker.feed(pid, "foobar\r\n") == :ok
assert Vt.Worker.feed(pid, "baz") == :ok
assert Vt.Worker.feed(pid, "qux") == :ok
assert {:ok, screen} = Vt.Worker.dump_screen(pid, 1000)
assert %{"lines" => [_ | _], "cursor" => %{"x" => 6, "y" => 1, "visible" => true}} = screen
assert Vt.Worker.new(pid, 120, 80) == :ok
Enum.each(1..3000, fn _ ->
:ok = Vt.Worker.feed(pid, "aaaaaaaaaaaaaaaaaaaaaaaa")
end)
assert {:ok, %{"cursor" => %{"x" => 120, "y" => 79}}} = Vt.Worker.dump_screen(pid, 10000)
end
test "Vt" do
result =
Vt.with_vt(8, 3, fn vt ->
:ok = Vt.feed(vt, "foobar\r\n")
:ok = Vt.feed(vt, "baz")
:ok = Vt.feed(vt, "qux")
Vt.dump_screen(vt)
end)
assert {:ok, %{"cursor" => %{"x" => 6, "y" => 1}}} = result
end
end
| 26.947368
| 95
| 0.539063
|
03a3b182a2088ea2709fe3397d9569ee599911e0
| 943
|
ex
|
Elixir
|
test/support/channel_case.ex
|
no0x9d/chankins
|
b4fd37d3145a001e4ebbe86eea91742d5a812858
|
[
"MIT"
] | null | null | null |
test/support/channel_case.ex
|
no0x9d/chankins
|
b4fd37d3145a001e4ebbe86eea91742d5a812858
|
[
"MIT"
] | null | null | null |
test/support/channel_case.ex
|
no0x9d/chankins
|
b4fd37d3145a001e4ebbe86eea91742d5a812858
|
[
"MIT"
] | null | null | null |
defmodule Chankins.Web.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 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 channels
use Phoenix.ChannelTest
# The default endpoint for testing
@endpoint Chankins.Web.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Chankins.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Chankins.Repo, {:shared, self()})
end
:ok
end
end
| 24.815789
| 70
| 0.715801
|
03a3b4d9f85c14755e3de02975d317e8a0a98731
| 2,991
|
ex
|
Elixir
|
clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__request_logging_config.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1
|
2021-12-20T03:40:53.000Z
|
2021-12-20T03:40:53.000Z
|
clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__request_logging_config.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1
|
2020-08-18T00:11:23.000Z
|
2020-08-18T00:44:16.000Z
|
clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__request_logging_config.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.MachineLearning.V1.Model.GoogleCloudMlV1_RequestLoggingConfig do
@moduledoc """
Configuration for logging request-response pairs to a BigQuery table. Online prediction requests to a model version and the responses to these requests are converted to raw strings and saved to the specified BigQuery table. Logging is constrained by [BigQuery quotas and limits](/bigquery/quotas). If your project exceeds BigQuery quotas or limits, AI Platform Prediction does not log request-response pairs, but it continues to serve predictions. If you are using [continuous evaluation](/ml-engine/docs/continuous-evaluation/), you do not need to specify this configuration manually. Setting up continuous evaluation automatically enables logging of request-response pairs.
## Attributes
* `bigqueryTableName` (*type:* `String.t`, *default:* `nil`) - Required. Fully qualified BigQuery table name in the following format: " project_id.dataset_name.table_name" The specified table must already exist, and the "Cloud ML Service Agent" for your project must have permission to write to it. The table must have the following [schema](/bigquery/docs/schemas): Field nameType Mode model STRING REQUIRED model_version STRING REQUIRED time TIMESTAMP REQUIRED raw_data STRING REQUIRED raw_prediction STRING NULLABLE groundtruth STRING NULLABLE
* `samplingPercentage` (*type:* `float()`, *default:* `nil`) - Percentage of requests to be logged, expressed as a fraction from 0 to 1. For example, if you want to log 10% of requests, enter `0.1`. The sampling window is the lifetime of the model version. Defaults to 0.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:bigqueryTableName => String.t() | nil,
:samplingPercentage => float() | nil
}
field(:bigqueryTableName)
field(:samplingPercentage)
end
defimpl Poison.Decoder,
for: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_RequestLoggingConfig do
def decode(value, options) do
GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_RequestLoggingConfig.decode(value, options)
end
end
defimpl Poison.Encoder,
for: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_RequestLoggingConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 57.519231
| 677
| 0.775995
|
03a3bd2314713ce3b7e7b2c74a69e30790e1b027
| 10,697
|
ex
|
Elixir
|
clients/docs/lib/google_api/docs/v1/model/section_style.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/docs/lib/google_api/docs/v1/model/section_style.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/docs/lib/google_api/docs/v1/model/section_style.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.Docs.V1.Model.SectionStyle do
@moduledoc """
The styling that applies to a section.
## Attributes
* `columnProperties` (*type:* `list(GoogleApi.Docs.V1.Model.SectionColumnProperties.t)`, *default:* `nil`) - The section's columns properties.
If empty, the section contains one column with the default properties in
the Docs editor.
A section can be updated to have no more than three columns.
When updating this property, setting a concrete value is required.
Unsetting this property will result in a 400 bad request error.
* `columnSeparatorStyle` (*type:* `String.t`, *default:* `nil`) - The style of column separators.
This style can be set even when there is one column in the section.
When updating this property, setting a concrete value is required.
Unsetting this property results in a 400 bad request error.
* `contentDirection` (*type:* `String.t`, *default:* `nil`) - The content direction of this section. If unset, the value defaults to
LEFT_TO_RIGHT.
When updating this property, setting a concrete value is required.
Unsetting this property results in a 400 bad request error.
* `defaultFooterId` (*type:* `String.t`, *default:* `nil`) - The ID of the default footer. If unset, the value inherits from the
previous SectionBreak's SectionStyle.
If the value is unset in the first SectionBreak, it inherits from
DocumentStyle's default_footer_id.
This property is read-only.
* `defaultHeaderId` (*type:* `String.t`, *default:* `nil`) - The ID of the default header. If unset, the value inherits from the
previous SectionBreak's SectionStyle.
If the value is unset in the first SectionBreak, it inherits from
DocumentStyle's default_header_id.
This property is read-only.
* `evenPageFooterId` (*type:* `String.t`, *default:* `nil`) - The ID of the footer used only for even pages. If the value of
DocumentStyle's use_even_page_header_footer is true,
this value is used for the footers on even pages in the section. If it
is false, the footers on even pages uses the default_footer_id. If unset, the value
inherits from the previous SectionBreak's SectionStyle. If the value is unset in
the first SectionBreak, it inherits from DocumentStyle's
even_page_footer_id.
This property is read-only.
* `evenPageHeaderId` (*type:* `String.t`, *default:* `nil`) - The ID of the header used only for even pages. If the value of
DocumentStyle's use_even_page_header_footer is true,
this value is used for the headers on even pages in the section. If it
is false, the headers on even pages uses the default_header_id. If unset, the value
inherits from the previous SectionBreak's SectionStyle. If the value is unset in
the first SectionBreak, it inherits from DocumentStyle's
even_page_header_id.
This property is read-only.
* `firstPageFooterId` (*type:* `String.t`, *default:* `nil`) - The ID of the footer used only for the first page of the section.
If use_first_page_header_footer is true,
this value is used for the footer on the first page of the section. If
it is false, the footer on the first page of the section uses the
default_footer_id.
If unset, the value inherits from the previous SectionBreak's SectionStyle. If the value is unset in
the first SectionBreak, it inherits from DocumentStyle's
first_page_footer_id.
This property is read-only.
* `firstPageHeaderId` (*type:* `String.t`, *default:* `nil`) - The ID of the header used only for the first page of the section.
If use_first_page_header_footer is true,
this value is used for the header on the first page of the section. If
it is false, the header on the first page of the section uses the
default_header_id.
If unset, the value inherits from the previous SectionBreak's SectionStyle. If the value is unset in
the first SectionBreak, it inherits from DocumentStyle's
first_page_header_id.
This property is read-only.
* `marginBottom` (*type:* `GoogleApi.Docs.V1.Model.Dimension.t`, *default:* `nil`) - The bottom page margin of the section. If unset, uses margin_bottom from DocumentStyle.
When updating this property, setting a concrete value is required.
Unsetting this property results in a 400 bad request error.
* `marginFooter` (*type:* `GoogleApi.Docs.V1.Model.Dimension.t`, *default:* `nil`) - The footer margin of the section. If unset, uses margin_footer from DocumentStyle. If
updated, use_custom_header_footer_margins is set
to true on DocumentStyle. The value of use_custom_header_footer_margins on
DocumentStyle indicates if a footer margin is being respected for this
section
When updating this property, setting a concrete value is required.
Unsetting this property results in a 400 bad request error.
* `marginHeader` (*type:* `GoogleApi.Docs.V1.Model.Dimension.t`, *default:* `nil`) - The header margin of the section. If unset, uses margin_header from DocumentStyle. If
updated, use_custom_header_footer_margins is set
to true on DocumentStyle. The value of use_custom_header_footer_margins on
DocumentStyle indicates if a header margin is being respected for this
section.
When updating this property, setting a concrete value is required.
Unsetting this property results in a 400 bad request error.
* `marginLeft` (*type:* `GoogleApi.Docs.V1.Model.Dimension.t`, *default:* `nil`) - The left page margin of the section. If unset, uses margin_left from DocumentStyle.
Updating left margin causes columns in this section to resize. Since
the margin affects column width, it is applied before column properties.
When updating this property, setting a concrete value is required.
Unsetting this property results in a 400 bad request error.
* `marginRight` (*type:* `GoogleApi.Docs.V1.Model.Dimension.t`, *default:* `nil`) - The right page margin of the section. If unset, uses margin_right from DocumentStyle.
Updating right margin causes columns in this section to resize. Since
the margin affects column width, it is applied before column properties.
When updating this property, setting a concrete value is required.
Unsetting this property results in a 400 bad request error.
* `marginTop` (*type:* `GoogleApi.Docs.V1.Model.Dimension.t`, *default:* `nil`) - The top page margin of the section. If unset, uses margin_top from DocumentStyle.
When updating this property, setting a concrete value is required.
Unsetting this property results in a 400 bad request error.
* `pageNumberStart` (*type:* `integer()`, *default:* `nil`) - The page number from which to start counting the number of pages for this
section. If unset, page numbering continues from the previous section.
If the value is unset in the first
SectionBreak, refer to DocumentStyle's
page_number_start.
When updating this property, setting a concrete value is required.
Unsetting this property results in a 400 bad request error.
* `sectionType` (*type:* `String.t`, *default:* `nil`) - Output only. The type of section.
* `useFirstPageHeaderFooter` (*type:* `boolean()`, *default:* `nil`) - Indicates whether to use the first page header / footer IDs for the first
page of the section. If unset, it inherits from DocumentStyle's
use_first_page_header_footer for the
first section. If the value is unset for subsequent sectors, it should be
interpreted as false.
When updating this property, setting a concrete value is required.
Unsetting this property results in a 400 bad request error.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:columnProperties => list(GoogleApi.Docs.V1.Model.SectionColumnProperties.t()),
:columnSeparatorStyle => String.t(),
:contentDirection => String.t(),
:defaultFooterId => String.t(),
:defaultHeaderId => String.t(),
:evenPageFooterId => String.t(),
:evenPageHeaderId => String.t(),
:firstPageFooterId => String.t(),
:firstPageHeaderId => String.t(),
:marginBottom => GoogleApi.Docs.V1.Model.Dimension.t(),
:marginFooter => GoogleApi.Docs.V1.Model.Dimension.t(),
:marginHeader => GoogleApi.Docs.V1.Model.Dimension.t(),
:marginLeft => GoogleApi.Docs.V1.Model.Dimension.t(),
:marginRight => GoogleApi.Docs.V1.Model.Dimension.t(),
:marginTop => GoogleApi.Docs.V1.Model.Dimension.t(),
:pageNumberStart => integer(),
:sectionType => String.t(),
:useFirstPageHeaderFooter => boolean()
}
field(:columnProperties, as: GoogleApi.Docs.V1.Model.SectionColumnProperties, type: :list)
field(:columnSeparatorStyle)
field(:contentDirection)
field(:defaultFooterId)
field(:defaultHeaderId)
field(:evenPageFooterId)
field(:evenPageHeaderId)
field(:firstPageFooterId)
field(:firstPageHeaderId)
field(:marginBottom, as: GoogleApi.Docs.V1.Model.Dimension)
field(:marginFooter, as: GoogleApi.Docs.V1.Model.Dimension)
field(:marginHeader, as: GoogleApi.Docs.V1.Model.Dimension)
field(:marginLeft, as: GoogleApi.Docs.V1.Model.Dimension)
field(:marginRight, as: GoogleApi.Docs.V1.Model.Dimension)
field(:marginTop, as: GoogleApi.Docs.V1.Model.Dimension)
field(:pageNumberStart)
field(:sectionType)
field(:useFirstPageHeaderFooter)
end
defimpl Poison.Decoder, for: GoogleApi.Docs.V1.Model.SectionStyle do
def decode(value, options) do
GoogleApi.Docs.V1.Model.SectionStyle.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Docs.V1.Model.SectionStyle do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 52.955446
| 176
| 0.718332
|
03a3d8a1e7fd98dd6cc3d1c651d4658f7f2b0e75
| 1,488
|
ex
|
Elixir
|
lib/xdr/transactions/fee_bump_inner_tx.ex
|
einerzg/stellar_base
|
2d10c5fc3b8159efc5de10b5c7c665e3b57b3d8f
|
[
"MIT"
] | 3
|
2021-08-17T20:32:45.000Z
|
2022-03-13T20:26:02.000Z
|
lib/xdr/transactions/fee_bump_inner_tx.ex
|
einerzg/stellar_base
|
2d10c5fc3b8159efc5de10b5c7c665e3b57b3d8f
|
[
"MIT"
] | 45
|
2021-08-12T20:19:41.000Z
|
2022-03-27T21:00:10.000Z
|
lib/xdr/transactions/fee_bump_inner_tx.ex
|
einerzg/stellar_base
|
2d10c5fc3b8159efc5de10b5c7c665e3b57b3d8f
|
[
"MIT"
] | 2
|
2021-09-22T23:11:13.000Z
|
2022-01-23T03:19:11.000Z
|
defmodule StellarBase.XDR.FeeBumpInnerTx do
@moduledoc """
Representation of Stellar `FeeBumpInnerTx` type.
"""
alias StellarBase.XDR.{EnvelopeType, TransactionV1Envelope}
@behaviour XDR.Declaration
@arms [ENVELOPE_TYPE_TX: TransactionV1Envelope]
@type envelope :: TransactionV1Envelope.t()
@type t :: %__MODULE__{envelope: envelope(), type: EnvelopeType.t()}
defstruct [:envelope, :type]
@spec new(envelope :: envelope(), type :: EnvelopeType.t()) :: t()
def new(envelope, %EnvelopeType{} = type),
do: %__MODULE__{envelope: envelope, type: type}
@impl true
def encode_xdr(%__MODULE__{envelope: envelope, type: type}) do
type
|> XDR.Union.new(@arms, envelope)
|> XDR.Union.encode_xdr()
end
@impl true
def encode_xdr!(%__MODULE__{envelope: envelope, type: type}) do
type
|> XDR.Union.new(@arms, envelope)
|> XDR.Union.encode_xdr!()
end
@impl true
def decode_xdr(bytes, spec \\ union_spec())
def decode_xdr(bytes, spec) do
case XDR.Union.decode_xdr(bytes, spec) do
{:ok, {{type, envelope}, rest}} -> {:ok, {new(envelope, type), rest}}
error -> error
end
end
@impl true
def decode_xdr!(bytes, spec \\ union_spec())
def decode_xdr!(bytes, spec) do
{{type, envelope}, rest} = XDR.Union.decode_xdr!(bytes, spec)
{new(envelope, type), rest}
end
@spec union_spec() :: XDR.Union.t()
defp union_spec do
nil
|> EnvelopeType.new()
|> XDR.Union.new(@arms)
end
end
| 24.8
| 75
| 0.66129
|
03a3ee3666b656d05c99a03fb41b6a2cc21f5462
| 6,923
|
ex
|
Elixir
|
mpc-wallet/demo/server/lib/mpcwallet.ex
|
acatinon/nash-rust
|
f2350bbd99a3193cadf95ef62d7e62aca9145ec2
|
[
"MIT"
] | 4
|
2020-10-30T00:15:51.000Z
|
2021-07-05T09:14:58.000Z
|
mpc-wallet/demo/server/lib/mpcwallet.ex
|
acatinon/nash-rust
|
f2350bbd99a3193cadf95ef62d7e62aca9145ec2
|
[
"MIT"
] | 33
|
2020-09-16T22:43:27.000Z
|
2021-11-11T20:24:35.000Z
|
mpc-wallet/demo/server/lib/mpcwallet.ex
|
acatinon/nash-rust
|
f2350bbd99a3193cadf95ef62d7e62aca9145ec2
|
[
"MIT"
] | 8
|
2020-09-18T06:45:35.000Z
|
2021-03-27T19:53:15.000Z
|
defmodule Server.MPCwallet do
@moduledoc """
Library for the server part of the MPC-based API keys.
Glossary of terms:
- MPC: Multi-party computation. A method to have multiple parties compute a function while keeping their inputs private. For our case, the function is creating a digital signature and the (private) inputs are secret shares.
- DH: Diffie-Hellman key exchange. A method to derive a shared secret key over an insecure channel.
- Paillier: A public-key, additive homomorphic cryptosystem. Allows the client to conduct operations on the ciphertext.
- r: Random value shared between client and server (derived via DH), from which the r value of the ECDSA signature is derived.
- k: Server part of the nonce used in the signature. This should be handled like a secret key, i.e., store securely, delete/zeroize after use, ..
- curve: Elliptic curve to be used in an ECDSA signature. Currently we support secp256k1 (for BTC and ETH) and secp256r1 (for NEO).
- presig: A presignature generated on the client that can be finalized to a conventional signature by the server.
- rpool: Pool of random values shared between client and server that allows to generate signatures with a single message.
- r, s: a conventional ECDSA signature.
- recovery_id: 2 bits that help recovering the public key from a signature, used in Ethereum to save space.
- correct_key_proof: ZK proof that the Paillier public key was generated correctly.
"""
use Rustler, otp_app: :server, crate: "mpc_wallet_elixir"
@doc ~S"""
Generate Paillier keypair with safe primes and proof that the keypair was generated correctly.
## Parameters
- none
## Returns
- Paillier secret key
- Paillier public key
- correct_key_proof: proof
"""
def generate_paillier_keypair_and_proof(), do: :erlang.nif_error(:nif_not_loaded)
@doc ~S"""
Compute rpool values via Diffie-Hellman.
## Parameters
- client_dh_publics: list of DH public keys received from the client
- curve: Secp256k1 or Secp256r1 curve
## Returns
- rpool_new: map of rpool values to be added to the local pool
- server_dh_publics: list of public keys (to be sent to the client)
"""
def dh_rpool(_client_dh_publics, _curve), do: :erlang.nif_error(:nif_not_loaded)
@doc ~S"""
Complete presignature to conventional ECDSA signature.
## Parameters
- paillier_sk: Paillier secret key
- presig: presignature received from client
- r: random value shared between server and client
- k: server part of the nonce used in the signature
- curve: Secp256k1 or Secp256r1 curve
- public_key: public key under which the completed signature is (supposed to be) valid
- msg_hash: hash of the message under which the completed signature is (supposed to be) valid
## Returns
- r: r part of a conventional ECDSA signature
- s: s part of a conventional ECDSA signature
- recovery_id: 2 bits that help recovering the public key from a signature
"""
def complete_sig(_paillier_sk, _presig, _r, _k, _curve, _pubkey, _msg_hash), do: :erlang.nif_error(:nif_not_loaded)
@doc ~S"""
Verify conventional ECDSA signature.
## Parameters
- r: r part of a conventional ECDSA signature
- s: s part of a conventional ECDSA signature
- pubkey: ECDSA public key
- msg_hash: hash of the message
- curve: Secp256k1 or Secp256r1 curve
## Returns
- ok | error: boolean indicating success
"""
def verify(_r, _s, _pubkey, _msg_hash, _curve), do: :erlang.nif_error(:nif_not_loaded)
@doc ~S"""
Generate key pairs for Diffie-Hellman.
## Parameters
- n: number of key pairs to generate
- curve: Secp256k1 or Secp256r1 curve
## Returns
- dh_secrets: list of (n) secret keys
- dh_publics: list of (n) public keys
First public key corresponds to first secret key, ..
"""
def dh_init(_n, _curve), do: :erlang.nif_error(:nif_not_loaded)
@doc ~S"""
Compute presignature of a message.
## Parameters
- apikey: API key struct
- msg_hash: hash of the message to be signed
- curve: Secp256k1 or Secp256r1 curve
## Returns
- presig: presignature that is to be completed by the server
- r: message-independent part of the signature that was used to compute the presignature
"""
def compute_presig(_apikey, _msg_hash, _curve), do: :erlang.nif_error(:nif_not_loaded)
@doc ~S"""
(re-)Fill pool of r-values from dh secret and public values.
## Parameters
- client_dh_secrets: list of client DH secret keys
- server_dh_publics: list of DH public keys received from the server
- curve: Secp256k1 or Secp256r1 curve
- paillier_pk: Paillier public key
## Returns
- ok | error: boolean indicating success
"""
def fill_rpool(_client_dh_secrets, _server_dh_publics, _curve, _paillier_pk), do: :erlang.nif_error(:nif_not_loaded)
@doc ~S"""
Initialize API childkey creation by setting the full secret key.
## Parameters
- secret_key: full secret key
## Returns
- api_childkey_creator: API childkey creation struct
"""
def init_api_childkey_creator(_secret_key), do: :erlang.nif_error(:nif_not_loaded)
@doc ~S"""
Initialize API childkey creation by setting the full secret key and the paillier public key, assuming that the paillier public key has been verified before.
## Parameters
- secret_key: full secret key
- paillier_pk: Paillier public key
## Returns
- api_childkey_creator: API childkey creation struct
"""
def init_api_childkey_creator_with_verified_paillier(_secret_key, _paillier_pk), do: :erlang.nif_error(:nif_not_loaded)
@doc ~S"""
Verify that the Paillier public key was generated correctly.
## Parameters
- api_childkeyc_reator: API childkey creation struct
- paillier_pk: Paillier public key
- correct_key_proof: ZK proof that the Paillier public key was generated correctly
## Returns
- api_childkey_creator: API key creation struct
"""
def verify_paillier(_api_childkey_creator, _paillier_pk, _correct_key_proof), do: :erlang.nif_error(:nif_not_loaded)
@doc ~S"""
Create API childkey.
## Parameters
- api_childkey_creator: API childkey creation struct
- curve: Secp256k1 or Secp256r1 curve
## Returns
- api_childkey: API childkey struct
"""
def create_api_childkey(_api_childkey_creator, _curve), do: :erlang.nif_error(:nif_not_loaded)
@doc ~S"""
Derive public key from given secret key.
## Parameters
- secret_key: (full) secret key)
- curve: Secp256k1 or Secp256r1 curve
## Returns
- public_key: corresponding public key
"""
def publickey_from_secretkey(_secret_key, _curve), do: :erlang.nif_error(:nif_not_loaded)
end
| 30.364035
| 229
| 0.707352
|
03a400a3b791f3331083c8afd6580ba3c8c0f61c
| 7,922
|
exs
|
Elixir
|
test/ack_test.exs
|
angrycandy/elixir-mllp
|
f3b5988c0d9f2fefaca16890b13f8c08db2ce382
|
[
"Apache-2.0"
] | 22
|
2018-10-08T18:37:23.000Z
|
2022-02-22T13:53:38.000Z
|
test/ack_test.exs
|
angrycandy/elixir-mllp
|
f3b5988c0d9f2fefaca16890b13f8c08db2ce382
|
[
"Apache-2.0"
] | 27
|
2020-03-03T16:29:22.000Z
|
2022-03-16T20:09:59.000Z
|
test/ack_test.exs
|
angrycandy/elixir-mllp
|
f3b5988c0d9f2fefaca16890b13f8c08db2ce382
|
[
"Apache-2.0"
] | 10
|
2019-03-29T04:19:59.000Z
|
2021-12-13T17:39:08.000Z
|
defmodule AckTest do
use ExUnit.Case
alias MLLP.Ack
doctest Ack
import HL7.Query
describe "get_ack_for_message" do
test "for an invalid HL7 message returns a valid AR ack message" do
bad_message =
"Bad Message"
|> HL7.Message.new()
ack = Ack.get_ack_for_message(bad_message, "AA")
assert "AR" == ack |> get_part("MSA-1")
assert "ACK" == ack.header.message_type
assert ack |> get_part("MSA-3") =~ "missing_header_or_encoding"
end
test "for an invalid HL7 string" do
bad_message = "Bad Message"
ack = Ack.get_ack_for_message(bad_message, "AA")
assert "AR" == ack |> get_part("MSA-1")
assert "ACK" == ack.header.message_type
assert ack |> get_part("MSA-3") =~ "missing_header_or_encoding"
end
test "with code `application_accepted`" do
hl7_ack = get_ack_for_wikipedia_example(:application_accept)
assert "AA" == hl7_ack |> get_part("MSA-1")
end
test "with code `AA`" do
hl7_ack = get_ack_for_wikipedia_example("AA")
assert "AA" == hl7_ack |> get_part("MSA-1")
end
test "with code `CA`" do
hl7_ack = get_ack_for_wikipedia_example("CA")
assert "CA" == hl7_ack |> get_part("MSA-1")
end
test "with code `application_reject`" do
hl7_ack = get_ack_for_wikipedia_example(:application_reject)
assert "AR" == hl7_ack |> get_part("MSA-1")
end
test "with code `AR`" do
hl7_ack = get_ack_for_wikipedia_example("AR")
assert "AR" == hl7_ack |> get_part("MSA-1")
end
test "with code `CR`" do
hl7_ack = get_ack_for_wikipedia_example("CR")
assert "CR" == hl7_ack |> get_part("MSA-1")
end
test "with code `application_error`" do
hl7_ack = get_ack_for_wikipedia_example(:application_error)
assert "AE" == hl7_ack |> get_part("MSA-1")
end
test "with code `AE`" do
hl7_ack = get_ack_for_wikipedia_example("AE")
assert "AE" == hl7_ack |> get_part("MSA-1")
end
test "with code `CE`" do
hl7_ack = get_ack_for_wikipedia_example("CE")
assert "CE" == hl7_ack |> get_part("MSA-1")
end
test "returns an ACK message with the proper message_type" do
hl7_ack = get_ack_for_wikipedia_example(:application_accept)
assert "ACK" == hl7_ack.header.message_type
assert "A01" == hl7_ack.header.trigger_event
assert "ACK" == HL7.Query.get_part(hl7_ack, "MSH-9.3")
end
test "return an ACK message with a matching message_control_id" do
hl7_ack = get_ack_for_wikipedia_example(:application_accept)
assert "01052901" == hl7_ack |> new() |> get_part("MSA-2")
end
test "returns an ACK message with the sender and receiver fields properly reversed" do
hl7_ack = get_ack_for_wikipedia_example(:application_accept)
assert "MegaReg" == hl7_ack |> get_part("MSH-5")
assert "XYZHospC" == hl7_ack |> get_part("MSH-6")
assert "SuperOE" == hl7_ack |> get_part("MSH-3")
assert "XYZImgCtr" == hl7_ack |> get_part("MSH-4")
end
end
describe "verify_ack_against_message" do
test "works fine for a good message and a matching ACK message" do
message = HL7.Examples.wikipedia_sample_hl7()
ack_message = get_ack_for_wikipedia_example(:application_accept)
expected_ack = %Ack{acknowledgement_code: "AA"}
assert {:ok, :application_accept, expected_ack} ==
Ack.verify_ack_against_message(message, ack_message)
end
test "with code `AA`" do
hl7_message = HL7.Examples.wikipedia_sample_hl7()
hl7_ack = get_ack_for_wikipedia_example("AA")
expected_ack = %Ack{acknowledgement_code: "AA"}
assert {:ok, :application_accept, expected_ack} ==
Ack.verify_ack_against_message(hl7_message, hl7_ack)
end
test "with code `CA`" do
hl7_message = HL7.Examples.wikipedia_sample_hl7()
hl7_ack = get_ack_for_wikipedia_example("CA")
expected_ack = %Ack{acknowledgement_code: "CA"}
assert {:ok, :application_accept, expected_ack} ==
Ack.verify_ack_against_message(hl7_message, hl7_ack)
end
test "with code `application_reject`" do
hl7_message = HL7.Examples.wikipedia_sample_hl7()
hl7_ack = get_ack_for_wikipedia_example(:application_reject)
expected_ack = %Ack{acknowledgement_code: "AR"}
assert {:error, :application_reject, expected_ack} ==
Ack.verify_ack_against_message(hl7_message, hl7_ack)
end
test "with code `AR`" do
hl7_message = HL7.Examples.wikipedia_sample_hl7()
hl7_ack = get_ack_for_wikipedia_example("AR")
expected_ack = %Ack{acknowledgement_code: "AR"}
assert {:error, :application_reject, expected_ack} ==
Ack.verify_ack_against_message(hl7_message, hl7_ack)
end
test "with code `CR`" do
hl7_message = HL7.Examples.wikipedia_sample_hl7()
hl7_ack = get_ack_for_wikipedia_example("CR")
expected_ack = %Ack{acknowledgement_code: "CR"}
assert {:error, :application_reject, expected_ack} ==
Ack.verify_ack_against_message(hl7_message, hl7_ack)
end
test "with code `application_error`" do
hl7_message = HL7.Examples.wikipedia_sample_hl7()
hl7_ack = get_ack_for_wikipedia_example(:application_error)
expected_ack = %Ack{acknowledgement_code: "AE"}
assert {:error, :application_error, expected_ack} ==
Ack.verify_ack_against_message(hl7_message, hl7_ack)
end
test "with code `AE`" do
hl7_message = HL7.Examples.wikipedia_sample_hl7()
hl7_ack = get_ack_for_wikipedia_example("AE")
expected_ack = %Ack{acknowledgement_code: "AE"}
assert {:error, :application_error, expected_ack} ==
Ack.verify_ack_against_message(hl7_message, hl7_ack)
end
test "with code `CE`" do
hl7_message = HL7.Examples.wikipedia_sample_hl7()
hl7_ack = get_ack_for_wikipedia_example("CE")
expected_ack = %Ack{acknowledgement_code: "CE"}
assert {:error, :application_error, expected_ack} ==
Ack.verify_ack_against_message(hl7_message, hl7_ack)
end
test "errors on ACK containing a mismatching message_control_id" do
message = HL7.Examples.wikipedia_sample_hl7()
bad_ack =
"MSH|^~\\&|SuperOE|XYZImgCtr|MegaReg|XYZHospC|20060529090131-0500||ACK^O01|01052901|P|2.5\rMSA|AA|**BAD_MESSAGE_CONTROL**\r"
assert {:error, :bad_message_control_id,
"The message_control_id of the message 01052901 does not match the message_control_id of the ACK message (**BAD_MESSAGE_CONTROL**)."} ==
Ack.verify_ack_against_message(message, bad_ack)
end
test "errors on ACK with a bad ack_code" do
message = HL7.Examples.wikipedia_sample_hl7()
bad_ack =
"MSH|^~\\&|SuperOE|XYZImgCtr|MegaReg|XYZHospC|20060529090131-0500||ACK^O01|01052901|P|2.5\rMSA|**BAD_ACK_CODE**|01052901\r"
assert {:error, :bad_ack_code,
"The value **BAD_ACK_CODE** is not a valid acknowledgment_code"} ==
Ack.verify_ack_against_message(message, bad_ack)
end
test "errors on an invalid message" do
message = "Nothing like a valid HL7 message"
ack = ""
assert {:error, :invalid_message, "missing_header_or_encoding"} ==
Ack.verify_ack_against_message(message, ack)
end
test "errors on an invalid ack message" do
message = HL7.Examples.wikipedia_sample_hl7()
bad_ack = "Nothing like a valid ACK message"
assert {:error, :invalid_ack_message, "missing_header_or_encoding"} ==
Ack.verify_ack_against_message(message, bad_ack)
end
end
defp get_ack_for_wikipedia_example(ack_type) do
incoming_raw = HL7.Examples.wikipedia_sample_hl7()
incoming_raw
|> Ack.get_ack_for_message(ack_type)
|> HL7.Message.new()
end
end
| 34.745614
| 150
| 0.673441
|
03a42c0253fd43a6e0b627a24eb70175d72b727b
| 1,129
|
ex
|
Elixir
|
test/support/channel_case.ex
|
yosefbennywidyo/phoenix_app
|
04c49fc324e137589006ada3a6cb414c466be86d
|
[
"MIT"
] | 47
|
2020-03-04T00:24:26.000Z
|
2022-01-14T23:34:52.000Z
|
test/support/channel_case.ex
|
yosefbennywidyo/phoenix_app
|
04c49fc324e137589006ada3a6cb414c466be86d
|
[
"MIT"
] | 2
|
2020-06-09T22:25:06.000Z
|
2020-06-30T21:18:37.000Z
|
test_projects/phoenix_app/test/support/channel_case.ex
|
qhwa/dockerize
|
d930f06da89a686961da7a5b5bdadb4c9b01ec32
|
[
"MIT"
] | null | null | null |
defmodule PhoenixAppWeb.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 PhoenixAppWeb.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 PhoenixAppWeb.ChannelCase
# The default endpoint for testing
@endpoint PhoenixAppWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(PhoenixApp.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(PhoenixApp.Repo, {:shared, self()})
end
:ok
end
end
| 27.536585
| 72
| 0.731621
|
03a44acf9d018c5fcb256454c3e53586c9d9ee7f
| 912
|
ex
|
Elixir
|
lib/data_generator/application.ex
|
UrbanOS-Examples/data-generator
|
dcf3fb19fbb04809a73b52aac12e564a7749e71f
|
[
"Apache-2.0"
] | null | null | null |
lib/data_generator/application.ex
|
UrbanOS-Examples/data-generator
|
dcf3fb19fbb04809a73b52aac12e564a7749e71f
|
[
"Apache-2.0"
] | null | null | null |
lib/data_generator/application.ex
|
UrbanOS-Examples/data-generator
|
dcf3fb19fbb04809a73b52aac12e564a7749e71f
|
[
"Apache-2.0"
] | null | null | null |
defmodule DataGenerator.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
# List all child processes to be supervised
children = [
# Start the endpoint when the application starts
DataGeneratorWeb.Endpoint
# Starts a worker by calling: DataGenerator.Worker.start_link(arg)
# {DataGenerator.Worker, arg},
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: DataGenerator.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
DataGeneratorWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 30.4
| 72
| 0.73136
|
03a4565006bead8166bc57b07f0b377d398fdc63
| 993
|
ex
|
Elixir
|
lib/tarkus/application.ex
|
ramonsantos/tarkus
|
fe59b810b448824e149c19c7568bd284aef6407a
|
[
"MIT"
] | 1
|
2020-11-07T01:59:11.000Z
|
2020-11-07T01:59:11.000Z
|
lib/tarkus/application.ex
|
ramonsantos/tarkus
|
fe59b810b448824e149c19c7568bd284aef6407a
|
[
"MIT"
] | null | null | null |
lib/tarkus/application.ex
|
ramonsantos/tarkus
|
fe59b810b448824e149c19c7568bd284aef6407a
|
[
"MIT"
] | null | null | null |
defmodule Tarkus.Application do
use Application
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec
# Define workers and child supervisors to be supervised
children = [
# Start the endpoint when the application starts
supervisor(TarkusWeb.Endpoint, []),
supervisor(Tarkus.EmailSenderJob , []),
# Start your own worker by calling: Tarkus.Worker.start_link(arg1, arg2, arg3)
# worker(Tarkus.Worker, [arg1, arg2, arg3]),
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Tarkus.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
TarkusWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 32.032258
| 84
| 0.716012
|
03a46345cb93439205f4efdd608b3372bff0dc37
| 1,163
|
exs
|
Elixir
|
clients/cloud_functions/mix.exs
|
mocknen/elixir-google-api
|
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
|
[
"Apache-2.0"
] | null | null | null |
clients/cloud_functions/mix.exs
|
mocknen/elixir-google-api
|
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
|
[
"Apache-2.0"
] | null | null | null |
clients/cloud_functions/mix.exs
|
mocknen/elixir-google-api
|
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
|
[
"Apache-2.0"
] | null | null | null |
defmodule GoogleApi.CloudFunctions.V1.Mixfile do
use Mix.Project
@version "0.2.0"
def project() do
[
app: :google_api_cloud_functions,
version: @version,
elixir: "~> 1.4",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/cloud_functions"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.1.0"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
API for managing lightweight user-provided functions executed in response to events.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/cloud_functions",
"Homepage" => "https://cloud.google.com/functions/"
}
]
end
end
| 23.734694
| 115
| 0.602752
|
03a476c07e74f666f5de3ece9b407b8cb647f4a3
| 483
|
ex
|
Elixir
|
lib/elixir_jobs_web/plugs/guardian_pipeline.ex
|
duksis/elixir_jobs
|
e4715cdb6ad2e5a067396358c576992b1e0212e3
|
[
"MIT"
] | 86
|
2017-09-22T08:08:23.000Z
|
2021-05-28T19:51:17.000Z
|
lib/elixir_jobs_web/plugs/guardian_pipeline.ex
|
duksis/elixir_jobs
|
e4715cdb6ad2e5a067396358c576992b1e0212e3
|
[
"MIT"
] | 24
|
2017-09-23T08:23:36.000Z
|
2021-09-20T14:36:06.000Z
|
lib/elixir_jobs_web/plugs/guardian_pipeline.ex
|
duksis/elixir_jobs
|
e4715cdb6ad2e5a067396358c576992b1e0212e3
|
[
"MIT"
] | 21
|
2017-09-23T18:50:23.000Z
|
2019-10-15T19:41:44.000Z
|
defmodule ElixirJobsWeb.Plugs.GuardianPipeline do
@moduledoc """
Main pipeline for Guardian set-up on each request.
"""
use Guardian.Plug.Pipeline, otp_app: :elixir_jobs
alias ElixirJobsWeb.Plugs.CurrentUser
plug Guardian.Plug.Pipeline,
module: ElixirJobsWeb.Guardian,
error_handler: ElixirJobsWeb.AuthController
plug Guardian.Plug.VerifySession
plug Guardian.Plug.VerifyHeader
plug Guardian.Plug.LoadResource, allow_blank: true
plug CurrentUser
end
| 24.15
| 52
| 0.784679
|
03a477a6f45da0078b396ee7201d199aebdb41db
| 361
|
exs
|
Elixir
|
priv/repo/seeds.exs
|
janeek1995/AiMiddleware
|
0ca3b4d5dd89ad80c46a5e8f18bb2615ed809bd3
|
[
"MIT"
] | null | null | null |
priv/repo/seeds.exs
|
janeek1995/AiMiddleware
|
0ca3b4d5dd89ad80c46a5e8f18bb2615ed809bd3
|
[
"MIT"
] | null | null | null |
priv/repo/seeds.exs
|
janeek1995/AiMiddleware
|
0ca3b4d5dd89ad80c46a5e8f18bb2615ed809bd3
|
[
"MIT"
] | null | null | null |
# 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:
#
# AiMiddleware.Repo.insert!(%AiMiddleware.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
| 30.083333
| 61
| 0.714681
|
03a486c91ba14cbca12ad541af79af917c6b4c45
| 13,234
|
ex
|
Elixir
|
lib/phoenix/endpoint/supervisor.ex
|
blutack/phoenix
|
e6d19272edfd980745d0a31a9217312580959eb9
|
[
"MIT"
] | 1
|
2021-06-26T03:57:48.000Z
|
2021-06-26T03:57:48.000Z
|
lib/phoenix/endpoint/supervisor.ex
|
blutack/phoenix
|
e6d19272edfd980745d0a31a9217312580959eb9
|
[
"MIT"
] | 1
|
2020-04-28T21:39:07.000Z
|
2020-04-28T21:39:07.000Z
|
lib/phoenix/endpoint/supervisor.ex
|
blutack/phoenix
|
e6d19272edfd980745d0a31a9217312580959eb9
|
[
"MIT"
] | 1
|
2021-06-22T08:06:06.000Z
|
2021-06-22T08:06:06.000Z
|
defmodule Phoenix.Endpoint.Supervisor do
# This module contains the logic used by most functions in Phoenix.Endpoint
# as well the supervisor for sockets, adapters, watchers, etc.
@moduledoc false
require Logger
use Supervisor
@doc """
Starts the endpoint supervision tree.
"""
def start_link(otp_app, mod, opts \\ []) do
case Supervisor.start_link(__MODULE__, {otp_app, mod, opts}, name: mod) do
{:ok, _} = ok ->
warmup(mod)
log_access_url(otp_app, mod, opts)
ok
{:error, _} = error ->
error
end
end
defp check_compile_configs!(mod, runtime_configs) do
compile_configs = mod.__compile_config__()
bad_keys =
Enum.filter(Phoenix.Endpoint.Supervisor.compile_config_keys(), fn key ->
compile_config = Keyword.get(compile_configs, key)
runtime_config = Keyword.get(runtime_configs, key)
if compile_config != runtime_config do
require Logger
Logger.error("""
#{inspect(key)} mismatch for #{inspect(mod)}.
Compile time configuration: #{inspect(compile_config)}
Runtime configuration : #{inspect(runtime_config)}
#{inspect(key)} is a compile-time configuration, so setting
it at runtime has no effect. Therefore you must set it in your
config/prod.exs or similar (not in your config/releases.exs)
and make sure the value doesn't change.
""")
true
else
false
end
end)
unless Enum.empty?(bad_keys) do
raise ArgumentError,
"expected these options to be unchanged from compile time: #{inspect(bad_keys)}"
end
:ok
end
@doc false
def init({otp_app, mod, opts}) do
default_conf = Phoenix.Config.merge(defaults(otp_app, mod), opts)
env_conf = config(otp_app, mod, default_conf)
secret_conf =
case mod.init(:supervisor, env_conf) do
{:ok, init_conf} ->
if is_nil(Application.get_env(otp_app, mod)) and init_conf == env_conf do
Logger.warn("no configuration found for otp_app #{inspect(otp_app)} and module #{inspect(mod)}")
end
init_conf
other ->
raise ArgumentError, "expected init/2 callback to return {:ok, config}, got: #{inspect other}"
end
extra_conf = [
endpoint_id: :crypto.strong_rand_bytes(16) |> Base.encode64(padding: false),
# TODO: Remove this once :pubsub is removed
pubsub_server: secret_conf[:pubsub_server] || secret_conf[:pubsub][:name]
]
secret_conf = extra_conf ++ secret_conf
default_conf = extra_conf ++ default_conf
# Drop all secrets from secret_conf before passing it around
conf = Keyword.drop(secret_conf, [:secret_key_base])
server? = server?(conf)
check_compile_configs!(mod, conf)
if conf[:instrumenters] do
Logger.warn(":instrumenters configuration for #{inspect(mod)} is deprecated and has no effect")
end
if server? and conf[:code_reloader] do
Phoenix.CodeReloader.Server.check_symlinks()
end
children =
config_children(mod, secret_conf, default_conf) ++
pubsub_children(mod, conf) ++
socket_children(mod) ++
server_children(mod, conf, server?) ++
watcher_children(mod, conf, server?)
Supervisor.init(children, strategy: :one_for_one)
end
defp pubsub_children(mod, conf) do
pub_conf = conf[:pubsub]
if pub_conf do
Logger.warn """
The :pubsub key in your #{inspect mod} is deprecated.
You must now start the pubsub in your application supervision tree.
Go to lib/my_app/application.ex and add the following:
{Phoenix.PubSub, #{inspect pub_conf}}
Now, back in your config files in config/*, you can remove the :pubsub
key and add the :pubsub_server key, with the PubSub name:
pubsub_server: #{inspect pub_conf[:name]}
"""
end
if pub_conf[:adapter] do
[{Phoenix.PubSub, pub_conf}]
else
[]
end
end
defp socket_children(endpoint) do
endpoint.__sockets__
|> Enum.uniq_by(&elem(&1, 1))
|> Enum.map(fn {_, socket, opts} -> socket.child_spec([endpoint: endpoint] ++ opts) end)
end
defp config_children(mod, conf, default_conf) do
args = {mod, conf, default_conf, name: Module.concat(mod, "Config")}
[{Phoenix.Config, args}]
end
defp server_children(mod, config, server?) do
if server? do
adapter = config[:adapter] || Phoenix.Endpoint.Cowboy2Adapter
adapter.child_specs(mod, config)
else
[]
end
end
defp watcher_children(_mod, conf, server?) do
if server? do
Enum.map(conf[:watchers], fn {cmd, args} ->
{Phoenix.Endpoint.Watcher, watcher_args(cmd, args)}
end)
else
[]
end
end
defp watcher_args(cmd, cmd_args) do
{args, opts} = Enum.split_while(cmd_args, &is_binary(&1))
{cmd, args, opts}
end
@doc """
The endpoint configuration used at compile time.
"""
def config(otp_app, endpoint) do
config(otp_app, endpoint, defaults(otp_app, endpoint))
end
defp config(otp_app, endpoint, defaults) do
Phoenix.Config.from_env(otp_app, endpoint, defaults)
end
@doc """
Checks if Endpoint's web server has been configured to start.
"""
def server?(otp_app, endpoint) when is_atom(otp_app) and is_atom(endpoint) do
otp_app
|> config(endpoint)
|> server?()
end
def server?(conf) when is_list(conf) do
Keyword.get(conf, :server, Application.get_env(:phoenix, :serve_endpoints, false))
end
defp defaults(otp_app, module) do
[otp_app: otp_app,
# Compile-time config
code_reloader: false,
debug_errors: false,
render_errors: [view: render_errors(module), accepts: ~w(html), layout: false],
# Runtime config
cache_static_manifest: nil,
check_origin: true,
http: false,
https: false,
reloadable_apps: nil,
reloadable_compilers: [:gettext, :phoenix, :elixir],
secret_key_base: nil,
static_url: nil,
url: [host: "localhost", path: "/"],
cache_manifest_skip_vsn: false,
# Supervisor config
watchers: []]
end
defp render_errors(module) do
module
|> Module.split
|> Enum.at(0)
|> Module.concat("ErrorView")
end
@doc """
Callback that changes the configuration from the app callback.
"""
def config_change(endpoint, changed, removed) do
res = Phoenix.Config.config_change(endpoint, changed, removed)
warmup(endpoint)
res
end
@doc """
Builds the endpoint url from its configuration.
The result is wrapped in a `{:cache, value}` tuple so
the `Phoenix.Config` layer knows how to cache it.
"""
def url(endpoint) do
{:cache, build_url(endpoint, endpoint.config(:url)) |> String.Chars.URI.to_string()}
end
@doc """
Builds the host for caching.
"""
def host(endpoint) do
{:cache, host_to_binary(endpoint.config(:url)[:host] || "localhost")}
end
@doc """
Builds the path for caching.
"""
def path(endpoint) do
{:cache, empty_string_if_root(endpoint.config(:url)[:path] || "/")}
end
@doc """
Builds the script_name for caching.
"""
def script_name(endpoint) do
{:cache, String.split(endpoint.config(:url)[:path] || "/", "/", trim: true)}
end
@doc """
Builds the static url from its configuration.
The result is wrapped in a `{:cache, value}` tuple so
the `Phoenix.Config` layer knows how to cache it.
"""
def static_url(endpoint) do
url = endpoint.config(:static_url) || endpoint.config(:url)
{:cache, build_url(endpoint, url) |> String.Chars.URI.to_string()}
end
@doc """
Builds a struct url for user processing.
The result is wrapped in a `{:cache, value}` tuple so
the `Phoenix.Config` layer knows how to cache it.
"""
def struct_url(endpoint) do
url = endpoint.config(:url)
{:cache, build_url(endpoint, url)}
end
defp build_url(endpoint, url) do
https = endpoint.config(:https)
http = endpoint.config(:http)
{scheme, port} =
cond do
https ->
{"https", https[:port]}
http ->
{"http", http[:port]}
true ->
{"http", 80}
end
scheme = url[:scheme] || scheme
host = host_to_binary(url[:host] || "localhost")
port = port_to_integer(url[:port] || port)
if host =~ ~r"[^:]:\d" do
Logger.warn("url: [host: ...] configuration value #{inspect(host)} for #{inspect(endpoint)} is invalid")
end
%URI{scheme: scheme, port: port, host: host}
end
@doc """
Returns the script path root.
"""
def static_path(endpoint) do
script_path = (endpoint.config(:static_url) || endpoint.config(:url))[:path] || "/"
{:cache, empty_string_if_root(script_path)}
end
defp empty_string_if_root("/"), do: ""
defp empty_string_if_root(other), do: other
@doc """
Returns a two item tuple with the first element containing the
static path of a file in the static root directory
and the second element containing the sha512 of that file (for SRI).
When the file exists, it includes a timestamp. When it doesn't exist,
just the static path is returned.
The result is wrapped in a `{:cache | :nocache, value}` tuple so
the `Phoenix.Config` layer knows how to cache it.
"""
@invalid_local_url_chars ["\\"]
def static_lookup(_endpoint, "//" <> _ = path) do
raise_invalid_path(path)
end
def static_lookup(_endpoint, "/" <> _ = path) do
if String.contains?(path, @invalid_local_url_chars) do
raise ArgumentError, "unsafe characters detected for path #{inspect path}"
else
{:nocache, {path, nil}}
end
end
def static_lookup(_endpoint, path) when is_binary(path) do
raise_invalid_path(path)
end
defp raise_invalid_path(path) do
raise ArgumentError, "expected a path starting with a single / but got #{inspect path}"
end
# TODO: Deprecate {:system, env_var} once we require Elixir v1.9+
defp host_to_binary({:system, env_var}), do: host_to_binary(System.get_env(env_var))
defp host_to_binary(host), do: host
# TODO: Deprecate {:system, env_var} once we require Elixir v1.9+
defp port_to_integer({:system, env_var}), do: port_to_integer(System.get_env(env_var))
defp port_to_integer(port) when is_binary(port), do: String.to_integer(port)
defp port_to_integer(port) when is_integer(port), do: port
@doc """
Invoked to warm up caches on start and config change.
"""
def warmup(endpoint) do
endpoint.host()
endpoint.script_name()
endpoint.path("/")
warmup_url(endpoint)
warmup_static(endpoint)
:ok
rescue
_ -> :ok
end
defp warmup_url(endpoint) do
endpoint.url()
endpoint.static_url()
endpoint.struct_url()
end
defp warmup_static(endpoint) do
warmup_static(endpoint, cache_static_manifest(endpoint))
endpoint.static_path("/")
end
defp warmup_static(endpoint, %{"latest" => latest, "digests" => digests}) do
Phoenix.Config.put_new(endpoint, :cache_static_manifest_latest, latest)
with_vsn? = !endpoint.config(:cache_manifest_skip_vsn)
Enum.each(latest, fn {key, _} ->
Phoenix.Config.cache(endpoint, {:__phoenix_static__, "/" <> key}, fn _ ->
{:cache, static_cache(digests, Map.get(latest, key), with_vsn?)}
end)
end)
end
defp warmup_static(_endpoint, _manifest) do
raise ArgumentError, "expected warmup_static/2 to include 'latest' and 'digests' keys in manifest"
end
defp static_cache(digests, value, true) do
{"/#{value}?vsn=d", static_integrity(digests[value]["sha512"])}
end
defp static_cache(digests, value, false) do
{"/#{value}", static_integrity(digests[value]["sha512"])}
end
defp static_integrity(nil), do: nil
defp static_integrity(sha), do: "sha512-#{sha}"
defp cache_static_manifest(endpoint) do
if inner = endpoint.config(:cache_static_manifest) do
{app, inner} =
case inner do
{_, _} = inner -> inner
inner when is_binary(inner) -> {endpoint.config(:otp_app), inner}
_ -> raise ArgumentError, ":cache_static_manifest must be a binary or a tuple"
end
outer = Application.app_dir(app, inner)
if File.exists?(outer) do
outer |> File.read!() |> Phoenix.json_library().decode!()
else
Logger.error "Could not find static manifest at #{inspect outer}. " <>
"Run \"mix phx.digest\" after building your static files " <>
"or remove the configuration from \"config/prod.exs\"."
end
else
%{}
end
end
defp log_access_url(otp_app, endpoint, opts) do
if Keyword.get(opts, :log_access_url, true) && Phoenix.Endpoint.server?(otp_app, endpoint) do
Logger.info("Access #{inspect(endpoint)} at #{endpoint.url()}")
end
end
@doc """
List of keys which we ensure are unchanged from compile time to runtime. For
example, the :force_ssl option must be available at compile time in order to
work properly. We check these keys so we can warn the user that changing the
option at runtime may lead to undesirable behavior.
"""
def compile_config_keys do
[:force_ssl]
end
end
| 29.02193
| 110
| 0.655509
|
03a488d22c504911ec701d19c7df7d1aa516abf3
| 131
|
exs
|
Elixir
|
test/test_helper.exs
|
kddeisz/pro-publica
|
4d41de8d2873e6aa639378def3df7f736a36ff93
|
[
"MIT"
] | null | null | null |
test/test_helper.exs
|
kddeisz/pro-publica
|
4d41de8d2873e6aa639378def3df7f736a36ff93
|
[
"MIT"
] | null | null | null |
test/test_helper.exs
|
kddeisz/pro-publica
|
4d41de8d2873e6aa639378def3df7f736a36ff93
|
[
"MIT"
] | null | null | null |
File.exists?(".token") && !System.get_env("TOKEN") &&
System.put_env("TOKEN", File.read!(".token") |> String.trim)
ExUnit.start
| 26.2
| 62
| 0.648855
|
03a48a2028cdd1e792256ae8ab80c162dcbbfe7f
| 8,023
|
ex
|
Elixir
|
lib/kafka_ex/server_0_p_9_p_0.ex
|
tigertext/kafka_ex_tc
|
1f03132d3635281483b323751a60efa3b87586ef
|
[
"MIT"
] | null | null | null |
lib/kafka_ex/server_0_p_9_p_0.ex
|
tigertext/kafka_ex_tc
|
1f03132d3635281483b323751a60efa3b87586ef
|
[
"MIT"
] | null | null | null |
lib/kafka_ex/server_0_p_9_p_0.ex
|
tigertext/kafka_ex_tc
|
1f03132d3635281483b323751a60efa3b87586ef
|
[
"MIT"
] | null | null | null |
defmodule KafkaEx.Server0P9P0 do
@moduledoc """
Implements KafkaEx.Server behaviors for Kafka >= 0.9.0 < 0.10.1 API.
"""
# these functions aren't implemented for 0.9.0
@dialyzer [
{:nowarn_function, kafka_server_create_topics: 3},
{:nowarn_function, kafka_server_delete_topics: 3},
{:nowarn_function, kafka_server_api_versions: 1}
]
use KafkaEx.Server
alias KafkaEx.Config
alias KafkaEx.ConsumerGroupRequiredError
alias KafkaEx.InvalidConsumerGroupError
alias KafkaEx.Protocol.ConsumerMetadata.Response, as: ConsumerMetadataResponse
alias KafkaEx.Protocol.Heartbeat
alias KafkaEx.Protocol.JoinGroup
alias KafkaEx.Protocol.LeaveGroup
alias KafkaEx.Protocol.Metadata.Broker
alias KafkaEx.Protocol.SyncGroup
alias KafkaEx.Server.State
alias KafkaEx.NetworkClient
alias KafkaEx.Server0P8P2
alias KafkaEx.Utils.Logger
@consumer_group_update_interval 30_000
def start_link(args, name \\ __MODULE__)
def start_link(args, :no_name) do
GenServer.start_link(__MODULE__, [args])
end
def start_link(args, name) do
GenServer.start_link(__MODULE__, [args, name], name: name)
end
# The functions below are all defined in KafkaEx.Server0P8P2 and their
# implementation is exactly same across both versions of Kafka.
defdelegate kafka_server_consumer_group(state), to: Server0P8P2
defdelegate kafka_server_fetch(fetch_request, state), to: Server0P8P2
defdelegate kafka_server_offset_fetch(offset_fetch, state), to: Server0P8P2
defdelegate kafka_server_offset_commit(offset_commit_request, state),
to: Server0P8P2
defdelegate kafka_server_consumer_group_metadata(state), to: Server0P8P2
defdelegate kafka_server_update_consumer_metadata(state), to: Server0P8P2
defdelegate update_consumer_metadata(state, num, error_code), to: Server0P8P2
def kafka_server_api_versions(_state),
do: raise("ApiVersions is not supported in 0.9.0 version of kafka")
def kafka_server_create_topics(_, _, _state),
do: raise("CreateTopic is not supported in 0.9.0 version of Kafka")
def kafka_server_delete_topics(_, _, _state),
do: raise("DeleteTopic is not supported in 0.9.0 version of Kafka")
def kafka_server_init([args]) do
kafka_server_init([args, self()])
end
def kafka_server_init([args, name]) do
uris = Keyword.get(args, :uris, [])
metadata_update_interval =
Keyword.get(args, :metadata_update_interval, @metadata_update_interval)
consumer_group_update_interval =
Keyword.get(
args,
:consumer_group_update_interval,
@consumer_group_update_interval
)
# this should have already been validated, but it's possible someone could
# try to short-circuit the start call
consumer_group = Keyword.get(args, :consumer_group)
unless KafkaEx.valid_consumer_group?(consumer_group) do
raise InvalidConsumerGroupError, consumer_group
end
use_ssl = Keyword.get(args, :use_ssl, false)
ssl_options = Keyword.get(args, :ssl_options, [])
brokers =
Enum.map(uris, fn {host, port} ->
%Broker{
host: host,
port: port,
socket: NetworkClient.create_socket(host, port, ssl_options, use_ssl)
}
end)
check_brokers_sockets!(brokers)
{correlation_id, metadata} =
try do
retrieve_metadata(brokers, 0, config_sync_timeout())
rescue
e ->
sleep_for_reconnect()
Kernel.reraise(e, System.stacktrace())
end
state = %State{
metadata: metadata,
brokers: brokers,
correlation_id: correlation_id,
consumer_group: consumer_group,
metadata_update_interval: metadata_update_interval,
consumer_group_update_interval: consumer_group_update_interval,
worker_name: name,
ssl_options: ssl_options,
use_ssl: use_ssl,
api_versions: [:unsupported]
}
# Get the initial "real" broker list and start a regular refresh cycle.
state = update_metadata(state)
{:ok, _} =
:timer.send_interval(state.metadata_update_interval, :update_metadata)
state =
if consumer_group?(state) do
# If we are using consumer groups then initialize the state and start the update cycle
{_, updated_state} = update_consumer_metadata(state)
{:ok, _} =
:timer.send_interval(
state.consumer_group_update_interval,
:update_consumer_metadata
)
updated_state
else
state
end
{:ok, state}
end
def kafka_server_join_group(request, network_timeout, state_in) do
{response, state_out} =
consumer_group_sync_request(
request,
JoinGroup,
network_timeout,
state_in
)
{:reply, response, state_out}
end
def kafka_server_sync_group(request, network_timeout, state_in) do
{response, state_out} =
consumer_group_sync_request(
request,
SyncGroup,
network_timeout,
state_in
)
{:reply, response, state_out}
end
def kafka_server_leave_group(request, network_timeout, state_in) do
{response, state_out} =
consumer_group_sync_request(
request,
LeaveGroup,
network_timeout,
state_in
)
{:reply, response, state_out}
end
def kafka_server_heartbeat(request, network_timeout, state_in) do
{response, state_out} =
consumer_group_sync_request(
request,
Heartbeat,
network_timeout,
state_in
)
{:reply, response, state_out}
end
defp consumer_group_sync_request(
request,
protocol_module,
network_timeout,
state
) do
unless consumer_group?(state) do
raise ConsumerGroupRequiredError, request
end
{broker, state} = broker_for_consumer_group_with_update(state)
state_out = increment_state_correlation_id(state)
sync_timeout = config_sync_timeout(network_timeout)
wire_request =
protocol_module.create_request(
state.correlation_id,
Config.client_id(),
request
)
wire_response =
NetworkClient.send_sync_request(
broker,
wire_request,
sync_timeout
)
case wire_response do
{:error, reason} ->
{{:error, reason}, state_out}
_ ->
response = protocol_module.parse_response(wire_response)
if response.error_code == :not_coordinator_for_consumer do
{_, updated_state_out} = update_consumer_metadata(state_out)
consumer_group_sync_request(
request,
protocol_module,
network_timeout,
updated_state_out
)
else
{response, state_out}
end
end
end
defp update_consumer_metadata(state),
do: update_consumer_metadata(state, @retry_count, 0)
defp broker_for_consumer_group(state) do
ConsumerMetadataResponse.broker_for_consumer_group(
state.brokers,
state.consumer_metadata
)
end
# refactored from two versions, one that used the first broker as valid answer, hence
# the optional extra flag to do that. Wraps broker_for_consumer_group with an update
# call if no broker was found.
def broker_for_consumer_group_with_update(
state,
use_first_as_default \\ false
) do
case broker_for_consumer_group(state) do
nil ->
{_, updated_state} = update_consumer_metadata(state)
default_broker =
if use_first_as_default, do: hd(state.brokers), else: nil
{broker_for_consumer_group(updated_state) || default_broker,
updated_state}
broker ->
{broker, state}
end
end
# note within the GenServer state, we've already validated the
# consumer group, so it can only be either :no_consumer_group or a
# valid binary consumer group name
def consumer_group?(%State{consumer_group: :no_consumer_group}), do: false
def consumer_group?(_), do: true
end
| 27.857639
| 94
| 0.690764
|
03a4a65afd732da42096e6af2652805fc8a90020
| 1,323
|
exs
|
Elixir
|
config/config.exs
|
abadongutierrez/ecto_test
|
b3ad37c0e157117fd1b3b340452de4939589f605
|
[
"Apache-2.0"
] | null | null | null |
config/config.exs
|
abadongutierrez/ecto_test
|
b3ad37c0e157117fd1b3b340452de4939589f605
|
[
"Apache-2.0"
] | null | null | null |
config/config.exs
|
abadongutierrez/ecto_test
|
b3ad37c0e157117fd1b3b340452de4939589f605
|
[
"Apache-2.0"
] | null | null | null |
# This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :ecto_test, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:ecto_test, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
config :ecto_test, EctoTest.Repo,
adapter: Ecto.Adapters.Postgres,
database: "ecto_test",
username: "postgres",
password: "",
hostname: "localhost"
config :ecto_test, ecto_repos: [EctoTest.Repo]
| 33.075
| 73
| 0.749811
|
03a4b03ade417daec71232b2277c946242b4bfd5
| 1,480
|
ex
|
Elixir
|
clients/cloud_error_reporting/lib/google_api/cloud_error_reporting/v1beta1/model/reported_error_event.ex
|
GoNZooo/elixir-google-api
|
cf3ad7392921177f68091f3d9001f1b01b92f1cc
|
[
"Apache-2.0"
] | null | null | null |
clients/cloud_error_reporting/lib/google_api/cloud_error_reporting/v1beta1/model/reported_error_event.ex
|
GoNZooo/elixir-google-api
|
cf3ad7392921177f68091f3d9001f1b01b92f1cc
|
[
"Apache-2.0"
] | null | null | null |
clients/cloud_error_reporting/lib/google_api/cloud_error_reporting/v1beta1/model/reported_error_event.ex
|
GoNZooo/elixir-google-api
|
cf3ad7392921177f68091f3d9001f1b01b92f1cc
|
[
"Apache-2.0"
] | 1
|
2018-07-28T20:50:50.000Z
|
2018-07-28T20:50:50.000Z
|
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.CloudErrorReporting.V1beta1.Model.ReportedErrorEvent do
@moduledoc """
An error event which is reported to the Error Reporting system.
"""
@derive [Poison.Encoder]
defstruct [
:"context",
:"eventTime",
:"message",
:"serviceContext"
]
end
defimpl Poison.Decoder, for: GoogleApi.CloudErrorReporting.V1beta1.Model.ReportedErrorEvent do
import GoogleApi.CloudErrorReporting.V1beta1.Deserializer
def decode(value, options) do
value
|> deserialize(:"context", :struct, GoogleApi.CloudErrorReporting.V1beta1.Model.ErrorContext, options)
|> deserialize(:"serviceContext", :struct, GoogleApi.CloudErrorReporting.V1beta1.Model.ServiceContext, options)
end
end
| 34.418605
| 115
| 0.758784
|
03a4d1dc64c3f480c9df461a40fb15a05f4a9218
| 5,313
|
ex
|
Elixir
|
implementations/elixir/lib/ockam/vault.ex
|
hollyfeld/ockam
|
10a618b60b5b913821bfa8df3ad9693a70913ace
|
[
"Apache-2.0"
] | 1
|
2021-01-02T11:42:16.000Z
|
2021-01-02T11:42:16.000Z
|
implementations/elixir/lib/ockam/vault.ex
|
ercanersoy/ockam
|
b537a4951770d223f5493bcff5358d0677865a0f
|
[
"Apache-2.0"
] | null | null | null |
implementations/elixir/lib/ockam/vault.ex
|
ercanersoy/ockam
|
b537a4951770d223f5493bcff5358d0677865a0f
|
[
"Apache-2.0"
] | null | null | null |
defmodule Ockam.Vault do
@moduledoc """
"""
alias Ockam.Vault.NIF
defmodule Secret do
@moduledoc false
defstruct [:reference]
@opaque t :: %__MODULE__{}
end
defmodule SecretAttributes do
@moduledoc false
defstruct ty: :buffer, length: 0, persistence: :ephemeral, purpose: :key_agreement
end
defstruct [:reference]
@opaque t :: %__MODULE__{}
@spec create(Keyword.t()) :: {:ok, t} | {:error, term}
def create(options \\ []) when is_list(options) do
with {:ok, reference} <- NIF.make_vault(), do: {:ok, %__MODULE__{reference: reference}}
end
@spec sha256(t, binary) :: {:ok, binary} | {:error, term}
def sha256(%__MODULE__{reference: vault_ref}, data) when is_binary(data),
do: NIF.sha256(vault_ref, data)
def generate_secret(%__MODULE__{reference: vault_ref}, attributes \\ []) do
{type, attributes} = Keyword.pop(attributes, :type)
attributes = if type, do: Keyword.put(attributes, :ty, type), else: attributes
attributes = struct(SecretAttributes, attributes)
with {:ok, secret_ref} <- NIF.generate_secret(vault_ref, attributes) do
{:ok, %Secret{reference: secret_ref}}
end
end
def generate_curve25519_keypair(vault) do
with {:ok, private_key} <- generate_secret(vault, type: :curve25519_private),
{:ok, public_key} <- get_public_key(vault, private_key) do
{:ok, %{private: private_key, public: public_key}}
end
end
def import_secret(%__MODULE__{reference: vault_ref}, secret, attributes \\ []) do
{type, attributes} = Keyword.pop(attributes, :type)
attributes = if type, do: Keyword.put(attributes, :ty, type), else: attributes
attributes = struct(SecretAttributes, attributes)
attributes = Map.put(attributes, :length, byte_size(secret))
with {:ok, secret_ref} <- NIF.import_secret(vault_ref, secret, attributes) do
{:ok, %Secret{reference: secret_ref}}
end
end
def export_secret(%__MODULE__{reference: vault_ref}, %Secret{reference: secret_ref}),
do: NIF.export_secret(vault_ref, secret_ref)
def get_secret_attributes(%__MODULE__{reference: vault_ref}, %Secret{reference: secret_ref}) do
with {:ok, attributes} <- NIF.get_secret_attributes(vault_ref, secret_ref) do
{type, attributes} = attributes |> Map.from_struct() |> Map.to_list() |> Keyword.pop(:ty)
if type, do: Keyword.put(attributes, :type, type), else: attributes
end
end
def set_secret_type(%__MODULE__{reference: vault_ref}, %Secret{reference: secret_ref}, type),
do: NIF.set_secret_type(vault_ref, secret_ref, type)
@spec get_public_key(t, Secret.t()) :: {:ok, binary()} | {:error, term}
def get_public_key(%__MODULE__{reference: vault_ref}, %Secret{reference: secret_ref}),
do: NIF.get_public_key(vault_ref, secret_ref)
def ecdh(%__MODULE__{reference: vault_ref}, %Secret{reference: private_key_ref}, peer_pubkey) do
with {:ok, secret_ref} <- NIF.ecdh(vault_ref, private_key_ref, peer_pubkey) do
{:ok, %Secret{reference: secret_ref}}
end
end
def hkdf_sha256(
%__MODULE__{reference: vault_ref},
%Secret{reference: salt_ref},
nil,
num_outputs
) do
with {:ok, outputs} <- NIF.hkdf_sha256(vault_ref, salt_ref, nil, num_outputs) do
{:ok, Enum.map(outputs, fn x -> %Secret{reference: x} end)}
end
end
def hkdf_sha256(
%__MODULE__{reference: vault_ref},
%Secret{reference: salt_ref},
%Secret{reference: ikm_ref},
num_outputs
) do
with {:ok, outputs} <- NIF.hkdf_sha256(vault_ref, salt_ref, ikm_ref, num_outputs) do
{:ok, Enum.map(outputs, fn x -> %Secret{reference: x} end)}
end
end
def encrypt(
%__MODULE__{reference: vault_ref},
%Secret{reference: key_ref},
nonce,
aad,
plaintext
)
when is_integer(nonce) do
NIF.aead_aes_gcm_encrypt(vault_ref, key_ref, nonce, aad, plaintext)
end
def decrypt(
%__MODULE__{reference: vault_ref},
%Secret{reference: key_ref},
nonce,
aad,
ciphertext_and_tag
)
when is_integer(nonce) do
NIF.aead_aes_gcm_decrypt(vault_ref, key_ref, nonce, aad, ciphertext_and_tag)
end
defmodule NIF do
@moduledoc false
use Rustler, otp_app: :ockam, crate: :ockam_nif
def make_vault, do: exit(:nif_not_loaded)
def random(_vault), do: exit(:nif_not_loaded)
def sha256(_vault, _data), do: exit(:nif_not_loaded)
def generate_secret(_vault, _attrs), do: exit(:nif_not_loaded)
def import_secret(_vault, _data, _attrs), do: exit(:nif_not_loaded)
def export_secret(_vault, _secret), do: exit(:nif_not_loaded)
def get_secret_attributes(_vault, _secret), do: exit(:nif_not_loaded)
def set_secret_type(_vault, _secret, _secret_type), do: exit(:nif_not_loaded)
def get_public_key(_vault, _secret), do: exit(:nif_not_loaded)
def ecdh(_vault, _private_key, _peer_pubkey), do: exit(:nif_not_loaded)
def hkdf_sha256(_vault, _salt, _ikm, _num_derived_outputs), do: exit(:nif_not_loaded)
def aead_aes_gcm_encrypt(_vault, _key, _nonce, _additional_data, _plaintext),
do: exit(:nif_not_loaded)
def aead_aes_gcm_decrypt(_vault, _key, _nonce, _additional_data, _ciphertext_and_tag),
do: exit(:nif_not_loaded)
end
end
| 35.18543
| 98
| 0.685488
|
03a4d8416a2bd0d282fdec6334010cc92cbde9b9
| 12,216
|
ex
|
Elixir
|
lib/stripe/connect/account.ex
|
mmmries/stripity_stripe
|
7bfaa2316f24a86fbbfc3cf140b1caff05f5ef9d
|
[
"BSD-3-Clause"
] | null | null | null |
lib/stripe/connect/account.ex
|
mmmries/stripity_stripe
|
7bfaa2316f24a86fbbfc3cf140b1caff05f5ef9d
|
[
"BSD-3-Clause"
] | null | null | null |
lib/stripe/connect/account.ex
|
mmmries/stripity_stripe
|
7bfaa2316f24a86fbbfc3cf140b1caff05f5ef9d
|
[
"BSD-3-Clause"
] | null | null | null |
defmodule Stripe.Account do
@moduledoc """
Work with Stripe Connect account objects.
You can:
- Retrieve your own account
- Retrieve an account with a specified `id`
This module does not yet support managed accounts.
Stripe API reference: https://stripe.com/docs/api#account
"""
use Stripe.Entity
import Stripe.Request
@type decline_charge_on :: %{
avs_failure: boolean,
cvc_failure: boolean
}
@type legal_entity :: %{
additional_owners: [legal_entity_additional_owner] | nil,
address: legal_entity_address,
address_kana: legal_entity_japan_address | nil,
address_kanji: legal_entity_japan_address | nil,
business_name: String.t() | nil,
business_name_kana: String.t() | nil,
business_name_kanji: String.t() | nil,
business_tax_id_provided: boolean,
business_vat_id_provided: boolean,
deleted: boolean | nil,
dob: legal_entity_dob,
first_name: String.t() | nil,
first_name_kana: String.t() | nil,
first_name_kanji: String.t() | nil,
gender: String.t() | nil,
last_name: String.t() | nil,
last_name_kana: String.t() | nil,
last_name_kanji: String.t() | nil,
maiden_name: String.t() | nil,
personal_address: legal_entity_address,
personal_address_kana: legal_entity_japan_address | nil,
personal_address_kanji: legal_entity_japan_address | nil,
personal_id_number_provided: boolean,
phone_number: String.t() | nil,
ssn_last_4_provided: String.t(),
tax_id_registar: String.t(),
type: String.t() | nil,
verification: legal_entity_verification
}
@type legal_entity_additional_owner :: %{
address: legal_entity_address,
dob: legal_entity_dob,
first_name: String.t() | nil,
last_name: String.t() | nil,
maiden_name: String.t() | nil,
verification: legal_entity_verification
}
@type legal_entity_address :: %{
city: String.t() | nil,
country: String.t() | nil,
line1: String.t() | nil,
line2: String.t() | nil,
postal_code: String.t() | nil,
state: String.t() | nil
}
@type legal_entity_dob :: %{
day: 1..31 | nil,
month: 1..12 | nil,
year: pos_integer | nil
}
@type legal_entity_japan_address :: %{
city: String.t() | nil,
country: String.t() | nil,
line1: String.t() | nil,
line2: String.t() | nil,
postal_code: String.t() | nil,
state: String.t() | nil,
town: String.t() | nil
}
@type legal_entity_verification :: %{
details: String.t() | nil,
details_code: String.t() | nil,
document: Stripe.id() | Stripe.FileUpload.t() | nil,
status: String.t()
}
@type tos_acceptance :: %{
date: Stripe.timestamp() | nil,
ip: String.t() | nil,
user_agent: String.t() | nil
}
@type verification :: %{
disabled_reason: String.t() | nil,
due_by: Stripe.timestamp() | nil,
fields_needed: [String.t()]
}
@type t :: %__MODULE__{
id: Stripe.id(),
object: String.t(),
business_logo: String.t() | nil,
business_name: String.t() | nil,
business_url: String.t() | nil,
charges_enabled: boolean,
created: Stripe.timestamp() | nil,
country: String.t(),
debit_negative_balances: boolean,
decline_charge_on: decline_charge_on,
default_currency: String.t(),
details_submitted: boolean,
display_name: String.t() | nil,
email: String.t() | nil,
external_accounts: Stripe.List.t(Stripe.BankAccount.t() | Stripe.Card.t()),
legal_entity: legal_entity,
metadata: Stripe.Types.metadata(),
payout_schedule: Stripe.Types.transfer_schedule(),
payout_statement_descriptor: String.t() | nil,
payouts_enabled: boolean,
product_description: String.t() | nil,
statement_descriptor: String.t() | nil,
support_email: String.t() | nil,
support_phone: String.t() | nil,
timezone: String.t() | nil,
tos_acceptance: tos_acceptance,
type: String.t(),
verification: verification
}
defstruct [
:id,
:object,
:business_logo,
:business_name,
:business_url,
:charges_enabled,
:country,
:created,
:debit_negative_balances,
:decline_charge_on,
:default_currency,
:deleted,
:details_submitted,
:display_name,
:email,
:external_accounts,
:legal_entity,
:metadata,
:payout_schedule,
:payout_statement_descriptor,
:payouts_enabled,
:product_description,
:statement_descriptor,
:support_email,
:support_phone,
:timezone,
:tos_acceptance,
:transfers_enabled,
:type,
:verification
]
@singular_endpoint "account"
@plural_endpoint "accounts"
@type create_params :: %{
:type => String.t(),
optional(:account_token) => String.t(),
optional(:business_logo) => String.t(),
optional(:business_name) => String.t(),
optional(:business_primary_color) => String.t(),
optional(:business_url) => String.t(),
optional(:country) => String.t(),
optional(:debit_negative_balances) => boolean,
optional(:decline_charge_on) => decline_charge_on,
optional(:default_currency) => String.t(),
optional(:email) => String.t(),
optional(:external_account) => String.t(),
optional(:legal_entity) => legal_entity,
optional(:metadata) => Stripe.Types.metadata(),
optional(:payout_schedule) => Stripe.Types.transfer_schedule(),
optional(:payout_statement_descriptor) => String.t(),
optional(:product_description) => String.t(),
optional(:statement_descriptor) => String.t(),
optional(:support_email) => String.t(),
optional(:support_phone) => String.t(),
optional(:support_url) => String.t(),
optional(:tos_acceptance) => tos_acceptance
}
@doc """
Create an account.
"""
@spec create(params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
when params: %{
optional(:country) => String.t(),
optional(:email) => String.t(),
optional(:type) => String.t()
}
def create(params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint)
|> put_params(params)
|> put_method(:post)
|> cast_to_id([:coupon, :default_source, :source])
|> make_request()
end
@doc """
Retrieve your own account without options.
"""
@spec retrieve :: {:ok, t} | {:error, Stripe.Error.t()}
def retrieve, do: retrieve([])
@doc """
Retrieve your own account with options.
"""
@spec retrieve(list) :: {:ok, t} | {:error, Stripe.Error.t()}
def retrieve(opts) when is_list(opts), do: do_retrieve(@singular_endpoint, opts)
@doc """
Retrieve an account with a specified `id`.
"""
@spec retrieve(binary, list) :: {:ok, t} | {:error, Stripe.Error.t()}
def retrieve(id, opts \\ []), do: do_retrieve(@plural_endpoint <> "/" <> id, opts)
@spec do_retrieve(String.t(), list) :: {:ok, t} | {:error, Stripe.Error.t()}
defp do_retrieve(endpoint, opts) do
new_request(opts)
|> put_endpoint(endpoint)
|> put_method(:get)
|> make_request()
end
@type update_params :: %{
optional(:account_token) => String.t(),
optional(:business_logo) => String.t(),
optional(:business_name) => String.t(),
optional(:business_primary_color) => String.t(),
optional(:business_url) => String.t(),
optional(:country) => String.t(),
optional(:debit_negative_balances) => boolean,
optional(:decline_charge_on) => decline_charge_on,
optional(:default_currency) => String.t(),
optional(:email) => String.t(),
optional(:external_account) => String.t(),
optional(:legal_entity) => legal_entity,
optional(:metadata) => Stripe.Types.metadata(),
optional(:payout_schedule) => Stripe.Types.transfer_schedule(),
optional(:payout_statement_descriptor) => String.t(),
optional(:product_description) => String.t(),
optional(:statement_descriptor) => String.t(),
optional(:support_email) => String.t(),
optional(:support_phone) => String.t(),
optional(:support_url) => String.t(),
optional(:tos_acceptance) => tos_acceptance
}
@doc """
Update an account.
Takes the `id` and a map of changes.
"""
@spec update(Stripe.id() | t, params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
when params: %{
optional(:business_logo) => String.t(),
optional(:business_name) => String.t(),
optional(:business_primary_color) => String.t(),
optional(:business_url) => String.t(),
optional(:double_negative_balances) => boolean,
optional(:decline_charge_on) => decline_charge_on,
optional(:default_currency) => String.t(),
optional(:email) => String.t(),
optional(:external_accounts) => String.t(),
optional(:legal_entity) => legal_entity,
optional(:metadata) => String.Types.metadata(),
optional(:payout_schedule) => String.Types.transfer_schedule(),
optional(:payout_statement_descriptor) => String.t(),
optional(:product_description) => String.t(),
optional(:statement_descriptor) => String.t(),
optional(:support_phone) => String.t(),
optional(:support_email) => String.t(),
optional(:support_url) => String.t(),
optional(:tos_acceptance) => tos_acceptance
}
def update(id, params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_method(:post)
|> put_params(params)
|> make_request()
end
@doc """
Delete an account.
"""
@spec delete(Stripe.id() | t, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
def delete(id, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_method(:delete)
|> make_request()
end
@doc """
Reject an account.
Takes the `id` and `reason`.
"""
@spec reject(Stripe.id() | t, String.t(), Stripe.options()) ::
{:ok, t} | {:error, Stripe.Error.t()}
def reject(id, reason, opts \\ []) do
params = %{
reason: reason
}
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}/reject")
|> put_method(:post)
|> put_params(params)
|> cast_to_id([:account])
|> make_request()
end
@doc """
List all connected accounts.
"""
@spec list(params, Stripe.options()) :: {:ok, Stripe.List.t(t)} | {:error, Stripe.Error.t()}
when params: %{
optional(:ending_before) => t | Stripe.id(),
optional(:limit) => 1..100,
optional(:starting_after) => t | Stripe.id()
}
def list(params \\ %{}, opts \\ []) do
new_request(opts)
|> prefix_expansions()
|> put_endpoint(@plural_endpoint)
|> put_method(:get)
|> put_params(params)
|> cast_to_id([:ending_before, :starting_after])
|> make_request()
end
@doc """
Create a login link.
"""
@spec create_login_link(Stripe.id() | t, params, Stripe.options()) ::
{:ok, t} | {:error, Stripe.Error.t()}
when params: %{
optional(:redirect_url) => String.t()
}
def create_login_link(id, params, opts \\ []) do
Stripe.LoginLink.create(id, params, opts)
end
end
| 33.56044
| 98
| 0.576785
|
03a4e39069962f82ce168cfcff25e80ef148f5e6
| 6,257
|
exs
|
Elixir
|
test/integration/build_test.exs
|
dvjoness/construct
|
e07ec8e776b0ef1a8fea94691d912cef03d76573
|
[
"MIT"
] | 32
|
2017-12-26T18:08:41.000Z
|
2022-03-24T21:18:11.000Z
|
test/integration/build_test.exs
|
dvjoness/construct
|
e07ec8e776b0ef1a8fea94691d912cef03d76573
|
[
"MIT"
] | 4
|
2018-01-17T11:56:08.000Z
|
2022-03-24T21:16:27.000Z
|
test/integration/build_test.exs
|
dvjoness/construct
|
e07ec8e776b0ef1a8fea94691d912cef03d76573
|
[
"MIT"
] | 7
|
2017-12-29T13:06:31.000Z
|
2022-03-24T05:56:56.000Z
|
defmodule Construct.Integration.BuildTest do
use Construct.TestCase
test "use/2 creates make/0,1,2 make!/0,1,2 and cast/1,2" do
module = create_construct do
field :key
end
module_name = name(module)
Enum.each(0..2, fn(arity) ->
assert function_exported?(module_name, :make, arity)
end)
Enum.each(0..2, fn(arity) ->
assert function_exported?(module_name, :make!, arity)
end)
Enum.each(1..2, fn(arity) ->
assert function_exported?(module_name, :cast, arity)
end)
end
test "pass `empty_values` to use/2" do
module = create_construct [empty_values: ["empty_val"]] do
field :a
end
assert {:ok, %{a: ""}} = make(module, %{a: ""})
assert {:error, %{a: :missing}} == make(module, %{a: "empty_val"})
end
test "pass `make_map` to use/2" do
module = create_construct [make_map: true] do
field :a
end
assert {:ok, %{a: ""}} == make(module, %{a: ""})
end
test "include other structure" do
include1_module = create_construct do
field :a, :string, default: nil
field :b
end
include2_module = create_construct do
field :c, :integer, custom_option: 42
field :d
end
include1 = name(include1_module)
include2 = name(include2_module)
module = create_construct do
include include1
include include2
end
module_name = name(module)
assert %{a: {:string, [default: nil]}, b: {:string, []}, c: {:integer, [custom_option: 42]}, d: {:string, []}}
== module_name.__construct__(:types)
end
test "make nested fields" do
module = create_construct do
field :parent do
field :nested_struct do
field :SOME_OF_1 do
field :c
end
end
end
end
assert {:ok, root = %{parent: parent = %{nested_struct: nested = %{SOME_OF_1: some = %{c: "test"}}}}}
= make(module, %{parent: %{nested_struct: %{SOME_OF_1: %{c: "test"}}}})
assert Construct.Integration.BuildTest_67 == root.__struct__
assert Construct.Integration.BuildTest_67.Parent == parent.__struct__
assert Construct.Integration.BuildTest_67.Parent.NestedStruct == nested.__struct__
assert Construct.Integration.BuildTest_67.Parent.NestedStruct.SOME_OF1 == some.__struct__
end
test "raise when try to use non-atom field name" do
assert_raise(Construct.DefinitionError, ~s(expected atom for field name, got `"key"`), fn ->
create_construct do
field "key", :string
end
end)
end
test "raise when try to use non-atom field name for nested" do
assert_raise(Construct.DefinitionError, ~s(expected atom for field name, got `"key"`), fn ->
create_construct do
field "key" do
field "asd"
end
end
end)
end
test "raise when trying to use function with non-zero arity as default argument" do
assert_raise(Construct.DefinitionError, ~s(functions in default values should be zero-arity), fn ->
defmodule M do
use Construct do
field :err, :integer, default: fn(_, _) -> 42 end
end
end
end)
assert_raise(Construct.DefinitionError, ~s(functions in default values should be zero-arity), fn ->
defmodule N do
use Construct do
field :err, :integer, default: fn(_) -> 42 end
end
end
end)
end
test "raise when trying to use undefined module as custom type" do
assert_raise(Construct.DefinitionError, ~s(undefined module UndefinedModule), fn ->
create_construct do
field :key, UndefinedModule
end
end)
assert_raise(Construct.DefinitionError, ~s(undefined module UndefinedModule), fn ->
create_construct do
field :key, {:array, UndefinedModule}
end
end)
assert_raise(Construct.DefinitionError, ~s(undefined module UndefinedModule), fn ->
create_construct do
field :key, {:map, UndefinedModule}
end
end)
assert_raise(Construct.DefinitionError, ~s(undefined module UndefinedModule), fn ->
create_construct do
field :key, {UndefinedModule, []}
end
end)
assert_raise(Construct.DefinitionError, ~s(undefined module UndefinedModule), fn ->
create_construct do
field :key, [UndefinedModule]
end
end)
assert_raise(Construct.DefinitionError, ~s(undefined module UndefinedModule), fn ->
create_construct do
field :key, [CustomType, UndefinedModule]
end
end)
end
test "raise when trying to use custom type that doesn't have cast/1 function" do
assert_raise(Construct.DefinitionError, ~s(undefined function cast/1 for CustomTypeEmpty), fn ->
create_construct do
field :key, CustomTypeEmpty
end
end)
assert_raise(Construct.DefinitionError, ~s(undefined function cast/1 for CustomTypeEmpty), fn ->
create_construct do
field :key, {:array, CustomTypeEmpty}
end
end)
assert_raise(Construct.DefinitionError, ~s(undefined function cast/1 for CustomTypeEmpty), fn ->
create_construct do
field :key, {:map, CustomTypeEmpty}
end
end)
assert_raise(Construct.DefinitionError, ~s(undefined function castc/2 for CustomTypeEmpty), fn ->
create_construct do
field :key, {CustomTypeEmpty, []}
end
end)
assert_raise(Construct.DefinitionError, ~s(undefined function cast/1 for CustomTypeEmpty), fn ->
create_construct do
field :key, [CustomTypeEmpty]
end
end)
assert_raise(Construct.DefinitionError, ~s(undefined function cast/1 for CustomTypeEmpty), fn ->
create_construct do
field :key, [CustomType, CustomTypeEmpty]
end
end)
end
test "raise when trying to include undefined module" do
assert_raise(Construct.DefinitionError, ~s(provided UndefinedModule is not Construct module), fn ->
create_construct do
include UndefinedModule
end
end)
end
test "raise when trying to include invalid structure (some module)" do
assert_raise(Construct.DefinitionError, ~s(provided CustomTypeEmpty is not Construct module), fn ->
create_construct do
include CustomTypeEmpty
end
end)
end
end
| 29.238318
| 114
| 0.655746
|
03a4e88862c7d689464e8bca77b0d88b819487e8
| 147
|
exs
|
Elixir
|
test/reverse_iap_test.exs
|
bbhoss/reverse_iap
|
313daf3a4a30a4bb52a137209132336e0ab931b7
|
[
"Apache-2.0"
] | 8
|
2020-08-10T10:05:15.000Z
|
2021-04-21T07:25:04.000Z
|
test/reverse_iap_test.exs
|
bbhoss/reverse_iap
|
313daf3a4a30a4bb52a137209132336e0ab931b7
|
[
"Apache-2.0"
] | null | null | null |
test/reverse_iap_test.exs
|
bbhoss/reverse_iap
|
313daf3a4a30a4bb52a137209132336e0ab931b7
|
[
"Apache-2.0"
] | 1
|
2021-04-20T19:00:15.000Z
|
2021-04-20T19:00:15.000Z
|
defmodule ReverseIapTest do
use ExUnit.Case
doctest ReverseIap
test "greets the world" do
assert ReverseIap.hello() == :world
end
end
| 16.333333
| 39
| 0.727891
|
03a4f2a8c962545ae8e926a6aac8b0c1cf9295cf
| 1,003
|
exs
|
Elixir
|
test/etdpay/users/create_test.exs
|
epsilveira/etdpay
|
8460bd6bf128ae93d04895494220bff121778f2f
|
[
"MIT"
] | null | null | null |
test/etdpay/users/create_test.exs
|
epsilveira/etdpay
|
8460bd6bf128ae93d04895494220bff121778f2f
|
[
"MIT"
] | null | null | null |
test/etdpay/users/create_test.exs
|
epsilveira/etdpay
|
8460bd6bf128ae93d04895494220bff121778f2f
|
[
"MIT"
] | null | null | null |
defmodule Etdpay.Users.CreateTest do
use Etdpay.DataCase, async: true
alias Etdpay.User
alias Etdpay.Users.Create
describe "call/1" do
test "when all params are valid, returns an user" do
params = %{
name: "Fulano De Tal",
password: "12345678",
nickname: "fulano",
email: "fulano@dominio.com.br",
age: 18
}
{:ok, %User{id: user_id}} = Create.call(params)
user = Repo.get(User, user_id)
assert %User{name: "Fulano De Tal", age: 18, id: ^user_id} = user
end
test "when there are invalid params, returns an error" do
params = %{
name: "Fulano De Tal",
nickname: "fulano",
email: "fulano@dominio.com.br",
age: 15
}
{:error, changeset} = Create.call(params)
expected_response = %{
age: ["must be greater than or equal to 18"],
password: ["can't be blank"]
}
assert errors_on(changeset) == expected_response
end
end
end
| 23.325581
| 71
| 0.581256
|
03a57217c6fbe70ce9ab0846c65c8749951eda70
| 2,226
|
ex
|
Elixir
|
ex_graphs_book/apps/native_graph/lib/native_graph/serializers/dot.ex
|
NickMcG/ExGraphsBook
|
89276d374dd21cc4605a4b1b5a05b177723680c2
|
[
"Apache-2.0"
] | null | null | null |
ex_graphs_book/apps/native_graph/lib/native_graph/serializers/dot.ex
|
NickMcG/ExGraphsBook
|
89276d374dd21cc4605a4b1b5a05b177723680c2
|
[
"Apache-2.0"
] | null | null | null |
ex_graphs_book/apps/native_graph/lib/native_graph/serializers/dot.ex
|
NickMcG/ExGraphsBook
|
89276d374dd21cc4605a4b1b5a05b177723680c2
|
[
"Apache-2.0"
] | null | null | null |
defmodule NativeGraph.Serializers.DOT do
use NativeGraph.Serializer
alias NativeGraph.Serializer
def serialize(%Graph{type: type} = g) do
type = if type == :directed, do: "digraph", else: "graph"
result = "strict #{type} {\n" <> serialize_nodes(g) <> serialize_edges(g) <> "}\n"
{:ok, result}
end
def serialize!(%Graph{type: type} = g) do
type = if type == :directed, do: "digraph", else: "graph"
result = "strict #{type} {\n" <> serialize_nodes(g) <> serialize_edges(g) <> "}\n"
result
end
defp serialize_nodes(%Graph{vertices: vertices} = g) do
Enum.reduce(vertices, "", fn {id, v}, acc ->
label = Serializer.get_vertex_label(g, id, v)
if is_nil(label) do
acc <> Serializer.indent(1) <> Serializer.get_vertex_string(g, id, v) <> "\n"
else
acc <> Serializer.indent(1) <> Serializer.get_vertex_string(g, id, v) <> " [label=" <> label <> "]" <> "\n"
end
end)
end
defp serialize_edges(%Graph{type: type, vertices: vertices, out_edges: oe, edges: em} = g) do
edges =
Enum.reduce(vertices, [], fn {id, v}, acc ->
v_label = Serializer.get_vertex_string(g, id, v)
edges =
oe
|> Map.get(id, MapSet.new())
|> Enum.flat_map(fn id2 ->
v2_label = Serializer.get_vertex_string(g, id2, Map.get(vertices, id2))
Enum.map(Map.fetch!(em, {id, id2}), fn
{nil, weight} ->
{v_label, v2_label, weight}
{label, weight} ->
{v_label, v2_label, weight, Serializer.encode_label(label)}
end)
end)
case edges do
[] -> acc
_ -> acc ++ edges
end
end)
arrow = if type == :directed, do: "->", else: "--"
Enum.reduce(edges, "", fn
{v_label, v2_label, weight, edge_label}, acc ->
acc <>
Serializer.indent(1) <>
v_label <>
" #{arrow} " <> v2_label <> " [" <> "label=#{edge_label}, weight=#{weight}" <> "]\n"
{v_label, v2_label, weight}, acc ->
acc <>
Serializer.indent(1) <>
v_label <> " #{arrow} " <> v2_label <> " [" <> "weight=#{weight}" <> "]\n"
end)
end
end
| 31.8
| 116
| 0.535939
|
03a5d8c37d30f1c90b985b6529ef6012e4e64302
| 241
|
ex
|
Elixir
|
lib/ptolemy/application.ex
|
D-Town44/ptolemy
|
5764c48f05e68bc6f7bc7b7af76fc640845b662e
|
[
"MIT"
] | null | null | null |
lib/ptolemy/application.ex
|
D-Town44/ptolemy
|
5764c48f05e68bc6f7bc7b7af76fc640845b662e
|
[
"MIT"
] | null | null | null |
lib/ptolemy/application.ex
|
D-Town44/ptolemy
|
5764c48f05e68bc6f7bc7b7af76fc640845b662e
|
[
"MIT"
] | null | null | null |
defmodule Ptolemy.Application do
@moduledoc false
use Application
def start(_type, _args) do
children = []
opts = [strategy: :one_for_one, name: Ptolemy.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 17.214286
| 63
| 0.692946
|
03a604bbc1e2adafe4d9faba016b45d3aa753ebb
| 7,881
|
exs
|
Elixir
|
test/prometheus_parser_test.exs
|
Logflare/turnio-prometheus-parser
|
588e72e3779fb78621a008a81ee5426909145f89
|
[
"Apache-2.0"
] | null | null | null |
test/prometheus_parser_test.exs
|
Logflare/turnio-prometheus-parser
|
588e72e3779fb78621a008a81ee5426909145f89
|
[
"Apache-2.0"
] | null | null | null |
test/prometheus_parser_test.exs
|
Logflare/turnio-prometheus-parser
|
588e72e3779fb78621a008a81ee5426909145f89
|
[
"Apache-2.0"
] | null | null | null |
defmodule PrometheusParserTest do
use ExUnit.Case
import PrometheusParser
test "parse garbage" do
assert parse("blurp") == {:error, "Unsupported syntax: \"blurp\""}
end
test "parse comment" do
assert parse("# Some documenting text") ==
{:ok,
%PrometheusParser.Line{
documentation: "Some documenting text",
line_type: "COMMENT"
}}
end
test "write comment" do
assert to_string(%PrometheusParser.Line{
documentation: "Some documenting text",
line_type: "COMMENT"
}) == "# Some documenting text"
end
test "parse help" do
assert parse("# HELP web_uptime Number of seconds since web server has started") ==
{:ok,
%PrometheusParser.Line{
documentation: "Number of seconds since web server has started",
label: "web_uptime",
line_type: "HELP"
}}
end
test "write help" do
assert to_string(%PrometheusParser.Line{
documentation: "Number of seconds since web server has started",
label: "web_uptime",
line_type: "HELP"
}) == "# HELP web_uptime Number of seconds since web server has started"
end
test "parse type" do
assert parse("# TYPE web_uptime gauge") ==
{:ok, %PrometheusParser.Line{label: "web_uptime", line_type: "TYPE", type: "gauge"}}
end
test "write type" do
assert to_string(%PrometheusParser.Line{label: "web_uptime", line_type: "TYPE", type: "gauge"}) ==
"# TYPE web_uptime gauge"
end
test "parse entry without key and value" do
assert parse("pending_messages 0") ==
{:ok,
%PrometheusParser.Line{
documentation: nil,
label: "pending_messages",
line_type: "ENTRY",
pairs: [],
timestamp: nil,
type: nil,
value: "0"
}}
end
test "write entry without key and value" do
assert to_string(%PrometheusParser.Line{
documentation: nil,
label: "pending_messages",
line_type: "ENTRY",
pairs: [],
timestamp: nil,
type: nil,
value: "0"
}) == "pending_messages 0"
end
test "parse entry with key and value" do
assert parse("web_connections{node=\"abc-123-def-0\"} 607180") ==
{:ok,
%PrometheusParser.Line{
documentation: nil,
label: "web_connections",
line_type: "ENTRY",
pairs: [{"node", "abc-123-def-0"}],
timestamp: nil,
type: nil,
value: "607180"
}}
end
test "empty attributes" do
assert parse("out_message_sent_duration_ms_count{retry=\"0\",type=\"\"} 2") ==
{:ok,
%PrometheusParser.Line{
label: "out_message_sent_duration_ms_count",
line_type: "ENTRY",
pairs: [{"retry", "0"}, {"type", ""}],
timestamp: nil,
type: nil,
value: "2"
}}
end
test "multiple attributes without spaces" do
assert parse("out_message_sent_duration_ms_count{retry=\"0\",type=\"undefined\"} 2") ==
{:ok,
%PrometheusParser.Line{
label: "out_message_sent_duration_ms_count",
line_type: "ENTRY",
pairs: [{"retry", "0"}, {"type", "undefined"}],
timestamp: nil,
type: nil,
value: "2"
}}
end
test "parse entry with key and value with colons and full stops" do
assert parse("api_requests_coreapp_duration_ms_sum{app=\"127.0.0.1:6250\"} 122") ==
{:ok,
%PrometheusParser.Line{
documentation: nil,
label: "api_requests_coreapp_duration_ms_sum",
line_type: "ENTRY",
pairs: [{"app", "127.0.0.1:6250"}],
timestamp: nil,
type: nil,
value: "122"
}}
end
test "write entry with key and value" do
assert to_string(%PrometheusParser.Line{
documentation: nil,
label: "web_connections",
line_type: "ENTRY",
pairs: [{"node", "abc-123-def-0"}],
timestamp: nil,
type: nil,
value: "607180"
}) ==
"web_connections{node=\"abc-123-def-0\"} 607180"
end
test "parse entry with multiple keys and value" do
assert parse("web_connections{node=\"abc-123-def-0\", bar=\"baz\"} 607180") ==
{:ok,
%PrometheusParser.Line{
documentation: nil,
label: "web_connections",
line_type: "ENTRY",
pairs: [{"node", "abc-123-def-0"}, {"bar", "baz"}],
timestamp: nil,
type: nil,
value: "607180"
}}
end
test "parse entry with float value" do
assert parse(
~s(pg_stat_statements_total_queries{supabase_project_ref="ixlqpcigbdlbmfnvzxtw",service_type="postgresql",server="localhost:5432"} 4.37379e+06)
) ==
{:ok,
%PrometheusParser.Line{
documentation: nil,
label: "pg_stat_statements_total_queries",
line_type: "ENTRY",
pairs: [
{"supabase_project_ref", "ixlqpcigbdlbmfnvzxtw"},
{"service_type", "postgresql"},
{"server", "localhost:5432"}
],
timestamp: nil,
type: nil,
value: "4.37379e+06"
}}
end
test "parse entry with uppercase prom_label" do
assert parse(
~s(node_memory_KReclaimable_bytes{supabase_project_ref="ixlqpcigbdlbmfnvzxtw",service_type="db"} 8.8190976e+07)
) ==
{:ok,
%PrometheusParser.Line{
documentation: nil,
label: "node_memory_KReclaimable_bytes",
line_type: "ENTRY",
pairs: [
{"supabase_project_ref", "ixlqpcigbdlbmfnvzxtw"},
{"service_type", "db"}
],
timestamp: nil,
type: nil,
value: "8.8190976e+07"
}}
end
test "write entry with multiple keys and values" do
assert to_string(%PrometheusParser.Line{
documentation: nil,
label: "web_connections",
line_type: "ENTRY",
pairs: [{"node", "abc-123-def-0"}, {"bar", "baz"}],
timestamp: "1234",
type: nil,
value: "607180"
}) ==
"web_connections{node=\"abc-123-def-0\", bar=\"baz\"} 607180 1234"
end
test "parse entry with timestamp" do
assert parse("web_connections{node=\"abc-123-def-0\"} 607180 200") ==
{:ok,
%PrometheusParser.Line{
documentation: nil,
label: "web_connections",
line_type: "ENTRY",
pairs: [{"node", "abc-123-def-0"}],
timestamp: "200",
type: nil,
value: "607180"
}}
end
test "write entry with timestamp" do
assert to_string(%PrometheusParser.Line{
documentation: nil,
label: "web_connections",
line_type: "ENTRY",
pairs: [{"node", "abc-123-def-0"}],
timestamp: "1234",
type: nil,
value: "607180"
}) ==
"web_connections{node=\"abc-123-def-0\"} 607180 1234"
end
end
| 32.974895
| 156
| 0.501332
|
03a68f9562ada7bd325b68b64d91c44b864e0e4a
| 4,514
|
ex
|
Elixir
|
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p2beta1_entity_annotation.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1
|
2021-12-20T03:40:53.000Z
|
2021-12-20T03:40:53.000Z
|
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p2beta1_entity_annotation.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1
|
2020-08-18T00:11:23.000Z
|
2020-08-18T00:44:16.000Z
|
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p2beta1_entity_annotation.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.Vision.V1.Model.GoogleCloudVisionV1p2beta1EntityAnnotation do
@moduledoc """
Set of detected entity features.
## Attributes
* `boundingPoly` (*type:* `GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1BoundingPoly.t`, *default:* `nil`) - Image region to which this entity belongs. Not produced for `LABEL_DETECTION` features.
* `confidence` (*type:* `number()`, *default:* `nil`) - **Deprecated. Use `score` instead.** The accuracy of the entity detection in an image. For example, for an image in which the "Eiffel Tower" entity is detected, this field represents the confidence that there is a tower in the query image. Range [0, 1].
* `description` (*type:* `String.t`, *default:* `nil`) - Entity textual description, expressed in its `locale` language.
* `locale` (*type:* `String.t`, *default:* `nil`) - The language code for the locale in which the entity textual `description` is expressed.
* `locations` (*type:* `list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1LocationInfo.t)`, *default:* `nil`) - The location information for the detected entity. Multiple `LocationInfo` elements can be present because one location may indicate the location of the scene in the image, and another location may indicate the location of the place where the image was taken. Location information is usually present for landmarks.
* `mid` (*type:* `String.t`, *default:* `nil`) - Opaque entity ID. Some IDs may be available in [Google Knowledge Graph Search API](https://developers.google.com/knowledge-graph/).
* `properties` (*type:* `list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1Property.t)`, *default:* `nil`) - Some entities may have optional user-supplied `Property` (name/value) fields, such a score or string that qualifies the entity.
* `score` (*type:* `number()`, *default:* `nil`) - Overall score of the result. Range [0, 1].
* `topicality` (*type:* `number()`, *default:* `nil`) - The relevancy of the ICA (Image Content Annotation) label to the image. For example, the relevancy of "tower" is likely higher to an image containing the detected "Eiffel Tower" than to an image containing a detected distant towering building, even though the confidence that there is a tower in each image may be the same. Range [0, 1].
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:boundingPoly =>
GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1BoundingPoly.t() | nil,
:confidence => number() | nil,
:description => String.t() | nil,
:locale => String.t() | nil,
:locations =>
list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1LocationInfo.t()) | nil,
:mid => String.t() | nil,
:properties =>
list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1Property.t()) | nil,
:score => number() | nil,
:topicality => number() | nil
}
field(:boundingPoly, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1BoundingPoly)
field(:confidence)
field(:description)
field(:locale)
field(:locations,
as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1LocationInfo,
type: :list
)
field(:mid)
field(:properties, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1Property, type: :list)
field(:score)
field(:topicality)
end
defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1EntityAnnotation do
def decode(value, options) do
GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1EntityAnnotation.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1EntityAnnotation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 55.728395
| 436
| 0.72397
|
03a6b0438b7f7e7992ce022e573dd29d8bf83705
| 881
|
ex
|
Elixir
|
lib/anchore_engine_api_server/model/image_reference.ex
|
michaeljguarino/anchore-elixir-client
|
156a44f429ecb62433729a2b4c52de5dc0ef44d2
|
[
"MIT"
] | null | null | null |
lib/anchore_engine_api_server/model/image_reference.ex
|
michaeljguarino/anchore-elixir-client
|
156a44f429ecb62433729a2b4c52de5dc0ef44d2
|
[
"MIT"
] | null | null | null |
lib/anchore_engine_api_server/model/image_reference.ex
|
michaeljguarino/anchore-elixir-client
|
156a44f429ecb62433729a2b4c52de5dc0ef44d2
|
[
"MIT"
] | null | null | null |
# 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 AnchoreEngineAPIServer.Model.ImageReference do
@moduledoc """
A summary of an image identity, including digest, id (if available), and any tags known to have ever been mapped to the digest
"""
@derive [Poison.Encoder]
defstruct [
:analyzed_at,
:digest,
:id,
:tag_history
]
@type t :: %__MODULE__{
:analyzed_at => String.t,
:digest => String.t,
:id => String.t,
:tag_history => [TagEntry]
}
end
defimpl Poison.Decoder, for: AnchoreEngineAPIServer.Model.ImageReference do
import AnchoreEngineAPIServer.Deserializer
def decode(value, options) do
value
|> deserialize(:tag_history, :list, AnchoreEngineAPIServer.Model.TagEntry, options)
end
end
| 25.911765
| 128
| 0.713961
|
03a6b36de74e1bfaea82a694d2e3d67b87568bd3
| 877
|
ex
|
Elixir
|
deps/phoenix_live_reload/lib/phoenix_live_reload/channel.ex
|
dmitrinesterenko/sample_phoenix_ecs
|
d6b94f35680163302e372cf30c70d3e409b0c9b1
|
[
"MIT"
] | 1
|
2015-08-24T06:01:51.000Z
|
2015-08-24T06:01:51.000Z
|
deps/phoenix_live_reload/lib/phoenix_live_reload/channel.ex
|
Thrashmandicoot/my-first-phoenix-app
|
7cdfe34a1d874cbce8dba17e9824a5c91e3b47da
|
[
"MIT"
] | null | null | null |
deps/phoenix_live_reload/lib/phoenix_live_reload/channel.ex
|
Thrashmandicoot/my-first-phoenix-app
|
7cdfe34a1d874cbce8dba17e9824a5c91e3b47da
|
[
"MIT"
] | null | null | null |
defmodule Phoenix.LiveReload.Channel do
@moduledoc """
Phoenix's live-reload channel
"""
use Phoenix.Channel
def join("phoenix:live_reload", _msg, socket) do
{:ok, _} = Application.ensure_all_started(:phoenix_live_reload)
patterns = socket.endpoint.config(:live_reload)[:patterns]
:fs.subscribe()
{:ok, assign(socket, :patterns, patterns)}
end
def handle_info({_pid, {:fs, :file_event}, {path, _event}}, socket) do
if matches_any_pattern?(path, socket.assigns[:patterns]) do
asset_type = Path.extname(path) |> String.lstrip(?.)
push socket, "assets_change", %{asset_type: asset_type}
end
{:noreply, socket}
end
defp matches_any_pattern?(path, patterns) do
path = to_string(path)
Enum.any?(patterns, fn pattern ->
String.match?(path, pattern) and !String.match?(path, ~r/_build/)
end)
end
end
| 26.575758
| 72
| 0.677309
|
03a6ca831d9ceb7adc40db32432331661508c490
| 7,148
|
exs
|
Elixir
|
test/unit/datatypes/generic_test.exs
|
pukkamustard/rdf-ex
|
c459d8e7fa548fdfad82643338b68decf380a296
|
[
"MIT"
] | null | null | null |
test/unit/datatypes/generic_test.exs
|
pukkamustard/rdf-ex
|
c459d8e7fa548fdfad82643338b68decf380a296
|
[
"MIT"
] | null | null | null |
test/unit/datatypes/generic_test.exs
|
pukkamustard/rdf-ex
|
c459d8e7fa548fdfad82643338b68decf380a296
|
[
"MIT"
] | null | null | null |
defmodule RDF.Literal.GenericTest do
use RDF.Test.Case
alias RDF.Literal
alias RDF.Literal.Generic
@valid %{
# input => { value , datatype }
"foo" => { "foo" , "http://example.com/datatype" },
}
describe "new" do
test "with value and datatype" do
Enum.each @valid, fn {input, {value, datatype}} ->
assert %Literal{literal: %Generic{value: ^value, datatype: ^datatype}} =
Generic.new(input, datatype: datatype)
assert %Literal{literal: %Generic{value: ^value, datatype: ^datatype}} =
Generic.new(input, datatype: RDF.iri(datatype))
end
end
test "with datatype directly" do
Enum.each @valid, fn {input, {_, datatype}} ->
datatype_iri = RDF.iri(datatype)
assert Generic.new(input, datatype) == Generic.new(input, datatype: datatype)
assert Generic.new(input, datatype_iri) == Generic.new(input, datatype: datatype_iri)
end
end
test "with datatype as a vocabulary term" do
datatype = EX.Datatype |> RDF.iri() |> to_string()
assert %Literal{literal: %Generic{value: "foo", datatype: ^datatype}} =
Generic.new("foo", datatype: EX.Datatype)
assert Generic.new("foo", EX.Datatype) == Generic.new("foo", datatype: EX.Datatype)
end
test "with canonicalize opts" do
Enum.each @valid, fn {input, {value, datatype}} ->
assert %Literal{literal: %Generic{value: ^value, datatype: ^datatype}} =
Generic.new(input, datatype: datatype, canonicalize: true)
end
end
test "without a datatype it produces an invalid literal" do
Enum.each @valid, fn {input, {value, _}} ->
assert %Literal{literal: %Generic{value: ^value, datatype: nil}} =
literal = Generic.new(input, [])
assert Generic.valid?(literal) == false
end
end
test "with nil as a datatype it produces an invalid literal" do
Enum.each @valid, fn {input, {value, _}} ->
assert %Literal{literal: %Generic{value: ^value, datatype: nil}} =
literal = Generic.new(input, datatype: nil)
assert Generic.valid?(literal) == false
end
end
test "with the empty string as a datatype it produces an invalid literal" do
Enum.each @valid, fn {input, {value, _}} ->
assert %Literal{literal: %Generic{value: ^value, datatype: nil}} =
literal = Generic.new(input, datatype: "")
assert Generic.valid?(literal) == false
end
end
end
describe "new!" do
test "with valid values, it behaves the same as new" do
Enum.each @valid, fn {input, {_, datatype}} ->
assert Generic.new!(input, datatype: datatype) ==
Generic.new(input, datatype: datatype)
assert Generic.new!(input, datatype: datatype, canonicalize: true) ==
Generic.new(input, datatype: datatype, canonicalize: true)
end
end
test "without a datatype it raises an error" do
Enum.each @valid, fn {input, _} ->
assert_raise ArgumentError, fn -> Generic.new!(input, []) end
end
end
test "with nil as a datatype it raises an error" do
Enum.each @valid, fn {input, _} ->
assert_raise ArgumentError, fn -> Generic.new!(input, datatype: nil) end
end
end
test "with the empty string as a datatype it raises an error" do
Enum.each @valid, fn {input, _} ->
assert_raise ArgumentError, fn -> Generic.new!(input, datatype: "") end
end
end
end
test "datatype?/1" do
assert Generic.datatype?(Generic) == true
Enum.each @valid, fn {input, {_, datatype}} ->
literal = Generic.new(input, datatype: datatype)
assert Generic.datatype?(literal) == true
assert Generic.datatype?(literal.literal) == true
end
end
test "datatype_id/1" do
Enum.each @valid, fn {input, {_, datatype}} ->
assert (Generic.new(input, datatype: datatype) |> Generic.datatype_id()) == RDF.iri(datatype)
end
end
test "language/1" do
Enum.each @valid, fn {input, {_, datatype}} ->
assert (Generic.new(input, datatype: datatype) |> Generic.language()) == nil
end
end
test "value/1" do
Enum.each @valid, fn {input, {value, datatype}} ->
assert (Generic.new(input, datatype: datatype) |> Generic.value()) == value
end
end
test "lexical/1" do
Enum.each @valid, fn {input, {value, datatype}} ->
assert (Generic.new(input, datatype: datatype) |> Generic.lexical()) == value
end
end
test "canonical/1" do
Enum.each @valid, fn {input, {_, datatype}} ->
assert (Generic.new(input, datatype: datatype) |> Generic.canonical()) ==
Generic.new(input, datatype: datatype)
end
end
test "canonical?/1" do
Enum.each @valid, fn {input, {_, datatype}} ->
assert (Generic.new(input, datatype: datatype) |> Generic.canonical?()) == true
end
end
describe "valid?/1" do
test "with a datatype" do
Enum.each @valid, fn {input, {_, datatype}} ->
assert (Generic.new(input, datatype: datatype) |> Generic.valid?()) == true
end
end
test "without a datatype" do
Enum.each @valid, fn {input, _} ->
assert (Generic.new(input, datatype: nil) |> Generic.valid?()) == false
assert (Generic.new(input, datatype: "") |> Generic.valid?()) == false
end
end
end
describe "cast/1" do
test "always return nil (RDF.Literal.Generic does not support cast)" do
Enum.each @valid, fn {input, {_, datatype}} ->
assert (Generic.new(input, datatype: datatype) |> Generic.cast()) == nil
end
end
end
test "equal_value?/2" do
Enum.each @valid, fn {input, {_, datatype}} ->
assert Generic.equal_value?(
Generic.new(input, datatype: datatype),
Generic.new(input, datatype: datatype)) == true
end
assert Generic.equal_value?(
Generic.new("foo", datatype: "http://example.com/foo"),
Generic.new("foo", datatype: "http://example.com/bar")) == nil
assert Generic.equal_value?(Generic.new("foo", []), Generic.new("foo", [])) == true
assert Generic.equal_value?(Generic.new("foo", []), Generic.new("bar", [])) == false
assert Generic.equal_value?(Generic.new("foo", datatype: "foo"), RDF.XSD.String.new("foo")) == nil
end
test "compare/2" do
Enum.each @valid, fn {input, {_, datatype}} ->
assert Generic.compare(
Generic.new(input, datatype: datatype),
Generic.new(input, datatype: datatype)) == :eq
end
assert Generic.compare(Generic.new("foo", datatype: "en"), Generic.new("bar", datatype: "en")) == :gt
assert Generic.compare(Generic.new("bar", datatype: "en"), Generic.new("baz", datatype: "en")) == :lt
assert Generic.compare(
Generic.new("foo", datatype: "en"),
Generic.new("foo", datatype: "de")) == nil
assert Generic.compare(Generic.new("foo", []), Generic.new("foo", [])) == nil
assert Generic.compare(Generic.new("foo", []), RDF.XSD.String.new("foo")) == nil
end
end
| 35.919598
| 105
| 0.608702
|
03a707c13483fb5f5e718792040f54c8d0058caa
| 1,757
|
ex
|
Elixir
|
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_fulfillment_set_parameter_action.ex
|
mcrumm/elixir-google-api
|
544f22797cec52b3a23dfb6e39117f0018448610
|
[
"Apache-2.0"
] | null | null | null |
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_fulfillment_set_parameter_action.ex
|
mcrumm/elixir-google-api
|
544f22797cec52b3a23dfb6e39117f0018448610
|
[
"Apache-2.0"
] | null | null | null |
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_fulfillment_set_parameter_action.ex
|
mcrumm/elixir-google-api
|
544f22797cec52b3a23dfb6e39117f0018448610
|
[
"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.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1FulfillmentSetParameterAction do
@moduledoc """
Setting a parameter value.
## Attributes
* `parameter` (*type:* `String.t`, *default:* `nil`) - Display name of the parameter.
* `value` (*type:* `any()`, *default:* `nil`) - The new value of the parameter. A null value clears the parameter.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:parameter => String.t(),
:value => any()
}
field(:parameter)
field(:value)
end
defimpl Poison.Decoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1FulfillmentSetParameterAction do
def decode(value, options) do
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1FulfillmentSetParameterAction.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1FulfillmentSetParameterAction do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.945455
| 118
| 0.738759
|
03a70920818f1760bdf1a41af2db35629e8378f5
| 1,658
|
ex
|
Elixir
|
lib/changelog/buffer/buffer.ex
|
PsOverflow/changelog.com
|
53f4ecfc39b021c6b8cfcc0fa11f29aff8038a7f
|
[
"MIT"
] | null | null | null |
lib/changelog/buffer/buffer.ex
|
PsOverflow/changelog.com
|
53f4ecfc39b021c6b8cfcc0fa11f29aff8038a7f
|
[
"MIT"
] | null | null | null |
lib/changelog/buffer/buffer.ex
|
PsOverflow/changelog.com
|
53f4ecfc39b021c6b8cfcc0fa11f29aff8038a7f
|
[
"MIT"
] | null | null | null |
defmodule Changelog.Buffer do
alias Changelog.NewsItem
alias Changelog.Buffer.{Client, Content}
@shared ~w(506b005149bbd8223400006b 5d27885cb3e9832ca87111a8)
@afk ~w(5af9b7a28bae46d01ead92d3)
@brainscience ~w(5d49c7410eb4bb4992040a42)
@changelog ~w(4f3ad7c8512f7ef962000004)
@founderstalk ~w(5b23f65f772894a723424ec5)
@gotime ~w(5734d7fc1b14578733224a70)
@jsparty ~w(58b47fd78d23761f5f19ca89)
@practicalai ~w(5ac3c64b3fda312b116ca788)
def queue(item = %NewsItem{type: :audio, object_id: id}) when is_binary(id) do
link = Content.episode_link(item)
text = Content.episode_text(item)
profiles = cond do
String.starts_with?(id, "afk") -> @afk
String.starts_with?(id, "brainscience") -> @brainscience
String.starts_with?(id, "founderstalk") -> @founderstalk
String.starts_with?(id, "gotime") -> @gotime
String.starts_with?(id, "jsparty") -> @jsparty
String.starts_with?(id, "practicalai") -> @practicalai
true -> @changelog
end
Client.create(with_shared(profiles), text, [link: link])
end
def queue(%NewsItem{type: :audio}), do: false
def queue(item = %NewsItem{object_id: id}) when is_binary(id) do
link = Content.post_link(item)
text = Content.post_text(item)
Client.create(with_shared(@changelog), text, [link: link])
end
def queue(item = %NewsItem{}) do
image = Content.news_item_image(item)
link = Content.news_item_link(item)
text = Content.news_item_text(item)
Client.create(with_shared(@changelog), text, [link: link, photo: image])
end
def with_shared(profiles), do: profiles ++ @shared
end
| 36.043478
| 80
| 0.698432
|
03a70e482aa52b8bbb455fbc595cee9ec77da2ed
| 2,819
|
ex
|
Elixir
|
clients/you_tube/lib/google_api/you_tube/v3/model/memberships_details.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/you_tube/lib/google_api/you_tube/v3/model/memberships_details.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1
|
2020-12-18T09:25:12.000Z
|
2020-12-18T09:25:12.000Z
|
clients/you_tube/lib/google_api/you_tube/v3/model/memberships_details.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.YouTube.V3.Model.MembershipsDetails do
@moduledoc """
## Attributes
* `accessibleLevels` (*type:* `list(String.t)`, *default:* `nil`) - Ids of all levels that the user has access to. This includes the currently active level and all other levels that are included because of a higher purchase.
* `highestAccessibleLevel` (*type:* `String.t`, *default:* `nil`) - Id of the highest level that the user has access to at the moment.
* `highestAccessibleLevelDisplayName` (*type:* `String.t`, *default:* `nil`) - Display name for the highest level that the user has access to at the moment.
* `membershipsDuration` (*type:* `GoogleApi.YouTube.V3.Model.MembershipsDuration.t`, *default:* `nil`) - Data about memberships duration without taking into consideration pricing levels.
* `membershipsDurationAtLevels` (*type:* `list(GoogleApi.YouTube.V3.Model.MembershipsDurationAtLevel.t)`, *default:* `nil`) - Data about memberships duration on particular pricing levels.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:accessibleLevels => list(String.t()),
:highestAccessibleLevel => String.t(),
:highestAccessibleLevelDisplayName => String.t(),
:membershipsDuration => GoogleApi.YouTube.V3.Model.MembershipsDuration.t(),
:membershipsDurationAtLevels =>
list(GoogleApi.YouTube.V3.Model.MembershipsDurationAtLevel.t())
}
field(:accessibleLevels, type: :list)
field(:highestAccessibleLevel)
field(:highestAccessibleLevelDisplayName)
field(:membershipsDuration, as: GoogleApi.YouTube.V3.Model.MembershipsDuration)
field(:membershipsDurationAtLevels,
as: GoogleApi.YouTube.V3.Model.MembershipsDurationAtLevel,
type: :list
)
end
defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.MembershipsDetails do
def decode(value, options) do
GoogleApi.YouTube.V3.Model.MembershipsDetails.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.MembershipsDetails do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.046875
| 228
| 0.740688
|
03a71bf487d98979c67c6cfd7061205f8f206369
| 1,529
|
exs
|
Elixir
|
test/cocktail/span_test.exs
|
camelohq/cocktail
|
9b25d8f24d148397be6537ab1414abdbdec1ce8d
|
[
"MIT"
] | 117
|
2017-09-09T00:02:32.000Z
|
2022-02-10T15:36:28.000Z
|
test/cocktail/span_test.exs
|
camelohq/cocktail
|
9b25d8f24d148397be6537ab1414abdbdec1ce8d
|
[
"MIT"
] | 193
|
2017-09-09T22:49:18.000Z
|
2022-03-30T13:05:25.000Z
|
test/cocktail/span_test.exs
|
camelohq/cocktail
|
9b25d8f24d148397be6537ab1414abdbdec1ce8d
|
[
"MIT"
] | 20
|
2018-01-04T14:58:42.000Z
|
2021-11-25T13:59:10.000Z
|
defmodule Cocktail.SpanTest do
use ExUnit.Case
alias Cocktail.Span
doctest Cocktail.Span, import: true
test "contains" do
span1 = Span.new(~N[2017-09-09 09:00:00], ~N[2017-09-09 12:00:00])
span2 = Span.new(~N[2017-09-09 10:00:00], ~N[2017-09-09 11:00:00])
assert Span.overlap_mode(span1, span2) == :contains
end
test "is_inside" do
span1 = Span.new(~N[2017-09-09 10:00:00], ~N[2017-09-09 11:00:00])
span2 = Span.new(~N[2017-09-09 09:00:00], ~N[2017-09-09 12:00:00])
assert Span.overlap_mode(span1, span2) == :is_inside
end
test "is_before" do
span1 = Span.new(~N[2017-09-09 09:00:00], ~N[2017-09-09 10:00:00])
span2 = Span.new(~N[2017-09-09 11:00:00], ~N[2017-09-09 12:00:00])
assert Span.overlap_mode(span1, span2) == :is_before
end
test "is_after" do
span1 = Span.new(~N[2017-09-09 11:00:00], ~N[2017-09-09 12:00:00])
span2 = Span.new(~N[2017-09-09 09:00:00], ~N[2017-09-09 10:00:00])
assert Span.overlap_mode(span1, span2) == :is_after
end
test "overlaps_the_start_of" do
span1 = Span.new(~N[2017-09-09 09:00:00], ~N[2017-09-09 11:00:00])
span2 = Span.new(~N[2017-09-09 10:00:00], ~N[2017-09-09 12:00:00])
assert Span.overlap_mode(span1, span2) == :overlaps_the_start_of
end
test "overlaps_the_end_of" do
span1 = Span.new(~N[2017-09-09 10:00:00], ~N[2017-09-09 12:00:00])
span2 = Span.new(~N[2017-09-09 09:00:00], ~N[2017-09-09 11:00:00])
assert Span.overlap_mode(span1, span2) == :overlaps_the_end_of
end
end
| 30.58
| 70
| 0.64552
|
03a7255f715b5eaa3aa5f408b61a27f8c54f775b
| 9,666
|
exs
|
Elixir
|
test/ecto/migrator_test.exs
|
jeregrine/ecto
|
98b2dd4bf7b39738ab9a5ae3fa7e48e43a4af39b
|
[
"Apache-2.0"
] | null | null | null |
test/ecto/migrator_test.exs
|
jeregrine/ecto
|
98b2dd4bf7b39738ab9a5ae3fa7e48e43a4af39b
|
[
"Apache-2.0"
] | null | null | null |
test/ecto/migrator_test.exs
|
jeregrine/ecto
|
98b2dd4bf7b39738ab9a5ae3fa7e48e43a4af39b
|
[
"Apache-2.0"
] | null | null | null |
defmodule Ecto.MigratorTest do
use ExUnit.Case
import Support.FileHelpers
import Ecto.Migrator
import ExUnit.CaptureLog
alias Ecto.TestRepo
alias Ecto.Migration.SchemaMigration
defmodule Migration do
use Ecto.Migration
def up do
execute "up"
end
def down do
execute "down"
end
end
defmodule ChangeMigration do
use Ecto.Migration
def change do
create table(:posts) do
add :name, :string
end
create index(:posts, [:title])
end
end
defmodule ChangeMigrationPrefix do
use Ecto.Migration
def change do
create table(:comments, prefix: :foo) do
add :name, :string
end
create index(:posts, [:title], prefix: :foo)
end
end
defmodule UpDownMigration do
use Ecto.Migration
def up do
alter table(:posts) do
add :name, :string
end
end
def down do
execute "foo"
end
end
defmodule NoTransactionMigration do
use Ecto.Migration
@disable_ddl_transaction true
def change do
create index(:posts, [:foo])
end
end
defmodule InvalidMigration do
use Ecto.Migration
end
defmodule TestSchemaRepo do
use Ecto.Repo, otp_app: :ecto, adapter: Ecto.TestAdapter
end
Application.put_env(:ecto, TestSchemaRepo, [migration_source: "my_schema_migrations"])
setup do
Process.put(:migrated_versions, [1, 2, 3])
:ok
end
test "custom schema migrations table is right" do
assert SchemaMigration.get_source(TestRepo) == "schema_migrations"
assert SchemaMigration.get_source(TestSchemaRepo) == "my_schema_migrations"
end
test "logs migrations" do
output = capture_log fn ->
:ok = up(TestRepo, 0, ChangeMigration)
end
assert output =~ "== Running Ecto.MigratorTest.ChangeMigration.change/0 forward"
assert output =~ "create table posts"
assert output =~ "create index posts_title_index"
assert output =~ ~r"== Migrated in \d.\ds"
output = capture_log fn ->
:ok = down(TestRepo, 0, ChangeMigration)
end
assert output =~ "== Running Ecto.MigratorTest.ChangeMigration.change/0 backward"
assert output =~ "drop table posts"
assert output =~ "drop index posts_title_index"
assert output =~ ~r"== Migrated in \d.\ds"
output = capture_log fn ->
:ok = up(TestRepo, 0, ChangeMigrationPrefix)
end
assert output =~ "== Running Ecto.MigratorTest.ChangeMigrationPrefix.change/0 forward"
assert output =~ "create table foo.comments"
assert output =~ "create index foo.posts_title_index"
assert output =~ ~r"== Migrated in \d.\ds"
output = capture_log fn ->
:ok = down(TestRepo, 0, ChangeMigrationPrefix)
end
assert output =~ "== Running Ecto.MigratorTest.ChangeMigrationPrefix.change/0 backward"
assert output =~ "drop table foo.comments"
assert output =~ "drop index foo.posts_title_index"
assert output =~ ~r"== Migrated in \d.\ds"
output = capture_log fn ->
:ok = up(TestRepo, 0, UpDownMigration)
end
assert output =~ "== Running Ecto.MigratorTest.UpDownMigration.up/0 forward"
assert output =~ "alter table posts"
assert output =~ ~r"== Migrated in \d.\ds"
output = capture_log fn ->
:ok = down(TestRepo, 0, UpDownMigration)
end
assert output =~ "== Running Ecto.MigratorTest.UpDownMigration.down/0 forward"
assert output =~ "execute \"foo\""
assert output =~ ~r"== Migrated in \d.\ds"
end
test "up invokes the repository adapter with up commands" do
assert up(TestRepo, 0, Migration, log: false) == :ok
assert up(TestRepo, 1, Migration, log: false) == :already_up
assert up(TestRepo, 10, ChangeMigration, log: false) == :ok
end
test "down invokes the repository adapter with down commands" do
assert down(TestRepo, 0, Migration, log: false) == :already_down
assert down(TestRepo, 1, Migration, log: false) == :ok
assert down(TestRepo, 2, ChangeMigration, log: false) == :ok
end
test "up raises error when missing up/0 and change/0" do
assert_raise Ecto.MigrationError, fn ->
Ecto.Migrator.up(TestRepo, 0, InvalidMigration, log: false)
end
end
test "down raises error when missing down/0 and change/0" do
assert_raise Ecto.MigrationError, fn ->
Ecto.Migrator.down(TestRepo, 1, InvalidMigration, log: false)
end
end
test "expects files starting with an integer" do
in_tmp fn path ->
create_migration "a_sample.exs"
assert run(TestRepo, path, :up, all: true, log: false) == []
end
end
test "fails if there is no migration in file" do
in_tmp fn path ->
File.write! "13_sample.exs", ":ok"
assert_raise Ecto.MigrationError, "file 13_sample.exs does not contain any Ecto.Migration", fn ->
run(TestRepo, path, :up, all: true, log: false)
end
end
end
test "fails if there are duplicated versions" do
in_tmp fn path ->
create_migration "13_hello.exs"
create_migration "13_other.exs"
assert_raise Ecto.MigrationError, "migrations can't be executed, migration version 13 is duplicated", fn ->
run(TestRepo, path, :up, all: true, log: false)
end
end
end
test "fails if there are duplicated name" do
in_tmp fn path ->
create_migration "13_hello.exs"
create_migration "14_hello.exs"
assert_raise Ecto.MigrationError, "migrations can't be executed, migration name hello is duplicated", fn ->
run(TestRepo, path, :up, all: true, log: false)
end
end
end
test "upwards migrations skips migrations that are already up" do
in_tmp fn path ->
create_migration "1_sample.exs"
assert run(TestRepo, path, :up, all: true, log: false) == []
end
end
test "downwards migrations skips migrations that are already down" do
in_tmp fn path ->
create_migration "1_sample1.exs"
create_migration "4_sample2.exs"
assert run(TestRepo, path, :down, all: true, log: false) == [1]
end
end
test "stepwise migrations stop before all have been run" do
in_tmp fn path ->
create_migration "13_step_premature_end1.exs"
create_migration "14_step_premature_end2.exs"
assert run(TestRepo, path, :up, step: 1, log: false) == [13]
end
end
test "stepwise migrations stop at the number of available migrations" do
in_tmp fn path ->
create_migration "13_step_to_the_end1.exs"
create_migration "14_step_to_the_end2.exs"
assert run(TestRepo, path, :up, step: 2, log: false) == [13, 14]
end
end
test "stepwise migrations stop even if asked to exceed available" do
in_tmp fn path ->
create_migration "13_step_past_the_end1.exs"
create_migration "14_step_past_the_end2.exs"
assert run(TestRepo, path, :up, step: 3, log: false) == [13, 14]
end
end
test "version migrations stop before all have been run" do
in_tmp fn path ->
create_migration "13_version_premature_end1.exs"
create_migration "14_version_premature_end2.exs"
assert run(TestRepo, path, :up, to: 13, log: false) == [13]
end
end
test "version migrations stop at the number of available migrations" do
in_tmp fn path ->
create_migration "13_version_to_the_end1.exs"
create_migration "14_version_to_the_end2.exs"
assert run(TestRepo, path, :up, to: 14, log: false) == [13, 14]
end
end
test "version migrations stop even if asked to exceed available" do
in_tmp fn path ->
create_migration "13_version_past_the_end1.exs"
create_migration "14_version_past_the_end2.exs"
assert run(TestRepo, path, :up, to: 15, log: false) == [13, 14]
end
end
test "version migrations work iside directories" do
in_tmp fn path ->
File.mkdir_p!("foo")
create_migration "foo/13_version_in_dir.exs"
assert run(TestRepo, Path.join(path, "foo"), :up, to: 15, log: false) == [13]
end
end
test "migrations will give the up and down migration status" do
in_tmp fn path ->
create_migration "1_up_migration_1.exs"
create_migration "2_up_migration_2.exs"
create_migration "3_up_migration_3.exs"
create_migration "4_down_migration_1.exs"
create_migration "5_down_migration_2.exs"
expected_result = [
{:up, 1, "up_migration_1"},
{:up, 2, "up_migration_2"},
{:up, 3, "up_migration_3"},
{:down, 4, "down_migration_1"},
{:down, 5, "down_migration_2"}
]
assert migrations(TestRepo, path) == expected_result
end
end
test "migrations run inside a transaction if the adapter supports ddl transactions" do
capture_log fn ->
Process.put(:supports_ddl_transaction?, true)
up(TestRepo, 0, ChangeMigration)
assert_receive {:transaction, _}
end
end
test "migrations can be forced to run outside a transaction" do
capture_log fn ->
Process.put(:supports_ddl_transaction?, true)
up(TestRepo, 0, NoTransactionMigration)
refute_received {:transaction, _}
end
end
test "migrations does not run inside a transaction if the adapter does not support ddl transactions" do
capture_log fn ->
Process.put(:supports_ddl_transaction?, false)
up(TestRepo, 0, ChangeMigration)
refute_received {:transaction, _}
end
end
defp create_migration(name) do
module = name |> Path.basename |> Path.rootname
File.write! name, """
defmodule Ecto.MigrationTest.S#{module} do
use Ecto.Migration
def up do
execute "up"
end
def down do
execute "down"
end
end
"""
end
end
| 28.682493
| 113
| 0.669874
|
03a729b20677a63060a097d65d4d7c3aabb50e35
| 12,970
|
exs
|
Elixir
|
test/burox_test.exs
|
erickueen/burox
|
ca750675d2b654cf7804f6a403780db950a1c42e
|
[
"MIT"
] | 14
|
2018-03-21T18:03:14.000Z
|
2022-01-23T05:21:57.000Z
|
test/burox_test.exs
|
erickueen/burox
|
ca750675d2b654cf7804f6a403780db950a1c42e
|
[
"MIT"
] | 11
|
2018-03-06T21:35:17.000Z
|
2019-03-28T21:38:34.000Z
|
test/burox_test.exs
|
erickueen/burox
|
ca750675d2b654cf7804f6a403780db950a1c42e
|
[
"MIT"
] | 10
|
2018-02-26T19:41:08.000Z
|
2020-03-19T18:58:41.000Z
|
defmodule BuroxTest do
use ExUnit.Case
import Mox
alias Burox.Request
alias Burox.Request.Persona
alias Burox.Request.Direccion
@valid_person_data %Request{
persona: %Persona{
apellido_paterno: "MENDEZ",
apellido_materno: "GONZALEZ",
primer_nombre: "ANTUANET",
rfc: "MEGA510503RE3"
},
direccion: %Direccion{
primera_linea_de_direccion: "PICO DE VERAPAZ 435 PISO 5",
colonia: "JARDINES EN LA MONTANA",
municipio: "TLALPAN",
ciudad: "MEXICO",
estado: "CDMX",
codigo_postal: "14210",
origen_del_domicilio: "MX"
}
}
@invalid_state_data %Request{
persona: %Persona{
apellido_paterno: "MENDEZ",
apellido_materno: "GONZALEZ",
primer_nombre: "ANTUANET",
rfc: "MEGA510503RE3"
},
direccion: %Direccion{
primera_linea_de_direccion: "PICO DE VERAPAZ 435 PISO 5",
colonia: "JARDINES EN LA MONTANA",
municipio: "TLALPAN",
ciudad: "MEXICO",
estado: "Ciudad de México",
codigo_postal: "14210",
origen_del_domicilio: "MX"
}
}
@invalid_address_data %Request{
persona: %Persona{
apellido_paterno: "MENDEZ",
apellido_materno: "GONZALEZ",
primer_nombre: "ANTUANET",
rfc: "MEGA510503RE3"
},
direccion: %Direccion{
primera_linea_de_direccion:
"Una direccion con una larga descripcion sin importancia. No es aceptada XD XD XD",
colonia: "JARDINES EN LA MONTANA No 54",
municipio: "TLALPAN",
ciudad: "MEXICO",
estado: "Ciudad de México",
codigo_postal: "14210",
origen_del_domicilio: "MX"
}
}
setup [:verify_on_exit!]
@valid_person_data_string "INTL13 507MX0000userpasswordICCMX000000000SP01 0000000PN06MENDEZ0008GONZALEZ0208ANTUANET0513MEGA510503RE3PA26PICO DE VERAPAZ 435 PISO 50122JARDINES EN LA MONTANA0207TLALPAN0306MEXICO0404CDMX0505142101302MXES05002500002**"
@success_response "INTL13 MX0010Usuario12300PN06AVELAR0009HERNANDEZ0204JOSE0304LUIS0408131019830513AEHL8310136J6PA08HUERTA 10121VILLAS DE LA HACIENDA0220TLAJOMULCO DE ZUNIGA0320TLAJOMULCO DE ZUNIGA0403JAL0505456541208180720161302MXIQ08180720160110Usuario1230208RESUELVE031055864796020402CC060100701I0801Y09010IQ0818072016000400000215BURO DE CREDITO0402CC0502MX06090000000000801Y09011RS08180720160002000102000202000302000402000502000602000702000802000904000010040000110400001204000013040000140400001502001602011701Y1805NNNNN1901N210900000000022090000000002310000000000+24090000000002509000000000260300027090000000002810000000000+29090000000003009000000000310200320200330200340800000000350800000000360201370818072016380200390800000000400200410800000000SC08BC SCORE00030070104-009ES0500811001012123420590102**"
@invalid_user_response "ERRRUR25 0312UserPasswordES05000700002**"
test "Gets the information of a person in Buro de Crédito" do
Burox.BuroService.Mock
|> expect(:post, fn _, _ ->
{:ok, @success_response <> <<19>>}
end)
assert Burox.solicitar(@valid_person_data) ==
{:ok,
%{
cadena_peticion: @valid_person_data_string,
cadena_respuesta: @success_response,
respuesta:
{:ok,
%Burox.Response{
consultas: [
%{
clave_del_usuario: "Usuario123",
fecha_de_consulta: ~D[2016-07-18],
importe_del_credito: "0",
indicador_de_cliente_nuevo: "Y",
nombre_del_usuario: "RESUELVE",
numero_telefonico_del_usuario: "5586479602",
reserved: "0",
tipo_de_producto: "CC",
tipo_de_responsabilidad_de_la_cuenta: "I"
},
%{
clave_del_usuario: "Usuario123",
fecha_de_consulta: ~D[2016-07-18],
importe_del_credito: "000000000",
indicador_de_cliente_nuevo: "Y",
moneda_del_credito: "MX",
nombre_del_usuario: "BURO DE CREDITO",
numero_telefonico_del_usuario: "5586479602",
reserved: "1",
tipo_de_producto: "CC",
tipo_de_responsabilidad_de_la_cuenta: "I"
}
],
creditos: [],
declarativa_consumidor: %{},
direcciones: [
%{
ciudad: "TLAJOMULCO DE ZUNIGA",
codigo_postal: "45654",
colonia: "VILLAS DE LA HACIENDA",
estado: "JAL",
fecha_de_reporte_de_la_direccion: ~D[2016-07-18],
municipio: "TLAJOMULCO DE ZUNIGA",
origen_del_domicilio: "MX",
primera_linea_de_direccion: "HUERTA 1"
}
],
direcciones_de_trabajo: [],
error: %Burox.Response.ErrorUser{
clave_de_usuario_o_contrasena_erronea: nil,
error_en_el_sistema_de_buro_de_credito: nil,
etiqueta_de_segmento__erronea: nil,
expediente_bloqueado_para_consulta: nil,
falta_campo_requerido: nil,
informacion_erronea_para_consulta: nil,
numero_de_referencia_del_operador: nil,
numero_erroneo_de_segmentos: nil,
orden_erroneo_del_segmento: nil,
producto_solicitado_erroneo: nil,
segmento_requerido_no_proporcionado: nil,
solicitud_del_cliente_erronea: nil,
informacion_a_validar_del_cliente: nil,
valor_erroneo_en_una_campo_relacionado: nil,
version_proporcionada_erronea: nil
},
fin: %{
fin_del_registro_de_respuesta: "**",
longitud_de_transmision: 811,
numero_de_control_de_la_consulta: "1212342059"
},
hawk_inquiry: %{},
hawk_response: [],
persona: %{
apellido_materno: "HERNANDEZ",
apellido_paterno: "AVELAR",
fecha_de_nacimiento: ~D[1983-10-13],
primer_nombre: "JOSE",
rfc: "AEHL8310136J6",
segundo_nombre: "LUIS"
},
resumen: %{
fecha_de_apertura_de_cuenta_mas_reciente: nil,
fecha_de_apertura_mas_reciente_de_una_cuenta_en_despacho_de_cobranza: nil,
total_de_importe_de_pago_para_cuentas_revolventes: 0.0,
numero_de_cuentas: 0,
total_de_saldos_vencidos_para_cuentas_revolventes: 0.0,
numero_de_solicitudes_de_informe_de_buro: 1,
numero_de_solicitudes_del_informe_buro_realizadas_por_despachos_de_cobranza:
0,
total_de_saldos_vencidos_para_cuentas_de_pagos_fijos_e_hipotecarios: 0,
numero_de_cuentas_con_MOP_98: 0,
total_de_limites_de_credito_para_cuentas_revolventes: 0.0,
numero_de_cuentas_con_historial_de_morosidad_actual: 0,
total_de_creditos_maximos_para_cuentas_de_pagos_fijos_e_hipotecarios: 0,
fecha_de_integracion: ~D[2016-07-18],
numero_de_cuentas_en_aclaracion: 0,
numero_de_cuentas_con_morosidad_actual: 0,
fecha_de_apertura_de_cuenta_mas_antigua: nil,
nueva_direccion_en_los_ultimos_60_dias: "Y",
numero_de_cuentas_de_pagos_fijos_e_hipotecario: 0,
numero_de_cuentas_con_MOP_07: 0,
numero_de_cuentas_revolventes_y_sin_limite_establecido: 0,
numero_de_cuentas_con_MOP_01: 0,
declarativa: "N",
fecha_de_la_consulta_mas_reciente_realizada_por_un_despacho_de_cobranza:
nil,
numero_de_cuentas_con_MOP_05: 0,
total_de_saldos_actuales_para_cuentas_revolventes: 0.0,
mensaje_de_alerta: "NNNNN",
numero_de_cuentas_cerradas: 0,
numero_de_cuentas_con_MOP_97: 0,
total_de_creditos_maximos_para_cuentas_revolventes: 0.0,
numero_de_cuentas_con_MOP_03: 0,
numero_de_solicitudes_de_consulta: 1,
numero_de_cuentas_con_MOP_00: 0,
numero_de_cuentas_con_MOP_96: 0,
total_de_importe_de_pago_para_cuentas_de_pagos_fijos_e_hipotecarios: 0,
number_of_accounts_with_MOP_03: 0,
numero_de_cuentas_con_MOP_02: 0,
numero_de_cuentas_con_MOP_06: 0,
porcentaje_del_limite_de_credito_utilizado_para_cuentas_revolventes: 0.0,
numero_de_cuentas_con_MOP_UR: 0,
fecha_de_la_consulta_mas_reciente: ~D[2016-07-18],
total_de_saldos_actuales_para_cuentas_de_pagos_fijos_e_hipotecarios: 0.0,
numero_de_cuentas_en_despacho_de_cobranza: 0
},
score: %{
codigo_del_score: "007",
nombre_del_score: "BC SCORE",
valor_del_score: -9,
valor_de_exclusion: "Expediente sin cuentas para cálculo de BC-Score"
}
}}
}}
end
test "Gets a generic error when trying to get information of a person in Buro de Crédito" do
Burox.BuroService.Mock
|> expect(:post, fn _, _ ->
{:ok, "ERRRUR25 1101YES05000530002**"}
end)
assert Burox.solicitar(@valid_person_data) ==
{:error,
%{
cadena_respuesta: "ERRRUR25 1101YES05000530002**",
respuesta: [
error_en_el_sistema_de_buro_de_credito: "Y",
numero_de_referencia_del_operador: " "],
cadena_peticion: @valid_person_data_string
}}
end
test "Gets an error when the request sent is invalid" do
Burox.BuroService.Mock
|> expect(:post, fn _, _ ->
{:ok, @invalid_user_response <> <<19>>}
end)
assert Burox.solicitar(@valid_person_data) ==
{:error,
%{
cadena_peticion: @valid_person_data_string,
cadena_respuesta: @invalid_user_response,
respuesta: [
clave_de_usuario_o_contrasena_erronea: "UserPassword",
numero_de_referencia_del_operador: " "]
}
}
end
test "Gets an error trying to autenticate a client in Buro de Crédito" do
Burox.BuroService.Mock
|> expect(:post, fn _, _ ->
{:ok, "ERRRAR25 0014NO AUTENTICADOES05000660002**"}
end)
assert Burox.solicitar(@valid_person_data) ==
{:error, %{
cadena_peticion: @valid_person_data_string,
cadena_respuesta: "ERRRAR25 0014NO AUTENTICADOES05000660002**",
respuesta: [numero_de_referencia_del_operador: " ",
solicitud_del_cliente_erronea: "NO AUTENTICADO"]
}
}
end
test "Gets an error trying to send an invalid address" do
assert Burox.solicitar(@invalid_address_data) ==
{:error, %{
cadena_peticion: "",
cadena_respuesta: "",
respuesta: [
{"primera_linea_de_direccion(length)", "must have a length of no more than 40"},
{"primera_linea_de_direccion(format)", "must have the correct format"}]}
}
end
test "Change the code when trying to send an invalid state" do
Burox.BuroService.Mock
|> expect(:post, fn _, _ ->
{:ok, @success_response <> <<19>>}
end)
result = Burox.solicitar(@invalid_state_data)
assert elem(result, 0) == :ok
end
end
| 45.034722
| 833
| 0.5633
|
03a736f9f5265997b840037741e34c43d4b5b1cc
| 3,479
|
exs
|
Elixir
|
test/logger_logstash_backend_test.exs
|
otherchris/logger_logstash_backend
|
f1eaf05468d4dc9af43d58f398a15e02d0b6af76
|
[
"Apache-2.0"
] | null | null | null |
test/logger_logstash_backend_test.exs
|
otherchris/logger_logstash_backend
|
f1eaf05468d4dc9af43d58f398a15e02d0b6af76
|
[
"Apache-2.0"
] | null | null | null |
test/logger_logstash_backend_test.exs
|
otherchris/logger_logstash_backend
|
f1eaf05468d4dc9af43d58f398a15e02d0b6af76
|
[
"Apache-2.0"
] | null | null | null |
################################################################################
# Copyright 2015 Marcelo Gornstein <marcelog@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
defmodule LoggerLogstashBackendTest do
use ExUnit.Case, async: false
require Logger
use Timex
@backend {LoggerLogstashBackend, :test}
Logger.add_backend @backend
setup do
Logger.configure_backend @backend, [
host: "127.0.0.1",
port: 10001,
level: :info,
type: "some_app",
metadata: [
some_metadata: "go here"
]
]
{:ok, socket} = :gen_udp.open 10001, [:binary, {:active, true}]
on_exit fn ->
:ok = :gen_udp.close socket
end
:ok
end
test "can log" do
Logger.info "hello world", [key1: "field1"]
json = get_log()
{:ok, data} = JSX.decode json
assert data["type"] === "some_app"
assert data["message"] === "hello world"
expected = %{
"function" => "test can log/1",
"level" => "info",
"module" => "Elixir.LoggerLogstashBackendTest",
"pid" => (inspect self()),
"some_metadata" => "go here",
"line" => 42,
"key1" => "field1"
}
assert contains?(data["fields"], expected)
{:ok, ts} = Timex.parse data["@timestamp"], "{ISO:Extended}"
ts = Timex.to_unix ts
now = Timex.to_unix Timex.local
assert (now - ts) < 1000
end
test "can log pids" do
Logger.info "pid", [pid_key: self()]
json = get_log()
{:ok, data} = JSX.decode json
assert data["type"] === "some_app"
assert data["message"] === "pid"
expected = %{
"function" => "test can log pids/1",
"level" => "info",
"module" => "Elixir.LoggerLogstashBackendTest",
"pid" => (inspect self()),
"pid_key" => inspect(self()),
"some_metadata" => "go here",
"line" => 65
}
assert contains?(data["fields"], expected)
{:ok, ts} = Timex.parse data["@timestamp"], "{ISO:Extended}"
ts = Timex.to_unix ts
now = Timex.to_unix Timex.local
assert (now - ts) < 1000
end
test "cant log when minor levels" do
Logger.debug "hello world", [key1: "field1"]
:nothing_received = get_log()
end
test "can pass ex_jsx_options" do
conf_with_uescape
Logger.info "µ", [pid_key: self()]
json = get_log()
{:ok, data} = JSX.decode json
assert data["message"] === "µ"
end
defp get_log do
receive do
{:udp, _, _, _, json} -> json
after 500 -> :nothing_received
end
end
defp contains?(map1, map2) do
Enum.all?(Map.to_list(map2), fn {key, value} ->
Map.fetch!(map1, key) == value
end)
end
defp conf_with_uescape do
Logger.configure_backend @backend, [
host: "127.0.0.1",
port: 10001,
level: :info,
type: "some_app",
metadata: [
some_metadata: "go here"
],
ex_jsx_opts: [:uescape]
]
end
end
| 27.611111
| 80
| 0.579477
|
03a7a9a4968a83050937180d763d11615e98c909
| 220
|
ex
|
Elixir
|
lib/tidy/report.ex
|
IanLuites/tidy
|
8427986dd0261139a8e25a6fb6f9a938608500c6
|
[
"MIT"
] | null | null | null |
lib/tidy/report.ex
|
IanLuites/tidy
|
8427986dd0261139a8e25a6fb6f9a938608500c6
|
[
"MIT"
] | 1
|
2020-09-02T10:03:53.000Z
|
2020-09-02T10:03:53.000Z
|
lib/tidy/report.ex
|
IanLuites/tidy
|
8427986dd0261139a8e25a6fb6f9a938608500c6
|
[
"MIT"
] | 1
|
2020-09-01T16:20:38.000Z
|
2020-09-01T16:20:38.000Z
|
defmodule Tidy.Report.Errors do
defstruct module: [],
function: %{}
end
defmodule Tidy.Report do
@moduledoc """
"""
defstruct [
:module,
:reference,
errors: %Tidy.Report.Errors{}
]
end
| 14.666667
| 33
| 0.6
|
03a7b9fe7b4e528744c24094cdfb2fb2aff9d260
| 970
|
ex
|
Elixir
|
dev/market/lib/market.ex
|
miniguez/elixirmarket
|
e8ef1fcd062abdad754a017bfd58fa160f8fed44
|
[
"Apache-2.0"
] | null | null | null |
dev/market/lib/market.ex
|
miniguez/elixirmarket
|
e8ef1fcd062abdad754a017bfd58fa160f8fed44
|
[
"Apache-2.0"
] | null | null | null |
dev/market/lib/market.ex
|
miniguez/elixirmarket
|
e8ef1fcd062abdad754a017bfd58fa160f8fed44
|
[
"Apache-2.0"
] | null | null | null |
defmodule Market do
use Application
# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
# Start the endpoint when the application starts
supervisor(Market.Endpoint, []),
# Start the Ecto repository
supervisor(Market.Repo, []),
# Here you could define other workers and supervisors as children
# worker(Market.Worker, [arg1, arg2, arg3]),
]
# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Market.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
Market.Endpoint.config_change(changed, removed)
:ok
end
end
| 31.290323
| 71
| 0.709278
|
03a7bc22313ee70d39ba83044292258681d0aaf8
| 12,458
|
ex
|
Elixir
|
lib/statix.ex
|
dnlserrano/statix
|
00c9d690f41847cab8ad5e70f28e501f98035797
|
[
"0BSD"
] | 255
|
2015-05-14T13:39:57.000Z
|
2022-03-02T14:50:33.000Z
|
lib/statix.ex
|
dnlserrano/statix
|
00c9d690f41847cab8ad5e70f28e501f98035797
|
[
"0BSD"
] | 47
|
2015-05-17T13:14:13.000Z
|
2021-07-16T15:07:52.000Z
|
lib/statix.ex
|
dnlserrano/statix
|
00c9d690f41847cab8ad5e70f28e501f98035797
|
[
"0BSD"
] | 68
|
2015-05-16T15:30:04.000Z
|
2022-02-02T16:29:39.000Z
|
defmodule Statix do
@moduledoc """
Writer for [StatsD](https://github.com/etsy/statsd)-compatible servers.
To get started with Statix, you have to create a module that calls `use
Statix`, like this:
defmodule MyApp.Statix do
use Statix
end
This will make `MyApp.Statix` a Statix connection that implements the `Statix`
behaviour. This connection can be started with the `MyApp.Statix.connect/1`
function (see the `c:connect/1` callback) and a few functions can be called on
it to report metrics to the StatsD-compatible server read from the
configuration. Usually, `connect/1` is called in your application's
`c:Application.start/2` callback:
def start(_type, _args) do
:ok = MyApp.Statix.connect()
# ...
end
## Configuration
Statix can be configured either globally or on a per-connection basis.
The global configuration will affect all Statix connections created with
`use Statix`; it can be specified by configuring the `:statix` application:
config :statix,
prefix: "sample",
host: "stats.tld",
port: 8181
The per-connection configuration can be specified by configuring each specific
connection module under the `:statix` application:
config :statix, MyApp.Statix,
port: 8123
The following is a list of all the supported options:
* `:prefix` - (binary) all metrics sent to the StatsD-compatible
server through the configured Statix connection will be prefixed with the
value of this option. By default this option is not present.
* `:host` - (binary) the host where the StatsD-compatible server is running.
Defaults to `"127.0.0.1"`.
* `:port` - (integer) the port (on `:host`) where the StatsD-compatible
server is running. Defaults to `8125`.
* `:tags` - ([binary]) a list of global tags that will be sent with all
metrics. By default this option is not present.
See the "Tags" section for more information.
* `:pool_size` - (integer) number of ports used to distribute the metric sending.
Defaults to `1`. See the "Pooling" section for more information.
By default, the configuration is evaluated once, at compile time.
If you plan on changing the configuration at runtime, you must specify the
`:runtime_config` option to be `true` when calling `use Statix`:
defmodule MyApp.Statix do
use Statix, runtime_config: true
end
## Tags
Tags are a way of adding dimensions to metrics:
MyApp.Statix.gauge("memory", 1, tags: ["region:east"])
In the example above, the `memory` measurement has been tagged with
`region:east`. Not all StatsD-compatible servers support this feature.
Tags could also be added globally to be included in every metric sent:
config :statix, tags: ["env:\#{Mix.env()}"]
## Sampling
All the callbacks from the `Statix` behaviour that accept options support
sampling via the `:sample_rate` option (see also the `t:options/0` type).
MyApp.Statix.increment("page_view", 1, sample_rate: 0.5)
In the example above, the UDP packet will only be sent to the server about
half of the time, but the resulting value will be adjusted on the server
according to the given sample rate.
## Pooling
Statix transmits data using [ports](https://hexdocs.pm/elixir/Port.html).
If a port is busy when you try to send a command to it, the sender may be suspended and some blocking may occur. This becomes more of an issue in highly concurrent environments.
In order to get around that, Statix allows you to start multiple ports, and randomly picks one at the time of transmit.
This option can be configured via the `:pool_size` option:
config :statix, MyApp.Statix,
pool_size: 3
"""
alias __MODULE__.Conn
@type key :: iodata
@type options :: [sample_rate: float, tags: [String.t()]]
@type on_send :: :ok | {:error, term}
@doc """
Same as `connect([])`.
"""
@callback connect() :: :ok
@doc """
Opens the connection to the StatsD-compatible server.
The configuration is read from the environment for the `:statix` application
(both globally and per connection).
The given `options` override the configuration read from the application environment.
"""
@callback connect(options :: keyword) :: :ok
@doc """
Increments the StatsD counter identified by `key` by the given `value`.
`value` is supposed to be zero or positive and `c:decrement/3` should be
used for negative values.
## Examples
iex> MyApp.Statix.increment("hits", 1, [])
:ok
"""
@callback increment(key, value :: number, options) :: on_send
@doc """
Same as `increment(key, 1, [])`.
"""
@callback increment(key) :: on_send
@doc """
Same as `increment(key, value, [])`.
"""
@callback increment(key, value :: number) :: on_send
@doc """
Decrements the StatsD counter identified by `key` by the given `value`.
Works same as `c:increment/3` but subtracts `value` instead of adding it. For
this reason `value` should be zero or negative.
## Examples
iex> MyApp.Statix.decrement("open_connections", 1, [])
:ok
"""
@callback decrement(key, value :: number, options) :: on_send
@doc """
Same as `decrement(key, 1, [])`.
"""
@callback decrement(key) :: on_send
@doc """
Same as `decrement(key, value, [])`.
"""
@callback decrement(key, value :: number) :: on_send
@doc """
Writes to the StatsD gauge identified by `key`.
## Examples
iex> MyApp.Statix.gauge("cpu_usage", 0.83, [])
:ok
"""
@callback gauge(key, value :: String.Chars.t(), options) :: on_send
@doc """
Same as `gauge(key, value, [])`.
"""
@callback gauge(key, value :: String.Chars.t()) :: on_send
@doc """
Writes `value` to the histogram identified by `key`.
Not all StatsD-compatible servers support histograms. An example of a such
server [statsite](https://github.com/statsite/statsite).
## Examples
iex> MyApp.Statix.histogram("online_users", 123, [])
:ok
"""
@callback histogram(key, value :: String.Chars.t(), options) :: on_send
@doc """
Same as `histogram(key, value, [])`.
"""
@callback histogram(key, value :: String.Chars.t()) :: on_send
@doc """
Same as `timing(key, value, [])`.
"""
@callback timing(key, value :: String.Chars.t()) :: on_send
@doc """
Writes the given `value` to the StatsD timing identified by `key`.
`value` is expected in milliseconds.
## Examples
iex> MyApp.Statix.timing("rendering", 12, [])
:ok
"""
@callback timing(key, value :: String.Chars.t(), options) :: on_send
@doc """
Writes the given `value` to the StatsD set identified by `key`.
## Examples
iex> MyApp.Statix.set("unique_visitors", "user1", [])
:ok
"""
@callback set(key, value :: String.Chars.t(), options) :: on_send
@doc """
Same as `set(key, value, [])`.
"""
@callback set(key, value :: String.Chars.t()) :: on_send
@doc """
Measures the execution time of the given `function` and writes that to the
StatsD timing identified by `key`.
This function returns the value returned by `function`, making it suitable for
easily wrapping existing code.
## Examples
iex> MyApp.Statix.measure("integer_to_string", [], fn -> Integer.to_string(123) end)
"123"
"""
@callback measure(key, options, function :: (() -> result)) :: result when result: var
@doc """
Same as `measure(key, [], function)`.
"""
@callback measure(key, function :: (() -> result)) :: result when result: var
defmacro __using__(opts) do
current_statix =
if Keyword.get(opts, :runtime_config, false) do
quote do
@statix_key Module.concat(__MODULE__, :__statix__)
def connect(options \\ []) do
statix = Statix.new(__MODULE__, options)
Application.put_env(:statix, @statix_key, statix)
Statix.open(statix)
:ok
end
@compile {:inline, [current_statix: 0]}
defp current_statix() do
Application.fetch_env!(:statix, @statix_key)
end
end
else
quote do
@statix Statix.new(__MODULE__, [])
def connect(options \\ []) do
if @statix != Statix.new(__MODULE__, options) do
raise(
"the current configuration for #{inspect(__MODULE__)} differs from " <>
"the one that was given during the compilation.\n" <>
"Be sure to use :runtime_config option " <>
"if you want to have different configurations"
)
end
Statix.open(@statix)
:ok
end
@compile {:inline, [current_statix: 0]}
defp current_statix(), do: @statix
end
end
quote location: :keep do
@behaviour Statix
unquote(current_statix)
def increment(key, val \\ 1, options \\ []) when is_number(val) do
Statix.transmit(current_statix(), :counter, key, val, options)
end
def decrement(key, val \\ 1, options \\ []) when is_number(val) do
Statix.transmit(current_statix(), :counter, key, [?-, to_string(val)], options)
end
def gauge(key, val, options \\ []) do
Statix.transmit(current_statix(), :gauge, key, val, options)
end
def histogram(key, val, options \\ []) do
Statix.transmit(current_statix(), :histogram, key, val, options)
end
def timing(key, val, options \\ []) do
Statix.transmit(current_statix(), :timing, key, val, options)
end
def measure(key, options \\ [], fun) when is_function(fun, 0) do
{elapsed, result} = :timer.tc(fun)
timing(key, div(elapsed, 1000), options)
result
end
def set(key, val, options \\ []) do
Statix.transmit(current_statix(), :set, key, val, options)
end
defoverridable(
increment: 3,
decrement: 3,
gauge: 3,
histogram: 3,
timing: 3,
measure: 3,
set: 3
)
end
end
defstruct [:conn, :tags, :pool]
@doc false
def new(module, options) do
config = get_config(module, options)
conn = Conn.new(config.host, config.port)
header = IO.iodata_to_binary([conn.header | config.prefix])
%__MODULE__{
conn: %{conn | header: header},
pool: build_pool(module, config.pool_size),
tags: config.tags
}
end
defp build_pool(module, 1), do: [module]
defp build_pool(module, size) do
Enum.map(1..size, &:"#{module}-#{&1}")
end
@doc false
def open(%__MODULE__{conn: conn, pool: pool}) do
Enum.each(pool, fn name ->
%{sock: sock} = Conn.open(conn)
Process.register(sock, name)
end)
end
@doc false
def transmit(
%{conn: conn, pool: pool, tags: tags},
type,
key,
value,
options
)
when (is_binary(key) or is_list(key)) and is_list(options) do
sample_rate = Keyword.get(options, :sample_rate)
if is_nil(sample_rate) or sample_rate >= :rand.uniform() do
options = put_global_tags(options, tags)
%{conn | sock: pick_name(pool)}
|> Conn.transmit(type, key, to_string(value), options)
else
:ok
end
end
defp pick_name([name]), do: name
defp pick_name(pool), do: Enum.random(pool)
defp get_config(module, overrides) do
{module_env, global_env} =
:statix
|> Application.get_all_env()
|> Keyword.pop(module, [])
env = module_env ++ global_env
options = overrides ++ env
tags =
Keyword.get_lazy(overrides, :tags, fn ->
env |> Keyword.get_values(:tags) |> Enum.concat()
end)
%{
prefix: build_prefix(env, overrides),
host: Keyword.get(options, :host, "127.0.0.1"),
port: Keyword.get(options, :port, 8125),
pool_size: Keyword.get(options, :pool_size, 1),
tags: tags
}
end
defp build_prefix(env, overrides) do
case Keyword.fetch(overrides, :prefix) do
{:ok, prefix} ->
[prefix, ?.]
:error ->
env
|> Keyword.get_values(:prefix)
|> Enum.map_join(&(&1 && [&1, ?.]))
end
end
defp put_global_tags(options, []), do: options
defp put_global_tags(options, tags) do
Keyword.update(options, :tags, tags, &(&1 ++ tags))
end
end
| 27.62306
| 179
| 0.628672
|
03a7d4d5dd4d626d97e662a78230e39524ed8a3a
| 2,641
|
ex
|
Elixir
|
test/support/api.ex
|
Switch168/MongoosePush
|
d997bd9cd0e63e16684bec9495cd12790bcaa8f1
|
[
"Apache-2.0"
] | null | null | null |
test/support/api.ex
|
Switch168/MongoosePush
|
d997bd9cd0e63e16684bec9495cd12790bcaa8f1
|
[
"Apache-2.0"
] | null | null | null |
test/support/api.ex
|
Switch168/MongoosePush
|
d997bd9cd0e63e16684bec9495cd12790bcaa8f1
|
[
"Apache-2.0"
] | null | null | null |
defmodule MongoosePush.Support.API do
alias HTTPoison.Response
def sample_notification(service) do
%{
:service => service,
:alert => %{
:title => "title value",
:body => "body value",
:click_action => "click.action",
:tag => "tag value"
}
}
end
def sample_bad_notification(service) do
%{
:service => service,
:alert => %{
:title => "title value",
:body => "body value",
:click_action => "click.action",
:tag => "tag value"
},
:data => %{
:x => %{"a" => 222}
}
}
end
def post(path, json) do
%Response{status_code: status_code, body: body} =
HTTPoison.post!(
"https://localhost:8443" <> path,
Poison.encode!(json),
[{"Content-Type", "application/json"}],
hackney: [:insecure]
)
details = Poison.decode!(body)
{status_code, details}
end
def post_conn_error(path, json) do
%Response{status_code: status_code, body: body} =
HTTPoison.post!(
"https://localhost:8443" <> path,
Poison.encode!(json),
[{"Content-Type", "application/json"}],
hackney: [:insecure]
)
{status_code, body}
end
def mock_apns(json) do
{:ok, conn} = get_connection(:apns)
payload = Poison.encode!(json)
headers = headers("POST", "/error-tokens", payload)
:h2_client.send_request(conn, headers, payload)
{"200", _payload} = get_response(conn)
:ok
end
def mock_fcm(path, json) do
HTTPoison.post!(
"http://localhost:4001/mock" <> path,
Poison.encode!(json),
[{"Content-Type", "application/json"}]
)
end
def reset(:apns) do
{:ok, conn} = get_connection(:apns)
payload = ""
headers = headers("POST", "/reset", payload)
:h2_client.send_request(conn, headers, payload)
{"200", "OK"} = get_response(conn)
:ok
end
def reset(:fcm) do
%Response{status_code: 200} = mock_fcm("/reset", "")
end
def get_connection(:apns) do
:h2_client.start_link(:https, 'localhost', 2197, [])
end
def headers(method, path, payload) do
[
{":method", method},
{":authority", "localhost"},
{":scheme", "https"},
{":path", path},
{"content-length", "#{byte_size(payload)}"},
{"content-type", "application/json"}
]
end
def get_response(conn) do
receive do
{:END_STREAM, stream_id} ->
{:ok, {headers, body}} = :h2_client.get_response(conn, stream_id)
{":status", code} = List.keyfind(headers, ":status", 0)
{code, Enum.join(body)}
end
end
end
| 23.792793
| 73
| 0.563044
|
03a7f86dfd7bfcc5c05054d7b603471dbfc9f9ff
| 191
|
ex
|
Elixir
|
apps/emporium_api/modules/mod_hello/controllers/hello_controller.ex
|
impressarix/Phoenix-Webstore
|
31376183b853e594b224fb1051897a00cd20b6ec
|
[
"Apache-2.0"
] | null | null | null |
apps/emporium_api/modules/mod_hello/controllers/hello_controller.ex
|
impressarix/Phoenix-Webstore
|
31376183b853e594b224fb1051897a00cd20b6ec
|
[
"Apache-2.0"
] | null | null | null |
apps/emporium_api/modules/mod_hello/controllers/hello_controller.ex
|
impressarix/Phoenix-Webstore
|
31376183b853e594b224fb1051897a00cd20b6ec
|
[
"Apache-2.0"
] | null | null | null |
defmodule Emporium.HelloController do
use EmporiumApi.Web, :controller
def index(conn, _params) do
render conn, "index.html", layout: {Emporium.HelloLayoutView, "app.html"}
end
end
| 27.285714
| 77
| 0.748691
|
03a820e9b7779c156985f336972fe42761b59de2
| 1,822
|
ex
|
Elixir
|
clients/app_engine/lib/google_api/app_engine/v1/model/resource_record.ex
|
matehat/elixir-google-api
|
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
|
[
"Apache-2.0"
] | 1
|
2018-12-03T23:43:10.000Z
|
2018-12-03T23:43:10.000Z
|
clients/app_engine/lib/google_api/app_engine/v1/model/resource_record.ex
|
matehat/elixir-google-api
|
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
|
[
"Apache-2.0"
] | null | null | null |
clients/app_engine/lib/google_api/app_engine/v1/model/resource_record.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.AppEngine.V1.Model.ResourceRecord do
@moduledoc """
A DNS resource record.
## Attributes
* `name` (*type:* `String.t`, *default:* `nil`) - Relative name of the object affected by this record. Only applicable for CNAME records. Example: 'www'.
* `rrdata` (*type:* `String.t`, *default:* `nil`) - Data for this record. Values vary by record type, as defined in RFC 1035 (section 5) and RFC 1034 (section 3.6.1).
* `type` (*type:* `String.t`, *default:* `nil`) - Resource record type. Example: AAAA.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:name => String.t(),
:rrdata => String.t(),
:type => String.t()
}
field(:name)
field(:rrdata)
field(:type)
end
defimpl Poison.Decoder, for: GoogleApi.AppEngine.V1.Model.ResourceRecord do
def decode(value, options) do
GoogleApi.AppEngine.V1.Model.ResourceRecord.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AppEngine.V1.Model.ResourceRecord do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.377358
| 170
| 0.705818
|
03a84b29499cd94b5cfe65b8e821f461db7c5413
| 3,034
|
exs
|
Elixir
|
apps/ello_v2/test/controllers/manage/activity_count_controller_test.exs
|
ello/apex
|
4acb096b3ce172ff4ef9a51e5d068d533007b920
|
[
"MIT"
] | 16
|
2017-06-21T21:31:20.000Z
|
2021-05-09T03:23:26.000Z
|
apps/ello_v2/test/controllers/manage/activity_count_controller_test.exs
|
ello/apex
|
4acb096b3ce172ff4ef9a51e5d068d533007b920
|
[
"MIT"
] | 25
|
2017-06-07T12:18:28.000Z
|
2018-06-08T13:27:43.000Z
|
apps/ello_v2/test/controllers/manage/activity_count_controller_test.exs
|
ello/apex
|
4acb096b3ce172ff4ef9a51e5d068d533007b920
|
[
"MIT"
] | 3
|
2018-06-14T15:34:07.000Z
|
2022-02-28T21:06:13.000Z
|
defmodule Ello.V2.Manage.ActivityCountControllerTest do
use Ello.V2.ConnCase
setup %{conn: conn} do
Ecto.Adapters.SQL.Sandbox.mode(Ello.Core.Repo, {:shared, self()})
archer = Script.insert(:archer)
brand = Factory.insert(:user, username: "yolo")
staff = Factory.insert(:user, %{is_staff: true})
a_inv1 = Factory.insert(:artist_invite, %{status: "open"})
a_inv2 = Factory.insert(:artist_invite, %{status: "open", brand_account: brand})
later_created_at = FactoryTime.now_offset(1)
post1 = Factory.insert(:post, created_at: later_created_at)
_sub1 = Factory.insert(:artist_invite_submission, post: post1, artist_invite: a_inv2)
_comment1 = Factory.insert(:post, parent_post: post1, created_at: later_created_at)
_love1 = Factory.insert(:love, post: post1)
repost1 = Factory.insert(:post, reposted_source: post1, created_at: later_created_at)
_repost_comment1 = Factory.insert(:post, parent_post: repost1, created_at: later_created_at)
_repost_love1 = Factory.insert(:love, post: repost1)
_mention1 = Factory.insert(:post, mentioned_usernames: ["yolo"], created_at: later_created_at)
_follower1 = Factory.insert(:relationship, subject: brand, priority: "friend", created_at: later_created_at)
_following1 = Factory.insert(:relationship, owner: brand, priority: "friend", created_at: later_created_at)
_blocked1 = Factory.insert(:relationship, subject: brand, priority: "block", created_at: later_created_at)
{:ok,
unauth_conn: conn,
conn: auth_conn(conn, archer),
staff_conn: auth_conn(conn, staff),
brand_conn: auth_conn(conn, brand),
a_inv1: a_inv1,
a_inv2: a_inv2,
}
end
test "GET /api/v2/manage/artist-invites/:id/total-activities - brand token", %{brand_conn: conn, a_inv2: invite} do
conn = get(conn, "/api/v2/manage/artist-invites/#{invite.id}/total-activities")
assert %{"total_activities" => activities} = json_response(conn, 200)
assert [comments, loves, reposts, followers, mentions | _] = activities
assert comments["type"] == "comments"
assert comments["artist_invite_id"]
assert comments["id"]
assert comments["activities"] == 2
assert loves["type"] == "loves"
assert loves["artist_invite_id"]
assert loves["id"]
assert loves["activities"] == 2
assert reposts["type"] == "reposts"
assert reposts["artist_invite_id"]
assert reposts["id"]
assert reposts["activities"] == 1
assert mentions["type"] == "mentions"
assert mentions["artist_invite_id"]
assert mentions["id"]
assert mentions["activities"] == 1
assert followers["type"] == "followers"
assert followers["artist_invite_id"]
assert followers["id"]
assert followers["activities"] == 1
end
test "GET /api/v2/manage/artist-invites/:id/total-activities - brand token - wrong invite", %{brand_conn: conn, a_inv1: invite} do
conn = get(conn, "/api/v2/manage/artist-invites/#{invite.id}/total-activities")
assert conn.status == 404
end
end
| 46.676923
| 132
| 0.701055
|
03a85cfe240d1fadd70217583b334bea5bc557ee
| 2,588
|
ex
|
Elixir
|
clients/content/lib/google_api/content/v2/model/orders_custom_batch_request_entry_return_line_item.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/v2/model/orders_custom_batch_request_entry_return_line_item.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/v2/model/orders_custom_batch_request_entry_return_line_item.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.V2.Model.OrdersCustomBatchRequestEntryReturnLineItem do
@moduledoc """
## Attributes
* `lineItemId` (*type:* `String.t`, *default:* `nil`) - The ID of the line item to return. Either lineItemId or productId is required.
* `productId` (*type:* `String.t`, *default:* `nil`) - The ID of the product to return. This is the REST ID used in the products service. Either lineItemId or productId is required.
* `quantity` (*type:* `integer()`, *default:* `nil`) - The quantity to return.
* `reason` (*type:* `String.t`, *default:* `nil`) - The reason for the return. Acceptable values are: - "`customerDiscretionaryReturn`" - "`customerInitiatedMerchantCancel`" - "`deliveredTooLate`" - "`expiredItem`" - "`invalidCoupon`" - "`malformedShippingAddress`" - "`other`" - "`productArrivedDamaged`" - "`productNotAsDescribed`" - "`qualityNotAsExpected`" - "`undeliverableShippingAddress`" - "`unsupportedPoBoxAddress`" - "`wrongProductShipped`"
* `reasonText` (*type:* `String.t`, *default:* `nil`) - The explanation of the reason.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:lineItemId => String.t() | nil,
:productId => String.t() | nil,
:quantity => integer() | nil,
:reason => String.t() | nil,
:reasonText => String.t() | nil
}
field(:lineItemId)
field(:productId)
field(:quantity)
field(:reason)
field(:reasonText)
end
defimpl Poison.Decoder,
for: GoogleApi.Content.V2.Model.OrdersCustomBatchRequestEntryReturnLineItem do
def decode(value, options) do
GoogleApi.Content.V2.Model.OrdersCustomBatchRequestEntryReturnLineItem.decode(value, options)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Content.V2.Model.OrdersCustomBatchRequestEntryReturnLineItem do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 42.42623
| 456
| 0.710201
|
03a86181728cfb9dbb98f6c6cf88562ba6d0a269
| 880
|
exs
|
Elixir
|
mix.exs
|
papercups-io/ex_papercups
|
319c3c923c9015e8f3ea5e131581643a0978a3db
|
[
"MIT"
] | null | null | null |
mix.exs
|
papercups-io/ex_papercups
|
319c3c923c9015e8f3ea5e131581643a0978a3db
|
[
"MIT"
] | null | null | null |
mix.exs
|
papercups-io/ex_papercups
|
319c3c923c9015e8f3ea5e131581643a0978a3db
|
[
"MIT"
] | null | null | null |
defmodule ExPapercups.MixProject do
use Mix.Project
def project do
[
app: :ex_papercups,
version: "0.1.0",
elixir: "~> 1.11",
start_permanent: Mix.env() == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/papercups-io/ex_papercups"
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:ex_doc, "~> 0.18", only: :dev}
]
end
defp description() do
"The Papercups Elixir client."
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE*"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/papercups-io/ex_papercups"}
]
end
end
| 20.465116
| 74
| 0.582955
|
03a863730c65ab41031c4bb5c6dd28b916ae58c7
| 2,546
|
ex
|
Elixir
|
lib/exnn/connectome.ex
|
zampino/exnn
|
2be888df107644daab1aca7614fecb4940fe3c84
|
[
"MIT"
] | 104
|
2015-06-18T18:54:25.000Z
|
2021-11-04T15:07:02.000Z
|
lib/exnn/connectome.ex
|
nelyj/exnn
|
2be888df107644daab1aca7614fecb4940fe3c84
|
[
"MIT"
] | 3
|
2016-10-09T11:19:42.000Z
|
2018-09-17T16:36:32.000Z
|
lib/exnn/connectome.ex
|
nelyj/exnn
|
2be888df107644daab1aca7614fecb4940fe3c84
|
[
"MIT"
] | 17
|
2016-03-08T19:02:51.000Z
|
2019-04-27T16:40:52.000Z
|
defmodule EXNN.Connectome do
@moduledoc """
Stores genomes forming the system,
with their inner information.
On boot it expands
a pattern of the form:
[sensor: [S_ID_1, S_ID_2, ..., S_ID_l],
neuron: {N_1, N_2, ..., N_m},
actuator: [A_ID_1, A_ID_2, ..., A_ID_n]
where N_s, N_i, N_a are natural numbers,
into a linking information between nodes with
m hidden layers each of size N_i
"""
alias EXNN.Utils.Random
# TODO: decouple storage from link/patterns
# into Connectome.Links and Connectome.Pattern
def start_link do
{pattern, dimensions} = EXNN.Config.get_pattern
Random.seed
store = pattern
|> EXNN.Pattern.build_layers
|> link([], dimensions)
|> Enum.reduce(HashDict.new, &store/2)
Agent.start_link(fn() -> store end, name: __MODULE__)
end
@doc "returns the list of all genomes"
def all do
unkey = fn(dict)-> dict |> Enum.map(&elem &1, 1) end
Agent.get __MODULE__, unkey
end
@doc "returns all neuron genomes"
def neurons do
Enum.filter all, &(:neuron == &1.type)
end
def get(id) do
Agent.get __MODULE__, &(Dict.get &1, id)
end
@doc "accepts anything map or dict like"
def update(id, dict) do
# skim out unwanted keys!
safe_dict = struct(EXNN.Genome, dict)
update_fun = fn(state) ->
genome = HashDict.get(state, id)
# ugly but used to preserve the type
type = genome.type
genome = Map.merge(genome, safe_dict)
HashDict.put state, id, %{genome | type: type}
end
Agent.update(__MODULE__, update_fun)
end
defp store(genome, hash) do
HashDict.put(hash, genome.id, genome)
end
# TOPOLOGY AND CONNECTIONS
defp link([], acc, _), do: List.flatten(acc)
defp link([{:actuator, list} | rest], [], dimensions) do
[{_previous_type, previous_list} | _tail] = rest
genomes = EXNN.Genome.collect(:actuator, list)
|> EXNN.Genome.set_ins(previous_list)
link(rest, [genomes], dimensions)
end
defp link([{:sensor, first_list}], acc, dimensions) do
[outs | _rest] = acc
genomes = EXNN.Genome.collect(:sensor, first_list)
|> EXNN.Genome.set_outs(outs)
link([], [genomes | acc], dimensions)
end
defp link([{type, list} | rest], acc, dimensions) do
[{_previous_type, previous_list} | _tail] = rest
[outs | _tail] = acc
genomes = EXNN.Genome.collect(type, list)
|> EXNN.Genome.set_ins(previous_list, dimensions)
|> EXNN.Genome.set_outs(outs)
link(rest, [genomes | acc], dimensions)
end
end
| 26.247423
| 58
| 0.649254
|
03a8812fe576542e3c187d6dfc7dfcdcb878d5e7
| 10,343
|
ex
|
Elixir
|
lib/quantum/job_broadcaster.ex
|
ericdude4/quantum-core
|
faf6522e08a590472301864f2c8be492c60db332
|
[
"Apache-2.0"
] | null | null | null |
lib/quantum/job_broadcaster.ex
|
ericdude4/quantum-core
|
faf6522e08a590472301864f2c8be492c60db332
|
[
"Apache-2.0"
] | null | null | null |
lib/quantum/job_broadcaster.ex
|
ericdude4/quantum-core
|
faf6522e08a590472301864f2c8be492c60db332
|
[
"Apache-2.0"
] | null | null | null |
defmodule Quantum.JobBroadcaster do
@moduledoc false
# This Module is here to broadcast added / removed tabs into the execution pipeline.
use GenStage
require Logger
alias Quantum.Job
alias __MODULE__.{InitOpts, StartOpts, State}
@type event :: {:add, Job.t()} | {:remove, Job.t()}
# Start Job Broadcaster
@spec start_link(StartOpts.t()) :: GenServer.on_start()
def start_link(%StartOpts{name: name} = opts) do
__MODULE__
|> GenStage.start_link(
struct!(InitOpts, Map.take(opts, [:jobs, :storage, :scheduler, :debug_logging])),
name: name
)
|> case do
{:ok, pid} ->
{:ok, pid}
{:error, {:already_started, pid}} ->
Process.monitor(pid)
{:ok, pid}
{:error, _reason} = error ->
error
end
end
@impl GenStage
def init(%InitOpts{
jobs: jobs,
storage: storage,
scheduler: scheduler,
debug_logging: debug_logging
}) do
storage_pid = GenServer.whereis(Module.concat(scheduler, Storage))
effective_jobs =
storage_pid
|> storage.jobs()
|> case do
:not_applicable ->
debug_logging &&
Logger.debug(fn ->
"[#{inspect(Node.self())}][#{__MODULE__}] Loading Initial Jobs from Config"
end)
jobs
storage_jobs when is_list(storage_jobs) ->
debug_logging &&
Logger.debug(fn ->
"[#{inspect(Node.self())}][#{__MODULE__}] Loading Initial Jobs from Storage, skipping config"
end)
for %Job{state: :active} = job <- storage_jobs do
# Send event to telemetry incase the end user wants to monitor events
:telemetry.execute([:quantum, :job, :add], %{}, %{
job: job,
scheduler: scheduler
})
end
storage_jobs
end
{:producer,
%State{
jobs: effective_jobs |> Enum.map(&{&1.name, &1}) |> Map.new(),
buffer: for(%{state: :active} = job <- effective_jobs, do: {:add, job}),
storage: storage,
storage_pid: storage_pid,
scheduler: scheduler,
debug_logging: debug_logging
}}
end
@impl GenStage
def handle_demand(demand, %State{buffer: buffer} = state) do
{to_send, remaining} = Enum.split(buffer, demand)
{:noreply, to_send, %{state | buffer: remaining}}
end
@impl GenStage
def handle_cast(
{:add, %Job{state: :active, name: job_name} = job},
%State{
jobs: jobs,
storage: storage,
storage_pid: storage_pid,
debug_logging: debug_logging
} = state
) do
case jobs do
%{^job_name => %Job{state: :active} = old_job} ->
debug_logging &&
Logger.debug(fn ->
"[#{inspect(Node.self())}][#{__MODULE__}] Replacing job #{inspect(job_name)}"
end)
# Send event to telemetry incase the end user wants to monitor events
:telemetry.execute([:quantum, :job, :update], %{}, %{
job: job,
scheduler: state.scheduler
})
:ok = storage.delete_job(storage_pid, job_name)
:ok = storage.add_job(storage_pid, job)
{:noreply, [{:delete, old_job}, {:add, job}],
%{state | jobs: Map.put(jobs, job_name, job)}}
%{^job_name => %Job{state: :inactive}} ->
debug_logging &&
Logger.debug(fn ->
"[#{inspect(Node.self())}][#{__MODULE__}] Replacing job #{inspect(job_name)}"
end)
# Send event to telemetry incase the end user wants to monitor events
:telemetry.execute([:quantum, :job, :update], %{}, %{
job: job,
scheduler: state.scheduler
})
:ok = storage.delete_job(storage_pid, job_name)
:ok = storage.add_job(storage_pid, job)
{:noreply, [{:add, job}], %{state | jobs: Map.put(jobs, job_name, job)}}
_ ->
debug_logging &&
Logger.debug(fn ->
"[#{inspect(Node.self())}][#{__MODULE__}] Adding job #{inspect(job_name)}"
end)
# Send event to telemetry incase the end user wants to monitor events
:telemetry.execute([:quantum, :job, :add], %{}, %{
job: job,
scheduler: state.scheduler
})
:ok = storage.add_job(storage_pid, job)
{:noreply, [{:add, job}], %{state | jobs: Map.put(jobs, job_name, job)}}
end
end
def handle_cast(
{:add, %Job{state: :inactive, name: job_name} = job},
%State{
jobs: jobs,
storage: storage,
storage_pid: storage_pid,
debug_logging: debug_logging
} = state
) do
case jobs do
%{^job_name => %Job{state: :active} = old_job} ->
debug_logging &&
Logger.debug(fn ->
"[#{inspect(Node.self())}][#{__MODULE__}] Replacing job #{inspect(job_name)}"
end)
# Send event to telemetry incase the end user wants to monitor events
:telemetry.execute([:quantum, :job, :update], %{}, %{
job: job,
scheduler: state.scheduler
})
:ok = storage.delete_job(storage_pid, job_name)
:ok = storage.add_job(storage_pid, job)
{:noreply, [{:delete, old_job}], %{state | jobs: Map.put(jobs, job_name, job)}}
%{^job_name => %Job{state: :inactive}} ->
debug_logging &&
Logger.debug(fn ->
"[#{inspect(Node.self())}][#{__MODULE__}] Replacing job #{inspect(job_name)}"
end)
# Send event to telemetry incase the end user wants to monitor events
:telemetry.execute([:quantum, :job, :update], %{}, %{
job: job,
scheduler: state.scheduler
})
:ok = storage.delete_job(storage_pid, job_name)
:ok = storage.add_job(storage_pid, job)
{:noreply, [], %{state | jobs: Map.put(jobs, job_name, job)}}
_ ->
debug_logging &&
Logger.debug(fn ->
"[#{inspect(Node.self())}][#{__MODULE__}] Adding job #{inspect(job_name)}"
end)
# Send event to telemetry incase the end user wants to monitor events
:telemetry.execute([:quantum, :job, :add], %{}, %{
job: job,
scheduler: state.scheduler
})
:ok = storage.add_job(storage_pid, job)
{:noreply, [], %{state | jobs: Map.put(jobs, job_name, job)}}
end
end
def handle_cast(
{:delete, name},
%State{
jobs: jobs,
storage: storage,
storage_pid: storage_pid,
debug_logging: debug_logging
} = state
) do
debug_logging &&
Logger.debug(fn ->
"[#{inspect(Node.self())}][#{__MODULE__}] Deleting job #{inspect(name)}"
end)
case Map.fetch(jobs, name) do
{:ok, %{state: :active, name: name} = job} ->
# Send event to telemetry incase the end user wants to monitor events
:telemetry.execute([:quantum, :job, :delete], %{}, %{
job: job,
scheduler: state.scheduler
})
:ok = storage.delete_job(storage_pid, name)
{:noreply, [{:remove, name}], %{state | jobs: Map.delete(jobs, name)}}
{:ok, %{state: :inactive, name: name} = job} ->
# Send event to telemetry incase the end user wants to monitor events
:telemetry.execute([:quantum, :job, :delete], %{}, %{
job: job,
scheduler: state.scheduler
})
:ok = storage.delete_job(storage_pid, name)
{:noreply, [], %{state | jobs: Map.delete(jobs, name)}}
:error ->
{:noreply, [], state}
end
end
def handle_cast(
{:change_state, name, new_state},
%State{
jobs: jobs,
storage: storage,
storage_pid: storage_pid,
debug_logging: debug_logging
} = state
) do
debug_logging &&
Logger.debug(fn ->
"[#{inspect(Node.self())}][#{__MODULE__}] Change job state #{inspect(name)}"
end)
case Map.fetch(jobs, name) do
:error ->
{:noreply, [], state}
{:ok, %{state: ^new_state}} ->
{:noreply, [], state}
{:ok, job} ->
# Send event to telemetry incase the end user wants to monitor events
:telemetry.execute([:quantum, :job, :update], %{}, %{
job: job,
scheduler: state.scheduler
})
jobs = Map.update!(jobs, name, &Job.set_state(&1, new_state))
:ok = storage.update_job_state(storage_pid, job.name, new_state)
case new_state do
:active ->
{:noreply, [{:add, %{job | state: new_state}}], %{state | jobs: jobs}}
:inactive ->
{:noreply, [{:remove, name}], %{state | jobs: jobs}}
end
end
end
def handle_cast(
{:run_job, name},
%State{
jobs: jobs,
debug_logging: debug_logging
} = state
) do
debug_logging &&
Logger.debug(fn ->
"[#{inspect(Node.self())}][#{__MODULE__}] Running job #{inspect(name)} once"
end)
case Map.fetch(jobs, name) do
:error ->
{:noreply, [], state}
{:ok, job} ->
{:noreply, [{:run, job}], state}
end
end
def handle_cast(
:delete_all,
%State{
jobs: jobs,
storage: storage,
storage_pid: storage_pid,
debug_logging: debug_logging
} = state
) do
debug_logging &&
Logger.debug(fn ->
"[#{inspect(Node.self())}][#{__MODULE__}] Deleting all jobs"
end)
for {_name, %Job{} = job} <- jobs do
# Send event to telemetry incase the end user wants to monitor events
:telemetry.execute([:quantum, :job, :delete], %{}, %{
job: job,
scheduler: state.scheduler
})
end
messages = for {name, %Job{state: :active}} <- jobs, do: {:remove, name}
:ok = storage.purge(storage_pid)
{:noreply, messages, %{state | jobs: %{}}}
end
@impl GenStage
def handle_call(:jobs, _, %State{jobs: jobs} = state),
do: {:reply, Map.to_list(jobs), [], state}
def handle_call({:find_job, name}, _, %State{jobs: jobs} = state),
do: {:reply, Map.get(jobs, name), [], state}
@impl GenStage
def handle_info(_message, state) do
{:noreply, [], state}
end
end
| 28.336986
| 107
| 0.546747
|
03a88cafd460fa0555fafb4c570fead7adbacbc1
| 2,587
|
ex
|
Elixir
|
lib/payment_messenger/types/validator.ex
|
aleDsz/payment-messenger
|
91477413373b96167fc8185ff7dc0acc78c8be41
|
[
"Apache-2.0"
] | 2
|
2021-07-18T11:41:29.000Z
|
2021-07-18T22:27:04.000Z
|
lib/payment_messenger/types/validator.ex
|
aleDsz/payment-messenger
|
91477413373b96167fc8185ff7dc0acc78c8be41
|
[
"Apache-2.0"
] | null | null | null |
lib/payment_messenger/types/validator.ex
|
aleDsz/payment-messenger
|
91477413373b96167fc8185ff7dc0acc78c8be41
|
[
"Apache-2.0"
] | null | null | null |
defmodule PaymentMessenger.Types.Validator do
@moduledoc """
The custom Ecto types validator for ISO-8583
"""
# Guard to check if given value is a valid tag
defguardp is_tag(tag) when byte_size(tag) == 3 or byte_size(tag) == 7
@typep value :: String.t() | integer()
@typep tlv :: {String.t(), pos_integer() | Range.t(), value()}
@typep success :: {:ok, tlv()}
@typep error :: {:error, keyword(String.t())}
@typep result :: success() | error()
@doc """
Cast TLV tuple into given data
"""
@spec cast(tlv(), Regex.t()) :: result()
def cast({tag, tag_length, value}, regex) when is_tag(tag) do
validate_value(value, regex, tag_length)
end
def cast(tuple, _) when is_tuple(tuple) do
{:error, [message: "invalid tuple format"]}
end
def cast(_, _) do
{:error, [message: "isn't tuple"]}
end
@doc """
Load TLV tuple into valid TLV tuple
"""
@spec load(tlv()) :: result()
def load({tag, tag_length, value}) when is_tag(tag) do
{:ok, {tag, length_to_string(value, tag_length), value}}
end
def load(tuple) when is_tuple(tuple) do
{:error, [message: "invalid tuple format"]}
end
def load(_) do
{:error, [message: "isn't tuple"]}
end
@doc """
Dump TLV tuple into valid TLV tuple
"""
@spec dump(tlv()) :: result()
def dump({tag, tag_length, value}) when is_tag(tag) do
{:ok, {tag, length_to_string(value, tag_length), value}}
end
def dump(tuple) when is_tuple(tuple) do
{:error, [message: "invalid tuple format"]}
end
def dump(_) do
{:error, [message: "isn't tuple"]}
end
defp validate_value(value, regex, tag_length) do
string_value = to_string(value)
with {:match, true} <- {:match, String.match?(string_value, regex)},
{:length, true} <- {:length, valid_length?(string_value, tag_length)} do
{:ok, value}
else
{:match, false} ->
{:error, [message: "invalid format"]}
{:length, false} ->
{:error, [message: "invalid size"]}
end
end
defp valid_length?(value, tag_length = _start_size.._end_size) do
String.length(value) in tag_length
end
defp valid_length?(value, tag_length) when is_integer(tag_length) do
String.length(value) == tag_length
end
defp valid_length?(_, _), do: false
defp length_to_string(_value, tag_length) when is_integer(tag_length) do
tag_length
|> to_string()
|> String.pad_leading(3, "0")
end
defp length_to_string(value, _start_size.._end_size) do
value
|> String.length()
|> to_string()
|> String.pad_leading(3, "0")
end
end
| 25.613861
| 81
| 0.635872
|
03a8b26e1795eb56eba73b57e3da242b643b7328
| 1,914
|
ex
|
Elixir
|
clients/analytics_reporting/lib/google_api/analytics_reporting/v4/model/date_range_values.ex
|
matehat/elixir-google-api
|
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
|
[
"Apache-2.0"
] | 1
|
2018-12-03T23:43:10.000Z
|
2018-12-03T23:43:10.000Z
|
clients/analytics_reporting/lib/google_api/analytics_reporting/v4/model/date_range_values.ex
|
matehat/elixir-google-api
|
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
|
[
"Apache-2.0"
] | null | null | null |
clients/analytics_reporting/lib/google_api/analytics_reporting/v4/model/date_range_values.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.AnalyticsReporting.V4.Model.DateRangeValues do
@moduledoc """
Used to return a list of metrics for a single DateRange / dimension
combination
## Attributes
* `pivotValueRegions` (*type:* `list(GoogleApi.AnalyticsReporting.V4.Model.PivotValueRegion.t)`, *default:* `nil`) - The values of each pivot region.
* `values` (*type:* `list(String.t)`, *default:* `nil`) - Each value corresponds to each Metric in the request.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:pivotValueRegions => list(GoogleApi.AnalyticsReporting.V4.Model.PivotValueRegion.t()),
:values => list(String.t())
}
field(
:pivotValueRegions,
as: GoogleApi.AnalyticsReporting.V4.Model.PivotValueRegion,
type: :list
)
field(:values, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.AnalyticsReporting.V4.Model.DateRangeValues do
def decode(value, options) do
GoogleApi.AnalyticsReporting.V4.Model.DateRangeValues.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AnalyticsReporting.V4.Model.DateRangeValues do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.178571
| 153
| 0.738245
|
03a8b5529ef33089f3bcf671f797f0e0fac8f48f
| 2,013
|
exs
|
Elixir
|
test/changelog/data/person_test.exs
|
joebew42/changelog.com
|
da4ec68d15f3a2b4b6c29033443d7e7afe814d18
|
[
"MIT"
] | 1
|
2018-01-22T20:07:10.000Z
|
2018-01-22T20:07:10.000Z
|
test/changelog/data/person_test.exs
|
joebew42/changelog.com
|
da4ec68d15f3a2b4b6c29033443d7e7afe814d18
|
[
"MIT"
] | null | null | null |
test/changelog/data/person_test.exs
|
joebew42/changelog.com
|
da4ec68d15f3a2b4b6c29033443d7e7afe814d18
|
[
"MIT"
] | null | null | null |
defmodule Changelog.PersonTest do
use Changelog.DataCase
alias Changelog.Person
@valid_attrs %{name: "Joe Blow", email: "joe@blow.com", handle: "joeblow"}
@invalid_attrs %{}
test "changeset with valid attributes" do
changeset = Person.changeset(%Person{}, @valid_attrs)
assert changeset.valid?
end
test "changeset with invalid attributes" do
changeset = Person.changeset(%Person{}, @invalid_attrs)
refute changeset.valid?
end
test "admin_changeset with a local file path image URL attribute" do
person = insert(:person)
local_file_path = File.cwd! <> "/test/fixtures/avatar600x600.png"
attrs = Map.put(@valid_attrs, :avatar, local_file_path)
changeset = Person.admin_changeset(person, attrs)
assert changeset.valid?
refute Map.has_key?(changeset.changes, :avatar)
end
test "encoded_auth and decoded_auth" do
user = %Person{email: "jenny@hits.com", auth_token: "8675309"}
{:ok, encoded} = Person.encoded_auth(user)
assert encoded == "6A656E6E7940686974732E636F6D7C38363735333039"
assert ["jenny@hits.com", "8675309"] = Person.decoded_auth(encoded)
end
describe "get_by_ueberauth" do
setup do
person = insert(:person, twitter_handle: "JoeBlow", github_handle: "kokomo")
[person: person]
end
test "it gets person with matching ci twitter handle", context do
auth = %{provider: :twitter, info: %{nickname: "joeBLOW"}}
assert Person.get_by_ueberauth(auth) == context[:person]
end
test "it gets person with matching ci github handle", context do
auth = %{provider: :github, info: %{nickname: "KOKOMO"}}
assert Person.get_by_ueberauth(auth) == context[:person]
end
test "it returns nil when no matching ci handles" do
auth = %{provider: :twitter, info: %{nickname: "joejoe"}}
assert Person.get_by_ueberauth(auth) == nil
end
test "it returns nil when no provider match" do
assert Person.get_by_ueberauth(%{}) == nil
end
end
end
| 30.969231
| 82
| 0.691505
|
03a8f3bd9642b2c17ac2b7f63f50418e31d4afdd
| 1,122
|
exs
|
Elixir
|
config/config.exs
|
hex337/attendance-phoenix
|
aaade35897b5910d00f2c047cc29bfe2d213f786
|
[
"MIT"
] | null | null | null |
config/config.exs
|
hex337/attendance-phoenix
|
aaade35897b5910d00f2c047cc29bfe2d213f786
|
[
"MIT"
] | null | null | null |
config/config.exs
|
hex337/attendance-phoenix
|
aaade35897b5910d00f2c047cc29bfe2d213f786
|
[
"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 :attendance,
ecto_repos: [Attendance.Repo]
# Configures the endpoint
config :attendance, AttendanceWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "9gQr8kwekjAY+bfu0C6TrbsxwOqj+VIVqfYlAP+VupRUlRAeblhOoNpwSBpmEgro",
render_errors: [view: AttendanceWeb.ErrorView, accepts: ~w(json)],
pubsub: [name: Attendance.PubSub,
adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:user_id]
# Guardian
config :attendance, Attendance.Guardian,
issuer: "Quantum Attendance",
secret_key: "W8Rr+VAqZLqSexEgcnOyfkiDY2/AlkPapq/UKDNz5rESvbNQjoIWLMZ+ulaKJpbk"
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
| 34
| 86
| 0.765597
|
03a8fdb5eaf362cca171e066570959e960d57623
| 568
|
exs
|
Elixir
|
config/test.exs
|
megalithic/canon
|
8178207cdaf1f137fcdf1f42481636e0209dcbeb
|
[
"MIT"
] | null | null | null |
config/test.exs
|
megalithic/canon
|
8178207cdaf1f137fcdf1f42481636e0209dcbeb
|
[
"MIT"
] | null | null | null |
config/test.exs
|
megalithic/canon
|
8178207cdaf1f137fcdf1f42481636e0209dcbeb
|
[
"MIT"
] | null | null | null |
use Mix.Config
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :canon, CanonWeb.Endpoint,
http: [port: 4002],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
# Configure your database
config :canon, Canon.Repo,
username: "postgres",
password: "postgres",
database: "canon_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
config :argon2_elixir, t_cost: 2, m_cost: 8
# config :bcrypt_elixir, log_rounds: 4
# config :pbkdf2_elixir, rounds: 1
| 24.695652
| 56
| 0.730634
|
03a921d941be14674324015dc54e7561e45d726c
| 1,152
|
ex
|
Elixir
|
apps/omg_jsonrpc/lib/server.ex
|
SingularityMatrix/elixir-omg
|
7db3fcc3adfa303e30ff7703148cc5110b587d20
|
[
"Apache-2.0"
] | null | null | null |
apps/omg_jsonrpc/lib/server.ex
|
SingularityMatrix/elixir-omg
|
7db3fcc3adfa303e30ff7703148cc5110b587d20
|
[
"Apache-2.0"
] | null | null | null |
apps/omg_jsonrpc/lib/server.ex
|
SingularityMatrix/elixir-omg
|
7db3fcc3adfa303e30ff7703148cc5110b587d20
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2018 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule OMG.JSONRPC.Server.Handler do
@moduledoc """
Exposes an API via jsonrpc 2.0 over HTTP. It leverages the generic `OMG.JSONRPC.Exposer` convenience module
Only handles the integration with the JSONRPC2 package
"""
use JSONRPC2.Server.Handler
# Compile time configuration:
# Compiling :omg_jsonrpc as a dependency requires setting this environmental variable
@api_module Application.fetch_env!(:omg_jsonrpc, :api_module)
def handle_request(method, params) do
OMG.JSONRPC.Exposer.handle_request_on_api(method, params, @api_module)
end
end
| 37.16129
| 109
| 0.770833
|
03a9362576bc34dd0f164451f252245cfac85885
| 339
|
exs
|
Elixir
|
priv/repo/migrations/20151225091657_create_list.exs
|
gridgentoo/ElixirTrelloKanban
|
11b91d9d864d2e332a94838d43c7a9b1015e17c6
|
[
"MIT"
] | 2,784
|
2016-01-06T03:16:07.000Z
|
2022-03-14T03:52:20.000Z
|
priv/repo/migrations/20151225091657_create_list.exs
|
gridgentoo/ElixirTrelloKanban
|
11b91d9d864d2e332a94838d43c7a9b1015e17c6
|
[
"MIT"
] | 49
|
2016-01-07T11:48:10.000Z
|
2020-04-27T16:10:12.000Z
|
priv/repo/migrations/20151225091657_create_list.exs
|
gridgentoo/ElixirTrelloKanban
|
11b91d9d864d2e332a94838d43c7a9b1015e17c6
|
[
"MIT"
] | 586
|
2016-01-11T17:02:13.000Z
|
2021-12-01T10:54:47.000Z
|
defmodule PhoenixTrello.Repo.Migrations.CreateList do
use Ecto.Migration
def change do
create table(:lists) do
add :name, :string, null: false
add :position, :integer, defaul: 0
add :board_id, references(:boards, on_delete: :delete_all)
timestamps
end
create index(:lists, [:board_id])
end
end
| 21.1875
| 64
| 0.675516
|
03a95089aff349014be4ee2c695ab103e9a806a9
| 7,313
|
ex
|
Elixir
|
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/api/user_role_permission_groups.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1
|
2021-12-20T03:40:53.000Z
|
2021-12-20T03:40:53.000Z
|
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/api/user_role_permission_groups.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1
|
2020-08-18T00:11:23.000Z
|
2020-08-18T00:44:16.000Z
|
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/api/user_role_permission_groups.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V33.Api.UserRolePermissionGroups do
@moduledoc """
API calls for all endpoints tagged `UserRolePermissionGroups`.
"""
alias GoogleApi.DFAReporting.V33.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets one user role permission group by ID.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `id` (*type:* `String.t`) - User role permission group ID.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V33.Model.UserRolePermissionGroup{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_user_role_permission_groups_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V33.Model.UserRolePermissionGroup.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def dfareporting_user_role_permission_groups_get(
connection,
profile_id,
id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/dfareporting/v3.3/userprofiles/{profileId}/userRolePermissionGroups/{id}",
%{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1),
"id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/))
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DFAReporting.V33.Model.UserRolePermissionGroup{}]
)
end
@doc """
Gets a list of all supported user role permission groups.
## Parameters
* `connection` (*type:* `GoogleApi.DFAReporting.V33.Connection.t`) - Connection to server
* `profile_id` (*type:* `String.t`) - User profile ID associated with this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DFAReporting.V33.Model.UserRolePermissionGroupsListResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dfareporting_user_role_permission_groups_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DFAReporting.V33.Model.UserRolePermissionGroupsListResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def dfareporting_user_role_permission_groups_list(
connection,
profile_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/dfareporting/v3.3/userprofiles/{profileId}/userRolePermissionGroups", %{
"profileId" => URI.encode(profile_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DFAReporting.V33.Model.UserRolePermissionGroupsListResponse{}]
)
end
end
| 40.854749
| 196
| 0.624778
|
03a95a934565a97566356f763267cb6acdf5331a
| 286
|
exs
|
Elixir
|
test/cableclub_web/live/page_live_test.exs
|
CableClub/cable-club-core
|
70c67c7a105dea83f2c1a1e2ee75a1ee97713bfb
|
[
"Apache-2.0"
] | null | null | null |
test/cableclub_web/live/page_live_test.exs
|
CableClub/cable-club-core
|
70c67c7a105dea83f2c1a1e2ee75a1ee97713bfb
|
[
"Apache-2.0"
] | null | null | null |
test/cableclub_web/live/page_live_test.exs
|
CableClub/cable-club-core
|
70c67c7a105dea83f2c1a1e2ee75a1ee97713bfb
|
[
"Apache-2.0"
] | null | null | null |
defmodule CableClubWeb.PageLiveTest do
use CableClubWeb.ConnCase
import Phoenix.LiveViewTest
test "disconnected and connected render", %{conn: conn} do
{:ok, page_live, disconnected_html} = live(conn, "/")
assert disconnected_html
assert render(page_live)
end
end
| 23.833333
| 60
| 0.744755
|
03a96267230b5089ad460d5e534bdad0d0cd3692
| 1,665
|
ex
|
Elixir
|
frameworks/Elixir/phoenix/web/controllers/page_controller.ex
|
kbrock/FrameworkBenchmarks
|
18e0797cd82438d4d37e0bc964dcc22dc48c0cb0
|
[
"BSD-3-Clause"
] | null | null | null |
frameworks/Elixir/phoenix/web/controllers/page_controller.ex
|
kbrock/FrameworkBenchmarks
|
18e0797cd82438d4d37e0bc964dcc22dc48c0cb0
|
[
"BSD-3-Clause"
] | 2
|
2022-01-21T23:51:43.000Z
|
2022-01-21T23:51:45.000Z
|
frameworks/Elixir/phoenix/web/controllers/page_controller.ex
|
kbrock/FrameworkBenchmarks
|
18e0797cd82438d4d37e0bc964dcc22dc48c0cb0
|
[
"BSD-3-Clause"
] | null | null | null |
defmodule Hello.PageController do
use Hello.Web, :controller
alias Hello.World
alias Hello.Fortune
def index(conn, _params) do
conn
|> json(%{"TE Benchmarks\n" => "Started"})
end
# avoid namespace collision
def _json(conn, _params) do
conn
|> json(%{message: "Hello, world!"})
end
def db(conn, _params) do
conn
|> json(Repo.get(World, :rand.uniform(10000)))
end
def queries(conn, params) do
q = try do
case String.to_integer(params["queries"]) do
x when x < 1 -> 1
x when x > 500 -> 500
x -> x
end
rescue
ArgumentError -> 1
end
conn
|> json(Enum.map(1..q, fn _ -> Repo.get(World, :rand.uniform(10000)) end))
end
def fortunes(conn, _params) do
additional_fortune = %Fortune{
id: 0,
message: "Additional fortune added at request time."
}
fortunes = [additional_fortune | Repo.all(Fortune)]
render conn, "fortunes.html", fortunes: Enum.sort(fortunes, fn f1, f2 -> f1.message < f2.message end)
end
def updates(conn, params) do
q = try do
case String.to_integer(params["queries"]) do
x when x < 1 -> 1
x when x > 500 -> 500
x -> x
end
rescue
ArgumentError -> 1
end
conn
|> json(Enum.map(1..q, fn _ ->
id = :rand.uniform(10000)
num = :rand.uniform(10000)
w = Repo.get(World, id)
changeset = World.changeset(w, %{randomnumber: num})
Repo.update(changeset)
%{id: id, randomnumber: num}
end))
end
def plaintext(conn, _params) do
conn
|> text("Hello, world!")
end
end
| 22.2
| 105
| 0.572973
|
03a9728cc116d6864f8fb6457f2993d4410c9d73
| 3,375
|
ex
|
Elixir
|
clients/content/lib/google_api/content/v21/model/account_item_updates.ex
|
mopp/elixir-google-api
|
d496227d17600bccbdf8f6be9ad1b7e7219d7ec6
|
[
"Apache-2.0"
] | null | null | null |
clients/content/lib/google_api/content/v21/model/account_item_updates.ex
|
mopp/elixir-google-api
|
d496227d17600bccbdf8f6be9ad1b7e7219d7ec6
|
[
"Apache-2.0"
] | null | null | null |
clients/content/lib/google_api/content/v21/model/account_item_updates.ex
|
mopp/elixir-google-api
|
d496227d17600bccbdf8f6be9ad1b7e7219d7ec6
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Content.V21.Model.AccountItemUpdates do
@moduledoc """
Turning on [item updates](https://support.google.com/merchants/answer/3246284) allows Google to automatically update items for you. When item updates are on, Google uses the structured data markup on the website and advanced data extractors to update the price and availability of the items. When the item updates are off, items with mismatched data aren't shown.
## Attributes
* `accountItemUpdatesSettings` (*type:* `GoogleApi.Content.V21.Model.AccountItemUpdatesSettings.t`, *default:* `nil`) - Determines which attributes of the items should be automatically updated. If this field is not present, then the settings will be deleted. If there are no settings for subaccount, they are inherited from aggregator.
* `effectiveAllowAvailabilityUpdates` (*type:* `boolean()`, *default:* `nil`) - Output only. The effective value of allow_availability_updates. If account_item_updates_settings is present, then this value is the same. Otherwise, it represents the inherited value of the parent account. Read-only.
* `effectiveAllowPriceUpdates` (*type:* `boolean()`, *default:* `nil`) - Output only. The effective value of allow_price_updates. If account_item_updates_settings is present, then this value is the same. Otherwise, it represents the inherited value of the parent account. Read-only.
* `effectiveAllowStrictAvailabilityUpdates` (*type:* `boolean()`, *default:* `nil`) - Output only. The effective value of allow_strict_availability_updates. If account_item_updates_settings is present, then this value is the same. Otherwise, it represents the inherited value of the parent account. Read-only.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:accountItemUpdatesSettings =>
GoogleApi.Content.V21.Model.AccountItemUpdatesSettings.t() | nil,
:effectiveAllowAvailabilityUpdates => boolean() | nil,
:effectiveAllowPriceUpdates => boolean() | nil,
:effectiveAllowStrictAvailabilityUpdates => boolean() | nil
}
field(:accountItemUpdatesSettings, as: GoogleApi.Content.V21.Model.AccountItemUpdatesSettings)
field(:effectiveAllowAvailabilityUpdates)
field(:effectiveAllowPriceUpdates)
field(:effectiveAllowStrictAvailabilityUpdates)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.AccountItemUpdates do
def decode(value, options) do
GoogleApi.Content.V21.Model.AccountItemUpdates.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.AccountItemUpdates do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 59.210526
| 365
| 0.769481
|
03a97d178c4b9e2ab11df9f3abcd3a884ad8171b
| 549
|
ex
|
Elixir
|
lib/analytics/service/consumer_dynamic_supervisor.ex
|
OnceApp/Analytics
|
4d3d6fd5eb5c7ec18b4df23515bb25661df818d9
|
[
"MIT"
] | null | null | null |
lib/analytics/service/consumer_dynamic_supervisor.ex
|
OnceApp/Analytics
|
4d3d6fd5eb5c7ec18b4df23515bb25661df818d9
|
[
"MIT"
] | null | null | null |
lib/analytics/service/consumer_dynamic_supervisor.ex
|
OnceApp/Analytics
|
4d3d6fd5eb5c7ec18b4df23515bb25661df818d9
|
[
"MIT"
] | 1
|
2019-08-08T16:39:56.000Z
|
2019-08-08T16:39:56.000Z
|
defmodule Analytics.ConsumerDynamicSupervisor do
use DynamicSupervisor
def start_link(_) do
DynamicSupervisor.start_link(__MODULE__, :ok, name: __MODULE__)
end
def start_child(type, pid_to_subscribe) do
DynamicSupervisor.start_child(
__MODULE__,
%{
id: Analytics.ConsumerSupervisor,
start: {Analytics.ConsumerSupervisor, :start_link, [type, pid_to_subscribe]},
restart: :transient
}
)
end
@impl true
def init(:ok) do
DynamicSupervisor.init(strategy: :one_for_one)
end
end
| 22.875
| 85
| 0.703097
|
03a9a6d25ac0b6430b01629860b3844649158b99
| 2,393
|
ex
|
Elixir
|
clients/cloud_deploy/lib/google_api/cloud_deploy/v1/model/date.ex
|
renovate-bot/elixir-google-api
|
1da34cd39b670c99f067011e05ab90af93fef1f6
|
[
"Apache-2.0"
] | 1
|
2021-12-20T03:40:53.000Z
|
2021-12-20T03:40:53.000Z
|
clients/cloud_deploy/lib/google_api/cloud_deploy/v1/model/date.ex
|
swansoffiee/elixir-google-api
|
9ea6d39f273fb430634788c258b3189d3613dde0
|
[
"Apache-2.0"
] | 1
|
2020-08-18T00:11:23.000Z
|
2020-08-18T00:44:16.000Z
|
clients/cloud_deploy/lib/google_api/cloud_deploy/v1/model/date.ex
|
dazuma/elixir-google-api
|
6a9897168008efe07a6081d2326735fe332e522c
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudDeploy.V1.Model.Date do
@moduledoc """
Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values * A month and day value, with a zero year, such as an anniversary * A year on its own, with zero month and day values * A year and month value, with a zero day, such as a credit card expiration date Related types are google.type.TimeOfDay and `google.protobuf.Timestamp`.
## Attributes
* `day` (*type:* `integer()`, *default:* `nil`) - Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant.
* `month` (*type:* `integer()`, *default:* `nil`) - Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day.
* `year` (*type:* `integer()`, *default:* `nil`) - Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:day => integer() | nil,
:month => integer() | nil,
:year => integer() | nil
}
field(:day)
field(:month)
field(:year)
end
defimpl Poison.Decoder, for: GoogleApi.CloudDeploy.V1.Model.Date do
def decode(value, options) do
GoogleApi.CloudDeploy.V1.Model.Date.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudDeploy.V1.Model.Date do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 45.150943
| 567
| 0.713331
|
03aa2005ee2c32056a5a301192d265c6ba285014
| 716
|
ex
|
Elixir
|
lib/doc/endpoint.ex
|
IanLuites/api_doc
|
b93ac8d82888c96bde7c55a08ec5716926976097
|
[
"MIT"
] | 1
|
2020-01-12T03:41:03.000Z
|
2020-01-12T03:41:03.000Z
|
lib/doc/endpoint.ex
|
IanLuites/api_doc
|
b93ac8d82888c96bde7c55a08ec5716926976097
|
[
"MIT"
] | 1
|
2019-04-17T15:32:15.000Z
|
2019-04-17T15:32:15.000Z
|
lib/doc/endpoint.ex
|
IanLuites/api_doc
|
b93ac8d82888c96bde7c55a08ec5716926976097
|
[
"MIT"
] | null | null | null |
defmodule APIDoc.Doc.Endpoint do
@moduledoc ~S"""
"""
alias APIDoc.Doc.{Param, Response}
@typedoc @moduledoc
@type t :: %__MODULE__{
method: :get | :post | :put | :patch | :delete,
path: [String.t() | atom],
id: String.t(),
summary: String.t(),
description: String.t() | nil,
parameters: [Param.t()],
responses: [Response.t()],
tags: [String.t()],
security: [atom | [atom]]
}
@enforce_keys [
:method,
:path,
:id,
:summary
]
defstruct [
:method,
:path,
:id,
:summary,
description: nil,
parameters: [],
responses: [],
tags: [],
security: []
]
end
| 18.842105
| 57
| 0.488827
|
03aa27abdfccfdaa6c0d9d9fedc76508721fcc7b
| 495
|
ex
|
Elixir
|
lib/codenamex_web/views/error_view.ex
|
bernardoamc/codenamex
|
6e3219569e4d9b8f4fe9273145b372ba182ab945
|
[
"MIT"
] | null | null | null |
lib/codenamex_web/views/error_view.ex
|
bernardoamc/codenamex
|
6e3219569e4d9b8f4fe9273145b372ba182ab945
|
[
"MIT"
] | 2
|
2020-07-20T14:23:21.000Z
|
2020-08-01T21:18:45.000Z
|
lib/codenamex_web/views/error_view.ex
|
bernardoamc/codenamex
|
6e3219569e4d9b8f4fe9273145b372ba182ab945
|
[
"MIT"
] | null | null | null |
defmodule CodenamexWeb.ErrorView do
use CodenamexWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.html", _assigns) do
# "Internal Server Error"
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.html" becomes
# "Not Found".
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| 29.117647
| 61
| 0.737374
|
03aa4d1e380d6751439e8f8977fbb4405fe26c52
| 1,866
|
ex
|
Elixir
|
clients/container_analysis/lib/google_api/container_analysis/v1alpha1/model/installation.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/container_analysis/lib/google_api/container_analysis/v1alpha1/model/installation.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/container_analysis/lib/google_api/container_analysis/v1alpha1/model/installation.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.ContainerAnalysis.V1alpha1.Model.Installation do
@moduledoc """
This represents how a particular software package may be installed on
a system.
## Attributes
* `location` (*type:* `list(GoogleApi.ContainerAnalysis.V1alpha1.Model.Location.t)`, *default:* `nil`) - All of the places within the filesystem versions of this package
have been found.
* `name` (*type:* `String.t`, *default:* `nil`) - Output only. The name of the installed package.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:location => list(GoogleApi.ContainerAnalysis.V1alpha1.Model.Location.t()),
:name => String.t()
}
field(:location, as: GoogleApi.ContainerAnalysis.V1alpha1.Model.Location, type: :list)
field(:name)
end
defimpl Poison.Decoder, for: GoogleApi.ContainerAnalysis.V1alpha1.Model.Installation do
def decode(value, options) do
GoogleApi.ContainerAnalysis.V1alpha1.Model.Installation.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ContainerAnalysis.V1alpha1.Model.Installation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.884615
| 173
| 0.740622
|
03aa8b8a10a4adf30e935785d19664778497f750
| 11,899
|
exs
|
Elixir
|
test/credo/check/warning/unused_string_operation_test.exs
|
elixir-twister/credo
|
619e0ec6e244c5e0c12eeeb58ed9de97e1571d99
|
[
"MIT"
] | null | null | null |
test/credo/check/warning/unused_string_operation_test.exs
|
elixir-twister/credo
|
619e0ec6e244c5e0c12eeeb58ed9de97e1571d99
|
[
"MIT"
] | null | null | null |
test/credo/check/warning/unused_string_operation_test.exs
|
elixir-twister/credo
|
619e0ec6e244c5e0c12eeeb58ed9de97e1571d99
|
[
"MIT"
] | null | null | null |
defmodule Credo.Check.Warning.UnusedStringOperationTest do
use Credo.TestHelper
@described_check Credo.Check.Warning.UnusedStringOperation
test "it should NOT report expected code" do
"""
defmodule CredoSampleModule do
def some_function(parameter1, parameter2) do
String.split(parameter1) + parameter2
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report when result is piped" do
"""
defmodule CredoSampleModule do
def some_function(parameter1, parameter2) do
String.split(parameter1)
|> some_where
parameter1
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when end of pipe AND return value" do
"""
defmodule CredoSampleModule do
def some_function(parameter1, parameter2) do
parameter1 + parameter2
|> String.split(parameter1)
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when inside of pipe" do
"""
defmodule CredoSampleModule do
def some_function(parameter1, parameter2) do
parameter1 + parameter2
|> String.split(parameter1)
|> some_func_who_knows_what_it_does
:ok
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when inside an assignment" do
"""
defmodule CredoSampleModule do
def some_function(parameter1, parameter2) do
offset = String.length(line) - String.length(String.trim(line))
parameter1 + parameter2 + offset
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when inside a condition" do
"""
defmodule CredoSampleModule do
def some_function(parameter1, parameter2) do
if String.length(x1) > String.length(String.trim(x2)) do
cond do
String.trim(x3) == "" -> IO.puts("1")
String.length(x) == 15 -> IO.puts("2")
String.replace(x, "a", "b") == "b" -> IO.puts("2")
end
else
case String.length(x3) do
0 -> true
1 -> false
_ -> something
end
end
unless String.trim(x4) == "" do
IO.puts "empty"
end
parameter1 + parameter2 + offset
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when inside a quote" do
"""
defmodule CredoSampleModule do
defp category_body(nil) do
quote do
__MODULE__
|> Module.split
|> Enum.at(2)
|> String.downcase
|> String.to_atom
end
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when inside of assignment" do
"""
defmodule CredoSampleModule do
defp print_issue(%Issue{check: check, message: message, filename: filename, priority: priority} = issue, source_file) do
pos =
pos_string(issue.line_no, issue.column)
[
Output.issue_color(issue), "┃ ",
Output.check_tag(check), " ", priority |> Output.priority_arrow,
:normal, :white, " ", message,
]
|> IO.ANSI.format
|> IO.puts
if issue.column do
offset = String.length(line) - String.length(String.trim(line))
[
String.duplicate(" ", x), :faint, String.duplicate("^", w),
]
|> IO.puts
end
[Output.issue_color(issue), :faint, "┃ "]
|> IO.ANSI.format
|> IO.puts
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when call is buried in else block but is the last call" do
"""
defmodule CredoSampleModule do
defp print_issue(%Issue{check: check, message: message, filename: filename, priority: priority} = issue, source_file) do
if issue.column do
IO.puts "."
else
[:this_actually_might_return, String.duplicate("^", w), :ok] # THIS is not the last_call!
end
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when call is buried in else block and is not the last call, but the result is assigned to a variable" do
"""
defmodule CredoSampleModule do
defp print_issue(%Issue{check: check, message: message, filename: filename, priority: priority} = issue, source_file) do
result =
if issue.column do
IO.puts "."
else
[:this_goes_nowhere, String.duplicate("^", w)]
end
IO.puts "8"
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when buried in :if, :when and :fn 2" do
"""
defmodule CredoSampleModule do
defp print_issue(%Issue{check: check, message: message, filename: filename, priority: priority} = issue, source_file) do
if issue.column do
IO.puts "."
else
case check do
true -> false
_ ->
Enum.reduce(arr, fn(w) ->
[:this_might_return, String.duplicate("^", w)]
end)
end
end
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when :for and :case" do
"""
defmodule CredoSampleModule do
defp convert_parsers(parsers) do
for parser <- parsers do
case Atom.to_string(parser) do
"Elixir." <> _ -> parser
reference -> String.upcase(reference)
end
end
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when part of a function call" do
"""
defmodule CredoSampleModule do
defp convert_parsers(parsers) do
for parser <- parsers do
case Atom.to_string(parser) do
"Elixir." <> _ -> parser
reference -> Module.concat(Plug.Parsers, String.upcase(reference))
end
end
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when :for and :case 2" do
"""
defmodule CredoSampleModule do
defp convert_parsers(parsers) do
for segment <- String.split(bin, "/"), segment != "", do: segment
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when in :after block" do
"""
defp my_function(fun, opts) do
try do
:fprof.analyse(
dest: analyse_dest,
totals: true,
details: Keyword.get(opts, :details, false),
callers: Keyword.get(opts, :callers, false),
sort: sorting
)
else
:ok ->
{_in, analysis_output} = StringIO.contents(analyse_dest)
String.to_charlist(analysis_output)
after
StringIO.close(analyse_dest)
end
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when in function call" do
"""
def my_function(url) when is_binary(url) do
if info.userinfo do
destructure [username, password], String.split(info.userinfo, ":")
end
Enum.reject(opts, fn {_k, v} -> is_nil(v) end)
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when in function call 2" do
"""
defp print_process(pid_atom, count, own) do
IO.puts([?", String.duplicate("-", 100)])
IO.write format_item(Path.join(path, item), String.pad_trailing(item, width))
print_row(["s", "B", "s", ".3f", "s"], [count, "", own, ""])
end
""" |> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report a violation when in list that is returned" do
"""
defp indent_line(str, indentation, with \\\\ " ") do
[String.duplicate(with, indentation), str]
end
""" |> to_source_file
|> refute_issues(@described_check)
end
##############################################################################
##############################################################################
test "it should report a violation" do
"""
defmodule CredoSampleModule do
def some_function(parameter1, parameter2) do
x = parameter1 + parameter2
String.split(parameter1)
parameter1
end
end
""" |> to_source_file
|> assert_issue(@described_check)
end
test "it should report a violation when end of pipe" do
"""
defmodule CredoSampleModule do
def some_function(parameter1, parameter2) do
parameter1 + parameter2
|> String.split(parameter1)
parameter1
end
end
""" |> to_source_file
|> assert_issue(@described_check)
end
test "it should report a violation when buried in :if" do
"""
defmodule CredoSampleModule do
defp print_issue(%Issue{check: check, message: message, filename: filename, priority: priority} = issue, source_file) do
if issue.column do
[
:this_goes_nowhere,
String.duplicate("^", w) # THIS is not the last_call!
]
IO.puts "."
else
IO.puts "x"
end
end
end
""" |> to_source_file
|> assert_issue(@described_check)
end
test "it should report a violation when buried in :else" do
"""
defmodule CredoSampleModule do
defp print_issue(%Issue{check: check, message: message, filename: filename, priority: priority} = issue, source_file) do
if issue.column do
IO.puts "."
else
String.trim(filename)
IO.puts "x"
end
end
end
""" |> to_source_file
|> assert_issue(@described_check)
end
test "it should report a violation when buried in :if, :when and :fn" do
"""
defmodule CredoSampleModule do
defp print_issue(%Issue{check: check, message: message, filename: filename, priority: priority} = issue, source_file) do
if issue.column do
IO.puts "."
else
case check do
true -> false
_ ->
Enum.reduce(arr, fn(w) ->
[:this_goes_nowhere, String.duplicate("^", w)]
end)
end
end
IO.puts "x"
end
end
""" |> to_source_file
|> assert_issue(@described_check)
end
test "it should report a violation when call is buried in else block but is the last call" do
"""
defmodule CredoSampleModule do
defp print_issue(%Issue{check: check, message: message, filename: filename, priority: priority} = issue, source_file) do
if issue.column do
IO.puts "."
else
[:this_goes_nowhere, String.duplicate("^", w)] # THIS is not the last_call!
end
IO.puts
end
end
""" |> to_source_file
|> assert_issue(@described_check)
end
test "it should report a violation when call is buried in else block but is the last call 2" do
"""
defmodule CredoSampleModule do
defp print_issue(%Issue{check: check, message: message, filename: filename, priority: priority} = issue, source_file) do
if issue.column do
IO.puts "."
else
[:this_goes_nowhere, String.duplicate("^", w)] # THIS is not the last_call!
IO.puts " "
end
end
end
""" |> to_source_file
|> assert_issue(@described_check, fn(issue) ->
assert "String.duplicate" == issue.trigger
end)
end
test "it should report several violations" do
"""
defmodule CredoSampleModule do
def some_function(parameter1, parameter2) do
String.split(parameter1)
parameter1
end
def some_function2(parameter1, parameter2) do
String.trim(parameter1)
parameter1
end
def some_function3(parameter1, parameter2) do
String.trim(parameter1)
parameter1
end
end
""" |> to_source_file
|> assert_issues(@described_check, fn(issues) ->
assert 3 == Enum.count(issues)
end)
end
test "it should report a violation when used incorrectly, even inside a :for" do
"""
defmodule CredoSampleModule do
defp something(bin) do
for segment <- String.split(bin, "/"), segment != "" do
String.upcase(segment)
segment
end
end
end
""" |> to_source_file
|> assert_issue(@described_check, fn(issue) ->
assert "String.upcase" == issue.trigger
end)
end
end
| 25.371002
| 145
| 0.652324
|
03aac7eda4a508886c172ff482c3eb2459246650
| 2,844
|
ex
|
Elixir
|
lib/extracker/router.ex
|
Cantido/ex_tracker
|
32f5785a39b5da209e2a4564f6e004479283fc1e
|
[
"MIT"
] | 1
|
2021-11-23T04:29:37.000Z
|
2021-11-23T04:29:37.000Z
|
lib/extracker/router.ex
|
Cantido/ex_tracker
|
32f5785a39b5da209e2a4564f6e004479283fc1e
|
[
"MIT"
] | 6
|
2020-11-10T03:44:44.000Z
|
2022-02-28T11:05:39.000Z
|
lib/extracker/router.ex
|
Cantido/ex_tracker
|
32f5785a39b5da209e2a4564f6e004479283fc1e
|
[
"MIT"
] | 1
|
2020-01-08T16:23:42.000Z
|
2020-01-08T16:23:42.000Z
|
# SPDX-FileCopyrightText: 2021 Rosa Richter
#
# SPDX-License-Identifier: MIT
defmodule Extracker.Router do
@moduledoc false
use Plug.Router
if Mix.env() == :dev do
use Plug.Debugger
end
use Plug.ErrorHandler
plug(:match)
plug(:dispatch)
get "/announce" do
conn = fetch_query_params(conn)
%{
"info_hash" => info_hash,
"peer_id" => peer_id,
"port" => port,
"uploaded" => uploaded,
"downloaded" => downloaded,
"left" => left
} = conn.query_params
info_hash = Base.decode16!(info_hash, case: :mixed)
event =
case Map.get(conn.query_params, "event", "") do
"started" -> :started
"stopped" -> :stopped
"completed" -> :completed
_ -> :interval
end
ip =
if Map.has_key?(conn.query_params, "ip") do
{:ok, iptuple} = :inet.parse_address(String.to_charlist(conn.query_params["ip"]))
iptuple
else
conn.remote_ip
end
address = {ip, String.to_integer(port)}
progress =
{String.to_integer(uploaded), String.to_integer(downloaded), String.to_integer(left)}
announce_result =
Extracker.announce(
info_hash,
peer_id,
address,
progress,
event: event
)
with {:ok, response} <- announce_result,
format_type = format_type(conn),
response_body = Extracker.Format.format(response, format_type),
{:ok, response_binary} <- Bento.encode(response_body) do
send_resp(conn, 200, response_binary)
end
end
get "/scrape" do
results =
hashes(conn)
|> Map.new(fn x -> {x, Extracker.scrape(x)} end)
failures = Enum.filter(results, fn {_hash, {status, _result}} -> status == :error end)
if Enum.any?(failures) do
encoded =
Map.new(failures, fn {hash, failure} ->
{Base.encode16(hash, case: :lower), failure}
end)
raise RuntimeError, "One or more scrapes failed: #{inspect(encoded)}"
end
successes = Map.new(results, fn {hash, {:ok, result}} -> {hash, result} end)
case Bento.encode(successes) do
{:ok, bin} -> send_resp(conn, 200, bin)
end
end
defp format_type(conn) do
if compact_peers?(conn), do: :compact, else: :standard
end
defp compact_peers?(conn) do
conn.query_params["compact"] == "1"
end
defp hashes(conn) do
conn.query_string
|> URI.query_decoder()
|> Stream.filter(fn {k, _} -> k == "info_hash" end)
|> Stream.map(fn {_, v} -> Base.decode16!(v) end)
end
match _ do
send_resp(conn, 404, "Not Found")
end
@doc false
# sobelow_skip ["XSS.SendResp"]
def handle_errors(conn, %{kind: _kind, reason: _reason, stack: _stack}) do
send_resp(conn, conn.status, Bento.encode!(%{"failure reason" => "internal server error"}))
end
end
| 23.89916
| 95
| 0.607947
|
03ab046c0410887b5b2cf1a5da5d08bada9921f8
| 243
|
ex
|
Elixir
|
lib/cip.ex
|
fletchermoore/cip
|
5dd1c6f105d6a4c8c34a9e824cbad2fcf78a0655
|
[
"Unlicense"
] | null | null | null |
lib/cip.ex
|
fletchermoore/cip
|
5dd1c6f105d6a4c8c34a9e824cbad2fcf78a0655
|
[
"Unlicense"
] | null | null | null |
lib/cip.ex
|
fletchermoore/cip
|
5dd1c6f105d6a4c8c34a9e824cbad2fcf78a0655
|
[
"Unlicense"
] | null | null | null |
defmodule Cip do
@moduledoc """
Cip keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
end
| 24.3
| 66
| 0.744856
|
03ab1b2fa2dbb5f6d5d32849a32ee75d0ed0e2a4
| 2,418
|
ex
|
Elixir
|
clients/books/lib/google_api/books/v1/model/reading_position.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/books/lib/google_api/books/v1/model/reading_position.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/books/lib/google_api/books/v1/model/reading_position.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.Books.V1.Model.ReadingPosition do
@moduledoc """
## Attributes
* `epubCfiPosition` (*type:* `String.t`, *default:* `nil`) - Position in an EPUB as a CFI.
* `gbImagePosition` (*type:* `String.t`, *default:* `nil`) - Position in a volume for image-based content.
* `gbTextPosition` (*type:* `String.t`, *default:* `nil`) - Position in a volume for text-based content.
* `kind` (*type:* `String.t`, *default:* `books#readingPosition`) - Resource type for a reading position.
* `pdfPosition` (*type:* `String.t`, *default:* `nil`) - Position in a PDF file.
* `updated` (*type:* `DateTime.t`, *default:* `nil`) - Timestamp when this reading position was last updated (formatted UTC timestamp with millisecond resolution).
* `volumeId` (*type:* `String.t`, *default:* `nil`) - Volume id associated with this reading position.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:epubCfiPosition => String.t(),
:gbImagePosition => String.t(),
:gbTextPosition => String.t(),
:kind => String.t(),
:pdfPosition => String.t(),
:updated => DateTime.t(),
:volumeId => String.t()
}
field(:epubCfiPosition)
field(:gbImagePosition)
field(:gbTextPosition)
field(:kind)
field(:pdfPosition)
field(:updated, as: DateTime)
field(:volumeId)
end
defimpl Poison.Decoder, for: GoogleApi.Books.V1.Model.ReadingPosition do
def decode(value, options) do
GoogleApi.Books.V1.Model.ReadingPosition.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Books.V1.Model.ReadingPosition do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.2
| 167
| 0.687758
|
03ab37c3c2b61fded1a1aaff3a69cd2dde15d405
| 965
|
exs
|
Elixir
|
priv/repo/migrations/20200916073549_create_character_sessions.exs
|
Bentheburrito/caidata
|
31ee94691293b926de77194585714d75c80fea0d
|
[
"MIT"
] | null | null | null |
priv/repo/migrations/20200916073549_create_character_sessions.exs
|
Bentheburrito/caidata
|
31ee94691293b926de77194585714d75c80fea0d
|
[
"MIT"
] | null | null | null |
priv/repo/migrations/20200916073549_create_character_sessions.exs
|
Bentheburrito/caidata
|
31ee94691293b926de77194585714d75c80fea0d
|
[
"MIT"
] | null | null | null |
defmodule CAIData.Repo.Migrations.CreateCharacterSessions do
use Ecto.Migration
def change do
create table(:character_sessions) do
add :character_id, :string, size: 19
add :faction_id, :integer
add :name, :string, size: 70
add :kills, :integer
add :kills_hs, :integer
add :kills_ivi, :integer
add :kills_hs_ivi, :integer
add :deaths, :integer
add :deaths_ivi, :integer
add :shots_fired, :integer
add :shots_hit, :integer
add :vehicle_kills, :integer
add :vehicle_deaths, :integer
add :vehicle_bails, :integer
add :vehicles_destroyed, {:map, :integer} # Like %{"vehicle_name" => amount_killed}
add :vehicles_lost, {:map, :integer}
add :xp_earned, :integer
add :xp_types, {:map, :integer} # Like %{"xp_type_name" => amount_earned}
add :base_captures, :integer
add :base_defends, :integer
add :login_timestamp, :integer
add :logout_timestamp, :integer
add :archived, :boolean
end
end
end
| 30.15625
| 86
| 0.701554
|
03ab500db5aca1a318dc2d0394047f4bab0bd550
| 1,592
|
exs
|
Elixir
|
apps/graphql/test/unit/middleware/check_user_role_test.exs
|
ehealth-ua/ehealth.api
|
4ffe26a464fe40c95fb841a4aa2e147068f65ca2
|
[
"Apache-2.0"
] | 8
|
2019-06-14T11:34:49.000Z
|
2021-08-05T19:14:24.000Z
|
apps/graphql/test/unit/middleware/check_user_role_test.exs
|
edenlabllc/ehealth.api.public
|
4ffe26a464fe40c95fb841a4aa2e147068f65ca2
|
[
"Apache-2.0"
] | 1
|
2019-07-08T15:20:22.000Z
|
2019-07-08T15:20:22.000Z
|
apps/graphql/test/unit/middleware/check_user_role_test.exs
|
ehealth-ua/ehealth.api
|
4ffe26a464fe40c95fb841a4aa2e147068f65ca2
|
[
"Apache-2.0"
] | 6
|
2018-05-11T13:59:32.000Z
|
2022-01-19T20:15:22.000Z
|
defmodule GraphQL.Unit.Middleware.CheckUserRoleTest do
@moduledoc false
use ExUnit.Case, async: true
import Mox
alias Ecto.UUID
alias GraphQL.Middleware.{CheckUserRole, FormatErrors}
@query """
query ResourceQuery {
resourceField {database_id}
}
"""
setup :verify_on_exit!
defmodule Schema do
@moduledoc false
use Absinthe.Schema
use FormatErrors
query do
field :resource_field, list_of(:resource) do
middleware(CheckUserRole, role: "ADMIN")
resolve(fn _, _ -> {:ok, []} end)
end
end
object :resource do
field(:database_id, :id)
end
def context(_), do: %{client_id: UUID.generate(), consumer_id: UUID.generate()}
end
describe "check user role middleware" do
test "allowed" do
expect(MithrilMock, :search_user_roles, fn %{client_id: _, user_id: _}, _ ->
{:ok, %{"data" => [%{"role_name" => "ADMIN"}]}}
end)
{:ok, %{data: data}} = Absinthe.run(@query, Schema)
assert %{"resourceField" => []} == data
end
test "forbidden" do
expect(MithrilMock, :search_user_roles, fn _, _ ->
{:ok, %{"data" => []}}
end)
{:ok, %{errors: [error]}} = Absinthe.run(@query, Schema)
assert "FORBIDDEN" == error[:extensions][:code]
end
test "error from Mithril" do
expect(MithrilMock, :search_user_roles, fn _, _ ->
{:ok, %{"error" => %{}}}
end)
{:ok, %{errors: [error]}} = Absinthe.run(@query, Schema)
assert "INTERNAL_SERVER_ERROR" == error[:extensions][:code]
end
end
end
| 22.422535
| 83
| 0.598618
|
03ab7b712b2d29d6ee4029ea68491efb19723f24
| 248
|
ex
|
Elixir
|
lib/cbstats_importer/supervisor.ex
|
micahyoung/cbstats-importer
|
a7176b3a25d8a4e919ddda32475c9ecf65e9892a
|
[
"Unlicense",
"MIT"
] | 1
|
2016-01-06T18:19:35.000Z
|
2016-01-06T18:19:35.000Z
|
lib/cbstats_importer/supervisor.ex
|
micahyoung/cbstats-importer
|
a7176b3a25d8a4e919ddda32475c9ecf65e9892a
|
[
"Unlicense",
"MIT"
] | null | null | null |
lib/cbstats_importer/supervisor.ex
|
micahyoung/cbstats-importer
|
a7176b3a25d8a4e919ddda32475c9ecf65e9892a
|
[
"Unlicense",
"MIT"
] | null | null | null |
defmodule CbstatsImporter.Supervisor do
use Supervisor
def start_link do
:supervisor.start_link(__MODULE__, [])
end
def init([]) do
tree = [ worker(CbstatsImporter.Repo, []) ]
supervise(tree, strategy: :one_for_all)
end
end
| 19.076923
| 47
| 0.697581
|
03ab88ab55ab14e46edd55dd891589f246b23407
| 429
|
exs
|
Elixir
|
test/regressions/i072_quotes_in_linx_test.exs
|
ZeLarpMaster/earmark
|
35c9661d6647059e507c0278347e21d92351c417
|
[
"Apache-1.1"
] | null | null | null |
test/regressions/i072_quotes_in_linx_test.exs
|
ZeLarpMaster/earmark
|
35c9661d6647059e507c0278347e21d92351c417
|
[
"Apache-1.1"
] | null | null | null |
test/regressions/i072_quotes_in_linx_test.exs
|
ZeLarpMaster/earmark
|
35c9661d6647059e507c0278347e21d92351c417
|
[
"Apache-1.1"
] | 1
|
2020-03-31T19:53:15.000Z
|
2020-03-31T19:53:15.000Z
|
defmodule Regressions.I072QuotesInLinx do
use ExUnit.Case, async: true
test "Issue https://github.com/pragdave/earmark/issues/72" do
# assert Earmark.as_html!(~s{"Earmark"}) ==
# ~s{<p>“Earmark”</p>\n}
assert Earmark.as_html!(~s{["Earmark"](https://github.com/pragdave/earmark/)}) ==
~s{<p><a href="https://github.com/pragdave/earmark/">“Earmark”</a></p>\n}
end
end
# SPDX-License-Identifier: Apache-2.0
| 30.642857
| 85
| 0.664336
|
03ab9007073463fce1cbb379de1c177dbd666281
| 8,263
|
ex
|
Elixir
|
lib/level/posts/create_post.ex
|
mindriot101/level
|
0a2cbae151869c2d9b79b3bfb388f5d00739ae12
|
[
"Apache-2.0"
] | 928
|
2018-04-03T16:18:11.000Z
|
2019-09-09T17:59:55.000Z
|
lib/level/posts/create_post.ex
|
mindriot101/level
|
0a2cbae151869c2d9b79b3bfb388f5d00739ae12
|
[
"Apache-2.0"
] | 74
|
2018-04-03T00:46:50.000Z
|
2019-03-10T18:57:27.000Z
|
lib/level/posts/create_post.ex
|
mindriot101/level
|
0a2cbae151869c2d9b79b3bfb388f5d00739ae12
|
[
"Apache-2.0"
] | 89
|
2018-04-03T17:33:20.000Z
|
2019-08-19T03:40:20.000Z
|
defmodule Level.Posts.CreatePost do
@moduledoc false
import Ecto.Query
alias Ecto.Multi
alias Level.Events
alias Level.Files
alias Level.Groups
alias Level.Mentions
alias Level.Notifications
alias Level.Posts
alias Level.Repo
alias Level.Schemas.Group
alias Level.Schemas.Post
alias Level.Schemas.PostLocator
alias Level.Schemas.PostLog
alias Level.Schemas.SpaceBot
alias Level.Schemas.SpaceUser
alias Level.StringHelpers
alias Level.TaggedGroups
alias Level.WebPush
alias LevelWeb.Router.Helpers
# TODO: make this more specific
@type result :: {:ok, map()} | {:error, any(), any(), map()}
@doc """
Creates a new post.
"""
@spec perform(SpaceUser.t(), Group.t(), map()) :: result()
def perform(%SpaceUser{} = author, %Group{} = group, params) do
Multi.new()
|> insert_post(author, params)
|> save_locator(params)
|> set_primary_group(group)
|> detect_tagged_groups(author)
|> record_mentions(author)
|> attach_files(author, params)
|> log(author)
|> Repo.transaction()
|> after_user_post(author, params)
end
@spec perform(SpaceUser.t(), map()) :: result()
def perform(%SpaceUser{} = author, params) do
Multi.new()
|> insert_post(author, params)
|> save_locator(params)
|> detect_tagged_groups(author)
|> record_mentions(author)
|> attach_files(author, params)
|> log(author)
|> Repo.transaction()
|> after_user_post(author, params)
end
@spec perform(SpaceBot.t(), map()) :: result()
def perform(%SpaceBot{} = author, params) do
Multi.new()
|> insert_post(author, params)
|> save_locator(params)
|> detect_tagged_groups(author)
|> record_mentions(author)
|> attach_files(author, params)
|> log(author)
|> Repo.transaction()
|> after_bot_post(author, params)
end
# Internal
defp insert_post(multi, %SpaceUser{} = author, params) do
params_with_relations =
params
|> Map.put(:space_id, author.space_id)
|> Map.put(:space_user_id, author.id)
Multi.insert(multi, :post, Post.user_changeset(%Post{}, params_with_relations))
end
defp insert_post(multi, %SpaceBot{} = author, params) do
params_with_relations =
params
|> Map.put(:space_id, author.space_id)
|> Map.put(:space_bot_id, author.id)
Multi.insert(multi, :post, Post.bot_changeset(%Post{}, params_with_relations))
end
defp save_locator(multi, %{locator: params}) do
# TODO: validate that the author is allowed to use the scope
Multi.run(multi, :locator, fn %{post: post} ->
params = Map.merge(params, %{space_id: post.space_id, post_id: post.id})
%PostLocator{}
|> PostLocator.create_changeset(params)
|> Repo.insert()
end)
end
defp save_locator(multi, _), do: multi
defp set_primary_group(multi, group) do
Multi.run(multi, :primary_group, fn %{post: post} ->
Posts.publish_to_group(post, group)
{:ok, group}
end)
end
defp detect_tagged_groups(multi, author) do
Multi.run(multi, :tagged_groups, fn %{post: post} = result ->
groups =
author
|> TaggedGroups.get_tagged_groups(post.body)
|> Enum.reject(fn group ->
result[:primary_group] && result[:primary_group].id == group.id
end)
|> Enum.map(fn group ->
Posts.publish_to_group(post, group)
group
end)
{:ok, groups}
end)
end
defp record_mentions(multi, author) do
Multi.run(multi, :mentions, fn %{post: post} ->
Mentions.record(author, post)
end)
end
defp attach_files(multi, author, %{file_ids: file_ids}) do
Multi.run(multi, :files, fn %{post: post} ->
files = Files.get_files(author, file_ids)
Posts.attach_files(post, files)
end)
end
defp attach_files(multi, _, _) do
Multi.run(multi, :files, fn _ -> {:ok, []} end)
end
defp log(multi, author) do
Multi.run(multi, :log, fn %{post: post} ->
PostLog.post_created(post, author)
end)
end
defp gather_groups(%{primary_group: primary_group, tagged_groups: tagged_groups}) do
[primary_group | tagged_groups] |> Enum.uniq_by(fn group -> group.id end)
end
defp gather_groups(%{tagged_groups: tagged_groups}) do
tagged_groups |> Enum.uniq_by(fn group -> group.id end)
end
defp after_user_post({:ok, %{post: post} = result}, author, params) do
Posts.subscribe(author, [post])
subscribe_recipients(post, author, params)
subscribe_mentioned_users(post, result)
subscribe_mentioned_groups(post, result)
subscribe_watchers(result)
{:ok, subscribers} = Posts.get_subscribers(post)
record_notifications(post, subscribers)
send_push_notifications(result, author, subscribers)
send_events(post)
{:ok, result}
end
defp after_user_post(err, _, _), do: err
defp after_bot_post({:ok, %{post: post} = result}, author, params) do
subscribe_recipients(post, author, params)
subscribe_mentioned_users(post, result)
subscribe_mentioned_groups(post, result)
subscribe_watchers(result)
{:ok, subscribers} = Posts.get_subscribers(post)
record_notifications(post, subscribers)
send_push_notifications(result, author, subscribers)
send_events(post)
{:ok, result}
end
defp after_bot_post(err, _, _), do: err
defp subscribe_recipients(_post, _author, %{recipient_ids: []}), do: nil
defp subscribe_recipients(post, _author, %{recipient_ids: ids}) do
query =
from su in SpaceUser,
where: su.space_id == ^post.space_id,
where: su.id in ^ids,
where: su.state == "ACTIVE"
recipients = Repo.all(query)
Enum.each(recipients, fn recipient ->
Posts.mark_as_unread(recipient, [post])
end)
end
defp subscribe_recipients(_post, _author, _params), do: nil
defp subscribe_mentioned_users(post, %{mentions: %{space_users: mentioned_users}}) do
Enum.each(mentioned_users, fn mentioned_user ->
Posts.mark_as_unread(mentioned_user, [post])
end)
end
defp subscribe_mentioned_groups(post, %{mentions: %{groups: mentioned_groups}}) do
Enum.each(mentioned_groups, fn mentioned_group ->
{:ok, group_users} = Groups.list_all_memberships(mentioned_group)
group_users = Repo.preload(group_users, :space_user)
Enum.each(group_users, fn group_user ->
Posts.mark_as_unread(group_user.space_user, [post])
end)
end)
end
defp subscribe_watchers(%{post: post} = result) do
groups = gather_groups(result)
Enum.each(groups, fn group ->
subscribe_group_watchers(post, group)
end)
end
defp subscribe_group_watchers(post, group) do
{:ok, watching_group_users} = Groups.list_all_watchers(group)
space_users =
watching_group_users
|> Repo.preload(:space_user)
|> Enum.map(fn group_user -> group_user.space_user end)
space_users
|> Enum.each(fn space_user ->
if space_user.id !== post.space_user_id do
Posts.mark_as_unread(space_user, [post])
end
end)
end
defp record_notifications(post, subscribers) do
Enum.each(subscribers, fn subscriber ->
if subscriber.id !== post.space_user_id do
Notifications.record_post_created(subscriber, post)
end
end)
end
defp send_push_notifications(
%{post: %Post{is_urgent: true} = post},
author,
subscribers
) do
payload = build_push_payload(post, author)
subscribers
|> Enum.each(fn %SpaceUser{id: id, user_id: user_id} ->
if id !== author.id do
WebPush.send_web_push(user_id, payload)
end
end)
end
defp send_push_notifications(_, _, _), do: true
defp build_push_payload(post, author) do
post = Repo.preload(post, :space)
snippet = StringHelpers.truncate(post.body)
body = "@#{author.handle}: #{snippet}"
url = Helpers.main_path(LevelWeb.Endpoint, :index, [post.space.slug, "posts", post.id])
%WebPush.Payload{
title: post.space.name,
body: body,
tag: nil,
require_interaction: true,
url: url
}
end
defp send_events(post) do
{:ok, space_user_ids} = Posts.get_accessor_ids(post)
Events.post_created(space_user_ids, post)
end
end
| 27.543333
| 91
| 0.667191
|
03abccf12aa401118ff40460187f9cdb14ee1d1e
| 351
|
exs
|
Elixir
|
server/priv/repo/seeds.exs
|
d-exclaimation/echoppe
|
d430439a5fff28a15d44ccf9881caced89e7303f
|
[
"Apache-2.0"
] | 1
|
2021-05-13T00:53:52.000Z
|
2021-05-13T00:53:52.000Z
|
server/priv/repo/seeds.exs
|
d-exclaimation/ez-cart
|
d430439a5fff28a15d44ccf9881caced89e7303f
|
[
"Apache-2.0"
] | 1
|
2021-06-02T19:18:10.000Z
|
2021-06-07T16:44:36.000Z
|
server/priv/repo/seeds.exs
|
d-exclaimation/ez-cart
|
d430439a5fff28a15d44ccf9881caced89e7303f
|
[
"Apache-2.0"
] | null | null | null |
# 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:
#
# Echoppe.Repo.insert!(%Echoppe.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
| 29.25
| 61
| 0.706553
|
03abf8f597665e2983c6dea469cdaeb92e3199b1
| 2,405
|
ex
|
Elixir
|
lib/2020/day7.ex
|
Bentheburrito/adventofcode
|
6fca0933c2a0e541567fe9f8bc34df4a048b5d8a
|
[
"MIT"
] | null | null | null |
lib/2020/day7.ex
|
Bentheburrito/adventofcode
|
6fca0933c2a0e541567fe9f8bc34df4a048b5d8a
|
[
"MIT"
] | null | null | null |
lib/2020/day7.ex
|
Bentheburrito/adventofcode
|
6fca0933c2a0e541567fe9f8bc34df4a048b5d8a
|
[
"MIT"
] | null | null | null |
defmodule AOC.Day7 do
def run(input) do
rules = String.split(input, [" bags contain ", "\n"]) |> build_rules()
num = AOC.time(&num_bags_containing/2, [rules, "shiny gold"])
IO.puts "Num of bags containing shiny gold: #{num}"
num2 = AOC.time(&num_bags_inside/2, [rules, "shiny gold"])
IO.puts "Num of bags inside shiny gold: #{num2}"
end
# need increment counter for each level gone down
def num_bags_containing(rules, bag_color) do
{_sub_list, new_rules} = Map.pop!(rules, bag_color)
do_num_bags_containing(new_rules, bag_color)
end
def do_num_bags_containing(rules, bag_color) do
Enum.reduce(rules, %{}, fn ({bag, sub_bags}, remapped_rules) -> remap_by_color(bag, sub_bags, bag_color, rules, remapped_rules) |> elem(1) end)
|> Map.values() |> Enum.sum()
end
def remap_by_color(bag, [], _bag_color, _rules, remapped_rules), do: {0, Map.put(remapped_rules, bag, 0)}
def remap_by_color(bag, _sub_bags, _bag_color, _rules, remapped_rules) when is_map_key(remapped_rules, bag), do: {Map.get(remapped_rules, bag), remapped_rules}
def remap_by_color(bag, sub_bags, bag_color, rules, remapped_rules) do
if Enum.any?(sub_bags, &match?({_, ^bag_color}, &1)) do # check remapped_rules for a true value too?
{1, Map.put(remapped_rules, bag, 1)}
else
{nested_contains, nested_remapped_rules} = Enum.map_reduce(sub_bags, remapped_rules, fn ({_amount, next_bag}, acc) ->
next_sub_bags = Map.get(rules, next_bag)
remap_by_color(next_bag, next_sub_bags, bag_color, rules, acc)
end)
contains = Enum.any?(nested_contains, &(&1 == 1)) && 1 || 0
{contains, Map.put(nested_remapped_rules, bag, contains)}
end
end
def num_bags_inside(_rules, []), do: 0
def num_bags_inside(rules, target_bag) when not is_list(target_bag), do: num_bags_inside(rules, Map.get(rules, target_bag))
def num_bags_inside(rules, target_sub_bags) do
Enum.reduce(target_sub_bags, 0, fn ({amount, sub_bag}, count) -> amount + (num_bags_inside(rules, sub_bag) * amount) + count end)
end
def build_rules([], acc), do: acc
def build_rules([bag, contents | rem_rules], acc) do
sub_bags = for <<num::binary-size(1)>> <> " " <> sub_bag <- String.split(contents, [" bags, ", " bag, ", " bags.", " bag."], trim: true) do
{String.to_integer(num), sub_bag}
end
build_rules(rem_rules, Map.put(acc, bag, sub_bags))
end
def build_rules(rule_list), do: build_rules(rule_list, %{})
end
| 45.377358
| 160
| 0.708108
|
03ac191a449aa0fcc29f772d23a08ce1e83e05e3
| 1,080
|
ex
|
Elixir
|
test/support/conn_case.ex
|
MThomassen/graphql-server-benchmark-absinthe-
|
b2e0bdeeb135ffc2d83d67fe4aea19025dc9a6e6
|
[
"Apache-2.0"
] | null | null | null |
test/support/conn_case.ex
|
MThomassen/graphql-server-benchmark-absinthe-
|
b2e0bdeeb135ffc2d83d67fe4aea19025dc9a6e6
|
[
"Apache-2.0"
] | null | null | null |
test/support/conn_case.ex
|
MThomassen/graphql-server-benchmark-absinthe-
|
b2e0bdeeb135ffc2d83d67fe4aea19025dc9a6e6
|
[
"Apache-2.0"
] | null | null | null |
defmodule GraphqlServerWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
alias GraphqlServerWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint GraphqlServerWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(GraphqlServer.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(GraphqlServer.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 27.692308
| 75
| 0.725926
|
03ac1afbb0ae25b888831a78b45dbbf8d998c33e
| 82
|
exs
|
Elixir
|
Phoenix_Sockets/example1/test/example1_web/views/page_view_test.exs
|
shubhamagiwal/DOSFall2017
|
3c1522c4163f57402f147b50614d4051b05a080f
|
[
"MIT"
] | 3
|
2019-10-28T21:02:55.000Z
|
2020-10-01T02:29:37.000Z
|
Phoenix_Sockets/example1/test/example1_web/views/page_view_test.exs
|
shubhamagiwal/DOSFall2017
|
3c1522c4163f57402f147b50614d4051b05a080f
|
[
"MIT"
] | null | null | null |
Phoenix_Sockets/example1/test/example1_web/views/page_view_test.exs
|
shubhamagiwal/DOSFall2017
|
3c1522c4163f57402f147b50614d4051b05a080f
|
[
"MIT"
] | 4
|
2019-10-12T19:41:58.000Z
|
2021-09-24T20:24:47.000Z
|
defmodule Example1Web.PageViewTest do
use Example1Web.ConnCase, async: true
end
| 20.5
| 39
| 0.829268
|
03ac6a2b1f5d3cc3a75618cf5b31b097427b0628
| 475
|
ex
|
Elixir
|
template/$PROJECT_NAME$/lib/$PROJECT_NAME$/application.ex
|
aforward/gen_template_ecto_service
|
02d2cf88e4ba75dc68bedc604f8e31a3c67bcacb
|
[
"Apache-2.0"
] | 3
|
2017-08-18T15:08:43.000Z
|
2022-01-03T23:53:42.000Z
|
template/$PROJECT_NAME$/lib/$PROJECT_NAME$/application.ex
|
aforward/gen_template_ecto_service
|
02d2cf88e4ba75dc68bedc604f8e31a3c67bcacb
|
[
"Apache-2.0"
] | 1
|
2019-01-03T07:49:54.000Z
|
2019-01-03T07:49:54.000Z
|
template/$PROJECT_NAME$/lib/$PROJECT_NAME$/application.ex
|
aforward/gen_template_ecto_service
|
02d2cf88e4ba75dc68bedc604f8e31a3c67bcacb
|
[
"Apache-2.0"
] | 2
|
2017-09-19T00:27:55.000Z
|
2019-10-23T03:05:11.000Z
|
defmodule <%= @project_name_camel_case %>.Application do
@moduledoc false
# See http://elixir-lang.org/docs/stable/elixir/Application.html
use Application
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
worker(<%= @project_name_camel_case %>.Repo, []),
]
opts = [
strategy: :one_for_one,
name: <%= @project_name_camel_case %>.Supervisor
]
Supervisor.start_link(children, opts)
end
end
| 20.652174
| 66
| 0.656842
|
03ac9cec351f551a75ed1083085bbd8a8732eed0
| 56
|
ex
|
Elixir
|
lib/elirc/plugin/message/spam.ex
|
rockerBOO/elirc_twitch
|
6399f717c012df10df7914c216f5d3f9c425844c
|
[
"MIT"
] | 20
|
2015-06-18T03:30:58.000Z
|
2021-01-11T19:55:00.000Z
|
lib/elirc/plugin/message/spam.ex
|
rockerBOO/elirc_twitch
|
6399f717c012df10df7914c216f5d3f9c425844c
|
[
"MIT"
] | 1
|
2015-06-24T01:03:31.000Z
|
2015-06-24T12:41:21.000Z
|
lib/elirc/plugin/message/spam.ex
|
rockerBOO/elirc_twitch
|
6399f717c012df10df7914c216f5d3f9c425844c
|
[
"MIT"
] | 7
|
2015-06-22T14:25:12.000Z
|
2016-01-21T03:39:02.000Z
|
defmodule Elirc.Spam do
def find(message) do
end
end
| 9.333333
| 23
| 0.75
|
03acb68aade027d7674af5b2f9e3dea2103429eb
| 187
|
ex
|
Elixir
|
2019/elixir/aoc/lib/aoc.ex
|
drincruz/advent-of-code
|
45b639fc2eddfe45ed4387f7bf2be9a3d3cd6ec2
|
[
"MIT"
] | 1
|
2020-11-08T22:17:37.000Z
|
2020-11-08T22:17:37.000Z
|
2019/elixir/aoc/lib/aoc.ex
|
drincruz/advent-of-code
|
45b639fc2eddfe45ed4387f7bf2be9a3d3cd6ec2
|
[
"MIT"
] | null | null | null |
2019/elixir/aoc/lib/aoc.ex
|
drincruz/advent-of-code
|
45b639fc2eddfe45ed4387f7bf2be9a3d3cd6ec2
|
[
"MIT"
] | null | null | null |
defmodule Aoc do
@moduledoc """
Documentation for Aoc.
"""
@doc """
Hello world.
## Examples
iex> Aoc.hello()
:world
"""
def hello do
:world
end
end
| 9.842105
| 24
| 0.534759
|
03acb697e914c590b3410c57fdf5ba4febe0ca9a
| 812
|
ex
|
Elixir
|
lib/farmbot/system/config_storage/network_interface.ex
|
pdgonzalez872/farmbot_os
|
a444248f05ee8f4fe57f6a4865b942131960f76c
|
[
"MIT"
] | 2
|
2018-08-01T23:07:52.000Z
|
2018-10-17T12:49:21.000Z
|
lib/farmbot/system/config_storage/network_interface.ex
|
pdgonzalez872/farmbot_os
|
a444248f05ee8f4fe57f6a4865b942131960f76c
|
[
"MIT"
] | null | null | null |
lib/farmbot/system/config_storage/network_interface.ex
|
pdgonzalez872/farmbot_os
|
a444248f05ee8f4fe57f6a4865b942131960f76c
|
[
"MIT"
] | 1
|
2017-07-22T21:51:14.000Z
|
2017-07-22T21:51:14.000Z
|
defmodule Farmbot.System.ConfigStorage.NetworkInterface do
@moduledoc false
use Ecto.Schema
import Ecto.Changeset
use Farmbot.Logger
schema "network_interfaces" do
field(:name, :string, null: false)
field(:type, :string, null: false)
## For wireless interfaces
field(:ssid, :string)
field(:psk, :string)
field(:security, :string)
# Advanced settings.
field(:ipv4_method, :string)
field(:ipv4_address, :string)
field(:ipv4_gateway, :string)
field(:ipv4_subnet_mask, :string)
field(:domain, :string)
field(:name_servers, :string)
end
@required_fields [:name, :type]
def changeset(config, params \\ %{}) do
config
|> cast(params, @required_fields)
|> validate_required(@required_fields)
|> unique_constraint(:name)
end
end
| 23.2
| 58
| 0.678571
|
03acba56796a6413e8938bc0e78913242f1f8748
| 3,224
|
ex
|
Elixir
|
clients/data_fusion/lib/google_api/data_fusion/v1beta1/model/expr.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/data_fusion/lib/google_api/data_fusion/v1beta1/model/expr.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1
|
2020-12-18T09:25:12.000Z
|
2020-12-18T09:25:12.000Z
|
clients/data_fusion/lib/google_api/data_fusion/v1beta1/model/expr.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.DataFusion.V1beta1.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(),
:expression => String.t(),
:location => String.t(),
:title => String.t()
}
field(:description)
field(:expression)
field(:location)
field(:title)
end
defimpl Poison.Decoder, for: GoogleApi.DataFusion.V1beta1.Model.Expr do
def decode(value, options) do
GoogleApi.DataFusion.V1beta1.Model.Expr.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DataFusion.V1beta1.Model.Expr do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 57.571429
| 1,092
| 0.736663
|
03ace64d4631a6da6345776cdd215b1505092c98
| 839
|
exs
|
Elixir
|
mix.exs
|
saulecabrera/leibniz
|
b26cff59bb571095f926f7df859810901c4ca33b
|
[
"MIT"
] | 19
|
2018-04-16T11:12:36.000Z
|
2020-02-21T08:07:36.000Z
|
mix.exs
|
saulecabrera/leibniz
|
b26cff59bb571095f926f7df859810901c4ca33b
|
[
"MIT"
] | 2
|
2018-05-05T21:08:39.000Z
|
2018-05-06T14:29:54.000Z
|
mix.exs
|
saulecabrera/leibniz
|
b26cff59bb571095f926f7df859810901c4ca33b
|
[
"MIT"
] | 1
|
2020-02-21T08:07:52.000Z
|
2020-02-21T08:07:52.000Z
|
defmodule Leibniz.MixProject do
use Mix.Project
@desc "Math expression parser and evaluator"
def project do
[
app: :leibniz,
version: "1.0.0",
elixir: "~> 1.6",
start_permanent: Mix.env() == :prod,
deps: deps(),
test_coverage: [tool: ExCoveralls],
preferred_cli_env: ["coveralls": :test, "coveralls.json": :test],
description: @desc,
package: package()
]
end
def application do
[
extra_applications: [:logger]
]
end
defp package() do
[
name: "leibniz",
maintainers: ["Saúl Cabrera"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/saulecabrera/leibniz"}
]
end
defp deps do
[
{:ex_doc, "~> 0.16", only: :dev, runtime: false},
{:excoveralls, "~> 0.8", only: :test}
]
end
end
| 19.97619
| 71
| 0.558999
|
03acf1d237954559dbb1a2174d85b5e2fd1551ca
| 165
|
exs
|
Elixir
|
config/test.ci.exs
|
kianmeng/cldr_trans
|
da3f01eb16cd25e8936d30805bfff5e3ab589409
|
[
"Apache-2.0"
] | 108
|
2018-08-24T19:47:59.000Z
|
2022-03-24T13:15:42.000Z
|
config/test.ci.exs
|
kianmeng/cldr_trans
|
da3f01eb16cd25e8936d30805bfff5e3ab589409
|
[
"Apache-2.0"
] | 20
|
2018-10-09T18:32:37.000Z
|
2022-03-19T08:46:16.000Z
|
config/test.ci.exs
|
kianmeng/cldr_trans
|
da3f01eb16cd25e8936d30805bfff5e3ab589409
|
[
"Apache-2.0"
] | 13
|
2018-10-09T18:30:16.000Z
|
2022-01-26T23:37:20.000Z
|
use Mix.Config
config :trans, Trans.Repo,
username: "postgres",
password: "postgres",
database: "trans_test",
pool: Ecto.Adapters.SQL.Sandbox,
log: false
| 18.333333
| 34
| 0.70303
|
03acfc69d2493c7db4eaa13ecc648d1587bf6b86
| 524
|
ex
|
Elixir
|
samples/client/petstore/elixir/lib/swagger_petstore/model/special_model_name.ex
|
derBiggi/swagger-codegen
|
99dad052ec506796f3ed13b19364cf827ff0f256
|
[
"Apache-2.0"
] | 14,570
|
2015-01-01T21:46:46.000Z
|
2022-03-31T22:28:15.000Z
|
samples/client/petstore/elixir/lib/swagger_petstore/model/special_model_name.ex
|
derBiggi/swagger-codegen
|
99dad052ec506796f3ed13b19364cf827ff0f256
|
[
"Apache-2.0"
] | 9,058
|
2015-01-08T15:49:17.000Z
|
2022-03-31T13:10:01.000Z
|
samples/client/petstore/elixir/lib/swagger_petstore/model/special_model_name.ex
|
LaudateCorpus1/swagger-codegen
|
e4f322ce197f1d6a0643de80f9a20bb521480426
|
[
"Apache-2.0"
] | 6,907
|
2015-01-02T05:29:47.000Z
|
2022-03-31T00:55:45.000Z
|
# 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 SwaggerPetstore.Model.SpecialModelName do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:"$special[property.name]"
]
@type t :: %__MODULE__{
:"$special[property.name]" => integer()
}
end
defimpl Poison.Decoder, for: SwaggerPetstore.Model.SpecialModelName do
def decode(value, _options) do
value
end
end
| 20.153846
| 75
| 0.704198
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.