hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequence
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequence
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequence
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
73df546811ac529efb7dfefe33b3e4aef075b9f4
1,037
exs
Elixir
test/day_08_space_image_format_test.exs
scmx/advent-of-code-2019-elixir
f3022efb422e15abead6b882c78855b26b138443
[ "MIT" ]
1
2019-12-02T16:27:06.000Z
2019-12-02T16:27:06.000Z
test/day_08_space_image_format_test.exs
scmx/advent-of-code-2019-elixir
f3022efb422e15abead6b882c78855b26b138443
[ "MIT" ]
null
null
null
test/day_08_space_image_format_test.exs
scmx/advent-of-code-2019-elixir
f3022efb422e15abead6b882c78855b26b138443
[ "MIT" ]
1
2020-12-10T10:47:21.000Z
2020-12-10T10:47:21.000Z
defmodule Adventofcode.Day08SpaceImageFormatTest do use Adventofcode.FancyCase import ExUnit.CaptureIO import Adventofcode.Day08SpaceImageFormat describe "least_corrupted_layer/1" do test "given an image 3 pixels wide and 2 pixels tall" do assert 1 = "123456789012" |> least_corrupted_layer({3, 2}) end end describe "render_pixels/1" do @output ~h""" 1 1 """ test "0222112222120000" do fun = fn -> "0222112222120000" |> part_2({2, 2}) end assert capture_io(fun) == @output end end describe "part_1/1" do test_with_puzzle_input do assert 1441 = puzzle_input() |> part_1({25, 6}) end end describe "part_2/1" do @output ~h""" 111 1 1 1111 111 111 1 1 1 1 1 1 1 1 1 1 1 1 1 1 111 1 1 111 1 1 1 1 1 111 1 1 1 1 1 1 1 1 1 1 11 1111 111 1 """ test_with_puzzle_input do fun = fn -> puzzle_input() |> part_2({25, 6}) end assert capture_io(fun) == @output end end end
22.06383
64
0.604629
73df572f24eee1248edc427da3f84162b8add6ad
604
ex
Elixir
lib/teslamate/log/update.ex
kuma/teslamate
ea175fddb49cc08070182455e0073c3dcfcb3b4c
[ "MIT" ]
2,602
2019-07-24T23:19:12.000Z
2022-03-31T15:03:48.000Z
lib/teslamate/log/update.ex
kuma/teslamate
ea175fddb49cc08070182455e0073c3dcfcb3b4c
[ "MIT" ]
1,547
2019-07-26T22:02:09.000Z
2022-03-31T15:39:41.000Z
lib/teslamate/log/update.ex
kuma/teslamate
ea175fddb49cc08070182455e0073c3dcfcb3b4c
[ "MIT" ]
524
2019-07-26T17:31:33.000Z
2022-03-29T15:16:36.000Z
defmodule TeslaMate.Log.Update do use Ecto.Schema import Ecto.Changeset alias TeslaMate.Log.Car schema "updates" do field :start_date, :utc_datetime_usec field :end_date, :utc_datetime_usec field :version, :string belongs_to :car, Car end @doc false def changeset(update, attrs) do update |> cast(attrs, [:start_date, :end_date, :version]) |> validate_required([:car_id, :start_date]) |> foreign_key_constraint(:car_id) |> check_constraint(:end_date, name: :positive_duration, message: "end date must be after start date" ) end end
22.37037
54
0.68543
73df58f77300615d7ce7d169b025d6a164675a37
966
ex
Elixir
lib/lovelace_integration/telegram/consumers/message_handler.ex
cciuenf/lovelaceccuenf_bot
22a9d4e25d59cf3e5f1de4c4de8e257a6b44fba9
[ "MIT" ]
null
null
null
lib/lovelace_integration/telegram/consumers/message_handler.ex
cciuenf/lovelaceccuenf_bot
22a9d4e25d59cf3e5f1de4c4de8e257a6b44fba9
[ "MIT" ]
null
null
null
lib/lovelace_integration/telegram/consumers/message_handler.ex
cciuenf/lovelaceccuenf_bot
22a9d4e25d59cf3e5f1de4c4de8e257a6b44fba9
[ "MIT" ]
null
null
null
defmodule LovelaceIntegration.Telegram.Consumers.MessageHandler do @moduledoc """ Stateless GenServer that subscribes to telegram messages and does something if they require an action """ use GenServer require Logger alias Lovelace.Events alias LovelaceIntegration.Telegram alias LovelaceIntegration.Telegram.Message def start_link(_), do: GenServer.start_link(__MODULE__, nil) @impl true def init(_) do Logger.info("Starting #{__MODULE__}") Phoenix.PubSub.subscribe( Application.get_env(:lovelace, :pubsub_channel), Events.TelegramMessage.topic() ) {:ok, nil} end @impl true def handle_info( %Message{} = message, state ) do Logger.info("#{__MODULE__} handling message") # fire and forget, and don't make our genserver stuck Task.async(fn -> Telegram.process_message(message) end) {:noreply, state} end def handle_info(_, state), do: {:noreply, state} end
23
66
0.700828
73df6a42ebe7a6f101b3d506fbafc060e4ebe9fe
1,795
ex
Elixir
clients/search_console/lib/google_api/search_console/v1/model/wmx_sitemap_content.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/search_console/lib/google_api/search_console/v1/model/wmx_sitemap_content.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/search_console/lib/google_api/search_console/v1/model/wmx_sitemap_content.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.SearchConsole.V1.Model.WmxSitemapContent do @moduledoc """ Information about the various content types in the sitemap. ## Attributes * `indexed` (*type:* `String.t`, *default:* `nil`) - *Deprecated; do not use.* * `submitted` (*type:* `String.t`, *default:* `nil`) - The number of URLs in the sitemap (of the content type). * `type` (*type:* `String.t`, *default:* `nil`) - The specific type of content in this sitemap. For example: `web`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :indexed => String.t() | nil, :submitted => String.t() | nil, :type => String.t() | nil } field(:indexed) field(:submitted) field(:type) end defimpl Poison.Decoder, for: GoogleApi.SearchConsole.V1.Model.WmxSitemapContent do def decode(value, options) do GoogleApi.SearchConsole.V1.Model.WmxSitemapContent.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.SearchConsole.V1.Model.WmxSitemapContent do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.867925
119
0.708078
73df70a8855484924572f9fc1f02bae70081385f
83
exs
Elixir
test/test_helper.exs
franknfjr/jaya_currency_converter
56dfcf40b2ed2c9307fa39d7a5d1121cf4a1a37e
[ "MIT" ]
null
null
null
test/test_helper.exs
franknfjr/jaya_currency_converter
56dfcf40b2ed2c9307fa39d7a5d1121cf4a1a37e
[ "MIT" ]
null
null
null
test/test_helper.exs
franknfjr/jaya_currency_converter
56dfcf40b2ed2c9307fa39d7a5d1121cf4a1a37e
[ "MIT" ]
null
null
null
ExUnit.start() Ecto.Adapters.SQL.Sandbox.mode(JayaCurrencyConverter.Repo, :manual)
27.666667
67
0.819277
73df7ebc005054900180c413b6e5508ba1b2b9c4
4,766
exs
Elixir
test/actions/side_load_test.exs
ChristianTovar/ash
66435322786c5d0b90a34051da969b68dcc8a045
[ "MIT" ]
null
null
null
test/actions/side_load_test.exs
ChristianTovar/ash
66435322786c5d0b90a34051da969b68dcc8a045
[ "MIT" ]
null
null
null
test/actions/side_load_test.exs
ChristianTovar/ash
66435322786c5d0b90a34051da969b68dcc8a045
[ "MIT" ]
null
null
null
defmodule Ash.Test.Actions.SideLoadTest do @moduledoc false use ExUnit.Case, async: false import Ash.Changeset require Ash.Query defmodule Author do @moduledoc false use Ash.Resource, data_layer: Ash.DataLayer.Ets, authorizers: [ Ash.Test.Authorizer ] ets do private?(true) end actions do read :read create :create end attributes do uuid_primary_key :id attribute :name, :string end relationships do has_many :posts, Ash.Test.Actions.SideLoadTest.Post, destination_field: :author_id end end defmodule Post do @moduledoc false use Ash.Resource, data_layer: Ash.DataLayer.Ets ets do private?(true) end actions do read :read create :create end attributes do uuid_primary_key :id attribute :title, :string attribute :contents, :string end relationships do belongs_to :author, Author many_to_many :categories, Ash.Test.Actions.SideLoadTest.Category, through: Ash.Test.Actions.SideLoadTest.PostCategory, destination_field_on_join_table: :category_id, source_field_on_join_table: :post_id end end defmodule PostCategory do @moduledoc false use Ash.Resource, data_layer: Ash.DataLayer.Ets ets do private?(true) end actions do read :read create :create end relationships do belongs_to :post, Post, primary_key?: true, required?: true belongs_to :category, Ash.Test.Actions.SideLoadTest.Category, primary_key?: true, required?: true end end defmodule Category do @moduledoc false use Ash.Resource, data_layer: Ash.DataLayer.Ets ets do private?(true) end actions do read :read create :create end attributes do uuid_primary_key :id attribute :name, :string end relationships do many_to_many :posts, Post, through: PostCategory, destination_field_on_join_table: :post_id, source_field_on_join_table: :category_id end end defmodule Api do @moduledoc false use Ash.Api resources do resource(Author) resource(Post) resource(Category) resource(PostCategory) end end setup do start_supervised( {Ash.Test.Authorizer, strict_check: :authorized, check: {:error, Ash.Error.Forbidden.exception([])}, strict_check_context: [:query]} ) :ok end describe "side_loads" do test "it allows sideloading related data" do author = Author |> new(%{name: "zerg"}) |> Api.create!() post1 = Post |> new(%{title: "post1"}) |> replace_relationship(:author, author) |> Api.create!() post2 = Post |> new(%{title: "post2"}) |> replace_relationship(:author, author) |> Api.create!() [author] = Author |> Ash.Query.load(posts: [:author]) |> Ash.Query.filter(posts.id == ^post1.id) |> Api.read!(authorize?: true) assert Enum.sort(Enum.map(author.posts, &Map.get(&1, :id))) == Enum.sort([post1.id, post2.id]) for post <- author.posts do assert post.author.id == author.id end end test "it allows sideloading many to many relationships" do category1 = Category |> new(%{name: "lame"}) |> Api.create!() category2 = Category |> new(%{name: "cool"}) |> Api.create!() post = Post |> new(%{title: "post1"}) |> replace_relationship(:categories, [category1, category2]) |> Api.create!() [post] = Post |> Ash.Query.load(:categories) |> Ash.Query.filter(id == ^post.id) |> Api.read!(authorize?: true) assert [%{id: id1}, %{id: id2}] = post.categories assert Enum.sort([category1.id, category2.id]) == Enum.sort([id1, id2]) end test "it allows sideloading nested many to many relationships" do category1 = Category |> new(%{name: "lame"}) |> Api.create!() category2 = Category |> new(%{name: "cool"}) |> Api.create!() post = Post |> new(%{title: "post1"}) |> replace_relationship(:categories, [category1, category2]) |> Api.create!() [post] = Post |> Ash.Query.load(categories: :posts) |> Ash.Query.filter(id == ^post.id) |> Api.read!(authorize?: true) post_id = post.id assert [%{posts: [%{id: ^post_id}]}, %{posts: [%{id: ^post_id}]}] = post.categories end end end
21.182222
89
0.578892
73dfdf2a4d53866ac81c153ae4264fde8102d855
2,035
ex
Elixir
lib/membrane/element/base.ex
treble37/membrane-core
3f7c7200a80eef370092ef252b5f75dc9eb16cbd
[ "Apache-2.0" ]
null
null
null
lib/membrane/element/base.ex
treble37/membrane-core
3f7c7200a80eef370092ef252b5f75dc9eb16cbd
[ "Apache-2.0" ]
null
null
null
lib/membrane/element/base.ex
treble37/membrane-core
3f7c7200a80eef370092ef252b5f75dc9eb16cbd
[ "Apache-2.0" ]
null
null
null
defmodule Membrane.Element.Base do @moduledoc """ Modules in this namespace contain behaviours, default callback implementations and other stuff useful when creating elements. Elements are units that produce, process or consume data. They can be linked with `Membrane.Pipeline`, and thus form a pipeline able to perform complex data processing. Each element defines a set of pads, through which it can be linked with other elements. During playback, pads can either send (output pads) or receive (input pads) data. For more information on pads, see `Membrane.Element.Pad`. To implement an element, one of base modules (`Membrane.Element.Base.Source`, `Membrane.Element.Base.Filter`, `Membrane.Element.Base.Sink`) has to be `use`d, depending on the element type: - source, producing buffers (contain only output pads), - filter, processing buffers (contain both input and output pads), - sink, consuming buffers (contain only input pads). For more information on each element type, check documentation for appropriate base module. ## Behaviours Element-specific behaviours are specified in modules: - `Membrane.Element.Base.Mixin.CommonBehaviour` - behaviour common to all elements, - `Membrane.Element.Base.Mixin.SourceBehaviour` - behaviour common to sources and filters, - `Membrane.Element.Base.Mixin.SinkBehaviour` - behaviour common to sinks and filters, - Base modules (`Membrane.Element.Base.Source`, `Membrane.Element.Base.Filter`, `Membrane.Element.Base.Sink`) - behaviours specific to each element type. ## Callbacks Modules listed above provide specifications of callbacks that define elements lifecycle. All of these callbacks have names with the `handle_` prefix. They are used to define reaction to certain events that happen during runtime, and indicate what actions frawork should undertake as a result, besides executing element-specific code. For actions that can be returned by each callback, see `Membrane.Element.Action` module. """ end
46.25
82
0.768059
73e00208433135d7f625e5c5298214ef1aa892f5
2,187
ex
Elixir
test/support/event_factory.ex
c-moss-talk/eventstore
f02a0d8cea78608afb9ed1368c1fd26076d652b6
[ "MIT" ]
null
null
null
test/support/event_factory.ex
c-moss-talk/eventstore
f02a0d8cea78608afb9ed1368c1fd26076d652b6
[ "MIT" ]
null
null
null
test/support/event_factory.ex
c-moss-talk/eventstore
f02a0d8cea78608afb9ed1368c1fd26076d652b6
[ "MIT" ]
null
null
null
defmodule EventStore.EventFactory do alias EventStore.{EventData,RecordedEvent} @serializer Application.get_env(:eventstore, EventStore.Storage)[:serializer] || EventStore.JsonSerializer defmodule Event do @derive Jason.Encoder defstruct event: nil end def create_events(number_of_events, initial_event_number \\ 1) when number_of_events > 0 do correlation_id = UUID.uuid4() causation_id = UUID.uuid4() 1..number_of_events |> Enum.map(fn number -> %EventData{ correlation_id: correlation_id, causation_id: causation_id, event_type: "Elixir.EventStore.EventFactory.Event", data: %EventStore.EventFactory.Event{event: (initial_event_number + number - 1)}, metadata: %{"user" => "[email protected]"} } end) end def create_recorded_events(number_of_events, stream_uuid, initial_event_number \\ 1, initial_stream_version \\ 1) when is_bitstring(stream_uuid) and number_of_events > 0 do correlation_id = UUID.uuid4() causation_id = UUID.uuid4() 1..number_of_events |> Enum.map(fn number -> event_number = initial_event_number + number - 1 stream_version = initial_stream_version + number - 1 %RecordedEvent{ event_id: UUID.uuid4(), event_number: event_number, stream_uuid: stream_uuid, stream_version: stream_version, correlation_id: correlation_id, causation_id: causation_id, event_type: "Elixir.EventStore.EventFactory.Event", data: serialize(%EventStore.EventFactory.Event{event: event_number}), metadata: serialize(%{"user" => "[email protected]"}), created_at: utc_now(), } end) end def deserialize_events(events) do events |> Enum.map(fn event -> %RecordedEvent{event | data: deserialize(event.data, type: "Elixir.EventStore.EventFactory.Event"), metadata: deserialize(event.metadata, []) } end) end defp serialize(term) do apply(@serializer, :serialize, [term]) end defp deserialize(term, type) do apply(@serializer, :deserialize, [term, type]) end defp utc_now, do: DateTime.utc_now end
29.958904
115
0.681299
73e04d2b99122bb0fd6f2957b0a5caf985ef7666
3,423
ex
Elixir
apps/url_dispatcher/lib/mix/tasks/omg.server.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
322
2018-02-28T07:38:44.000Z
2020-05-27T23:09:55.000Z
apps/url_dispatcher/lib/mix/tasks/omg.server.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
643
2018-02-28T12:05:20.000Z
2020-05-22T08:34:38.000Z
apps/url_dispatcher/lib/mix/tasks/omg.server.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
63
2018-02-28T10:57:06.000Z
2020-05-27T23:10:38.000Z
# Copyright 2018-2019 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # MIT License # Copyright (c) 2014 Chris McCord # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # and associated documentation files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom # the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR # ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. defmodule Mix.Tasks.Omg.Server do @moduledoc """ Starts the application by configuring all endpoints servers to run. This task is intended to be run in development environment. ## Command line options This task accepts the same command-line arguments as `run`. For additional information, refer to the documentation for `Mix.Tasks.Run`. For example, to run `omg.server` without checking dependencies: mix omg.server --no-deps-check The `--no-halt` flag is automatically added in case `omg.server` is invoked directly without IEx console attached. If you wish to run `omg.server` with IEx without starting the server, you can use: iex -S mix omg.server --no-serve ## OmiseGO-specific options This task can also be run with the following flags: - `--no-watch` - disables watching and building when frontend assets change - `--no-serve` - disables serving endpoints """ use Mix.Task alias Mix.Tasks.Run @shortdoc "Starts the eWallet applications and their servers" @doc false def run(args) do System.put_env("WEBPACK_WATCH", "true") System.put_env("SERVE_ENDPOINTS", "true") System.put_env("SERVE_LOCAL_STATIC", "true") run(args, []) end defp run(["--no-watch" | t], args2) do System.put_env("WEBPACK_WATCH", "false") run(t, args2) end defp run(["--no-serve" | t], args2) do System.put_env("SERVE_ENDPOINTS", "false") run(t, args2) end defp run([h | t], args2), do: run(t, args2 ++ [h]) defp run([], args2) do case iex_running?() do true -> Run.run(args2) _ -> Run.run(args2 ++ ["--no-halt"]) end end defp iex_running? do Code.ensure_loaded?(IEx) and IEx.started?() end end
33.23301
95
0.720421
73e05630f5df61e3cc13fe15b96c3925cfa50637
1,029
ex
Elixir
lib/chat_server/endpoint.ex
aswani521/chat_server
9400a6137992a48e7bc2dd0aebf05ad56e430fe3
[ "MIT" ]
null
null
null
lib/chat_server/endpoint.ex
aswani521/chat_server
9400a6137992a48e7bc2dd0aebf05ad56e430fe3
[ "MIT" ]
null
null
null
lib/chat_server/endpoint.ex
aswani521/chat_server
9400a6137992a48e7bc2dd0aebf05ad56e430fe3
[ "MIT" ]
null
null
null
defmodule ChatServer.Endpoint do use Phoenix.Endpoint, otp_app: :chat_server socket "/socket", ChatServer.UserSocket # Serve at "/" the static files from "priv/static" directory. # # You should set gzip to true if you are running phoenix.digest # when deploying your static files in production. plug Plug.Static, at: "/", from: :chat_server, gzip: false, only: ~w(css fonts images js favicon.ico robots.txt) # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. if code_reloading? do socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket plug Phoenix.LiveReloader plug Phoenix.CodeReloader end plug Plug.RequestId plug Plug.Logger plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Poison plug Plug.MethodOverride plug Plug.Head plug Plug.Session, store: :cookie, key: "_chat_server_key", signing_salt: "GY4HAtQn" plug ChatServer.Router end
25.725
69
0.715258
73e069561425c8b402dba464dd2833abee32a7c8
1,277
ex
Elixir
lib/blinkchain/config.ex
cloud8421/blinkchain
bf49d0530c77293ae7b419432687ac77f5ce3890
[ "MIT" ]
null
null
null
lib/blinkchain/config.ex
cloud8421/blinkchain
bf49d0530c77293ae7b419432687ac77f5ce3890
[ "MIT" ]
null
null
null
lib/blinkchain/config.ex
cloud8421/blinkchain
bf49d0530c77293ae7b419432687ac77f5ce3890
[ "MIT" ]
null
null
null
defmodule Blinkchain.Config do @moduledoc """ Represents the placement of the NeoPixel devices on the virtual drawing canvas. """ alias Blinkchain.Config alias Blinkchain.Config.{ Canvas, Channel } @typedoc @moduledoc @type t :: %__MODULE__{ canvas: Canvas.t(), channel0: Channel.t(), channel1: Channel.t() } defstruct [ :canvas, :channel0, :channel1 ] @doc """ Build a `t:Blinkchain.Config.t/0` struct based on Application configuration. """ @spec load(Keyword.t() | nil) :: Config.t() def load(nil) do :blinkchain |> Application.get_all_env() |> load() end def load(config) when is_list(config) do canvas = config |> Keyword.get(:canvas) |> load_canvas_config() channel0 = config |> Keyword.get(:channel0) |> Channel.new(0) channel1 = config |> Keyword.get(:channel1) |> Channel.new(1) %Config{ canvas: canvas, channel0: channel0, channel1: channel1 } end # Private Helpers defp load_canvas_config({width, height}), do: Canvas.new(width, height) defp load_canvas_config(_), do: raise(":blinkchain :canvas dimensions must be configured as {width, height}") end
19.953125
111
0.61159
73e09f9e4420f7b98608e443db37ebe79b39e41c
3,148
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/weighted_backend_service.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/weighted_backend_service.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/compute/lib/google_api/compute/v1/model/weighted_backend_service.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.Compute.V1.Model.WeightedBackendService do @moduledoc """ In contrast to a single BackendService in HttpRouteAction to which all matching traffic is directed to, WeightedBackendService allows traffic to be split across multiple BackendServices. The volume of traffic for each BackendService is proportional to the weight specified in each WeightedBackendService ## Attributes * `backendService` (*type:* `String.t`, *default:* `nil`) - The full or partial URL to the default BackendService resource. Before forwarding the request to backendService, the loadbalancer applies any relevant headerActions specified as part of this backendServiceWeight. * `headerAction` (*type:* `GoogleApi.Compute.V1.Model.HttpHeaderAction.t`, *default:* `nil`) - Specifies changes to request and response headers that need to take effect for the selected backendService. headerAction specified here take effect before headerAction in the enclosing HttpRouteRule, PathMatcher and UrlMap. Note that headerAction is not supported for Loadbalancers that have their loadBalancingScheme set to EXTERNAL. Not supported when the URL map is bound to target gRPC proxy that has validateForProxyless field set to true. * `weight` (*type:* `integer()`, *default:* `nil`) - Specifies the fraction of traffic sent to backendService, computed as weight / (sum of all weightedBackendService weights in routeAction) . The selection of a backend service is determined only for new traffic. Once a user's request has been directed to a backendService, subsequent requests will be sent to the same backendService as determined by the BackendService's session affinity policy. The value must be between 0 and 1000 """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :backendService => String.t(), :headerAction => GoogleApi.Compute.V1.Model.HttpHeaderAction.t(), :weight => integer() } field(:backendService) field(:headerAction, as: GoogleApi.Compute.V1.Model.HttpHeaderAction) field(:weight) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.WeightedBackendService do def decode(value, options) do GoogleApi.Compute.V1.Model.WeightedBackendService.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.WeightedBackendService do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
54.275862
306
0.766836
73e0a8a37b728b692395cc63e4b5dc96a924599c
2,629
ex
Elixir
lib/assent/strategies/oauth/base.ex
lmeier/assent
3f5a5d340eb1833cd9d6ada9d7e3056b7e3d4f41
[ "MIT" ]
null
null
null
lib/assent/strategies/oauth/base.ex
lmeier/assent
3f5a5d340eb1833cd9d6ada9d7e3056b7e3d4f41
[ "MIT" ]
null
null
null
lib/assent/strategies/oauth/base.ex
lmeier/assent
3f5a5d340eb1833cd9d6ada9d7e3056b7e3d4f41
[ "MIT" ]
null
null
null
defmodule Assent.Strategy.OAuth.Base do @moduledoc """ OAuth 1.0 strategy base. ## Usage defmodule MyApp.MyOAuthStratey do use Assent.Strategy.OAuth @impl true def default_config(_config) do [ site: "https://api.example.com", authorize_url: "/authorization/new", access_token_url: "/authorization/access_token" request_token_url: "/authorization/request_token", user_url: "/authorization.json", authorization_params: [scope: "default"] ] end @impl true def normalize(_config, user) do {:ok, # Conformed to https://openid.net/specs/openid-connect-core-1_0.html#rfc.section.5.1 %{ "sub" => user["id"], "name" => user["name"], "email" => user["email"] # }, # # Provider specific data not part of the standard claims spec # %{ # "bio" => user["bio"] } } end end """ alias Assent.Strategy, as: Helpers alias Assent.Strategy.OAuth @callback default_config(Keyword.t()) :: Keyword.t() @callback normalize(Keyword.t(), map()) :: {:ok, map()} | {:ok, map(), map()} | {:error, term()} @callback fetch_user(Keyword.t(), map()) :: {:ok, map()} | {:error, term()} @doc false defmacro __using__(_opts) do quote do @behaviour Assent.Strategy @behaviour unquote(__MODULE__) alias Assent.Strategy, as: Helpers @impl Assent.Strategy def authorize_url(config), do: unquote(__MODULE__).authorize_url(config, __MODULE__) @impl Assent.Strategy def callback(config, params), do: unquote(__MODULE__).callback(config, params, __MODULE__) @impl unquote(__MODULE__) def fetch_user(config, token), do: OAuth.fetch_user(config, token) defoverridable unquote(__MODULE__) end end @spec authorize_url(Keyword.t(), module()) :: {:ok, %{url: binary()}} | {:error, term()} def authorize_url(config, strategy) do config |> set_config(strategy) |> OAuth.authorize_url() end @spec callback(Keyword.t(), map(), module()) :: {:ok, %{user: map(), token: map()}} | {:error, term()} def callback(config, params, strategy) do config = set_config(config, strategy) config |> OAuth.callback(params, strategy) |> Helpers.__normalize__(config, strategy) end defp set_config(config, strategy) do config |> strategy.default_config() |> Keyword.merge(config) |> Keyword.put(:strategy, strategy) end end
29.211111
104
0.593762
73e0b53af9490230fa5308bcee65c8ae684c3955
260
ex
Elixir
lib/afk/hid_report.ex
nerves-keyboard/afk
9b7f55c98aa8c52dee3f134cef112c1361fe75f4
[ "MIT" ]
4
2020-10-31T04:55:04.000Z
2021-10-11T21:44:54.000Z
lib/afk/hid_report.ex
doughsay/afk
9b7f55c98aa8c52dee3f134cef112c1361fe75f4
[ "MIT" ]
46
2019-12-13T05:46:08.000Z
2020-10-29T13:07:40.000Z
lib/afk/hid_report.ex
nerves-keyboard/afk
9b7f55c98aa8c52dee3f134cef112c1361fe75f4
[ "MIT" ]
1
2020-01-02T13:35:03.000Z
2020-01-02T13:35:03.000Z
defmodule AFK.HIDReport do @moduledoc """ Defines a behaviour for converting an `AFK.State` struct into a binary USB HID report. Current implementations: * `AFK.HIDReport.SixKeyRollover` """ @callback hid_report(AFK.State.t()) :: binary() end
20
80
0.711538
73e0d6939dbc172dc2e6eb08380cd6ac843b05a5
1,580
exs
Elixir
lib/euler_042.exs
sorentwo/euler
76244a0ef3dcfa17d6b9571daa5d0b46f09057f4
[ "MIT" ]
8
2015-11-04T05:03:05.000Z
2022-01-25T19:34:46.000Z
lib/euler_042.exs
sorentwo/euler
76244a0ef3dcfa17d6b9571daa5d0b46f09057f4
[ "MIT" ]
null
null
null
lib/euler_042.exs
sorentwo/euler
76244a0ef3dcfa17d6b9571daa5d0b46f09057f4
[ "MIT" ]
null
null
null
defmodule EulerFortyTwo do @moduledoc """ The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? """ @alpha ~w(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) @fname "data/p042_words.txt" def solve do mapping = makemap triangles = 1..26 |> Enum.map(&tn/1) File.open!(@fname, [:read]) |> IO.read(:line) |> String.split(",") |> Enum.map(&String.strip/1) |> Enum.map(&(calc_tval(mapping, &1))) |> Enum.filter(&(is_triangle?(triangles, &1))) |> length end defp makemap do Enum.with_index(@alpha) |> Enum.map(fn({l, v}) -> {l, v + 1} end) |> Enum.reduce(%{}, fn({k, v}, m) -> Map.put(m, k, v) end) end defp calc_tval(mapping, word) do word |> String.graphemes |> Enum.map(&(tval(mapping, &1))) |> Enum.sum end defp tn(n), do: trunc((n / 2) * (n + 1)) defp tval(_, "\""), do: 0 defp tval(m, alph), do: Map.get(m, alph) defp is_triangle?(triangles, value), do: value in triangles end IO.puts EulerFortyTwo.solve
28.727273
70
0.620886
73e0f165f65eabdaeabdf3fd915b66fcd25f9c78
1,727
ex
Elixir
lib/tamyda_web.ex
RobertDober/tamyda
ebcf60366a0475554b49c7b531c18c40a748e345
[ "Apache-2.0" ]
null
null
null
lib/tamyda_web.ex
RobertDober/tamyda
ebcf60366a0475554b49c7b531c18c40a748e345
[ "Apache-2.0" ]
null
null
null
lib/tamyda_web.ex
RobertDober/tamyda
ebcf60366a0475554b49c7b531c18c40a748e345
[ "Apache-2.0" ]
null
null
null
defmodule TamydaWeb do @moduledoc """ The entrypoint for defining your web interface, such as controllers, views, channels and so on. This can be used in your application as: use TamydaWeb, :controller use TamydaWeb, :view The definitions below will be executed for every view, controller, etc, so keep them short and clean, focused on imports, uses and aliases. Do NOT define functions inside the quoted expressions below. Instead, define any helper function in modules and import those modules here. """ def controller do quote do use Phoenix.Controller, namespace: TamydaWeb import Plug.Conn import TamydaWeb.Gettext alias TamydaWeb.Router.Helpers, as: Routes end end def view do quote do use Phoenix.View, root: "lib/tamyda_web/templates", namespace: TamydaWeb # Import convenience functions from controllers import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1] # Use all HTML functionality (forms, tags, etc) use Phoenix.HTML import TamydaWeb.ErrorHelpers import TamydaWeb.Gettext alias TamydaWeb.Router.Helpers, as: Routes import Phoenix.LiveView, only: [live_render: 2, live_render: 3] end end def router do quote do use Phoenix.Router import Plug.Conn import Phoenix.Controller import Phoenix.LiveView.Router end end def channel do quote do use Phoenix.Channel import TamydaWeb.Gettext end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
23.337838
83
0.687319
73e1106601aee32955c9bec5462a2891f83d3773
677
exs
Elixir
apps/spec_test_runner/mix.exs
timjp87/panacea
5edddfa12a8f18b040248b9b186479b9ec8aed51
[ "MIT" ]
null
null
null
apps/spec_test_runner/mix.exs
timjp87/panacea
5edddfa12a8f18b040248b9b186479b9ec8aed51
[ "MIT" ]
null
null
null
apps/spec_test_runner/mix.exs
timjp87/panacea
5edddfa12a8f18b040248b9b186479b9ec8aed51
[ "MIT" ]
null
null
null
defmodule SpecTestRunner.MixProject do use Mix.Project def project do [ app: :spec_test_runner, version: "0.1.0", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", lockfile: "../../mix.lock", elixir: "~> 1.10", start_permanent: Mix.env() == :prod, deps: deps() ] 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 [ {:yaml_elixir, "~> 2.4"}, {:elixir_ssz, in_umbrella: true} ] end end
20.515152
59
0.565731
73e114ca4bbeaf6630922ec93dac99c64a26ef8d
1,005
ex
Elixir
test/support/conn_case.ex
Dania02525/widget_saas
17b853f07be08a851c3e355863c18e15755cb7cb
[ "MIT" ]
12
2016-01-27T01:30:42.000Z
2019-12-07T20:31:01.000Z
test/support/conn_case.ex
Dania02525/widget_saas
17b853f07be08a851c3e355863c18e15755cb7cb
[ "MIT" ]
3
2016-11-22T12:22:59.000Z
2017-08-01T17:26:40.000Z
test/support/conn_case.ex
Dania02525/widget_saas
17b853f07be08a851c3e355863c18e15755cb7cb
[ "MIT" ]
5
2016-07-11T18:39:02.000Z
2019-10-23T03:22:49.000Z
defmodule WidgetSaas.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 imports other functionality to make it easier to build and query models. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest alias WidgetSaas.Repo import Ecto.Model import Ecto.Query, only: [from: 2] import WidgetSaas.Router.Helpers # The default endpoint for testing @endpoint WidgetSaas.Endpoint end end setup tags do unless tags[:async] do Ecto.Adapters.SQL.restart_test_transaction(WidgetSaas.Repo, []) end :ok end end
23.928571
69
0.710448
73e11daa5346a1fc3dfd59a5d20e6f1606e919cd
1,991
ex
Elixir
clients/knowledge_graph_search/lib/google_api/knowledge_graph_search/v1/model/search_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/knowledge_graph_search/lib/google_api/knowledge_graph_search/v1/model/search_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/knowledge_graph_search/lib/google_api/knowledge_graph_search/v1/model/search_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.KnowledgeGraphSearch.V1.Model.SearchResponse do @moduledoc """ Response message includes the context and a list of matching results which contain the detail of associated entities. ## Attributes - @context (String.t): The local context applicable for the response. See more details at http://www.w3.org/TR/json-ld/#context-definitions. Defaults to: `null`. - @type (String.t): The schema type of top-level JSON-LD object, e.g. ItemList. Defaults to: `null`. - itemListElement ([String.t]): The item list of search results. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :"@context" => any(), :"@type" => any(), :itemListElement => list(any()) } field(:"@context") field(:"@type") field(:itemListElement, type: :list) end defimpl Poison.Decoder, for: GoogleApi.KnowledgeGraphSearch.V1.Model.SearchResponse do def decode(value, options) do GoogleApi.KnowledgeGraphSearch.V1.Model.SearchResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.KnowledgeGraphSearch.V1.Model.SearchResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.87037
163
0.731793
73e1574aeb1f3e2d1014d3c0f38b9ed6dfacd63b
707
ex
Elixir
apps/my_app_web/lib/my_app_web/gettext.ex
robmckinnon/phoenix-umbrella-with-node-js-example
48cce2d9d9fc4564bc5983840c66d09c6594462d
[ "MIT" ]
null
null
null
apps/my_app_web/lib/my_app_web/gettext.ex
robmckinnon/phoenix-umbrella-with-node-js-example
48cce2d9d9fc4564bc5983840c66d09c6594462d
[ "MIT" ]
null
null
null
apps/my_app_web/lib/my_app_web/gettext.ex
robmckinnon/phoenix-umbrella-with-node-js-example
48cce2d9d9fc4564bc5983840c66d09c6594462d
[ "MIT" ]
null
null
null
defmodule MyAppWeb.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. By using [Gettext](https://hexdocs.pm/gettext), your module gains a set of macros for translations, for example: import MyAppWeb.Gettext # Simple translation gettext "Here is the string to translate" # Plural translation ngettext "Here is the string to translate", "Here are the strings to translate", 3 # Domain-based translation dgettext "errors", "Here is the error message to translate" See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. """ use Gettext, otp_app: :my_app_web end
28.28
72
0.680339
73e16d8e29cd0bd4da14cce4c9344e13c584407e
396
ex
Elixir
apps/rex_data/lib/rex_data/application.ex
baymax42/rex
7c8571ac308960973fea9e8df77a6f1ad5c16906
[ "MIT" ]
null
null
null
apps/rex_data/lib/rex_data/application.ex
baymax42/rex
7c8571ac308960973fea9e8df77a6f1ad5c16906
[ "MIT" ]
16
2020-05-18T20:06:29.000Z
2020-06-08T14:32:11.000Z
apps/rex_data/lib/rex_data/application.ex
baymax42/rex
7c8571ac308960973fea9e8df77a6f1ad5c16906
[ "MIT" ]
null
null
null
defmodule RexData.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application alias RexData.{Repo, State} def start(_type, _args) do children = [ Repo, {State, %State{project: nil}} ] Supervisor.start_link(children, strategy: :one_for_one, name: RexData.Supervisor) end end
20.842105
85
0.699495
73e18b41f31fbd6b927dfbd611b9c1d1d791aaff
3,470
ex
Elixir
lib/codes/codes_m45.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_m45.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_m45.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_M45 do alias IcdCode.ICDCode def _M450 do %ICDCode{full_code: "M450", category_code: "M45", short_code: "0", full_name: "Ankylosing spondylitis of multiple sites in spine", short_name: "Ankylosing spondylitis of multiple sites in spine", category_name: "Ankylosing spondylitis of multiple sites in spine" } end def _M451 do %ICDCode{full_code: "M451", category_code: "M45", short_code: "1", full_name: "Ankylosing spondylitis of occipito-atlanto-axial region", short_name: "Ankylosing spondylitis of occipito-atlanto-axial region", category_name: "Ankylosing spondylitis of occipito-atlanto-axial region" } end def _M452 do %ICDCode{full_code: "M452", category_code: "M45", short_code: "2", full_name: "Ankylosing spondylitis of cervical region", short_name: "Ankylosing spondylitis of cervical region", category_name: "Ankylosing spondylitis of cervical region" } end def _M453 do %ICDCode{full_code: "M453", category_code: "M45", short_code: "3", full_name: "Ankylosing spondylitis of cervicothoracic region", short_name: "Ankylosing spondylitis of cervicothoracic region", category_name: "Ankylosing spondylitis of cervicothoracic region" } end def _M454 do %ICDCode{full_code: "M454", category_code: "M45", short_code: "4", full_name: "Ankylosing spondylitis of thoracic region", short_name: "Ankylosing spondylitis of thoracic region", category_name: "Ankylosing spondylitis of thoracic region" } end def _M455 do %ICDCode{full_code: "M455", category_code: "M45", short_code: "5", full_name: "Ankylosing spondylitis of thoracolumbar region", short_name: "Ankylosing spondylitis of thoracolumbar region", category_name: "Ankylosing spondylitis of thoracolumbar region" } end def _M456 do %ICDCode{full_code: "M456", category_code: "M45", short_code: "6", full_name: "Ankylosing spondylitis lumbar region", short_name: "Ankylosing spondylitis lumbar region", category_name: "Ankylosing spondylitis lumbar region" } end def _M457 do %ICDCode{full_code: "M457", category_code: "M45", short_code: "7", full_name: "Ankylosing spondylitis of lumbosacral region", short_name: "Ankylosing spondylitis of lumbosacral region", category_name: "Ankylosing spondylitis of lumbosacral region" } end def _M458 do %ICDCode{full_code: "M458", category_code: "M45", short_code: "8", full_name: "Ankylosing spondylitis sacral and sacrococcygeal region", short_name: "Ankylosing spondylitis sacral and sacrococcygeal region", category_name: "Ankylosing spondylitis sacral and sacrococcygeal region" } end def _M459 do %ICDCode{full_code: "M459", category_code: "M45", short_code: "9", full_name: "Ankylosing spondylitis of unspecified sites in spine", short_name: "Ankylosing spondylitis of unspecified sites in spine", category_name: "Ankylosing spondylitis of unspecified sites in spine" } end end
35.773196
82
0.645245
73e18cf259c4678ae4cdf3910bcc3dc72d013816
2,113
ex
Elixir
clients/tool_results/lib/google_api/tool_results/v1beta3/model/safe_html_proto.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/tool_results/lib/google_api/tool_results/v1beta3/model/safe_html_proto.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/tool_results/lib/google_api/tool_results/v1beta3/model/safe_html_proto.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.ToolResults.V1beta3.Model.SafeHtmlProto do @moduledoc """ IMPORTANT: It is unsafe to accept this message from an untrusted source, since it's trivial for an attacker to forge serialized messages that don't fulfill the type's safety contract -- for example, it could contain attacker controlled script. A system which receives a SafeHtmlProto implicitly trusts the producer of the SafeHtmlProto. So, it's generally safe to return this message in RPC responses, but generally unsafe to accept it in RPC requests. ## Attributes * `privateDoNotAccessOrElseSafeHtmlWrappedValue` (*type:* `String.t`, *default:* `nil`) - IMPORTANT: Never set or read this field, even from tests, it is private. See documentation at the top of .proto file for programming language packages with which to create or read this message. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :privateDoNotAccessOrElseSafeHtmlWrappedValue => String.t() | nil } field(:privateDoNotAccessOrElseSafeHtmlWrappedValue) end defimpl Poison.Decoder, for: GoogleApi.ToolResults.V1beta3.Model.SafeHtmlProto do def decode(value, options) do GoogleApi.ToolResults.V1beta3.Model.SafeHtmlProto.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ToolResults.V1beta3.Model.SafeHtmlProto do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
44.957447
454
0.770942
73e1f90a93c6af8c5f4672a2a668d078db96360d
30,514
ex
Elixir
clients/compute/lib/google_api/compute/v1/api/resource_policies.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/resource_policies.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/resource_policies.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.Compute.V1.Api.ResourcePolicies do @moduledoc """ API calls for all endpoints tagged `ResourcePolicies`. """ alias GoogleApi.Compute.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Retrieves an aggregated list of resource policies. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`. For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` * `:includeAllScopes` (*type:* `boolean()`) - Indicates whether every visible scope for each scope type (zone, region, global) should be included in the response. For new resource types added after this field, the flag has no effect as new resource types will always include every visible scope for each scope type in response. For resource types which predate this field, if this flag is omitted or false, only scopes of the scope types where the resource type is expected to be found will be included. * `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`) * `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by `name` or `creationTimestamp desc` is supported. * `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results. * `:returnPartialSuccess` (*type:* `boolean()`) - Opt-in for partial success behavior which provides partial results in case of failure. The default value is false. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.ResourcePolicyAggregatedList{}}` on success * `{:error, info}` on failure """ @spec compute_resource_policies_aggregated_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.ResourcePolicyAggregatedList.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def compute_resource_policies_aggregated_list( connection, project, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :filter => :query, :includeAllScopes => :query, :maxResults => :query, :orderBy => :query, :pageToken => :query, :returnPartialSuccess => :query } request = Request.new() |> Request.method(:get) |> Request.url("/projects/{project}/aggregated/resourcePolicies", %{ "project" => URI.encode(project, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Compute.V1.Model.ResourcePolicyAggregatedList{}] ) end @doc """ Deletes the specified resource policy. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `region` (*type:* `String.t`) - Name of the region for this request. * `resource_policy` (*type:* `String.t`) - Name of the resource policy to delete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_resource_policies_delete( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def compute_resource_policies_delete( connection, project, region, resource_policy, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/projects/{project}/regions/{region}/resourcePolicies/{resourcePolicy}", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "region" => URI.encode(region, &URI.char_unreserved?/1), "resourcePolicy" => URI.encode(resource_policy, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end @doc """ Retrieves all information of the specified resource policy. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `region` (*type:* `String.t`) - Name of the region for this request. * `resource_policy` (*type:* `String.t`) - Name of the resource policy to retrieve. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.ResourcePolicy{}}` on success * `{:error, info}` on failure """ @spec compute_resource_policies_get( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.ResourcePolicy.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def compute_resource_policies_get( connection, project, region, resource_policy, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/projects/{project}/regions/{region}/resourcePolicies/{resourcePolicy}", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "region" => URI.encode(region, &URI.char_unreserved?/1), "resourcePolicy" => URI.encode(resource_policy, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.ResourcePolicy{}]) end @doc """ Gets the access control policy for a resource. May be empty if no such policy or resource exists. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `region` (*type:* `String.t`) - The name of the region for this request. * `resource` (*type:* `String.t`) - Name or id of the resource for this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:optionsRequestedPolicyVersion` (*type:* `integer()`) - Requested IAM Policy version. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec compute_resource_policies_get_iam_policy( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def compute_resource_policies_get_iam_policy( connection, project, region, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :optionsRequestedPolicyVersion => :query } request = Request.new() |> Request.method(:get) |> Request.url( "/projects/{project}/regions/{region}/resourcePolicies/{resource}/getIamPolicy", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "region" => URI.encode(region, &URI.char_unreserved?/1), "resource" => URI.encode(resource, &URI.char_unreserved?/1) } ) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Policy{}]) end @doc """ Creates a new resource policy. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `region` (*type:* `String.t`) - Name of the region for this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `:body` (*type:* `GoogleApi.Compute.V1.Model.ResourcePolicy.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_resource_policies_insert( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def compute_resource_policies_insert( connection, project, region, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/projects/{project}/regions/{region}/resourcePolicies", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "region" => URI.encode(region, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end @doc """ A list all the resource policies that have been configured for the specified project in specified region. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `region` (*type:* `String.t`) - Name of the region for this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`. For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` * `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`) * `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by `name` or `creationTimestamp desc` is supported. * `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results. * `:returnPartialSuccess` (*type:* `boolean()`) - Opt-in for partial success behavior which provides partial results in case of failure. The default value is false. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.ResourcePolicyList{}}` on success * `{:error, info}` on failure """ @spec compute_resource_policies_list( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.ResourcePolicyList.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def compute_resource_policies_list( connection, project, region, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :filter => :query, :maxResults => :query, :orderBy => :query, :pageToken => :query, :returnPartialSuccess => :query } request = Request.new() |> Request.method(:get) |> Request.url("/projects/{project}/regions/{region}/resourcePolicies", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "region" => URI.encode(region, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.ResourcePolicyList{}]) end @doc """ Sets the access control policy on the specified resource. Replaces any existing policy. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `region` (*type:* `String.t`) - The name of the region for this request. * `resource` (*type:* `String.t`) - Name or id of the resource for this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:body` (*type:* `GoogleApi.Compute.V1.Model.RegionSetPolicyRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec compute_resource_policies_set_iam_policy( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def compute_resource_policies_set_iam_policy( connection, project, region, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url( "/projects/{project}/regions/{region}/resourcePolicies/{resource}/setIamPolicy", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "region" => URI.encode(region, &URI.char_unreserved?/1), "resource" => URI.encode(resource, &URI.char_unreserved?/1) } ) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Policy{}]) end @doc """ Returns permissions that a caller has on the specified resource. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `region` (*type:* `String.t`) - The name of the region for this request. * `resource` (*type:* `String.t`) - Name or id of the resource for this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:body` (*type:* `GoogleApi.Compute.V1.Model.TestPermissionsRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.TestPermissionsResponse{}}` on success * `{:error, info}` on failure """ @spec compute_resource_policies_test_iam_permissions( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.TestPermissionsResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def compute_resource_policies_test_iam_permissions( connection, project, region, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url( "/projects/{project}/regions/{region}/resourcePolicies/{resource}/testIamPermissions", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "region" => URI.encode(region, &URI.char_unreserved?/1), "resource" => URI.encode(resource, &URI.char_unreserved?/1) } ) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.TestPermissionsResponse{}]) end end
48.666667
511
0.640984
73e1fd95d9405d2783b7486c1f9fd0b91190ac52
540
ex
Elixir
lib/consul.ex
am-kantox/consul-ex
b1c5e1f44f1afe4fd6bd55010832d17b8284b547
[ "MIT" ]
null
null
null
lib/consul.ex
am-kantox/consul-ex
b1c5e1f44f1afe4fd6bd55010832d17b8284b547
[ "MIT" ]
null
null
null
lib/consul.ex
am-kantox/consul-ex
b1c5e1f44f1afe4fd6bd55010832d17b8284b547
[ "MIT" ]
null
null
null
# # The MIT License (MIT) # # Copyright (c) 2014-2015 Undead Labs, LLC # defmodule Consul do defmodule ResponseError do defexception response: nil def exception(value) do %__MODULE__{response: value} end def message(%{response: response}) do "Got non-200 OK status code: #{response.status_code}" end end use Application def start(_type, _args) do import Supervisor.Spec, warn: false opts = [strategy: :one_for_one, name: Consul.Supervisor] Supervisor.start_link([], opts) end end
18.62069
60
0.677778
73e21d92dcb75a0e31618d9a6c6d991f13f445a7
64
ex
Elixir
test/support/accu_tester.ex
RobertDober/md0
b2337e69a9bea6b2b17951b75daa15fe7fe8cfad
[ "Apache-2.0" ]
null
null
null
test/support/accu_tester.ex
RobertDober/md0
b2337e69a9bea6b2b17951b75daa15fe7fe8cfad
[ "Apache-2.0" ]
null
null
null
test/support/accu_tester.ex
RobertDober/md0
b2337e69a9bea6b2b17951b75daa15fe7fe8cfad
[ "Apache-2.0" ]
null
null
null
defmodule Support.AccuTester do use Accu add_info 42 end
10.666667
31
0.75
73e253071816d8849dfd195e53cb2aa28e9bb3a8
135
exs
Elixir
test/wrenex_test.exs
lkarthee/wrenex
67c188374ea1bfdc14fc80a77baa44b9ff782be8
[ "MIT" ]
1
2020-09-27T10:23:56.000Z
2020-09-27T10:23:56.000Z
test/wrenex_test.exs
lkarthee/wrenex
67c188374ea1bfdc14fc80a77baa44b9ff782be8
[ "MIT" ]
null
null
null
test/wrenex_test.exs
lkarthee/wrenex
67c188374ea1bfdc14fc80a77baa44b9ff782be8
[ "MIT" ]
null
null
null
defmodule WrenexTest do use ExUnit.Case doctest Wrenex test "greets the world" do assert Wrenex.hello() == :world end end
15
35
0.703704
73e26dd61a5657d593f06e142b335a669bc6cacd
1,967
exs
Elixir
test/week_in_month_test.exs
kianmeng/cldr_calendars
af1ffe1b40100792e8e643ce09cc7db7224060b6
[ "Apache-2.0" ]
6
2019-08-29T12:31:03.000Z
2021-08-28T23:15:39.000Z
test/week_in_month_test.exs
kianmeng/cldr_calendars
af1ffe1b40100792e8e643ce09cc7db7224060b6
[ "Apache-2.0" ]
8
2019-11-08T09:13:00.000Z
2021-12-26T05:34:28.000Z
test/week_in_month_test.exs
kianmeng/cldr_calendars
af1ffe1b40100792e8e643ce09cc7db7224060b6
[ "Apache-2.0" ]
2
2020-05-08T12:19:01.000Z
2022-03-03T14:53:06.000Z
defmodule Cldr.Calendar.WeekInMonth.Test do use ExUnit.Case, async: true import Cldr.Calendar.Helper test "Week in month for gregorian dates with ISO Week configuration" do assert Cldr.Calendar.week_of_month(~D[2019-01-01]) == {1, 1} # The Gregorian calendar has an ISO Week week configuration # So this gregorian date is actually in the next year, first month assert Cldr.Calendar.week_of_month(~D[2018-12-31]) == {1, 1} assert Cldr.Calendar.week_of_month(~D[2019-12-30]) == {1, 1} assert Cldr.Calendar.week_of_month(~D[2019-12-28]) == {12, 4} end test "Week in month for gregorian dates with first week starting on January 1st" do assert Cldr.Calendar.week_of_month(date(2019, 01, 01, Cldr.Calendar.BasicWeek)) == {1, 1} assert Cldr.Calendar.week_of_month(date(2018, 12, 31, Cldr.Calendar.BasicWeek)) == {12, 5} assert Cldr.Calendar.week_of_month(date(2019, 12, 30, Cldr.Calendar.BasicWeek)) == {12, 5} assert Cldr.Calendar.week_of_month(date(2019, 12, 28, Cldr.Calendar.BasicWeek)) == {12, 4} assert Cldr.Calendar.week_of_month(date(2019, 04, 01, Cldr.Calendar.BasicWeek)) == {4, 1} assert Cldr.Calendar.week_of_month(date(2019, 04, 07, Cldr.Calendar.BasicWeek)) == {4, 1} assert Cldr.Calendar.week_of_month(date(2019, 04, 08, Cldr.Calendar.BasicWeek)) == {4, 2} end test "Week in month for ISOWeek which has a 4, 4, 5 configuration" do assert Cldr.Calendar.week_of_month(date(2019, 01, 1, Cldr.Calendar.ISOWeek)) == {1, 1} assert Cldr.Calendar.week_of_month(date(2018, 04, 1, Cldr.Calendar.ISOWeek)) == {1, 4} assert Cldr.Calendar.week_of_month(date(2019, 05, 1, Cldr.Calendar.ISOWeek)) == {2, 1} assert Cldr.Calendar.week_of_month(date(2019, 12, 1, Cldr.Calendar.ISOWeek)) == {3, 3} assert Cldr.Calendar.week_of_month(date(2019, 13, 1, Cldr.Calendar.ISOWeek)) == {3, 4} assert Cldr.Calendar.week_of_month(date(2019, 14, 1, Cldr.Calendar.ISOWeek)) == {4, 1} end end
56.2
94
0.704626
73e2907d3b7454beaf5b5db0a8fa8a197fdf051e
558
ex
Elixir
lib/ambry/media/bookmark.ex
froseph/ambry
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
[ "MIT" ]
12
2021-09-30T20:51:49.000Z
2022-01-27T04:09:32.000Z
lib/ambry/media/bookmark.ex
froseph/ambry
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
[ "MIT" ]
76
2021-10-01T05:45:11.000Z
2022-03-28T04:12:39.000Z
lib/ambry/media/bookmark.ex
froseph/ambry
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
[ "MIT" ]
2
2021-10-04T19:27:28.000Z
2022-01-13T22:36:38.000Z
defmodule Ambry.Media.Bookmark do @moduledoc """ A user defined bookmark for a specific media. """ use Ecto.Schema import Ecto.Changeset alias Ambry.Accounts.User alias Ambry.Media.Media schema "bookmarks" do belongs_to :media, Media belongs_to :user, User field :position, :decimal field :label, :string timestamps() end @doc false def changeset(bookmark, attrs) do bookmark |> cast(attrs, [:position, :label, :media_id, :user_id]) |> validate_required([:position, :media_id, :user_id]) end end
19.241379
60
0.679211
73e29a25c5dd89fea35d0a11712e0842d40818f4
1,081
ex
Elixir
test/support/conn_case.ex
palm86/hex_flora
26dc95f948763507b4d7cb643d98696936b45e07
[ "CC-BY-3.0" ]
null
null
null
test/support/conn_case.ex
palm86/hex_flora
26dc95f948763507b4d7cb643d98696936b45e07
[ "CC-BY-3.0" ]
8
2021-06-04T18:50:28.000Z
2021-08-08T19:43:46.000Z
test/support/conn_case.ex
palm86/hex_flora
26dc95f948763507b4d7cb643d98696936b45e07
[ "CC-BY-3.0" ]
null
null
null
defmodule HexFloraWeb.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use HexFloraWeb.ConnCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections import Plug.Conn import Phoenix.ConnTest import HexFloraWeb.ConnCase alias HexFloraWeb.Router.Helpers, as: Routes # The default endpoint for testing @endpoint HexFloraWeb.Endpoint end end setup _tags do {:ok, conn: Phoenix.ConnTest.build_conn()} end end
28.447368
62
0.73543
73e29dc7ddd4eafdcd001725bb72205fe1c30df5
81
exs
Elixir
.formatter.exs
ma2gedev/power_assert_ex
e0131555e272a37dc41bda7df6ea544918034fcc
[ "Apache-2.0" ]
228
2015-10-01T03:21:12.000Z
2021-11-12T03:32:19.000Z
.formatter.exs
ma2gedev/power_assert_ex
e0131555e272a37dc41bda7df6ea544918034fcc
[ "Apache-2.0" ]
28
2015-10-13T13:03:38.000Z
2020-12-26T08:25:11.000Z
.formatter.exs
ma2gedev/power_assert_ex
e0131555e272a37dc41bda7df6ea544918034fcc
[ "Apache-2.0" ]
9
2015-11-14T03:16:56.000Z
2020-12-04T05:23:29.000Z
[ inputs: [ "{mix,.formatter}.exs", "{config,lib}/**/*.{ex,exs}" ] ]
11.571429
32
0.432099
73e2c3ac78fbe3e3d07cdd9a390580aefc08f2ef
236
ex
Elixir
lib/email/sender.ex
jakehafdahl/email-service
696c1fce52e0d432ade513ce6ad36edcd76ec0cd
[ "MIT" ]
null
null
null
lib/email/sender.ex
jakehafdahl/email-service
696c1fce52e0d432ade513ce6ad36edcd76ec0cd
[ "MIT" ]
null
null
null
lib/email/sender.ex
jakehafdahl/email-service
696c1fce52e0d432ade513ce6ad36edcd76ec0cd
[ "MIT" ]
null
null
null
defmodule ProfessorStats.WeeklyEmailSender do def send(email_info) do # pass email info into a template to let that do the email building # for now just write the email info to a file File.write("/", inspect email_info) end end
29.5
69
0.762712
73e2d8d4cd8c599de9eb236c77c799e372740ded
172
exs
Elixir
priv/repo/migrations/20180123144215_add_avatar_to_sponsors.exs
PsOverflow/changelog.com
53f4ecfc39b021c6b8cfcc0fa11f29aff8038a7f
[ "MIT" ]
2,599
2016-10-25T15:02:53.000Z
2022-03-26T02:34:42.000Z
priv/repo/migrations/20180123144215_add_avatar_to_sponsors.exs
type1fool/changelog.com
fbec3528cc3f5adfdc75b008bb92b17efc4f248f
[ "MIT" ]
253
2016-10-25T20:29:24.000Z
2022-03-29T21:52:36.000Z
priv/repo/migrations/20180123144215_add_avatar_to_sponsors.exs
type1fool/changelog.com
fbec3528cc3f5adfdc75b008bb92b17efc4f248f
[ "MIT" ]
298
2016-10-25T15:18:31.000Z
2022-01-18T21:25:52.000Z
defmodule Changelog.Repo.Migrations.AddAvatarToSponsors do use Ecto.Migration def change do alter table(:sponsors) do add :avatar, :string end end end
17.2
58
0.72093
73e31db731e8b4ec1693ff8b8ec9b1250664c17e
1,596
ex
Elixir
hello/lib/hello_web/endpoint.ex
arilsonsouza/programming_phoenix
71a2a44e8cf84b6b133422899324363a09ccc07c
[ "MIT" ]
null
null
null
hello/lib/hello_web/endpoint.ex
arilsonsouza/programming_phoenix
71a2a44e8cf84b6b133422899324363a09ccc07c
[ "MIT" ]
null
null
null
hello/lib/hello_web/endpoint.ex
arilsonsouza/programming_phoenix
71a2a44e8cf84b6b133422899324363a09ccc07c
[ "MIT" ]
null
null
null
defmodule HelloWeb.Endpoint do use Phoenix.Endpoint, otp_app: :hello # The session will be stored in the cookie and signed, # this means its contents can be read but not tampered with. # Set :encryption_salt if you would also like to encrypt it. @session_options [ store: :cookie, key: "_hello_key", signing_salt: "P56MgG1v" ] socket "/socket", HelloWeb.UserSocket, websocket: true, longpoll: false socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]] # Serve at "/" the static files from "priv/static" directory. # # You should set gzip to true if you are running phx.digest # when deploying your static files in production. plug Plug.Static, at: "/", from: :hello, gzip: false, only: ~w(css fonts images js favicon.ico robots.txt) # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. if code_reloading? do socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket plug Phoenix.LiveReloader plug Phoenix.CodeReloader plug Phoenix.Ecto.CheckRepoStatus, otp_app: :hello end plug Phoenix.LiveDashboard.RequestLogger, param_key: "request_logger", cookie_key: "request_logger" plug Plug.RequestId plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Phoenix.json_library() plug Plug.MethodOverride plug Plug.Head plug Plug.Session, @session_options plug HelloWeb.Router end
29.018182
97
0.716165
73e32ba3edf7104a5a230be25f29408325c3e486
1,627
exs
Elixir
mix.exs
nerdslabs/plugmap
19a3338c9f9558ecb94e35e1038a8651d4f20929
[ "MIT" ]
3
2017-07-25T20:01:32.000Z
2019-10-27T06:30:21.000Z
mix.exs
nerdslabs/plugmap
19a3338c9f9558ecb94e35e1038a8651d4f20929
[ "MIT" ]
null
null
null
mix.exs
nerdslabs/plugmap
19a3338c9f9558ecb94e35e1038a8651d4f20929
[ "MIT" ]
null
null
null
defmodule Plugmap.Mixfile do use Mix.Project def project do [app: :plugmap, version: "0.2.0", elixir: "~> 1.0", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, package: package(), description: description(), deps: deps(), # Docs name: "Plugmap", source_url: "https://github.com/nerdslabs/plugmap", homepage_url: "https://github.com/nerdslabs/plugmap", docs: [main: "Plugmap", # The main page in the docs # logo: "path/to/logo.png", extras: ["README.md"]] ] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do # Specify extra applications you'll use from Erlang/Elixir [extra_applications: [:logger]] end # Dependencies can be Hex packages: # # {:my_dep, "~> 0.3.0"} # # Or git/path repositories: # # {:my_dep, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options defp deps do [{:ex_doc, "~> 0.14", only: :dev, runtime: false}, {:xml_builder, "~> 0.1.1"}, {:inch_ex, "~> 0.5", only: [:dev, :test]}, {:plug, "~> 1.0", only: :test}] end defp description do """ Sitemap XML generator """ end defp package do # These are the default files included in the package [ name: :plugmap, files: ["lib", "mix.exs", "README*", "LICENSE*"], maintainers: ["Krystian Drożdżyński"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/nerdslabs/plugmap"} ] end end
25.030769
79
0.587585
73e3623ea6aec7e428da749d20f94abc4350449c
7,524
ex
Elixir
lib/chalk_authorization.ex
Coruja-Digital/chalk_authorization
376bff2e769634cba4f8cfd048ab6227e0d7a477
[ "MIT" ]
null
null
null
lib/chalk_authorization.ex
Coruja-Digital/chalk_authorization
376bff2e769634cba4f8cfd048ab6227e0d7a477
[ "MIT" ]
null
null
null
lib/chalk_authorization.ex
Coruja-Digital/chalk_authorization
376bff2e769634cba4f8cfd048ab6227e0d7a477
[ "MIT" ]
null
null
null
defmodule ChalkAuthorization do @moduledoc """ Chalk is an authorization module with support for roles that can handle configurable custom actions and permissions. It also supports user and group based authorization. It is inspired in the Unix file permissions. """ @doc """ Chalk integrates the next functions to handle the authorization system. ## `permission_map` Get the translation between a permission and its integer representation. ## `permission_changeset(item, attrs)` Get the changeset to update the permissions. * `item` can be an atom or a string. * `attrs` can be a... ## `can?(user, permission, element)` Check if a user has permission to perform an action on a specific element. * `user` can be a map or nil. * `permission` and `element`, both can be an atom or a string. """ defmacro __using__(repo: repo, group_permissions: group_permissions) do quote do @doc """ Get the translation between a permission and its integer representation """ def permission_map, do: Application.get_env(:chalk_authorization, :permission_map, %{c: 1, r: 2, u: 4, d: 8}) @doc """ Get the changeset to update the permissions. """ def permissions_changeset(item, attrs), do: cast(item, attrs, [:superuser, :groups, :permissions]) @doc """ Check if a user has permission to perform an action on a specific element. `user` can be a `map` or `nil`. `permission` and `element`, both can be an atom or a string. It returns `true` or `false`. """ def can?(nil, _permission, _element), do: false def can?(user, permission, element) when is_atom(permission), do: can?(user, Atom.to_string(permission), element) def can?(%{superuser: true}, _permission, _element), do: true def can?(%{groups: [group | groups]} = user, permission, element), do: user |> get_group_permissions(group) |> Map.put(:groups, groups) |> can?(permission, element) def can?(user, permission, element), do: user |> get_permissions(Atom.to_string(element)) |> permissions_int_to_string |> String.contains?(permission) @doc nil defp get_group_permissions(), do: unquote(group_permissions) || %{} defp get_group_permissions(user, group), do: if( Map.has_key?(get_group_permissions(), group) && Enum.member?(user.groups, group), do: upgrade_to_group(user, Map.get(get_group_permissions(), group)), else: user ) defp upgrade_to_group(%{permissions: permissions} = user, group_permissions), do: Map.put( user, :permissions, upgrade_to_group(permissions, Map.to_list(group_permissions)) ) defp upgrade_to_group(permissions, []), do: permissions defp upgrade_to_group(permissions, [{permission, value} | group_permissions]), do: if( Map.has_key?(permissions, permission) && permissions[permission] >= value, do: permissions, else: Map.put(permissions, permission, value) |> upgrade_to_group(group_permissions) ) @doc nil def get_permissions(user, element) when is_atom(element), do: get_permissions(user, Atom.to_string(element)) def get_permissions(user, element), do: if(Map.has_key?(user.permissions, element), do: user.permissions[element], else: 0 ) @doc nil def add_group(user, []), do: user def add_group(user, [group | groups]), do: add_group(add_group(user, group), groups) def add_group(user, group) when not is_bitstring(group), do: add_group(user, "#{group}") def add_group(%{groups: groups} = user, group), do: user |> __MODULE__.permissions_changeset(%{ groups: (groups ++ [group]) |> Enum.sort() |> Enum.uniq() }) |> unquote(repo).update() |> elem(1) @doc nil def remove_group(user, []), do: user def remove_group(user, [group | groups]), do: remove_group(remove_group(user, group), groups) def remove_group(user, group) when not is_bitstring(group), do: remove_group(user, "#{group}") def remove_group(%{groups: groups} = user, group), do: user |> __MODULE__.permissions_changeset(%{ groups: Enum.reject(groups, fn g -> g == group end) }) |> unquote(repo).update() |> elem(1) @doc nil def is_a?(user, groups) when is_list(groups), do: groups |> Enum.all?(fn g -> user |> is_a?(g) end) def is_a?(user, group) when not is_bitstring(group), do: is_a?(user, "#{group}") def is_a?(%{groups: groups}, group), do: Enum.member?(groups, group) @doc nil def set_permissions(user, element, value) when is_atom(element), do: set_permissions(user, Atom.to_string(element), value) def set_permissions(user, element, value) when is_integer(value) do if value >= 0 and value <= Enum.sum(Map.values(permission_map())) do user |> __MODULE__.permissions_changeset(%{ permissions: Map.put(user.permissions, element, value) }) |> unquote(repo).update() else {:error, user} end end def set_permissions(user, element, value) do case value do "+" <> permissions -> set_permissions( user, element, get_permissions(user, element) + permissions_string_to_int(permissions) ) "-" <> permissions -> set_permissions( user, element, get_permissions(user, element) - permissions_string_to_int(permissions) ) _ -> set_permissions(user, element, permissions_string_to_int(value)) end end @doc nil defp permissions_string_to_int(string) do string |> String.graphemes() |> Enum.uniq() |> Enum.map(fn p -> permission_map()[String.to_atom(p)] end) |> Enum.sum() end @doc nil defp permissions_int_to_string(int) when is_integer(int) do keys = Map.keys(permission_map()) |> Enum.sort_by(fn k -> permission_map()[k] end) |> Enum.reverse() permissions_int_to_string(int, keys, []) end defp permissions_int_to_string(rest, [], acc) do cond do rest == 0 -> acc |> Enum.map(fn a -> Atom.to_string(a) end) |> Enum.join() true -> :error end end defp permissions_int_to_string(rest, [key | tail], acc) do if rest - permission_map()[key] >= 0 do permissions_int_to_string(rest - permission_map()[key], tail, [key | acc]) else permissions_int_to_string(rest, tail, acc) end end def set_superuser(%{superuser: _} = user, boolean) when is_boolean(boolean), do: user |> __MODULE__.permissions_changeset(%{superuser: boolean}) |> unquote(repo).update() |> elem(1) end end end
30.096
171
0.578283
73e39b4b44018203bba31aa5bc4bc6f058ff1d54
3,197
ex
Elixir
lib/auto_api/states/lights_state.ex
highmobility/hm-auto-api-elixir
026c3f50871c56877a4acd5f39a8887118a87bb5
[ "MIT" ]
4
2018-01-19T16:11:10.000Z
2019-12-13T16:35:10.000Z
lib/auto_api/states/lights_state.ex
highmobility/auto-api-elixir
026c3f50871c56877a4acd5f39a8887118a87bb5
[ "MIT" ]
5
2020-07-16T07:20:21.000Z
2021-09-22T10:18:04.000Z
lib/auto_api/states/lights_state.ex
highmobility/hm-auto-api-elixir
026c3f50871c56877a4acd5f39a8887118a87bb5
[ "MIT" ]
1
2021-02-17T18:36:13.000Z
2021-02-17T18:36:13.000Z
# AutoAPI # The MIT License # # Copyright (c) 2018- High-Mobility GmbH (https://high-mobility.com) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. defmodule AutoApi.LightsState do @moduledoc """ Lights state """ alias AutoApi.{CommonData, State} use AutoApi.State, spec_file: "lights.json" @type front_exterior_light :: :inactive | :active | :active_with_full_beam | :dlr | :automatic @type ambient_light :: %{ red: integer, green: integer, blue: integer } @type light :: %{ location: CommonData.location_longitudinal(), state: CommonData.activity() } @type reading_lamp :: %{ location: CommonData.location(), state: CommonData.activity() } @type switch_position :: :automatic | :dipped_headlights | :parking_light_right | :parking_light_left | :sidelights @type t :: %__MODULE__{ front_exterior_light: State.property(front_exterior_light), rear_exterior_light: State.property(CommonData.activity()), ambient_light_colour: State.property(ambient_light), reverse_light: State.property(CommonData.activity()), emergency_brake_light: State.property(CommonData.activity()), fog_lights: State.multiple_property(light), reading_lamps: State.multiple_property(reading_lamp), interior_lights: State.multiple_property(light), switch_position: State.property(switch_position()) } @doc """ Build state based on binary value iex> bin = <<5, 0, 4, 1, 0, 1, 1>> iex> AutoApi.LightsState.from_bin(bin) %AutoApi.LightsState{reverse_light: %AutoApi.Property{data: :active}} """ @spec from_bin(binary) :: __MODULE__.t() def from_bin(bin) do parse_bin_properties(bin, %__MODULE__{}) end @doc """ Parse state to bin iex> state = %AutoApi.LightsState{reverse_light: %AutoApi.Property{data: :active}} iex> AutoApi.LightsState.to_bin(state) <<5, 0, 4, 1, 0, 1, 1>> """ @spec to_bin(__MODULE__.t()) :: binary def to_bin(%__MODULE__{} = state) do parse_state_properties(state) end end
35.921348
96
0.689396
73e3b0ded9cc35c5d0673636f045fbb9cbbb93f0
1,369
exs
Elixir
test/boltkit_test.exs
kristofka/bolt_sips
2471f35862b6031bb14626c941f3bc04b1949066
[ "Apache-2.0" ]
242
2016-09-09T22:32:00.000Z
2022-02-20T18:50:29.000Z
test/boltkit_test.exs
kristofka/bolt_sips
2471f35862b6031bb14626c941f3bc04b1949066
[ "Apache-2.0" ]
100
2016-10-18T04:19:09.000Z
2021-11-15T19:14:47.000Z
test/boltkit_test.exs
kristofka/bolt_sips
2471f35862b6031bb14626c941f3bc04b1949066
[ "Apache-2.0" ]
51
2016-10-31T20:05:52.000Z
2022-01-20T11:45:49.000Z
defmodule Bolt.Sips.BoltStubTest do @moduledoc """ !!Remember!! you cannot reuse the boltstub across the tests, therefore must use a unique prefix or use the one returned by the BoltKitCase """ use Bolt.Sips.BoltKitCase, async: false @moduletag :boltkit @tag boltkit: %{ url: "bolt://127.0.0.1:9001", scripts: [ {"test/scripts/return_x.bolt", 9001} ], debug: true } test "test/scripts/return_x.bolt", %{prefix: prefix} do assert %Bolt.Sips.Response{results: [%{"x" => 1}]} = Bolt.Sips.conn(:direct, prefix: prefix) |> Bolt.Sips.query!("RETURN $x", %{x: 1}) end @tag boltkit: %{ url: "bolt://127.0.0.1:9001", scripts: [ {"test/scripts/count.bolt", 9001} ] } test "test/scripts/count.bolt", %{prefix: prefix} do assert %Bolt.Sips.Response{ results: [ %{"n" => 1}, %{"n" => 2}, %{"n" => 3}, %{"n" => 4}, %{"n" => 5}, %{"n" => 6}, %{"n" => 7}, %{"n" => 8}, %{"n" => 9}, %{"n" => 10} ] } = Bolt.Sips.conn(:direct, prefix: prefix) |> Bolt.Sips.query!("UNWIND range(1, 10) AS n RETURN n") end end
27.938776
72
0.449233
73e3c81787f8045c389092ab06a88f6caea8bff3
299
ex
Elixir
lib/inmana.ex
marciorasf/next-level-week-5-Elixir
5af63fcf04202111db22209f61928772dbb167ad
[ "MIT" ]
null
null
null
lib/inmana.ex
marciorasf/next-level-week-5-Elixir
5af63fcf04202111db22209f61928772dbb167ad
[ "MIT" ]
null
null
null
lib/inmana.ex
marciorasf/next-level-week-5-Elixir
5af63fcf04202111db22209f61928772dbb167ad
[ "MIT" ]
null
null
null
defmodule Inmana do alias Inmana.{Restaurants, Supplies} # Restaurants defdelegate create_restaurant(params), to: Restaurants.Create, as: :call # Supplies defdelegate create_supply(params), to: Supplies.Create, as: :call defdelegate get_supply(params), to: Supplies.Get, as: :call end
27.181818
74
0.755853
73e3dd9cbae64b592628e716b5e47d7fff5398f6
376
ex
Elixir
discuss/lib/discuss_web/controllers/plugs/set_user.ex
ivoferro/elixir_phoenix_bootcamp
e3445dbf90c1eea81e8aa34cc7801934a516d7d7
[ "MIT" ]
null
null
null
discuss/lib/discuss_web/controllers/plugs/set_user.ex
ivoferro/elixir_phoenix_bootcamp
e3445dbf90c1eea81e8aa34cc7801934a516d7d7
[ "MIT" ]
null
null
null
discuss/lib/discuss_web/controllers/plugs/set_user.ex
ivoferro/elixir_phoenix_bootcamp
e3445dbf90c1eea81e8aa34cc7801934a516d7d7
[ "MIT" ]
null
null
null
defmodule DiscussWeb.Plugs.SetUser do import Plug.Conn alias Discuss.Accounts def init(_params) do end def call(conn, _params) do user_id = conn |> get_session(:user_id) cond do user = user_id && Accounts.get_user!(user_id) -> conn |> assign(:user, user) true -> assign(conn, :user, nil) end end end
16.347826
54
0.593085
73e3ec5e26d3eee06d55815d0edf721b46ca6d4b
856
ex
Elixir
lib/triton/keyspace.ex
jonzlin95/triton
7201102a10148db27bac1172f0f4d5fec5672674
[ "MIT" ]
71
2017-11-29T03:40:54.000Z
2022-01-10T22:11:48.000Z
lib/triton/keyspace.ex
jonzlin95/triton
7201102a10148db27bac1172f0f4d5fec5672674
[ "MIT" ]
19
2018-04-13T18:25:05.000Z
2020-12-24T05:22:41.000Z
lib/triton/keyspace.ex
jonzlin95/triton
7201102a10148db27bac1172f0f4d5fec5672674
[ "MIT" ]
23
2017-11-02T21:34:54.000Z
2021-08-24T08:29:34.000Z
defmodule Triton.Keyspace do defmacro __using__(_) do quote do import Triton.Keyspace end end defmacro keyspace(name, [conn: conn], [do: block]) do quote do @after_compile __MODULE__ @keyspace [] @fields %{} unquote(block) Module.put_attribute(__MODULE__, :keyspace, [ { :__conn__, unquote(conn) }, { :__name__, unquote(name) } | Module.get_attribute(__MODULE__, :keyspace) ]) def __after_compile__(_, _), do: Triton.Setup.Keyspace.setup(__MODULE__.__struct__) defstruct Module.get_attribute(__MODULE__, :keyspace) end end defmacro with_options(opts) do quote do Module.put_attribute(__MODULE__, :keyspace, [ { :__with_options__, unquote(opts) } | Module.get_attribute(__MODULE__, :keyspace) ]) end end end
22.526316
89
0.63785
73e42984edceee6ddd4628986316fa89259ec6b0
2,502
ex
Elixir
apps/ex_cucumber/lib/ex_cucumber/gherkin/traverser/scenario_traverser.ex
Ajwah/ex_cucumber
f2b9cf06caeef624c66424ae6160f274dc133fc6
[ "Apache-2.0" ]
2
2021-05-18T18:20:05.000Z
2022-02-13T00:15:06.000Z
apps/ex_cucumber/lib/ex_cucumber/gherkin/traverser/scenario_traverser.ex
Ajwah/ex_cucumber
f2b9cf06caeef624c66424ae6160f274dc133fc6
[ "Apache-2.0" ]
2
2021-04-22T00:28:17.000Z
2021-05-19T21:04:20.000Z
apps/ex_cucumber/lib/ex_cucumber/gherkin/traverser/scenario_traverser.ex
Ajwah/ex_cucumber
f2b9cf06caeef624c66424ae6160f274dc133fc6
[ "Apache-2.0" ]
4
2021-04-14T03:07:45.000Z
2021-12-12T21:23:59.000Z
defmodule ExCucumber.Gherkin.Traverser.Scenario do @moduledoc false alias ExCucumber.Gherkin.Traverser.Ctx alias ExCucumber.Gherkin.Traverser, as: MainTraverser alias ExGherkin.AstNdjson.Examples def run(%ExGherkin.AstNdjson.Scenario{} = s, acc, parse_tree) do s |> relevant_examples |> Enum.each(fn {tags, rows} -> rows |> Enum.each(fn row -> steps = if s.steps do s.steps else IO.warn( "Empty scenario encountered: #{acc.feature_file}:#{s.location.line}:#{ s.location.column }" ) [] end steps |> Enum.reduce(Ctx.extra(acc, scenario_meta(acc.extra.context_history, s, tags, row)), fn %ExGherkin.AstNdjson.Step{} = step, a -> MainTraverser.run(step, a, parse_tree) end) end) end) end defp example_tables(nil), do: [{nil, [%{}]}] defp example_tables([]), do: [{nil, [%{}]}] defp example_tables(examples), do: Enum.map(examples, &Examples.table_to_tagged_map/1) defp relevant_examples(scenario) do {tags, rows} = example_tables(scenario.examples) |> List.first() [{tags, rows}] end defp scenario_meta(context_history, scenario, example_tags, example_row) when is_map(example_row) do scenario_details = if scenario.parsed_sentence do title = scenario.parsed_sentence.vars |> Enum.reduce(scenario.parsed_sentence.template, fn var, template -> example = Map.fetch!(example_row, var) String.replace(template, "%", "#{example}", global: false) end) %{ name: :scenario, type: scenario.keyword, raw: scenario.name, title: title, location: Map.from_struct(scenario.location), keyword: scenario.keyword, tags: scenario.tags } else %{ name: :scenario, type: scenario.keyword, raw: scenario.name, title: scenario.name, location: Map.from_struct(scenario.location), keyword: scenario.keyword, tags: scenario.tags } end context_history = context_history |> Enum.reject(&(&1.name == :background)) %{ step_history: [], context_history: [scenario_details | context_history], scenario: scenario_details, examples: %{tags: example_tags, row: example_row} } end end
28.758621
97
0.586731
73e42fc42d8f5d7c52e199bf07022a1ca90844e6
882
ex
Elixir
clients/cloud_iot/lib/google_api/cloud_iot/v1/metadata.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
1
2021-10-01T09:20:41.000Z
2021-10-01T09:20:41.000Z
clients/cloud_iot/lib/google_api/cloud_iot/v1/metadata.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/cloud_iot/lib/google_api/cloud_iot/v1/metadata.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.CloudIot.V1 do @moduledoc """ API client metadata for GoogleApi.CloudIot.V1. """ @discovery_revision "20210222" def discovery_revision(), do: @discovery_revision end
32.666667
74
0.758503
73e44a0692dfd87ab0c8e9b50f2d317b6a656746
1,854
ex
Elixir
lib/protobuf/extype/timestamp.ex
addcninblue/protobuf-elixir
a18144710fe394909a37d4533bbc28a5636311d1
[ "MIT" ]
4
2021-01-16T02:21:44.000Z
2022-03-04T18:42:18.000Z
lib/protobuf/extype/timestamp.ex
addcninblue/protobuf-elixir
a18144710fe394909a37d4533bbc28a5636311d1
[ "MIT" ]
5
2020-04-07T20:22:38.000Z
2020-09-23T02:28:36.000Z
lib/protobuf/extype/timestamp.ex
addcninblue/protobuf-elixir
a18144710fe394909a37d4533bbc28a5636311d1
[ "MIT" ]
4
2020-07-22T23:38:34.000Z
2021-03-26T18:52:54.000Z
defimpl Extype.Protocol, for: Google.Protobuf.Timestamp do @moduledoc """ Implement DateTime and NaiveDateTime casting for Google Timestamp. """ def validate_and_to_atom_extype!(Google.Protobuf.Timestamp, "NaiveDateTime.t()"), do: :naivedatetime def validate_and_to_atom_extype!(Google.Protobuf.Timestamp, "DateTime.t()"), do: :datetime def validate_and_to_atom_extype!(type, extype) do raise "Invalid extype pairing, #{extype} not compatible with #{type}. " <> "Supported types are DateTime.t() or NaiveDateTime.t()" end def type_default(_type, _extype), do: nil def new(_type, value, _extype), do: value def encode_type(_type, v, extype) do v = if extype == :naivedatetime, do: DateTime.from_naive!(v, "Etc/UTC"), else: v unix = DateTime.to_unix(v, :nanosecond) seconds = System.convert_time_unit(unix, :nanosecond, :second) nanos = unix - System.convert_time_unit(seconds, :second, :nanosecond) value = Google.Protobuf.Timestamp.new(seconds: seconds, nanos: nanos) Protobuf.encode(value) end def decode_type(type, val, extype) do protobuf_timestamp = Protobuf.decode(val, type) value = protobuf_timestamp.seconds |> System.convert_time_unit(:second, :nanosecond) |> Kernel.+(protobuf_timestamp.nanos) |> DateTime.from_unix!(:nanosecond) if extype == :naivedatetime, do: DateTime.to_naive(value), else: value end def verify_type(_type, %DateTime{} = _val, :datetime), do: :ok def verify_type(_type, %NaiveDateTime{} = _val, :naivedatetime), do: :ok def verify_type(_type, _val, :datetime), do: {:error, "non-DateTime value for a timestamp field with extype DateTime.t()"} def verify_type(_type, _val, :naivedatetime), do: {:error, "non-NaiveDateTime value for a timestamp field with extype NaiveDateTime.t()"} end
34.333333
95
0.70658
73e4640220457f1a38440d3d0bed5a5145c12aa7
1,970
exs
Elixir
config/prod.exs
esemeniuc/selfme
f6f11eb32bab909c199d7a2090a8370470feaf27
[ "MIT" ]
1
2019-07-21T00:36:01.000Z
2019-07-21T00:36:01.000Z
config/prod.exs
esemeniuc/selfme
f6f11eb32bab909c199d7a2090a8370470feaf27
[ "MIT" ]
10
2019-08-01T03:50:13.000Z
2022-02-26T15:50:07.000Z
config/prod.exs
esemeniuc/selfme
f6f11eb32bab909c199d7a2090a8370470feaf27
[ "MIT" ]
null
null
null
use Mix.Config # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :selfme, SelfmeWeb.Endpoint, url: [host: "example.com", port: 80], cache_static_manifest: "priv/static/cache_manifest.json" # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :selfme, SelfmeWeb.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [ # :inet6, # port: 443, # cipher_suite: :strong, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH") # ] # # The `cipher_suite` is set to `:strong` to support only the # latest and more secure SSL ciphers. This means old browsers # and clients may not be supported. You can set it to # `:compatible` for wider support. # # `:keyfile` and `:certfile` expect an absolute path to the key # and cert in disk or a relative path inside priv, for example # "priv/ssl/server.key". For all supported SSL configuration # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 # # We also recommend setting `force_ssl` in your endpoint, ensuring # no data is ever sent via http, always redirecting to https: # # config :selfme, SelfmeWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # Finally import the config/prod.secret.exs which loads secrets # and configuration from environment variables. import_config "prod.secret.exs"
35.178571
66
0.71269
73e4b0fc1f74825e15bd9ef05de3ef65f409989a
2,799
ex
Elixir
lib/nebulex_redis_adapter/cluster.ex
scottming/nebulex_redis_adapter
896a023f7048473f7330e85274e4e90789eafdaf
[ "MIT" ]
null
null
null
lib/nebulex_redis_adapter/cluster.ex
scottming/nebulex_redis_adapter
896a023f7048473f7330e85274e4e90789eafdaf
[ "MIT" ]
null
null
null
lib/nebulex_redis_adapter/cluster.ex
scottming/nebulex_redis_adapter
896a023f7048473f7330e85274e4e90789eafdaf
[ "MIT" ]
null
null
null
defmodule NebulexRedisAdapter.Cluster do # Default Cluster @moduledoc false alias NebulexRedisAdapter.Cluster.Supervisor, as: ClusterSupervisor alias NebulexRedisAdapter.{Connection, Pool} @type hash_slot :: {:"$hash_slot", term} @type node_entry :: {node_name :: atom, pool_size :: pos_integer} @type nodes_config :: [node_entry] @compile {:inline, pool_name: 2} ## API @spec init(Keyword.t()) :: {:ok, [:supervisor.child_spec() | {module(), term()} | module()]} def init(opts) do cache = Keyword.fetch!(opts, :cache) children = for {node_name, node_opts} <- Keyword.get(opts, :nodes, []) do arg = {Connection, [name: pool_name(cache, node_name)] ++ node_opts} Supervisor.child_spec({ClusterSupervisor, arg}, type: :supervisor, id: {cache, node_name}) end {:ok, children} end @spec exec!( Nebulex.Adapter.adapter_meta(), Redix.command(), init_acc :: any, reducer :: (any, any -> any) ) :: any | no_return def exec!( %{name: name, nodes: nodes}, command, init_acc \\ nil, reducer \\ fn res, _ -> res end ) do # TODO: Perhaps this should be performed in parallel Enum.reduce(nodes, init_acc, fn {node_name, pool_size}, acc -> name |> pool_name(node_name) |> Pool.get_conn(pool_size) |> Redix.command!(command) |> reducer.(acc) end) end @spec get_conn(Nebulex.Cache.t(), nodes_config, atom) :: atom def get_conn(cache, nodes, node_name) do pool_size = Keyword.fetch!(nodes, node_name) cache |> pool_name(node_name) |> Pool.get_conn(pool_size) end @spec get_conn(Nebulex.Cache.t(), nodes_config, term, module) :: atom def get_conn(cache, nodes, key, module) do {node_name, pool_size} = get_node(module, nodes, key) cache |> pool_name(node_name) |> Pool.get_conn(pool_size) end @spec group_keys_by_hash_slot(Enum.t(), nodes_config, module) :: map def group_keys_by_hash_slot(enum, nodes, module) do Enum.reduce(enum, %{}, fn {key, _} = entry, acc -> hash_slot = hash_slot(module, key, nodes) Map.put(acc, hash_slot, [entry | Map.get(acc, hash_slot, [])]) key, acc -> hash_slot = hash_slot(module, key, nodes) Map.put(acc, hash_slot, [key | Map.get(acc, hash_slot, [])]) end) end @spec pool_name(Nebulex.Cache.t(), atom) :: atom def pool_name(cache, node_name), do: :"#{cache}.#{node_name}" ## Private Functions defp get_node(module, nodes, key) do index = module.hash_slot(key, length(nodes)) Enum.at(nodes, index) end defp hash_slot(module, key, nodes) do node = module |> get_node(nodes, key) |> elem(0) {:"$hash_slot", node} end end
27.712871
98
0.622365
73e4bd4ac7440a73a717ca45a19e4eede81886b7
1,153
ex
Elixir
lib/iban/iban.ex
ionutm87/validators_ro
8a78dc87a25419373f714380fa81d15d8516fa19
[ "MIT" ]
1
2016-09-06T17:40:46.000Z
2016-09-06T17:40:46.000Z
lib/iban/iban.ex
ionutm87/validators_ro
8a78dc87a25419373f714380fa81d15d8516fa19
[ "MIT" ]
null
null
null
lib/iban/iban.ex
ionutm87/validators_ro
8a78dc87a25419373f714380fa81d15d8516fa19
[ "MIT" ]
1
2020-11-27T16:10:53.000Z
2020-11-27T16:10:53.000Z
defmodule ValidatorsRo.IBAN do @moduledoc """ See `ValidatorsRo` """ defmacro __using__(_opts) do quote location: :keep do @bic_regexp ~r"([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$" @doc """ Provides basic validation of *Romanian* IBANs http://www.bnr.ro/files/d/Legislatie/EN/Reg_IBAN.pdf """ @spec valid_iban?(String.t) :: boolean def valid_iban?(iban) do {t, h} = iban |> String.trim |> String.split_at(4) n = transpose(h <> t) case Integer.parse(n) do {n, ""} -> rem(n, 97) === 1 _ -> false end end @doc """ Provides basic validation of BICs https://en.wikipedia.org/wiki/ISO_9362 """ @spec valid_bic?(String.t) :: boolean def valid_bic?(bic) do Regex.match?(@bic_regexp, bic) end defp transpose(iban) do Regex.replace ~r/[A-Z]/, String.upcase(iban), fn x -> x |> String.to_charlist |> hd |> Kernel.-(55) |> to_string end end end end end
23.530612
82
0.501301
73e4ec6612d59ee86223fce42955268fa0710796
957
ex
Elixir
Microsoft.Azure.Management.Preview.Addons/lib/microsoft/azure/management/preview/addons/model/canonical_support_plan_response_envelope.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
4
2018-09-29T03:43:15.000Z
2021-04-01T18:30:46.000Z
Microsoft.Azure.Management.Preview.Addons/lib/microsoft/azure/management/preview/addons/model/canonical_support_plan_response_envelope.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
Microsoft.Azure.Management.Preview.Addons/lib/microsoft/azure/management/preview/addons/model/canonical_support_plan_response_envelope.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
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 Microsoft.Azure.Management.Preview.Addons.Model.CanonicalSupportPlanResponseEnvelope do @moduledoc """ The status of the Canonical support plan. """ @derive [Poison.Encoder] defstruct [ :"id", :"name", :"type", :"properties" ] @type t :: %__MODULE__{ :"id" => String.t, :"name" => String.t, :"type" => String.t, :"properties" => CanonicalSupportPlanProperties } end defimpl Poison.Decoder, for: Microsoft.Azure.Management.Preview.Addons.Model.CanonicalSupportPlanResponseEnvelope do import Microsoft.Azure.Management.Preview.Addons.Deserializer def decode(value, options) do value |> deserialize(:"properties", :struct, Microsoft.Azure.Management.Preview.Addons.Model.CanonicalSupportPlanProperties, options) end end
28.147059
131
0.724138
73e4f9fc5aacbcd7c32f42550ee0b34a2b83c44e
735
exs
Elixir
apps/neoscan_sync/test/neoscan_sync/token_syncer_test.exs
vincentgeneste/neo-scan
4a654575331eeb3eb12d4fd61696a7bd6dbca3ce
[ "MIT" ]
75
2017-07-23T02:45:32.000Z
2021-12-13T11:04:17.000Z
apps/neoscan_sync/test/neoscan_sync/token_syncer_test.exs
vincentgeneste/neo-scan
4a654575331eeb3eb12d4fd61696a7bd6dbca3ce
[ "MIT" ]
252
2017-07-13T19:36:00.000Z
2021-07-28T18:40:00.000Z
apps/neoscan_sync/test/neoscan_sync/token_syncer_test.exs
vincentgeneste/neo-scan
4a654575331eeb3eb12d4fd61696a7bd6dbca3ce
[ "MIT" ]
87
2017-07-23T02:45:34.000Z
2022-03-02T14:54:27.000Z
defmodule NeoscanSync.TokenSyncerTest do use NeoscanSync.DataCase alias Neoscan.Repo alias Neoscan.Asset alias NeoscanSync.TokenSyncer test "handle_cast/2" do contract = Base.decode16!("3a4acd3647086e7c44398aac0349802e6a171129", case: :mixed) assert {:noreply, %{contracts: [contract]}} == TokenSyncer.handle_cast( {:contract, 0, contract}, %{contracts: [contract]} ) assert 0 == Enum.count(Repo.all(from(Asset))) assert {:noreply, %{contracts: [contract]}} == TokenSyncer.handle_cast( {:contract, 0, contract}, %{contracts: []} ) assert 1 == Enum.count(Repo.all(from(Asset))) end end
26.25
87
0.598639
73e52a4b52f3262485995ff58997c7aab6c7d490
257
ex
Elixir
test/support/models/channel/sms_result.ex
bducharme/polymorphic_embed
a9ec68169bc14e41b07cac479558d0b367c38379
[ "Apache-2.0" ]
null
null
null
test/support/models/channel/sms_result.ex
bducharme/polymorphic_embed
a9ec68169bc14e41b07cac479558d0b367c38379
[ "Apache-2.0" ]
null
null
null
test/support/models/channel/sms_result.ex
bducharme/polymorphic_embed
a9ec68169bc14e41b07cac479558d0b367c38379
[ "Apache-2.0" ]
1
2022-01-25T00:37:17.000Z
2022-01-25T00:37:17.000Z
defmodule PolymorphicEmbed.Channel.SMSResult do use Ecto.Schema import Ecto.Changeset @primary_key false embedded_schema do field(:success, :boolean) end def changeset(struct, attrs) do struct |> cast(attrs, [:success]) end end
16.0625
47
0.712062
73e55a628e27a19e30b7f3f81f4f529d3a486e8a
4,025
ex
Elixir
lib/exdns/zone/cache.ex
jeanparpaillon/exdns
53b7fc780399eda96d42052e11e03d5eb0dcd789
[ "MIT" ]
16
2016-05-26T10:11:57.000Z
2021-01-08T15:09:19.000Z
lib/exdns/zone/cache.ex
jeanparpaillon/exdns
53b7fc780399eda96d42052e11e03d5eb0dcd789
[ "MIT" ]
9
2016-08-11T00:48:27.000Z
2020-09-16T22:10:07.000Z
lib/exdns/zone/cache.ex
jeanparpaillon/exdns
53b7fc780399eda96d42052e11e03d5eb0dcd789
[ "MIT" ]
11
2016-08-10T08:13:36.000Z
2021-04-03T10:20:11.000Z
defmodule Exdns.Zone.Cache do @moduledoc """ In-memory cache for all zones. """ use GenServer require Exdns.Records def start_link() do GenServer.start_link(__MODULE__, [], name: Exdns.Zone.Cache) end def find_zone(qname) do find_zone(normalize_name(qname), get_authority(qname)) end def find_zone(qname, {:error, _}) do find_zone(qname, []) end def find_zone(qname, {:ok, authority}) do find_zone(qname, authority) end def find_zone(_qname, []) do {:error, :not_authoritative} end def find_zone(qname, authorities) when is_list(authorities) do find_zone(qname, List.last(authorities)) end def find_zone(name, authority) do name = normalize_name(name) case :dns.dname_to_labels(name) do [] -> {:error, :zone_not_found} [_|labels] -> case get_zone(name) do {:ok, zone} -> zone {:error, :zone_not_found} -> if name == Exdns.Records.dns_rr(authority, :name) do {:error, :zone_not_found} else find_zone(:dns.labels_to_dname(labels), authority) end end end end def get_zone(name) do name = normalize_name(name) case Exdns.Storage.select(:zones, name) do [{^name, zone}] -> {:ok, %{zone | records: [], records_by_name: :trimmed}} _ -> get_fallback() end end defp get_fallback do case get_wildcard_zone() do {:ok, zone} -> {:ok, %{zone | records: [], records_by_name: :trimmed}} _ -> {:error, :zone_not_found} end end defp get_wildcard_zone do if Exdns.Config.wildcard_fallback? do case Exdns.Storage.select(:zones, "*") do [{"*", zone}] -> {:ok, zone} _ -> {:error, :zone_not_found} end else {:error, :zone_not_found} end end def get_authority(name) when is_binary(name) do case find_zone_in_cache(normalize_name(name)) do {:ok, zone} -> {:ok, zone.authority} _ -> {:error, :authority_not_found} end end def get_authority(message) do case Exdns.Records.dns_message(message, :questions) do [] -> {:error, :no_question} questions -> List.last(questions) |> Exdns.Records.dns_query(:name) |> get_authority() end end def get_delegations(name) do case find_zone_in_cache(name) do {:ok, zone} -> Enum.filter(zone.records, fn(r) -> apply(Exdns.Records.match_type(:dns_terms_const.dns_type_ns), [r]) and apply(Exdns.Records.match_delegation(name), [r]) end) _ -> [] end end def get_records_by_name(name) do case find_zone_in_cache(name) do {:ok, zone} -> Map.get(zone.records_by_name, normalize_name(name), []) _ -> [] end end def in_zone?(name) do case find_zone_in_cache(name) do {:ok, zone} -> is_name_in_zone(name, zone) _ -> false end end def put_zone(name, zone) do Exdns.Storage.insert(:zones, {normalize_name(name), zone}) :ok end # GenServer callbacks def init([]) do Exdns.Storage.create(:schema) Exdns.Storage.create(:zones) Exdns.Storage.create(:authorities) {:ok, %{:parsers => []}} end # Internal API def is_name_in_zone(name, zone) do if Map.has_key?(zone.records_by_name, normalize_name(name)) do true else case :dns.dname_to_labels(name) do [] -> false [_] -> false [_|labels] -> is_name_in_zone(:dns.labels_to_dname(labels), zone) end end end def find_zone_in_cache(name) do find_zone_in_cache(normalize_name(name), :dns.dname_to_labels(name)) end def find_zone_in_cache(_name, []) do get_wildcard_zone() end def find_zone_in_cache(name, [_|labels]) do case Exdns.Storage.select(:zones, name) do [{_name, zone}] -> {:ok, zone} _ -> case labels do [] -> get_wildcard_zone() _ -> find_zone_in_cache(:dns.labels_to_dname(labels), labels) end end end def normalize_name(name), do: String.downcase(name) end
25.314465
167
0.624099
73e587ff66e9c1d1d06aff920559b69b8f414cfc
6,474
ex
Elixir
apps/tai/lib/tai/commander.ex
yurikoval/tai
94254b45d22fa0307b01577ff7c629c7280c0295
[ "MIT" ]
null
null
null
apps/tai/lib/tai/commander.ex
yurikoval/tai
94254b45d22fa0307b01577ff7c629c7280c0295
[ "MIT" ]
78
2020-10-12T06:21:43.000Z
2022-03-28T09:02:00.000Z
apps/tai/lib/tai/commander.ex
yurikoval/tai
94254b45d22fa0307b01577ff7c629c7280c0295
[ "MIT" ]
null
null
null
defmodule Tai.Commander do use GenServer def start_link(_) do GenServer.start_link(__MODULE__, :ok, name: __MODULE__) end def accounts(options \\ []) do options |> to_dest() |> GenServer.call(:accounts) end def products(options \\ []) do options |> to_dest() |> GenServer.call(:products) end def fees(options \\ []) do options |> to_dest() |> GenServer.call(:fees) end def markets(options \\ []) do options |> to_dest() |> GenServer.call(:markets) end def orders(options \\ []) do options |> to_dest() |> GenServer.call(:orders) end def new_orders(query \\ nil, options \\ []) do options |> to_dest() |> GenServer.call({:new_orders, query, options}) end def new_orders_count(query \\ nil, options \\ []) do options |> to_dest() |> GenServer.call({:new_orders_count, query}) end def get_new_order_by_client_id(client_id, options \\ []) do options |> to_dest() |> GenServer.call({:get_new_order_by_client_id, client_id}) end def get_new_orders_by_client_ids(client_ids, options \\ []) do options |> to_dest() |> GenServer.call({:get_new_orders_by_client_ids, client_ids}) end def order_transitions(client_id, query \\ nil, options \\ []) do options |> to_dest() |> GenServer.call({:order_transitions, client_id, query, options}) end def order_transitions_count(client_id, query \\ nil, options \\ []) do options |> to_dest() |> GenServer.call({:order_transitions_count, client_id, query}) end def failed_order_transitions(client_id, query \\ nil, options \\ []) do options |> to_dest() |> GenServer.call({:failed_order_transitions, client_id, query, options}) end def failed_order_transitions_count(client_id, query \\ nil, options \\ []) do options |> to_dest() |> GenServer.call({:failed_order_transitions_count, client_id, query}) end def delete_all_orders(options \\ []) do options |> to_dest() |> GenServer.call(:delete_all_orders, 60_000) end def positions(options \\ []) do options |> to_dest() |> GenServer.call(:positions) end def venues(options \\ []) do options |> to_dest() |> GenServer.call({:venues, options}) end def start_venue(venue_id, options \\ []) do options |> to_dest |> GenServer.call({:start_venue, venue_id, options}) end def stop_venue(venue_id, options \\ []) do options |> to_dest |> GenServer.call({:stop_venue, venue_id, options}) end def advisors(options \\ []) do options |> to_dest |> GenServer.call({:advisors, options}) end def start_advisors(options \\ []) do options |> to_dest |> GenServer.call({:start_advisors, options}) end def stop_advisors(options \\ []) do options |> to_dest |> GenServer.call({:stop_advisors, options}) end def settings(options \\ []) do options |> to_dest |> GenServer.call(:settings) end def enable_send_orders(options \\ []) do options |> to_dest |> GenServer.call(:enable_send_orders) end def disable_send_orders(options \\ []) do options |> to_dest |> GenServer.call(:disable_send_orders) end def init(state) do {:ok, state} end def handle_call(:accounts, _from, state) do {:reply, Tai.Commander.Accounts.get(), state} end def handle_call(:products, _from, state) do {:reply, Tai.Commander.Products.get(), state} end def handle_call(:fees, _from, state) do {:reply, Tai.Commander.Fees.get(), state} end def handle_call(:markets, _from, state) do {:reply, Tai.Commander.Markets.get(), state} end def handle_call(:orders, _from, state) do {:reply, Tai.Commander.Orders.get(), state} end def handle_call({:new_orders, query, options}, _from, state) do {:reply, Tai.Commander.NewOrders.get(query, options), state} end def handle_call({:new_orders_count, query}, _from, state) do {:reply, Tai.Commander.NewOrdersCount.get(query), state} end def handle_call({:get_new_order_by_client_id, client_id}, _from, state) do {:reply, Tai.Commander.GetNewOrderByClientId.get(client_id), state} end def handle_call({:get_new_orders_by_client_ids, client_ids}, _from, state) do {:reply, Tai.Commander.GetNewOrdersByClientIds.get(client_ids), state} end def handle_call({:order_transitions, client_id, query, options}, _from, state) do {:reply, Tai.Commander.OrderTransitions.get(client_id, query, options), state} end def handle_call({:order_transitions_count, client_id, query}, _from, state) do {:reply, Tai.Commander.OrderTransitionsCount.get(client_id, query), state} end def handle_call({:failed_order_transitions, client_id, query, options}, _from, state) do {:reply, Tai.Commander.FailedOrderTransitions.get(client_id, query, options), state} end def handle_call({:failed_order_transitions_count, client_id, query}, _from, state) do {:reply, Tai.Commander.FailedOrderTransitionsCount.get(client_id, query), state} end def handle_call(:delete_all_orders, _from, state) do {:reply, Tai.Commander.DeleteAllOrders.execute(), state} end def handle_call(:positions, _from, state) do {:reply, Tai.Commander.Positions.get(), state} end def handle_call({:venues, options}, _from, state) do {:reply, Tai.Commander.Venues.get(options), state} end def handle_call({:start_venue, venue_id, options}, _from, state) do {:reply, Tai.Commander.StartVenue.execute(venue_id, options), state} end def handle_call({:stop_venue, venue_id, store_id}, _from, state) do {:reply, Tai.Commander.StopVenue.execute(venue_id, store_id), state} end def handle_call({:advisors, options}, _from, state) do {:reply, Tai.Commander.Advisors.get(options), state} end def handle_call({:start_advisors, options}, _from, state) do {:reply, Tai.Commander.StartAdvisors.execute(options), state} end def handle_call({:stop_advisors, options}, _from, state) do {:reply, Tai.Commander.StopAdvisors.execute(options), state} end def handle_call(:settings, _from, state) do {:reply, Tai.Commander.Settings.get(), state} end def handle_call(:enable_send_orders, _from, state) do {:reply, Tai.Commander.EnableSendOrders.execute(), state} end def handle_call(:disable_send_orders, _from, state) do {:reply, Tai.Commander.DisableSendOrders.execute(), state} end defp to_dest(options) do options |> Keyword.get(:node) |> case do nil -> __MODULE__ node -> {__MODULE__, node} end end end
30.394366
98
0.693543
73e59a579cb6b9cb456a5b81403f8beb9865c023
55,684
ex
Elixir
clients/file/lib/google_api/file/v1/api/projects.ex
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
clients/file/lib/google_api/file/v1/api/projects.ex
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
clients/file/lib/google_api/file/v1/api/projects.ex
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "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.File.V1.Api.Projects do @moduledoc """ API calls for all endpoints tagged `Projects`. """ alias GoogleApi.File.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Gets information about a location. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Resource name for the location. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Location{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_get(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.File.V1.Model.Location.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Location{}]) end @doc """ Lists information about the supported locations for this service. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The resource that owns the locations collection, if applicable. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - A filter to narrow down results to a preferred subset. The filtering language accepts strings like "displayName=tokyo", and is documented in more detail in [AIP-160](https://google.aip.dev/160). * `:includeUnrevealedLocations` (*type:* `boolean()`) - If true, the returned list will include locations which are not yet revealed. * `:pageSize` (*type:* `integer()`) - The maximum number of results to return. If not set, the service will select a default. * `:pageToken` (*type:* `String.t`) - A page token received from the `next_page_token` field in the response. Send that page token to receive the subsequent page. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.ListLocationsResponse{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.File.V1.Model.ListLocationsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_list(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :includeUnrevealedLocations => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}/locations", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.ListLocationsResponse{}]) end @doc """ Creates a backup. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The backup's project and location, in the format projects/{project_number}/locations/{location}. In Cloud Filestore, backup locations map to GCP regions, for example **us-west1**. * `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"). * `:backupId` (*type:* `String.t`) - Required. The ID to use for the backup. The ID must be unique within the specified project and location. This value must start with a lowercase letter followed by up to 62 lowercase letters, numbers, or hyphens, and cannot end with a hyphen. Values that do not match this pattern will trigger an INVALID_ARGUMENT error. * `:body` (*type:* `GoogleApi.File.V1.Model.Backup.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_backups_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_backups_create( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :backupId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+parent}/backups", %{ "parent" => URI.encode(parent, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Operation{}]) end @doc """ Deletes a backup. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The backup resource name, in the format projects/{project_number}/locations/{location}/backups/{backup_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.File.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_backups_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_backups_delete(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Operation{}]) end @doc """ Gets the details of a specific backup. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The backup resource name, in the format projects/{project_number}/locations/{location}/backups/{backup_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.File.V1.Model.Backup{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_backups_get(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.File.V1.Model.Backup.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_backups_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Backup{}]) end @doc """ Lists all backups in a project for either a specified location or for all locations. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The project and location for which to retrieve backup information, in the format projects/{project_number}/locations/{location}. In Cloud Filestore, backup locations map to GCP regions, for example **us-west1**. To retrieve backup information for all locations, use "-" for the {location} value. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - List filter. * `:orderBy` (*type:* `String.t`) - Sort results. Supported values are "name", "name desc" or "" (unsorted). * `:pageSize` (*type:* `integer()`) - The maximum number of items to return. * `:pageToken` (*type:* `String.t`) - The next_page_token value to use if there are additional results to retrieve for this list request. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.ListBackupsResponse{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_backups_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.File.V1.Model.ListBackupsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_backups_list(connection, parent, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :orderBy => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/backups", %{ "parent" => URI.encode(parent, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.ListBackupsResponse{}]) end @doc """ Updates the settings of a specific backup. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Output only. The resource name of the backup, in the format projects/{project_number}/locations/{location_id}/backups/{backup_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"). * `:updateMask` (*type:* `String.t`) - Required. Mask of fields to update. At least one path must be supplied in this field. * `:body` (*type:* `GoogleApi.File.V1.Model.Backup.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_backups_patch( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_backups_patch(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Operation{}]) end @doc """ Creates an instance. When creating from a backup, the capacity of the new instance needs to be equal to or larger than the capacity of the backup (and also equal to or larger than the minimum capacity of the tier). ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The instance's project and location, in the format projects/{project_id}/locations/{location}. In Cloud Filestore, locations map to GCP zones, for example **us-west1-b**. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:instanceId` (*type:* `String.t`) - Required. The name of the instance to create. The name must be unique for the specified project and location. * `:body` (*type:* `GoogleApi.File.V1.Model.Instance.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_instances_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_instances_create( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :instanceId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+parent}/instances", %{ "parent" => URI.encode(parent, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Operation{}]) end @doc """ Deletes an instance. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The instance resource name, in the format projects/{project_id}/locations/{location}/instances/{instance_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.File.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_instances_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_instances_delete( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Operation{}]) end @doc """ Gets the details of a specific instance. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The instance resource name, in the format projects/{project_id}/locations/{location}/instances/{instance_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.File.V1.Model.Instance{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_instances_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Instance.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_instances_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Instance{}]) end @doc """ Lists all instances in a project for either a specified location or for all locations. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The project and location for which to retrieve instance information, in the format projects/{project_id}/locations/{location}. In Cloud Filestore, locations map to GCP zones, for example **us-west1-b**. To retrieve instance information for all locations, use "-" for the {location} value. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - List filter. * `:orderBy` (*type:* `String.t`) - Sort results. Supported values are "name", "name desc" or "" (unsorted). * `:pageSize` (*type:* `integer()`) - The maximum number of items to return. * `:pageToken` (*type:* `String.t`) - The next_page_token value to use if there are additional results to retrieve for this list request. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.ListInstancesResponse{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_instances_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.ListInstancesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_instances_list( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :orderBy => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/instances", %{ "parent" => URI.encode(parent, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.ListInstancesResponse{}]) end @doc """ Updates the settings of a specific instance. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Output only. The resource name of the instance, in the format projects/{project}/locations/{location}/instances/{instance}. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:updateMask` (*type:* `String.t`) - Mask of fields to update. At least one path must be supplied in this field. The elements of the repeated paths field may only include these fields: * "description" * "file_shares" * "labels" * `:body` (*type:* `GoogleApi.File.V1.Model.Instance.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_instances_patch( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_instances_patch(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Operation{}]) end @doc """ Restores an existing instance's file share from a backup. The capacity of the instance needs to be equal to or larger than the capacity of the backup (and also equal to or larger than the minimum capacity of the tier). ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The resource name of the instance, in the format projects/{project_number}/locations/{location_id}/instances/{instance_id}. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.File.V1.Model.RestoreInstanceRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_instances_restore( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_instances_restore( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+name}:restore", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Operation{}]) end @doc """ Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be cancelled. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.File.V1.Model.CancelOperationRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_operations_cancel( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_operations_cancel( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+name}:cancel", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Empty{}]) end @doc """ Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be deleted. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_operations_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_operations_delete( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Empty{}]) end @doc """ Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_operations_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_operations_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Operation{}]) end @doc """ Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation's parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - The standard list filter. * `:pageSize` (*type:* `integer()`) - The standard list page size. * `:pageToken` (*type:* `String.t`) - The standard list page token. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.ListOperationsResponse{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_operations_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.ListOperationsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def file_projects_locations_operations_list(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}/operations", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.ListOperationsResponse{}]) end end
46.480801
607
0.611325
73e5ace87f8ceee463e9dc24600c6fbbdaea25be
2,023
ex
Elixir
lib/chat_api/messages/message.ex
J0/papercups
a896081727abae07982a79fdf5b649354155f3a4
[ "MIT" ]
null
null
null
lib/chat_api/messages/message.ex
J0/papercups
a896081727abae07982a79fdf5b649354155f3a4
[ "MIT" ]
null
null
null
lib/chat_api/messages/message.ex
J0/papercups
a896081727abae07982a79fdf5b649354155f3a4
[ "MIT" ]
null
null
null
defmodule ChatApi.Messages.Message do use Ecto.Schema import Ecto.Changeset alias ChatApi.Conversations.Conversation alias ChatApi.Accounts.Account alias ChatApi.Customers.Customer alias ChatApi.Users.User alias ChatApi.Messages.MessageFile @type t :: %__MODULE__{ body: String.t(), sent_at: DateTime.t() | nil, seen_at: DateTime.t() | nil, source: String.t(), type: String.t(), private: boolean() | nil, metadata: map() | nil, # Foreign keys conversation_id: Ecto.UUID.t(), conversation: any(), account_id: Ecto.UUID.t(), account: any(), customer_id: Ecto.UUID.t(), customer: any(), user_id: integer(), user: any(), # Timestamps inserted_at: DateTime.t(), updated_at: DateTime.t() } @primary_key {:id, :binary_id, autogenerate: true} @foreign_key_type :binary_id schema "messages" do field(:body, :string) field(:sent_at, :utc_datetime) field(:seen_at, :utc_datetime) field(:source, :string, default: "chat") field(:type, :string, default: "reply") field(:private, :boolean, default: false) field(:metadata, :map) belongs_to(:conversation, Conversation) belongs_to(:account, Account) belongs_to(:customer, Customer) belongs_to(:user, User, type: :integer) has_many(:message_files, MessageFile) has_many(:attachments, through: [:message_files, :file]) timestamps() end @doc false def changeset(message, attrs) do message |> cast(attrs, [ :body, :type, :private, :conversation_id, :account_id, :customer_id, :user_id, :sent_at, :seen_at, :source, :metadata ]) |> validate_required([:account_id, :conversation_id]) |> validate_inclusion(:type, ["reply", "note"]) |> validate_inclusion(:source, ["chat", "slack", "mattermost", "email"]) end end
26.618421
76
0.601582
73e6421eeeaddedf0aded04e85b179ed974d7853
41,870
exs
Elixir
test/browser_test.exs
exit9/elixir-browser
d89daf3585f0ce942629decdce8e2a5542b30ead
[ "MIT" ]
33
2018-10-17T23:39:35.000Z
2022-03-09T11:17:00.000Z
test/browser_test.exs
exit9/elixir-browser
d89daf3585f0ce942629decdce8e2a5542b30ead
[ "MIT" ]
6
2018-11-06T19:19:32.000Z
2022-03-14T07:45:53.000Z
test/browser_test.exs
exit9/elixir-browser
d89daf3585f0ce942629decdce8e2a5542b30ead
[ "MIT" ]
9
2019-02-07T10:31:37.000Z
2022-02-18T03:35:12.000Z
defmodule BrowserTest do use ExUnit.Case use Plug.Test import Plug.Conn alias Browser.Ua test "returns empty string when Conn has no user-agent header" do assert conn(:get, "/") |> Ua.to_ua == "" end test "retrieves first UA when Conn has user-agent header" do conn = conn(:get, "/") |> put_req_header("user-agent", "Mozilla 5.0") |> put_req_header("user-agent", "Opera") assert conn |> Ua.to_ua == "Opera" end test "detects android" do ua = Fixtures.ua["ANDROID"] assert Browser.name(ua) == "Android" assert Browser.full_browser_name(ua) == "Android 3.1.2" assert Browser.full_display(ua) == "Android 3.1.2 on Android 1.5" assert Browser.android?(ua) refute Browser.safari?(ua) assert Browser.webkit?(ua) assert Browser.mobile?(ua) refute Browser.tablet?(ua) assert Browser.modern?(ua) assert Browser.full_version(ua) == "3.1.2" assert Browser.version(ua) == "3" end test "detects surface tablet" do ua = Fixtures.ua["SURFACE"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 10.0" assert Browser.full_display(ua) == "Internet Explorer 10.0 on Windows RT" assert Browser.surface?(ua) assert Browser.ie?(ua) refute Browser.mobile?(ua) assert Browser.modern?(ua) assert Browser.full_version(ua) == "10.0" assert Browser.version(ua) == "10" end test "detects quicktime" do ua = Fixtures.ua["QUICKTIME"] assert Browser.name(ua) == "QuickTime" assert Browser.full_browser_name(ua) == "QuickTime 7.6.8" assert Browser.full_display(ua) == "QuickTime 7.6.8 on Windows XP" assert Browser.quicktime?(ua) assert Browser.full_version(ua) == "7.6.8" assert Browser.version(ua) == "7" end test "detects core media" do ua = Fixtures.ua["COREMEDIA"] assert Browser.name(ua) == "Apple CoreMedia" assert Browser.full_browser_name(ua) == "Apple CoreMedia 1.0.0.10F569" assert Browser.full_display(ua) == "Apple CoreMedia 1.0.0.10F569 on MacOS" assert Browser.core_media?(ua) assert Browser.full_version(ua) == "1.0.0.10F569" assert Browser.version(ua) == "1" end test "detects phantom.js" do ua = Fixtures.ua["PHANTOM_JS"] assert Browser.name(ua) == "PhantomJS" assert Browser.full_browser_name(ua) == "PhantomJS 1.9.0" assert Browser.full_display(ua) == "PhantomJS 1.9.0 on MacOS" assert Browser.phantom_js?(ua) refute Browser.tablet?(ua) refute Browser.mobile?(ua) assert Browser.modern?(ua) assert Browser.full_version(ua) == "1.9.0" assert Browser.version(ua) == "1" end test "detects other mobiles" do ua = "Symbian OS" assert Browser.mobile?(ua) refute Browser.tablet?(ua) ua = "MIDP-2.0" assert Browser.mobile?(ua) refute Browser.tablet?(ua) end test "detects windows mobile" do ua = Fixtures.ua["WINDOWS_MOBILE"] assert Browser.mobile?(ua) assert Browser.windows?(ua) assert Browser.windows_mobile?(ua) refute Browser.windows_phone?(ua) refute Browser.tablet?(ua) end test "detects unknown id" do ua = "Unknown" assert Browser.id(ua) == :other end test "detects unknown name" do ua = "Unknown" assert Browser.name(ua) == "Other" assert Browser.full_browser_name(ua) == "Other 0.0" assert Browser.full_display(ua) == "Other 0.0 on Other" end test "detects ios platform" do iphone = Fixtures.ua["IPHONE"] ipad = Fixtures.ua["IPAD"] assert Browser.platform(iphone) == :ios assert Browser.platform(ipad) == :ios end test "detects android platform" do android_1 = Fixtures.ua["ANDROID"] android_2 = Fixtures.ua["ANDROID_WITH_SAFARI"] assert Browser.platform(android_1) == :android assert Browser.platform(android_2) == :android end test "detects mac platform" do ua = "Mac OS X" assert Browser.platform(ua) == :mac assert Browser.mac?(ua) end test "detects mac version with underscore notation" do ua = "Intel Mac OS X 10_13_1; en-us" assert Browser.mac_version(ua) == "10.13.1" end test "detects mac version with dot notation" do ua = "Intel Mac OS X 10.13.1; en-us" assert Browser.mac_version(ua) == "10.13.1" end test "mac version name" do ua_10_0 = "Intel Mac OS X 10_0_1; en-us" ua_10_1 = "Intel Mac OS X 10_1_1; en-us" ua_10_2 = "Intel Mac OS X 10_2_1; en-us" ua_10_3 = "Intel Mac OS X 10_3_1; en-us" ua_10_4 = "Intel Mac OS X 10_4_1; en-us" ua_10_5 = "Intel Mac OS X 10_5_1; en-us" ua_10_6 = "Intel Mac OS X 10_6_1; en-us" ua_10_7 = "Intel Mac OS X 10_7_1; en-us" ua_10_8 = "Intel Mac OS X 10_8_1; en-us" ua_10_9 = "Intel Mac OS X 10_9_1; en-us" ua_10_10 = "Intel Mac OS X 10_10_1; en-us" ua_10_11 = "Intel Mac OS X 10_11_1; en-us" ua_10_12 = "Intel Mac OS X 10_12_1; en-us" ua_10_13 = "Intel Mac OS X 10_13_1; en-us" assert Browser.mac_version_name(ua_10_13) == "High Sierra" assert Browser.mac_version_name(ua_10_12) == "Sierra" assert Browser.mac_version_name(ua_10_11) == "El Capitan" assert Browser.mac_version_name(ua_10_10) == "Yosemite" assert Browser.mac_version_name(ua_10_9) == "Mavericks" assert Browser.mac_version_name(ua_10_8) == "Mountain Lion" assert Browser.mac_version_name(ua_10_7) == "Lion" assert Browser.mac_version_name(ua_10_6) == "Snow Leopard" assert Browser.mac_version_name(ua_10_5) == "Leopard" assert Browser.mac_version_name(ua_10_4) == "Tiger" assert Browser.mac_version_name(ua_10_3) == "Panther" assert Browser.mac_version_name(ua_10_2) == "Jaguar" assert Browser.mac_version_name(ua_10_1) == "Puma" assert Browser.mac_version_name(ua_10_0) == "Cheetah" assert Browser.mac_version_name("Mac OS X") == "" end test "detects linux platform" do ua = "Linux" assert Browser.platform(ua) == :linux assert Browser.linux?(ua) end test "detects unknown platform" do ua = "Unknown" assert Browser.platform(ua) == :other end test "detects mobile device type" do ua = Fixtures.ua["IPHONE"] assert Browser.device_type(ua) == :mobile end test "detects tablet device type" do ua = Fixtures.ua["IPAD"] assert Browser.device_type(ua) == :tablet end test "detects console device type" do ua = Fixtures.ua["XBOXONE"] assert Browser.device_type(ua) == :console end test "detects desktop device type" do ua = Fixtures.ua["CHROME"] assert Browser.device_type(ua) == :desktop end test "detects unknown device type" do ua = "Unknown" assert Browser.device_type(ua) == :unknown end test "detects xoom" do ua = Fixtures.ua["XOOM"] assert Browser.android?(ua) assert Browser.tablet?(ua) refute Browser.mobile?(ua) end test "detects nexus tablet" do ua = Fixtures.ua["NEXUS_TABLET"] assert Browser.android?(ua) assert Browser.tablet?(ua) refute Browser.mobile?(ua) end test "detects nook" do ua = Fixtures.ua["NOOK"] assert Browser.tablet?(ua) refute Browser.mobile?(ua) end test "detects samsung" do ua = Fixtures.ua["SAMSUNG"] assert Browser.tablet?(ua) refute Browser.mobile?(ua) end test "detects tv" do ua = Fixtures.ua["SMART_TV"] assert Browser.tv?(ua) end test "knows a supported browser" do ua = "Chrome" assert Browser.known?(ua) end test "does not know an unsupported browser" do ua = "Fancy new browser" refute Browser.known?(ua) end test "detects adobe air" do ua = Fixtures.ua["ADOBE_AIR"] assert Browser.adobe_air?(ua) assert Browser.webkit?(ua) assert Browser.version(ua) == "13" assert Browser.full_version(ua) == "13.0" assert Browser.name(ua) == "Other" assert Browser.full_browser_name(ua) == "Other 13.0" assert Browser.full_display(ua) == "Other 13.0 on MacOS" end # android test "detect android cupcake (1.5)" do ua = Fixtures.ua["ANDROID_CUPCAKE"] assert Browser.android?(ua) assert Browser.android?(ua, 1.5) end test "detect android donut (1.6)" do ua = Fixtures.ua["ANDROID_DONUT"] assert Browser.android?(ua) assert Browser.android?(ua, 1.6) end test "detect android eclair (2.1)" do ua = Fixtures.ua["ANDROID_ECLAIR_21"] assert Browser.android?(ua) assert Browser.android?(ua, 2.1) end test "detect android froyo (2.2)" do ua = Fixtures.ua["ANDROID_FROYO"] assert Browser.android?(ua) assert Browser.android?(ua, 2.2) end test "detect android gingerbread (2.3)" do ua = Fixtures.ua["ANDROID_GINGERBREAD"] assert Browser.android?(ua) assert Browser.android?(ua, 2.3) end test "detect android honeycomb (3.0)" do ua = Fixtures.ua["ANDROID_HONEYCOMB_30"] assert Browser.android?(ua) assert Browser.android?(ua, 3.0) end test "detect android ice cream sandwich (4.0)" do ua = Fixtures.ua["ANDROID_ICECREAM"] assert Browser.android?(ua) assert Browser.android?(ua, 4.0) end test "detect android jellybean (4.1)" do ua = Fixtures.ua["ANDROID_JELLYBEAN_41"] assert Browser.android?(ua) assert Browser.android?(ua, 4.1) end test "detect android jellybean (4.2)" do ua = Fixtures.ua["ANDROID_JELLYBEAN_42"] assert Browser.android?(ua) assert Browser.android?(ua, 4.2) end test "detect android jellybean (4.3)" do ua = Fixtures.ua["ANDROID_JELLYBEAN_43"] assert Browser.android?(ua) assert Browser.android?(ua, 4.3) end test "detect android kitkat (4.4)" do ua = Fixtures.ua["ANDROID_KITKAT"] assert Browser.android?(ua) assert Browser.android?(ua, 4.4) end test "detect android lollipop (5.0)" do ua = Fixtures.ua["ANDROID_LOLLIPOP_50"] assert Browser.android?(ua) assert Browser.android?(ua, 5.0) end test "detect android lollipop (5.1)" do ua = Fixtures.ua["ANDROID_LOLLIPOP_51"] assert Browser.android?(ua) assert Browser.android?(ua, 5.1) end test "detect android tv" do ua = Fixtures.ua["ANDROID_TV"] assert Browser.android?(ua) assert Browser.tv?(ua) end test "detect nexus player" do ua = Fixtures.ua["ANDROID_NEXUS_PLAYER"] assert Browser.android?(ua) assert Browser.tv?(ua) end # blackberry test "detects blackberry" do ua = Fixtures.ua["BLACKBERRY"] assert Browser.name(ua), "BlackBerry" assert Browser.full_browser_name(ua) == "BlackBerry 4.1.0" assert Browser.full_display(ua) == "BlackBerry 4.1.0 on BlackBerry" assert Browser.blackberry?(ua) refute Browser.tablet?(ua) assert Browser.mobile?(ua) refute Browser.modern?(ua) assert Browser.full_version(ua) == "4.1.0" assert Browser.version(ua) == "4" end test "detects blackberry4" do ua = Fixtures.ua["BLACKBERRY4"] assert Browser.name(ua), "BlackBerry" assert Browser.full_browser_name(ua) == "BlackBerry 4.2.1" assert Browser.full_display(ua) == "BlackBerry 4.2.1 on BlackBerry 4" assert Browser.blackberry_version(ua) == "4" assert Browser.blackberry?(ua, 4) refute Browser.tablet?(ua) assert Browser.mobile?(ua) refute Browser.modern?(ua) assert Browser.full_version(ua) == "4.2.1" assert Browser.version(ua) == "4" end test "detects blackberry5" do ua = Fixtures.ua["BLACKBERRY5"] assert Browser.name(ua), "BlackBerry" assert Browser.full_browser_name(ua) == "BlackBerry 5.0.0.93" assert Browser.full_display(ua) == "BlackBerry 5.0.0.93 on BlackBerry 5" assert Browser.blackberry?(ua, 5) assert Browser.blackberry_version(ua) == "5" refute Browser.tablet?(ua) assert Browser.mobile?(ua) refute Browser.modern?(ua) assert Browser.full_version(ua) == "5.0.0.93" assert Browser.version(ua) == "5" end test "detects blackberry6" do ua = Fixtures.ua["BLACKBERRY6"] assert Browser.name(ua) =="Safari" assert Browser.full_browser_name(ua) == "Safari 534.11" assert Browser.full_display(ua) == "Safari 534.11 on BlackBerry 6" assert Browser.blackberry?(ua, 6) assert Browser.blackberry_version(ua) == "6" refute Browser.tablet?(ua) assert Browser.mobile?(ua) assert Browser.modern?(ua) assert Browser.full_version(ua) == "534.11" assert Browser.version(ua) == "534" end test "detects blackberry7" do ua = Fixtures.ua["BLACKBERRY7"] assert Browser.name(ua) =="Safari" assert Browser.full_browser_name(ua) == "Safari 534.11" assert Browser.full_display(ua) == "Safari 534.11 on BlackBerry 7" assert Browser.blackberry?(ua, 7) assert Browser.blackberry_version(ua) == "7" refute Browser.tablet?(ua) assert Browser.mobile?(ua) assert Browser.modern?(ua) assert Browser.full_version(ua) == "534.11" assert Browser.version(ua) == "534" end test "detects blackberry10" do ua = Fixtures.ua["BLACKBERRY10"] assert Browser.name(ua) =="Safari" assert Browser.full_browser_name(ua) == "Safari 10.0.9.1675" assert Browser.full_display(ua) == "Safari 10.0.9.1675 on BlackBerry 10" assert Browser.blackberry_version(ua) =="10" assert Browser.blackberry?(ua, 10) refute Browser.tablet?(ua) assert Browser.mobile?(ua) assert Browser.modern?(ua) assert Browser.full_version(ua) == "10.0.9.1675" assert Browser.version(ua) == "10" end test "detects blackberry playbook tablet" do ua = Fixtures.ua["PLAYBOOK"] refute Browser.android?(ua) assert Browser.tablet?(ua) refute Browser.mobile?(ua) assert Browser.full_version(ua) == "7.2.1.0" assert Browser.version(ua) == "7" end # bots test "detects bots" do refute Browser.bot?("") refute Browser.bot?(%Plug.Conn{}) Enum.each ~w[ APPLE_BOT DOT_BOT FACEBOOK_BOT GOOGLE_BOT LINKDEXBOT LOAD_TIME_BOT MAIL_RU MEGAINDEX_RU MSN_BOT QUERYSEEKER SCRAPY YANDEX_DIRECT YANDEX_METRIKA ], fn key -> ua = Fixtures.ua[key] assert Browser.bot?(ua), "#{Fixtures.ua[key]} should be a bot" conn = %Plug.Conn{} |> Plug.Conn.put_req_header("user-agent", ua) assert Browser.bot?(conn), "#{Fixtures.ua[key]} should be a bot" end ua = Fixtures.ua["CHROME"] refute Browser.bot?(ua) end test "detects Google Page Speed as a bot" do ua = Fixtures.ua["GOOGLE_PAGE_SPEED_INSIGHTS"] assert Browser.bot?(ua) end test "doesn't consider empty UA as bot" do ua = "" refute Browser.bot?(ua) end test "allows setting empty string as bots" do ua = "" assert Browser.bot?(ua, detect_empty_ua: true) end test "doesn't detect mozilla as a bot when considering empty UA" do ua = "Mozilla" refute Browser.bot?(ua, detect_empty_ua: true) end test "returns bot name" do ua = Fixtures.ua["GOOGLE_BOT"] assert Browser.bot_name(ua) == "googlebot" ua = Fixtures.ua["FACEBOOK_BOT"] assert Browser.bot_name(ua) == "facebookexternalhit" end test "returns bot name (empty string ua detection enabled)" do ua = "" assert Browser.bot_name(ua, detect_empty_ua: true) == "Generic Bot" end test "returns nil for non-bots" do ua = Fixtures.ua["CHROME"] assert Browser.bot_name(ua) == nil end test "detects as search engines" do refute Browser.search_engine?("") refute Browser.search_engine?(%Plug.Conn{}) Enum.each ~w[ ASK BAIDU BINGBOT DUCKDUCKGO GOOGLE_BOT YAHOO_SLURP ], fn key -> ua = Fixtures.ua[key] assert Browser.search_engine?(ua), "#{Fixtures.ua[key]} should be a search engine" conn = %Plug.Conn{} |> Plug.Conn.put_req_header("user-agent", ua) assert Browser.search_engine?(conn), "#{Fixtures.ua[key]} should be a search engine" end end test "detects Google Structured Data Testing Tool as a bot" do ua = Fixtures.ua["GOOGLE_STRUCTURED_DATA_TESTING_TOOL"] assert Browser.bot?(ua), "Google Structured Data Testing Tool should be a bot" end test "detects Daumoa" do ua = Fixtures.ua["DAUMOA"] assert :ie == Browser.id(ua) assert "Internet Explorer" == Browser.name(ua) assert "0.0" == Browser.msie_full_version(ua) assert "0" == Browser.msie_version(ua) assert "0.0" == Browser.full_version(ua) assert "0" == Browser.version(ua) assert Browser.ie?(ua) assert Browser.bot?(ua) refute Browser.windows10?(ua) refute Browser.windows_phone?(ua) refute Browser.edge?(ua) refute Browser.modern?(ua) refute Browser.mobile?(ua) refute Browser.webkit?(ua) refute Browser.chrome?(ua) refute Browser.safari?(ua) end # chrome test "detects chrome" do ua = Fixtures.ua["CHROME"] assert Browser.name(ua) =="Chrome" assert Browser.full_browser_name(ua) == "Chrome 5.0.375.99" assert Browser.full_display(ua) == "Chrome 5.0.375.99 on MacOS 10.6.4 Snow Leopard" assert Browser.chrome?(ua) refute Browser.safari?(ua) assert Browser.webkit?(ua) assert Browser.modern?(ua) assert Browser.full_version(ua) == "5.0.375.99" assert Browser.version(ua) == "5" end test "detects mobile chrome" do ua = Fixtures.ua["MOBILE_CHROME"] assert Browser.name(ua) =="Chrome" assert Browser.full_browser_name(ua) == "Chrome 19.0.1084.60" assert Browser.full_display(ua) == "Chrome 19.0.1084.60 on iOS 5" assert Browser.chrome?(ua) refute Browser.safari?(ua) assert Browser.webkit?(ua) assert Browser.modern?(ua) assert Browser.full_version(ua) == "19.0.1084.60" assert Browser.version(ua) == "19" end test "detects samsung chrome" do ua = Fixtures.ua["SAMSUNG_CHROME"] assert Browser.name(ua) =="Chrome" assert Browser.full_browser_name(ua) == "Chrome 28.0.1500.94" assert Browser.full_display(ua) == "Chrome 28.0.1500.94 on Android 4.4.2" assert Browser.chrome?(ua) assert Browser.android?(ua) refute Browser.safari?(ua) assert Browser.webkit?(ua) assert Browser.modern?(ua) assert Browser.full_version(ua) == "28.0.1500.94" assert Browser.version(ua) == "28" end test "detects chrome os" do ua = Fixtures.ua["CHROME_OS"] assert Browser.chrome_os?(ua) end test "detects yandex browser" do ua = Fixtures.ua["YANDEX_BROWSER"] assert Browser.yandex?(ua) assert Browser.chrome?(ua) refute Browser.safari?(ua) assert Browser.webkit?(ua) assert Browser.full_version(ua) == "41.0.2272.118" assert Browser.version(ua) == "41" end # console test "detects nintendo wii" do ua = Fixtures.ua["NINTENDO_WII"] assert Browser.console?(ua) assert Browser.nintendo?(ua) end test "detects nintendo wii u" do ua = Fixtures.ua["NINTENDO_WIIU"] assert Browser.console?(ua) assert Browser.nintendo?(ua) end test "detects playstation 3" do ua = Fixtures.ua["PLAYSTATION3"] assert Browser.console?(ua) assert Browser.playstation?(ua) refute Browser.playstation4?(ua) end test "detects playstation 4" do ua = Fixtures.ua["PLAYSTATION4"] assert Browser.console?(ua) assert Browser.playstation?(ua) assert Browser.playstation4?(ua) end test "detects xbox 360" do ua = Fixtures.ua["XBOX360"] assert Browser.console?(ua) assert Browser.xbox?(ua) refute Browser.xbox_one?(ua) end test "detects xbox one" do ua = Fixtures.ua["XBOXONE"] assert Browser.console?(ua) assert Browser.xbox?(ua) assert Browser.xbox_one?(ua) end test "detects psp" do ua = Fixtures.ua["PSP"] assert Browser.name(ua) == "PlayStation Portable" assert Browser.full_browser_name(ua) == "PlayStation Portable 0.0" assert Browser.full_display(ua) == "PlayStation Portable 0.0 on Other" assert Browser.psp?(ua) refute Browser.psp_vita?(ua) assert Browser.mobile?(ua) end test "detects psp vita" do ua = Fixtures.ua["PSP_VITA"] assert Browser.name(ua) == "PlayStation Portable" assert Browser.full_display(ua) == "PlayStation Portable 0.0 on Other" assert Browser.psp?(ua) assert Browser.psp_vita?(ua) assert Browser.mobile?(ua) end # firefox test "detects firefox" do ua = Fixtures.ua["FIREFOX"] assert Browser.name(ua) == "Firefox" assert Browser.full_browser_name(ua) == "Firefox 3.8" assert Browser.full_display(ua) == "Firefox 3.8 on Linux" assert Browser.firefox?(ua) refute Browser.modern?(ua) assert Browser.full_version(ua) == "3.8" assert Browser.version(ua) == "3" end test "detects modern firefox" do ua = Fixtures.ua["FIREFOX_MODERN"] assert Browser.id(ua) == :firefox assert Browser.name(ua) == "Firefox" assert Browser.full_browser_name(ua) == "Firefox 17.0" assert Browser.full_display(ua) == "Firefox 17.0 on Linux" assert Browser.firefox?(ua) assert Browser.modern?(ua) assert Browser.full_version(ua) == "17.0" assert Browser.version(ua) == "17" end test "detects firefox android tablet" do ua = Fixtures.ua["FIREFOX_TABLET"] assert Browser.id(ua) == :firefox assert Browser.name(ua) == "Firefox" assert Browser.full_browser_name(ua) == "Firefox 14.0" assert Browser.full_display(ua) == "Firefox 14.0 on Android" assert Browser.firefox?(ua) assert Browser.modern?(ua) assert Browser.tablet?(ua) assert Browser.android?(ua) assert Browser.full_version(ua) == "14.0" assert Browser.version(ua) == "14" end # IE test "detects ie6" do ua = Fixtures.ua["IE6"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 6.0" assert Browser.full_display(ua) == "Internet Explorer 6.0 on Windows XP" assert Browser.ie?(ua) assert Browser.ie?(ua, 6) refute Browser.modern?(ua) assert Browser.full_version(ua) == "6.0" assert Browser.version(ua) == "6" end test "detects ie7" do ua = Fixtures.ua["IE7"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 7.0" assert Browser.full_display(ua) == "Internet Explorer 7.0 on Windows Vista" assert Browser.ie?(ua) assert Browser.ie?(ua, 7) refute Browser.modern?(ua) assert Browser.full_version(ua) == "7.0" assert Browser.version(ua) == "7" end test "detects ie8" do ua = Fixtures.ua["IE8"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 8.0" assert Browser.full_display(ua) == "Internet Explorer 8.0 on Windows 8" assert Browser.ie?(ua) assert Browser.ie?(ua, 8) refute Browser.modern?(ua) refute Browser.compatibility_view?(ua) assert Browser.full_version(ua) == "8.0" assert Browser.version(ua) == "8" end test "detects ie8 in compatibility view" do ua = Fixtures.ua["IE8_COMPAT"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 8.0" assert Browser.full_display(ua) == "Internet Explorer 8.0 on Windows Vista" assert Browser.ie?(ua) assert Browser.ie?(ua, 8) refute Browser.modern?(ua) assert Browser.compatibility_view?(ua) assert Browser.full_version(ua) == "8.0" assert Browser.version(ua) == "8" assert Browser.msie_full_version(ua) == "7.0" assert Browser.msie_version(ua) == "7" end test "detects ie9" do ua = Fixtures.ua["IE9"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 9.0" assert Browser.full_display(ua) == "Internet Explorer 9.0 on Windows 7" assert Browser.ie?(ua) assert Browser.ie?(ua, 9) assert Browser.modern?(ua) refute Browser.compatibility_view?(ua) assert Browser.full_version(ua) == "9.0" assert Browser.version(ua) == "9" end test "detects ie9 in compatibility view" do ua = Fixtures.ua["IE9_COMPAT"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 9.0" assert Browser.full_display(ua) == "Internet Explorer 9.0 on Windows Vista" assert Browser.ie?(ua) assert Browser.ie?(ua, 9) refute Browser.modern?(ua) assert Browser.compatibility_view?(ua) assert Browser.full_version(ua) == "9.0" assert Browser.version(ua) == "9" assert Browser.msie_full_version(ua) == "7.0" assert Browser.msie_version(ua) == "7" end test "detects ie10" do ua = Fixtures.ua["IE10"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 10.0" assert Browser.full_display(ua) == "Internet Explorer 10.0 on Windows 7" assert Browser.ie?(ua) assert Browser.ie?(ua, 10) assert Browser.modern?(ua) refute Browser.compatibility_view?(ua) assert Browser.full_version(ua) == "10.0" assert Browser.version(ua) == "10" end test "detects ie10 in compatibility view" do ua = Fixtures.ua["IE10_COMPAT"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 10.0" assert Browser.full_display(ua) == "Internet Explorer 10.0 on Windows 7" assert Browser.ie?(ua) assert Browser.ie?(ua, 10) refute Browser.modern?(ua) assert Browser.compatibility_view?(ua) assert Browser.full_version(ua) == "10.0" assert Browser.version(ua) == "10" assert Browser.msie_full_version(ua) == "7.0" assert Browser.msie_version(ua) == "7" end test "detects ie11" do ua = Fixtures.ua["IE11"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 11.0" assert Browser.full_display(ua) == "Internet Explorer 11.0 on Windows 7" assert Browser.ie?(ua) assert Browser.ie?(ua, 11) assert Browser.modern?(ua) refute Browser.compatibility_view?(ua) assert Browser.full_version(ua) == "11.0" assert Browser.version(ua) == "11" end test "detects ie11 in compatibility view" do ua = Fixtures.ua["IE11_COMPAT"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 11.0" assert Browser.full_display(ua) == "Internet Explorer 11.0 on Windows 8.1" assert Browser.ie?(ua) assert Browser.ie?(ua, 11) refute Browser.modern?(ua) assert Browser.compatibility_view?(ua) assert Browser.full_version(ua) == "11.0" assert Browser.version(ua) == "11" assert Browser.msie_full_version(ua) == "7.0" assert Browser.msie_version(ua) == "7" end test "detects Lumia 800" do ua = Fixtures.ua["LUMIA800"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 9.0" assert Browser.full_display(ua) == "Internet Explorer 9.0 on Windows 7" assert Browser.ie?(ua) assert Browser.ie?(ua, 9) assert Browser.full_version(ua) == "9.0" assert Browser.version(ua) == "9" refute Browser.tablet?(ua) assert Browser.mobile?(ua) end test "detects ie11 touch desktop pc" do ua = Fixtures.ua["IE11_TOUCH_SCREEN"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 11.0" assert Browser.full_display(ua) == "Internet Explorer 11.0 on Windows 8.1" assert Browser.ie?(ua) assert Browser.ie?(ua, 11) assert Browser.modern?(ua) refute Browser.compatibility_view?(ua) refute Browser.windows_rt?(ua) assert Browser.windows_touchscreen_desktop?(ua) assert Browser.windows8?(ua) assert Browser.full_version(ua) == "11.0" assert Browser.version(ua) == "11" end test "detects Microsoft Edge" do ua = Fixtures.ua["MS_EDGE"] assert Browser.id(ua) == :edge assert Browser.name(ua) == "Microsoft Edge" assert Browser.full_browser_name(ua) == "Microsoft Edge 12.0" assert Browser.full_display(ua) == "Microsoft Edge 12.0 on Windows 10" assert Browser.full_version(ua) == "12.0" assert Browser.version(ua) == "12" assert Browser.windows10?(ua) assert Browser.edge?(ua) assert Browser.modern?(ua) refute Browser.webkit?(ua) refute Browser.chrome?(ua) refute Browser.safari?(ua) refute Browser.mobile?(ua) end test "detects Microsoft Edge in compatibility view" do ua = Fixtures.ua["MS_EDGE_COMPAT"] assert Browser.id(ua) == :edge assert Browser.name(ua) == "Microsoft Edge" assert Browser.full_browser_name(ua) == "Microsoft Edge 12.0" assert Browser.full_display(ua) == "Microsoft Edge 12.0 on Windows 8" assert Browser.full_version(ua) == "12.0" assert Browser.version(ua) == "12" assert Browser.msie_full_version(ua) == "7.0" assert Browser.msie_version(ua) == "7" assert Browser.edge?(ua) assert Browser.compatibility_view?(ua) refute Browser.modern?(ua) refute Browser.webkit?(ua) refute Browser.chrome?(ua) refute Browser.safari?(ua) refute Browser.mobile?(ua) end test "detects Microsoft Edge Mobile" do ua = Fixtures.ua["MS_EDGE_MOBILE"] assert Browser.id(ua) == :edge assert Browser.name(ua) == "Microsoft Edge" assert Browser.full_browser_name(ua) == "Microsoft Edge 12.0" assert Browser.full_display(ua) == "Microsoft Edge 12.0 on Android 4.2.1" assert Browser.full_version(ua) == "12.0" assert Browser.version(ua) == "12" refute Browser.windows10?(ua) assert Browser.windows_phone?(ua) assert Browser.edge?(ua) assert Browser.modern?(ua) assert Browser.mobile?(ua) refute Browser.webkit?(ua) refute Browser.chrome?(ua) refute Browser.safari?(ua) end test "detects ie8 without Trident" do ua = Fixtures.ua["IE8_WITHOUT_TRIDENT"] assert Browser.id(ua) == :ie assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 8.0" assert Browser.full_display(ua) == "Internet Explorer 8.0 on Windows Vista" assert Browser.msie_full_version(ua) == "8.0" assert Browser.msie_version(ua) == "8" assert Browser.full_version(ua) == "8.0" assert Browser.version(ua) == "8" refute Browser.windows10?(ua) refute Browser.windows_phone?(ua) refute Browser.edge?(ua) refute Browser.modern_edge?(ua) refute Browser.modern?(ua) refute Browser.modern_ie_version?(ua) refute Browser.mobile?(ua) refute Browser.webkit?(ua) refute Browser.chrome?(ua) refute Browser.safari?(ua) end test "detects ie9 without Trident" do ua = Fixtures.ua["IE9_WITHOUT_TRIDENT"] assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 9.0" assert Browser.full_display(ua) == "Internet Explorer 9.0 on Windows 7" assert Browser.ie?(ua) assert Browser.ie?(ua, 9) assert Browser.modern?(ua) refute Browser.compatibility_view?(ua) assert Browser.full_version(ua) == "9.0" assert Browser.version(ua) == "9" refute Browser.modern_edge?(ua) assert Browser.modern_ie_version?(ua) end test "detects windows phone" do ua = Fixtures.ua["WINDOWS_PHONE"] assert Browser.ie?(ua) assert Browser.version(ua) == "7" assert Browser.mobile?(ua) assert Browser.windows_phone?(ua) refute Browser.windows_mobile?(ua) refute Browser.tablet?(ua) end test "detects windows phone 8" do ua = Fixtures.ua["WINDOWS_PHONE8"] assert Browser.ie?(ua) assert Browser.version(ua) == "10" assert Browser.mobile?(ua) assert Browser.windows_phone?(ua) refute Browser.windows_mobile?(ua) refute Browser.tablet?(ua) end test "detects windows phone 8.1" do ua = Fixtures.ua["WINDOWS_PHONE_81"] assert Browser.ie?(ua) assert Browser.name(ua) == "Internet Explorer" assert Browser.full_browser_name(ua) == "Internet Explorer 11.0" assert Browser.full_display(ua) == "Internet Explorer 11.0 on iOS 7" assert Browser.id(ua) == :ie assert Browser.version(ua) == "11" assert Browser.full_version(ua) == "11.0" assert Browser.mobile?(ua) assert Browser.windows_phone?(ua) refute Browser.windows_mobile?(ua) refute Browser.tablet?(ua) end test "detects windows mobile (windows phone 8)" do ua = Fixtures.ua["WINDOWS_PHONE8"] assert Browser.ie?(ua) assert Browser.version(ua) == "10" assert Browser.mobile?(ua) assert Browser.windows_phone?(ua) refute Browser.windows_mobile?(ua) refute Browser.tablet?(ua) end test "detects windows x64" do ua = Fixtures.ua["IE10_X64_WINX64"] assert Browser.windows_x64?(ua) refute Browser.windows_wow64?(ua) assert Browser.windows_x64_inclusive?(ua) end test "detects windows wow64" do ua = Fixtures.ua["WINDOWS_WOW64"] refute Browser.windows_x64?(ua) assert Browser.windows_wow64?(ua) assert Browser.windows_x64_inclusive?(ua) end test "detects windows platform" do ua = "Windows" assert Browser.platform(ua) == :windows assert Browser.windows?(ua) end test "detects windows_xp" do ua = Fixtures.ua["WINDOWS_XP"] assert Browser.windows?(ua) assert Browser.windows_xp?(ua) end test "detects windows_vista" do ua = Fixtures.ua["WINDOWS_VISTA"] assert Browser.windows?(ua) assert Browser.windows_vista?(ua) end test "detects windows7" do ua = Fixtures.ua["WINDOWS7"] assert Browser.windows?(ua) assert Browser.windows7?(ua) end test "detects windows8" do ua = Fixtures.ua["WINDOWS8"] assert Browser.windows?(ua) assert Browser.windows8?(ua) refute Browser.windows8_1?(ua) end test "detects windows8.1" do ua = Fixtures.ua["WINDOWS81"] assert Browser.windows?(ua) assert Browser.windows8?(ua) assert Browser.windows8_1?(ua) end test "don't detect as two ie different versions" do ua = Fixtures.ua["IE8"] assert Browser.ie?(ua, 8) refute Browser.ie?(ua, 7) end test "detects windows version" do phone = Fixtures.ua["WINDOWS_PHONE"] phone8 = Fixtures.ua["WINDOWS_PHONE8"] phone81 = Fixtures.ua["WINDOWS_PHONE_81"] none = "Windows" xp = Fixtures.ua["WINDOWS_XP"] vista = Fixtures.ua["WINDOWS_VISTA"] win7 = Fixtures.ua["WINDOWS7"] win8 = Fixtures.ua["WINDOWS8"] win81 = Fixtures.ua["WINDOWS81"] win10 = Fixtures.ua["MS_EDGE"] assert Browser.windows_version_name(phone) == "Phone" assert Browser.windows_version_name(phone8) == "Phone" assert Browser.windows_version_name(phone81) == "Phone" assert Browser.windows_version_name(none) == "" assert Browser.windows_version_name(xp) == "XP" assert Browser.windows_version_name(vista) == "Vista" assert Browser.windows_version_name(win7) == "7" assert Browser.windows_version_name(win8) == "8" assert Browser.windows_version_name(win81) == "8.1" assert Browser.windows_version_name(win10) == "10" end # ios test "detects iphone" do ua = Fixtures.ua["IPHONE"] assert Browser.name(ua) == "iPhone" assert Browser.full_browser_name(ua) == "iPhone 3.0" assert Browser.full_display(ua) == "iPhone 3.0 on iOS 3" assert Browser.iphone?(ua) assert Browser.safari?(ua) assert Browser.webkit?(ua) assert Browser.mobile?(ua) assert Browser.modern?(ua) assert Browser.ios?(ua) refute Browser.tablet?(ua) refute Browser.mac?(ua) assert Browser.full_version(ua) == "3.0" assert Browser.version(ua) == "3" end test "detects safari" do ua = Fixtures.ua["SAFARI"] assert Browser.name(ua) == "Safari" assert Browser.full_browser_name(ua) == "Safari 5.0.1" assert Browser.full_display(ua) == "Safari 5.0.1 on MacOS 10.6.4 Snow Leopard" assert Browser.safari?(ua) assert Browser.webkit?(ua) assert Browser.modern?(ua) assert Browser.full_version(ua) == "5.0.1" assert Browser.version(ua) == "5" end test "detects safari in webapp mode" do ua = Fixtures.ua["SAFARI_IPAD_WEBAPP_MODE"] assert Browser.safari?(ua) ua = Fixtures.ua["SAFARI_IPHONE_WEBAPP_MODE"] assert Browser.safari?(ua) end test "detects ipod" do ua = Fixtures.ua["IPOD"] assert Browser.name(ua) == "iPod Touch" assert Browser.full_browser_name(ua) == "iPod Touch 3.0" assert Browser.full_display(ua) == "iPod Touch 3.0 on iOS" assert Browser.ipod?(ua) assert Browser.safari?(ua) assert Browser.webkit?(ua) assert Browser.mobile?(ua) assert Browser.modern?(ua) assert Browser.ios?(ua) refute Browser.tablet?(ua) refute Browser.mac?(ua) assert Browser.full_version(ua) == "3.0" assert Browser.version(ua) == "3" end test "detects ipad" do ua = Fixtures.ua["IPAD"] assert Browser.name(ua) == "iPad" assert Browser.full_browser_name(ua) == "iPad 4.0.4" assert Browser.full_display(ua) == "iPad 4.0.4 on iOS 3" assert Browser.ipad?(ua) assert Browser.safari?(ua) assert Browser.webkit?(ua) assert Browser.modern?(ua) assert Browser.ios?(ua) assert Browser.tablet?(ua) refute Browser.mobile?(ua) refute Browser.mac?(ua) assert Browser.full_version(ua) == "4.0.4" assert Browser.version(ua) == "4" end test "detects ipad gsa" do ua = Fixtures.ua["IPAD_GSA"] assert Browser.name(ua) == "iPad" assert Browser.full_browser_name(ua) == "iPad 13.1.72140" assert Browser.full_display(ua) == "iPad 13.1.72140 on iOS 9" assert Browser.ipad?(ua) assert Browser.safari?(ua) assert Browser.webkit?(ua) assert Browser.modern?(ua) assert Browser.ios?(ua) assert Browser.tablet?(ua) refute Browser.mobile?(ua) refute Browser.mac?(ua) assert Browser.full_version(ua) == "13.1.72140" assert Browser.version(ua) == "13" end test "detects ios4" do ua = Fixtures.ua["IOS4"] assert Browser.ios?(ua) assert Browser.ios?(ua, 4) refute Browser.mac?(ua) end test "detects ios5" do ua = Fixtures.ua["IOS5"] assert Browser.ios?(ua) assert Browser.ios?(ua, 5) refute Browser.mac?(ua) end test "detects ios6" do ua = Fixtures.ua["IOS6"] assert Browser.ios?(ua) assert Browser.ios?(ua, 6) refute Browser.mac?(ua) end test "detects ios7" do ua = Fixtures.ua["IOS7"] assert Browser.ios?(ua) assert Browser.ios?(ua, 7) refute Browser.mac?(ua) end test "detects ios8" do ua = Fixtures.ua["IOS8"] assert Browser.ios?(ua) assert Browser.ios?(ua, 8) refute Browser.mac?(ua) end test "detects ios9" do ua = Fixtures.ua["IOS9"] assert Browser.ios?(ua) assert Browser.ios?(ua, 9) refute Browser.mac?(ua) end test "don't detect as two ios different versions" do ua = Fixtures.ua["IOS8"] assert Browser.ios?(ua, 8) refute Browser.ios?(ua, 7) end # kindle test "detects kindle monochrome" do ua = Fixtures.ua["KINDLE"] assert Browser.kindle?(ua) assert Browser.webkit?(ua) end test "detects kindle fire" do ua = Fixtures.ua["KINDLE_FIRE"] assert Browser.kindle?(ua) assert Browser.webkit?(ua) end test "detects kindle fire hd" do ua = Fixtures.ua["KINDLE_FIRE_HD"] assert Browser.silk?(ua) assert Browser.kindle?(ua) assert Browser.webkit?(ua) assert Browser.modern?(ua) refute Browser.mobile?(ua) end test "detects kindle fire hd mobile" do ua = Fixtures.ua["KINDLE_FIRE_HD_MOBILE"] assert Browser.silk?(ua) assert Browser.kindle?(ua) assert Browser.webkit?(ua) assert Browser.modern?(ua) assert Browser.mobile?(ua) end # opera test "detects opera" do ua = Fixtures.ua["OPERA"] assert Browser.name(ua) == "Opera" assert Browser.full_browser_name(ua) == "Opera 11.64" assert Browser.full_display(ua) == "Opera 11.64 on MacOS 10.7.4 Lion" assert Browser.opera?(ua) refute Browser.modern?(ua) assert Browser.full_version(ua) == "11.64" assert Browser.version(ua) == "11" end test "detects opera next" do ua = Fixtures.ua["OPERA_NEXT"] assert Browser.name(ua) == "Opera" assert Browser.full_browser_name(ua) == "Opera 15.0.1147.44" assert Browser.full_display(ua) == "Opera 15.0.1147.44 on MacOS 10.8.4 Mountain Lion" assert Browser.id(ua) == :opera assert Browser.opera?(ua) assert Browser.webkit?(ua) assert Browser.modern?(ua) refute Browser.chrome?(ua) assert Browser.full_version(ua) == "15.0.1147.44" assert Browser.version(ua) == "15" end test "detects opera mini" do ua = Fixtures.ua["OPERA_MINI"] assert Browser.opera_mini?(ua) refute Browser.tablet?(ua) assert Browser.mobile?(ua) end test "detects opera mobi" do ua = Fixtures.ua["OPERA_MOBI"] assert Browser.opera?(ua) refute Browser.tablet?(ua) assert Browser.mobile?(ua) end # bug https://github.com/tuvistavie/elixir-browser/issues/13 test "detects opera on android" do ua = Fixtures.ua["OPERA_ANDROID"] assert Browser.opera?(ua) assert Browser.android?(ua) end test "detects UC Browser" do ua = Fixtures.ua["UC_BROWSER"] assert Browser.name(ua) == "UC Browser" assert Browser.version(ua) == "8" assert Browser.uc_browser?(ua) refute Browser.tablet?(ua) assert Browser.mobile?(ua) end test "fallbacks to other on unknown UA" do ua = Fixtures.ua["INVALID"] assert Browser.name(ua) == "Other" assert Browser.full_browser_name(ua) == "Other 0.0" assert Browser.full_display(ua) == "Other 0.0 on Other" assert Browser.id(ua) == :other assert Browser.full_version(ua) == "0.0" assert Browser.version(ua) == "0" end end
29.30021
90
0.668545
73e679da988e85c412e3b0a0fd0f83b0c09aebdd
1,282
exs
Elixir
test/surface_bulma/navbar_test.exs
kianmeng/surface_bulma
68c81e6364f7951ca688d924c9338ad062a311a1
[ "MIT" ]
30
2021-02-05T18:50:38.000Z
2022-03-12T22:42:29.000Z
test/surface_bulma/navbar_test.exs
kianmeng/surface_bulma
68c81e6364f7951ca688d924c9338ad062a311a1
[ "MIT" ]
19
2021-01-15T19:14:24.000Z
2022-02-05T14:57:18.000Z
test/surface_bulma/navbar_test.exs
kianmeng/surface_bulma
68c81e6364f7951ca688d924c9338ad062a311a1
[ "MIT" ]
17
2021-02-01T20:57:51.000Z
2022-03-20T17:06:57.000Z
defmodule SurfaceBulma.NavbarTest do use SurfaceBulma.ConnCase, async: true alias SurfaceBulma.Link alias SurfaceBulma.Navbar alias SurfaceBulma.Navbar.{Brand, Item, Start, End} test "basic navbar with start and end" do html = render_surface do ~F""" <Navbar id="main-menu"> <Start> <Link navigate="/">Home</Link> </Start> </Navbar> """ end assert html =~ ~r/redirect/ assert html =~ ~r/Home/ end test "navbar can have dropdown menu" do html = render_surface do ~F""" <Navbar id="main-menu"> <Start> <Navbar.Dropdown> <:label><Link>More</Link></:label> <Link navigate="/users">Users</Link> <Link navigate="/settings">Settings</Link> <Link navigate="/settings">Settings</Link> </Navbar.Dropdown> </Start> </Navbar> """ end assert html =~ ~r/redirect/ end test "navbar brand sets SurfacBulma.Link context" do html = render_surface do ~F""" <Navbar id="main"> <Brand> <Link to="test.com" /> </Brand> </Navbar> """ end assert html =~ ~r/navbar-item/ end end
22.103448
56
0.528861
73e6c9b62fccf223909e85c0b833aba97c6bbb52
1,123
ex
Elixir
installer/templates/phx_live/live/page_live.ex
nickurban/phoenix
116a0d4660248a09886e80da5e36dc6e395723d5
[ "MIT" ]
7
2021-01-31T04:51:08.000Z
2022-01-09T06:59:28.000Z
installer/templates/phx_live/live/page_live.ex
nickurban/phoenix
116a0d4660248a09886e80da5e36dc6e395723d5
[ "MIT" ]
2
2022-02-19T07:30:25.000Z
2022-02-27T14:12:26.000Z
installer/templates/phx_live/live/page_live.ex
nickurban/phoenix
116a0d4660248a09886e80da5e36dc6e395723d5
[ "MIT" ]
2
2021-02-06T08:40:23.000Z
2021-03-20T16:35:47.000Z
defmodule <%= @web_namespace %>.PageLive do use <%= @web_namespace %>, :live_view @impl true def mount(_params, _session, socket) do {:ok, assign(socket, query: "", results: %{})} end @impl true def handle_event("suggest", %{"q" => query}, socket) do {:noreply, assign(socket, results: search(query), query: query)} end @impl true def handle_event("search", %{"q" => query}, socket) do case search(query) do %{^query => vsn} -> {:noreply, redirect(socket, external: "https://hexdocs.pm/#{query}/#{vsn}")} _ -> {:noreply, socket |> put_flash(:error, "No dependencies found matching \"#{query}\"") |> assign(results: %{}, query: query)} end end defp search(query) do if not <%= @web_namespace %>.Endpoint.config(:code_reloader) do raise "action disabled when not in development" end for {app, desc, vsn} <- Application.started_applications(), app = to_string(app), String.starts_with?(app, query) and not List.starts_with?(desc, ~c"ERTS"), into: %{}, do: {app, vsn} end end
28.075
84
0.592164
73e6f94eabfddb0d950f01d2e0d13d34b9b05c6b
1,634
ex
Elixir
lib/livebook_web/live/home_live/import_url_component.ex
rodrigues/livebook
9822735bcf0b5bffbbc2bd59a7b942e81276ffe3
[ "Apache-2.0" ]
null
null
null
lib/livebook_web/live/home_live/import_url_component.ex
rodrigues/livebook
9822735bcf0b5bffbbc2bd59a7b942e81276ffe3
[ "Apache-2.0" ]
null
null
null
lib/livebook_web/live/home_live/import_url_component.ex
rodrigues/livebook
9822735bcf0b5bffbbc2bd59a7b942e81276ffe3
[ "Apache-2.0" ]
null
null
null
defmodule LivebookWeb.HomeLive.ImportUrlComponent do use LivebookWeb, :live_component alias Livebook.{ContentLoader, Utils} @impl true def mount(socket) do {:ok, assign(socket, url: "", error_message: nil)} end @impl true def render(assigns) do ~H""" <div class="flex-col space-y-5"> <%= if @error_message do %> <div class="error-box"> <%= @error_message %> </div> <% end %> <p class="text-gray-700"> Paste the URL to a .livemd file, to a GitHub file, or to a Gist to import it. </p> <.form let={f} for={:data} phx-submit="import" phx-change="validate" phx-target={@myself} autocomplete="off"> <%= text_input f, :url, value: @url, class: "input", placeholder: "Notebook URL", autofocus: true, spellcheck: "false" %> <button class="mt-5 button button-blue" type="submit" disabled={not Utils.valid_url?(@url)}> Import </button> </.form> </div> """ end @impl true def handle_event("validate", %{"data" => %{"url" => url}}, socket) do {:noreply, assign(socket, url: url)} end def handle_event("import", %{"data" => %{"url" => url}}, socket) do url |> ContentLoader.rewrite_url() |> ContentLoader.fetch_content() |> case do {:ok, content} -> send(self(), {:import_content, content, [origin: {:url, url}]}) {:noreply, socket} {:error, message} -> {:noreply, assign(socket, error_message: Utils.upcase_first(message))} end end end
26.786885
85
0.554468
73e774509a4031243288abe273c58fe3e5febb1d
257
ex
Elixir
lib/checker_mal.ex
Hiyori-API/checker-mal
c52f6e8a248ba160ffebc2c9369a933fc8fc4499
[ "MIT" ]
10
2020-06-12T18:36:58.000Z
2022-02-20T11:07:49.000Z
lib/checker_mal.ex
Hiyori-API/checker-mal
c52f6e8a248ba160ffebc2c9369a933fc8fc4499
[ "MIT" ]
7
2020-05-08T06:03:08.000Z
2022-01-24T02:57:16.000Z
lib/checker_mal.ex
Hiyori-API/checker-mal
c52f6e8a248ba160ffebc2c9369a933fc8fc4499
[ "MIT" ]
1
2020-12-03T03:49:27.000Z
2020-12-03T03:49:27.000Z
defmodule CheckerMal do @moduledoc """ CheckerMal 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
25.7
66
0.758755
73e793f1817780f36e055b8977693e966bf5997f
3,305
ex
Elixir
lib/serum/renderer.ex
dragsubil/Serum
a465c48b388ef1e6d69ee6e8793f2869035b0520
[ "MIT" ]
null
null
null
lib/serum/renderer.ex
dragsubil/Serum
a465c48b388ef1e6d69ee6e8793f2869035b0520
[ "MIT" ]
null
null
null
lib/serum/renderer.ex
dragsubil/Serum
a465c48b388ef1e6d69ee6e8793f2869035b0520
[ "MIT" ]
null
null
null
defmodule Serum.Renderer do @moduledoc """ This module provides functions for rendering pages into HTML. """ import Serum.Util alias Serum.Error alias Serum.Build @type state :: Build.state @re_media ~r/(?<type>href|src)="(?:%|%25)media:(?<url>[^"]*)"/ @re_old_post ~r/(?<type>href|src)="(?:%|%25)posts:(?<url>[^"]*)"/ @re_old_page ~r/(?<type>href|src)="(?:%|%25)pages:(?<url>[^"]*)"/ @re_post ~r/(?<type>href|src)="(?:%|%25)post:(?<url>[^"]*)"/ @re_page ~r/(?<type>href|src)="(?:%|%25)page:(?<url>[^"]*)"/ @doc """ Renders contents into a complete HTML page. `stub_ctx` is a list of variable bindings which is fed into `templates/<template_name>.html.eex` template file, and `page_ctx` is a list of variable bindings which is then fed into `templates/base.html.eex` template file. """ @spec render(binary, keyword, keyword, state) :: Error.result(binary) # render full page def render(template_name, stub_ctx, page_ctx, state) do %{project_info: proj, templates: templates} = state site_ctx = state.site_ctx page_template = templates[template_name] base_template = templates["base"] tmp = Keyword.merge(stub_ctx, site_ctx, fn _k, v, _ -> v end) case render_stub page_template, tmp, template_name do {:ok, stub} -> contents = process_links stub, proj.base_url ctx = [contents: contents] ++ page_ctx render_stub base_template, ctx ++ site_ctx, "base" error -> error end end @doc """ Renders contents into a (partial) HTML stub. """ @spec render_stub(Build.template_ast, keyword, binary) :: Error.result(binary) def render_stub(template, context, name \\ "") def render_stub(nil, _ctx, name) do filename = to_filename name {:error, {"template was not compiled successfully", filename, 0}} end def render_stub(template, context, name) do filename = to_filename name try do {html, _} = Code.eval_quoted template, context {:ok, html} rescue e in CompileError -> {:error, {e.description, filename, e.line}} e -> {:error, {Exception.message(e), filename, 0}} end end @spec to_filename(binary) :: binary defp to_filename(name) do case name do "" -> "nofile" s when is_binary(s) -> s <> ".html.eex" _ -> "nofile" end end @spec process_links(binary, binary) :: binary defp process_links(text, base) do if Regex.match? @re_old_page, text do warn "\"%pages:\" notation is deprecated, and will be removed in the " <> "future release. Please use \"%page:\" instead" end if Regex.match? @re_old_post, text do warn "\"%posts:\" notation is deprecated, and will be removed in the " <> "future release. Please use \"%post:\" instead" end text |> regex_replace(@re_media, ~s(\\1="#{base}media/\\2")) |> regex_replace(@re_old_page, ~s(\\1="#{base}\\2.html")) |> regex_replace(@re_old_post, ~s(\\1="#{base}posts/\\2.html")) |> regex_replace(@re_page, ~s(\\1="#{base}\\2.html")) |> regex_replace(@re_post, ~s(\\1="#{base}posts/\\2.html")) end @spec regex_replace(binary, Regex.t, binary) :: binary defp regex_replace(text, pattern, replacement) do Regex.replace pattern, text, replacement end end
31.47619
80
0.629652
73e79a2a8c04f05dd8933a350f7c3b27dbcc832b
1,022
ex
Elixir
apps/neoscan/lib/neoscan/tx_abstract/tx_abstract.ex
cc1776/neo-scan
49fc9256f5c7ed4e0a7cd43513b27ba5d9d4f287
[ "MIT" ]
null
null
null
apps/neoscan/lib/neoscan/tx_abstract/tx_abstract.ex
cc1776/neo-scan
49fc9256f5c7ed4e0a7cd43513b27ba5d9d4f287
[ "MIT" ]
null
null
null
apps/neoscan/lib/neoscan/tx_abstract/tx_abstract.ex
cc1776/neo-scan
49fc9256f5c7ed4e0a7cd43513b27ba5d9d4f287
[ "MIT" ]
null
null
null
defmodule Neoscan.TxAbstracts.TxAbstract do @moduledoc false use Ecto.Schema import Ecto.Changeset alias Neoscan.TxAbstracts.TxAbstract schema "tx_abstracts" do field(:address_from, :string) field(:address_to, :string) field(:amount, :string) field(:block_height, :integer) field(:txid, :string) field(:asset, :string) field(:time, :integer) field(:check_hash, :string) timestamps() end @doc false def changeset(attrs \\ %{}) do check_hash = "#{attrs.txid}#{attrs.address_from}#{attrs.address_to}" new_attrs = Map.merge(attrs, %{:check_hash => check_hash, :amount => to_string(attrs.amount)}) %TxAbstract{} |> cast(new_attrs, [ :address_from, :address_to, :amount, :block_height, :txid, :asset, :time, :check_hash, ]) |> validate_required([ :address_from, :address_to, :amount, :block_height, :txid, :asset, :time, :check_hash ]) end end
20.44
98
0.608611
73e7bbc0cb456c53a02208800779f3a50fd623f7
2,362
ex
Elixir
lib/printer/utils/elm_types.ex
HenkPoley/json-schema-to-elm
92230ac907d1eab27a0c8e4d969c5104f8e66383
[ "MIT" ]
null
null
null
lib/printer/utils/elm_types.ex
HenkPoley/json-schema-to-elm
92230ac907d1eab27a0c8e4d969c5104f8e66383
[ "MIT" ]
null
null
null
lib/printer/utils/elm_types.ex
HenkPoley/json-schema-to-elm
92230ac907d1eab27a0c8e4d969c5104f8e66383
[ "MIT" ]
null
null
null
defmodule JS2E.Printer.Utils.ElmTypes do @moduledoc ~S""" Module containing common utility functions for outputting Elm `type` and `type alias` definitions. """ require Logger alias JS2E.Printer alias JsonSchema.Types alias Printer.{ErrorUtil, PrinterError, Utils} alias Types.{PrimitiveType, SchemaDefinition} alias Utils.Naming @spec create_type_name( {:ok, {Types.typeDefinition(), SchemaDefinition.t()}} | {:error, PrinterError.t()}, SchemaDefinition.t(), String.t() ) :: {:ok, String.t()} | {:error, PrinterError.t()} def create_type_name({:error, error}, _schema, _name), do: {:error, error} def create_type_name( {:ok, {resolved_type, resolved_schema}}, context_schema, module_name ) do type_name = case resolved_type do %PrimitiveType{} -> determine_primitive_type_name(resolved_type.type) _ -> resolved_type_name = resolved_type.name {:ok, Naming.upcase_first(resolved_type_name)} end case type_name do {:ok, type_name} -> if resolved_schema.id != context_schema.id do {:ok, Naming.qualify_name(resolved_schema, type_name, module_name)} else {:ok, type_name} end {:error, error} -> {:error, error} end end @doc ~S""" Converts the following primitive types: "string", "integer", "number", and "boolean" into their Elm type equivalent. Raises and error otherwise. ## Examples iex> determine_primitive_type_name("string") {:ok, "String"} iex> determine_primitive_type_name("integer") {:ok, "Int"} iex> determine_primitive_type_name("number") {:ok, "Float"} iex> determine_primitive_type_name("boolean") {:ok, "Bool"} iex> {:error, error} = determine_primitive_type_name("array") iex> error.error_type :unknown_primitive_type """ @spec determine_primitive_type_name(String.t()) :: {:ok, String.t()} | {:error, PrinterError.t()} def determine_primitive_type_name(type_name) do case type_name do "string" -> {:ok, "String"} "integer" -> {:ok, "Int"} "number" -> {:ok, "Float"} "boolean" -> {:ok, "Bool"} _ -> {:error, ErrorUtil.unknown_primitive_type(type_name)} end end end
25.12766
77
0.623624
73e7be3525298aa19a41edf0ac4a5e1015fbdd21
1,532
ex
Elixir
farmbot_core/lib/farmbot_core/firmware_tty_detector.ex
bluewaysw/farmbot_os
3449864bc5c17a688ec2fe75e4a5cf247da57806
[ "MIT" ]
1
2021-04-22T10:18:50.000Z
2021-04-22T10:18:50.000Z
farmbot_core/lib/farmbot_core/firmware_tty_detector.ex
bluewaysw/farmbot_os
3449864bc5c17a688ec2fe75e4a5cf247da57806
[ "MIT" ]
null
null
null
farmbot_core/lib/farmbot_core/firmware_tty_detector.ex
bluewaysw/farmbot_os
3449864bc5c17a688ec2fe75e4a5cf247da57806
[ "MIT" ]
null
null
null
defmodule FarmbotCore.FirmwareTTYDetector do use GenServer require Logger alias Circuits.UART @error_retry_ms 5_000 if System.get_env("FARMBOT_TTY") do @expected_names ["ttyUSB0", "ttyAMA0", "ttyACM0", System.get_env("FARMBOT_TTY")] else @expected_names ["ttyUSB0", "ttyAMA0", "ttyACM0"] end @doc "Gets the detected TTY" def tty(server \\ __MODULE__) do GenServer.call(server, :tty) end def tty!(server \\ __MODULE__) do tty(server) || raise "No TTY detected" end @doc "Sets a TTY as detected by some other means" def set_tty(server \\ __MODULE__, tty) when is_binary(tty) do GenServer.call(server, {:tty, tty}) end def start_link(args, opts \\ [name: __MODULE__]) do GenServer.start_link(__MODULE__, args, opts) end def init([]) do {:ok, nil, 0} end def handle_call(:tty, _, detected_tty) do {:reply, detected_tty, detected_tty} end def handle_call({:tty, detected_tty}, _from, _old_value) do {:reply, :ok, detected_tty} end def handle_info(:timeout, state) do enumerated = UART.enumerate() |> Map.to_list() {:noreply, state, {:continue, enumerated}} end def handle_continue([{name, _} | rest], state) do if farmbot_tty?(name) do {:noreply, name} else {:noreply, state, {:continue, rest}} end end def handle_continue([], state) do Process.send_after(self(), :timeout, @error_retry_ms) {:noreply, state} end defp farmbot_tty?(file_path) do file_path in @expected_names end end
23.212121
84
0.66906
73e7d6e7a3a1764e39c1a070d7924f46fa0020ac
255
exs
Elixir
admin/priv/repo/migrations/20161220141846_create_user.exs
shipperizer/symmetrical-octo-parakeet
6c9c428898d3529c04d872fec8f099456cc54633
[ "MIT" ]
null
null
null
admin/priv/repo/migrations/20161220141846_create_user.exs
shipperizer/symmetrical-octo-parakeet
6c9c428898d3529c04d872fec8f099456cc54633
[ "MIT" ]
null
null
null
admin/priv/repo/migrations/20161220141846_create_user.exs
shipperizer/symmetrical-octo-parakeet
6c9c428898d3529c04d872fec8f099456cc54633
[ "MIT" ]
null
null
null
defmodule Admin.Repo.Migrations.CreateUser do use Ecto.Migration def change do create table(:users) do add :name, :string add :email, :string add :bio, :string add :password, :string timestamps() end end end
15.9375
45
0.627451
73e7df639d7ee51895ccdf749cbb1bf2d19b93f0
1,013
ex
Elixir
lib/goodbye_pulls_web/views/error_helpers.ex
CORDEA/goodbye_pulls
37544b4101f82da0507c9ca83dfce78152bdca90
[ "Apache-2.0" ]
null
null
null
lib/goodbye_pulls_web/views/error_helpers.ex
CORDEA/goodbye_pulls
37544b4101f82da0507c9ca83dfce78152bdca90
[ "Apache-2.0" ]
null
null
null
lib/goodbye_pulls_web/views/error_helpers.ex
CORDEA/goodbye_pulls
37544b4101f82da0507c9ca83dfce78152bdca90
[ "Apache-2.0" ]
null
null
null
defmodule GoodbyePullsWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # Because error messages were defined within Ecto, we must # call the Gettext module passing our Gettext backend. We # also use the "errors" domain as translations are placed # in the errors.po file. # Ecto will pass the :count keyword if the error message is # meant to be pluralized. # On your own code and templates, depending on whether you # need the message to be pluralized or not, this could be # written simply as: # # dngettext "errors", "1 file", "%{count} files", count # dgettext "errors", "is invalid" # if count = opts[:count] do Gettext.dngettext(GoodbyePullsWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(GoodbyePullsWeb.Gettext, "errors", msg, opts) end end end
33.766667
81
0.677196
73e8147102a6e42a776042d737a0177a6c85381e
41
exs
Elixir
.medic/require.exs
dbrody/playwright-elixir
48611c08dbdb8e36aa4dd8aa2d97a4014b753815
[ "MIT" ]
30
2021-06-01T16:59:35.000Z
2022-03-25T16:56:19.000Z
.medic/require.exs
dbrody/playwright-elixir
48611c08dbdb8e36aa4dd8aa2d97a4014b753815
[ "MIT" ]
35
2021-06-10T17:05:31.000Z
2022-02-11T22:30:36.000Z
.medic/require.exs
dbrody/playwright-elixir
48611c08dbdb8e36aa4dd8aa2d97a4014b753815
[ "MIT" ]
4
2021-08-13T20:38:18.000Z
2022-01-31T04:32:35.000Z
Mix.install([ {:medic, force: true} ])
10.25
23
0.585366
73e817ada5eb20c3df68d45d67803ac926d08d3a
878
ex
Elixir
clients/pub_sub/lib/google_api/pub_sub/v1/metadata.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/pub_sub/lib/google_api/pub_sub/v1/metadata.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/pub_sub/lib/google_api/pub_sub/v1/metadata.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.PubSub.V1 do @moduledoc """ API client metadata for GoogleApi.PubSub.V1. """ @discovery_revision "20220524" def discovery_revision(), do: @discovery_revision end
32.518519
74
0.757403
73e86f7b67f7a7ea11cd2e56a7b14671ab8f0fdf
538
ex
Elixir
lib/hexpm/repository/package_owner.ex
lau/hexpm
beee80f5358a356530debfea35ee65c3a0aa9b25
[ "Apache-2.0" ]
null
null
null
lib/hexpm/repository/package_owner.ex
lau/hexpm
beee80f5358a356530debfea35ee65c3a0aa9b25
[ "Apache-2.0" ]
null
null
null
lib/hexpm/repository/package_owner.ex
lau/hexpm
beee80f5358a356530debfea35ee65c3a0aa9b25
[ "Apache-2.0" ]
null
null
null
defmodule Hexpm.Repository.PackageOwner do use Hexpm.Web, :schema schema "package_owners" do field :level, :string, default: "full" belongs_to :package, Package belongs_to :user, User timestamps() end @valid_levels ["full", "maintainer"] def changeset(package_owner, params) do cast(package_owner, params, [:level]) |> unique_constraint(:user_id, name: "package_owners_unique", message: "is already owner") |> validate_required(:level) |> validate_inclusion(:level, @valid_levels) end end
24.454545
94
0.704461
73e8a52a954077059f0ee8882b8c1857c432fb5e
8,303
ex
Elixir
lib/changelog/data/episode/episode.ex
boneskull/changelog.com
2fa2e356bb0e8fcf038c46a4a947fef98822e37d
[ "MIT" ]
null
null
null
lib/changelog/data/episode/episode.ex
boneskull/changelog.com
2fa2e356bb0e8fcf038c46a4a947fef98822e37d
[ "MIT" ]
null
null
null
lib/changelog/data/episode/episode.ex
boneskull/changelog.com
2fa2e356bb0e8fcf038c46a4a947fef98822e37d
[ "MIT" ]
null
null
null
defmodule Changelog.Episode do use Changelog.Data, default_sort: :published_at alias Changelog.{EpisodeHost, EpisodeGuest, EpisodeTopic, EpisodeStat, EpisodeSponsor, Files, NewsItem, Podcast, Regexp, Transcripts} alias ChangelogWeb.{EpisodeView, TimeView} schema "episodes" do field :slug, :string field :guid, :string field :title, :string field :subtitle, :string field :featured, :boolean, default: false field :highlight, :string field :subhighlight, :string field :summary, :string field :notes, :string field :published, :boolean, default: false field :published_at, Timex.Ecto.DateTime field :recorded_at, Timex.Ecto.DateTime field :recorded_live, :boolean, default: false field :audio_file, Files.Audio.Type field :bytes, :integer field :duration, :integer field :download_count, :float field :import_count, :float field :reach_count, :integer field :transcript, {:array, :map} belongs_to :podcast, Podcast has_many :episode_hosts, EpisodeHost, on_delete: :delete_all has_many :hosts, through: [:episode_hosts, :person] has_many :episode_guests, EpisodeGuest, on_delete: :delete_all has_many :guests, through: [:episode_guests, :person] has_many :episode_topics, EpisodeTopic, on_delete: :delete_all has_many :topics, through: [:episode_topics, :topic] has_many :episode_sponsors, EpisodeSponsor, on_delete: :delete_all has_many :sponsors, through: [:episode_sponsors, :sponsor] has_many :episode_stats, EpisodeStat, on_delete: :delete_all timestamps() end def distinct_podcast(query), do: from(q in query, distinct: q.podcast_id) def featured(query \\ __MODULE__), do: from(q in query, where: q.featured == true) def next_after(query \\ __MODULE__, episode), do: from(q in query, where: q.published_at > ^episode.published_at) def previous_to(query \\ __MODULE__, episode), do: from(q in query, where: q.published_at < ^episode.published_at) def published(query \\ __MODULE__), do: from(q in query, where: q.published, where: q.published_at <= ^Timex.now) def recorded_between(query, start_time, end_time), do: from(q in query, where: q.recorded_at <= ^start_time, where: q.end_time < ^end_time) def recorded_future_to(query, time), do: from(q in query, where: q.recorded_at > ^time) def recorded_live(query \\ __MODULE__), do: from(q in query, where: q.recorded_live == true) def scheduled(query \\ __MODULE__), do: from(q in query, where: q.published, where: q.published_at > ^Timex.now) def search(query, term), do: from(q in query, where: fragment("search_vector @@ plainto_tsquery('english', ?)", ^term)) def unpublished(query \\ __MODULE__), do: from(q in query, where: not(q.published)) def with_numbered_slug(query \\ __MODULE__), do: from(q in query, where: fragment("slug ~ E'^\\\\d+$'")) def with_slug(query \\ __MODULE__, slug), do: from(q in query, where: q.slug == ^slug) def with_podcast_slug(query \\ __MODULE__, slug), do: from(q in query, join: p in Podcast, where: q.podcast_id == p.id, where: p.slug == ^slug) def is_public(episode, as_of \\ Timex.now) do is_published(episode) && Timex.before?(episode.published_at, as_of) end def is_published(episode), do: episode.published def is_publishable(episode) do validated = change(episode, %{}) |> validate_required([:slug, :title, :published_at, :summary, :audio_file]) |> validate_format(:slug, Regexp.slug, message: Regexp.slug_message) |> unique_constraint(:slug, name: :episodes_slug_podcast_id_index) |> cast_assoc(:episode_hosts) validated.valid? && !is_published(episode) end def admin_changeset(struct, params \\ %{}) do struct |> cast(params, ~w(slug title subtitle published featured highlight subhighlight summary notes published_at recorded_at recorded_live guid)) |> cast_attachments(params, ~w(audio_file)) |> validate_required([:slug, :title, :published, :featured]) |> validate_format(:slug, Regexp.slug, message: Regexp.slug_message) |> validate_published_has_published_at |> unique_constraint(:slug, name: :episodes_slug_podcast_id_index) |> cast_assoc(:episode_hosts) |> cast_assoc(:episode_guests) |> cast_assoc(:episode_sponsors) |> cast_assoc(:episode_topics) |> derive_bytes_and_duration end def get_news_item(episode), do: NewsItem.with_episode(episode) def object_id(episode), do: "#{episode.podcast.slug}:#{episode.slug}" def participants(episode) do episode = episode |> preload_guests |> preload_hosts episode.guests ++ episode.hosts end def preload_all(episode) do episode |> preload_podcast |> preload_topics |> preload_guests |> preload_hosts |> preload_sponsors end def preload_topics(query = %Ecto.Query{}) do query |> Ecto.Query.preload(episode_topics: ^EpisodeTopic.by_position) |> Ecto.Query.preload(:topics) end def preload_topics(episode) do episode |> Repo.preload(episode_topics: {EpisodeTopic.by_position, :topic}) |> Repo.preload(:topics) end def preload_hosts(query = %Ecto.Query{}) do query |> Ecto.Query.preload(episode_hosts: ^EpisodeHost.by_position) |> Ecto.Query.preload(:hosts) end def preload_hosts(episode) do episode |> Repo.preload(episode_hosts: {EpisodeHost.by_position, :person}) |> Repo.preload(:hosts) end def preload_guests(query = %Ecto.Query{}) do query |> Ecto.Query.preload(episode_guests: ^EpisodeGuest.by_position) |> Ecto.Query.preload(:guests) end def preload_guests(episode) do episode |> Repo.preload(episode_guests: {EpisodeGuest.by_position, :person}) |> Repo.preload(:guests) end def preload_podcast(nil), do: nil def preload_podcast(query = %Ecto.Query{}), do: Ecto.Query.preload(query, :podcast) def preload_podcast(episode), do: Repo.preload(episode, :podcast) def preload_sponsors(query = %Ecto.Query{}) do query |> Ecto.Query.preload(episode_sponsors: ^EpisodeSponsor.by_position) |> Ecto.Query.preload(:sponsors) end def preload_sponsors(episode) do episode |> Repo.preload(episode_sponsors: {EpisodeSponsor.by_position, :sponsor}) |> Repo.preload(:sponsors) end def update_stat_counts(episode) do stats = Repo.all(assoc(episode, :episode_stats)) new_downloads = stats |> Enum.map(&(&1.downloads)) |> Enum.sum |> Kernel.+(episode.import_count) |> Kernel./(1) |> Float.round(2) new_reach = stats |> Enum.map(&(&1.uniques)) |> Enum.sum episode |> change(%{download_count: new_downloads, reach_count: new_reach}) |> Repo.update! end def update_notes(episode, text) do episode |> change(notes: text) |> Repo.update! end def update_transcript(episode, text) do parsed = Transcripts.Parser.parse_text(text, participants(episode)) episode |> change(transcript: parsed) |> Repo.update! end defp derive_bytes_and_duration(changeset) do if new_audio_file = get_change(changeset, :audio_file) do tagged_file = EpisodeView.audio_local_path(%{changeset.data | audio_file: new_audio_file}) case File.stat(tagged_file) do {:ok, stats} -> seconds = extract_duration_seconds(tagged_file) change(changeset, bytes: stats.size, duration: seconds) {:error, _} -> changeset end else changeset end end defp extract_duration_seconds(path) do try do {info, _exit_code} = System.cmd("ffmpeg", ["-i", path], stderr_to_stdout: true) [_match, duration] = Regex.run ~r/Duration: (.*?),/, info TimeView.seconds(duration) catch _all -> 0 end end defp validate_published_has_published_at(changeset) do published = get_field(changeset, :published) published_at = get_field(changeset, :published_at) if published && is_nil(published_at) do add_error(changeset, :published_at, "can't be blank when published") else changeset end end end
34.740586
147
0.680116
73e8b28b88b2cdc4c441b5a222eccb01e6122b16
7,342
ex
Elixir
lib/core/registry.ex
maartenvanvliet/prom_ex
8eb4f86c169af3b184a1a45cf42e298af2b05816
[ "MIT" ]
null
null
null
lib/core/registry.ex
maartenvanvliet/prom_ex
8eb4f86c169af3b184a1a45cf42e298af2b05816
[ "MIT" ]
null
null
null
lib/core/registry.ex
maartenvanvliet/prom_ex
8eb4f86c169af3b184a1a45cf42e298af2b05816
[ "MIT" ]
null
null
null
defmodule PromEx.TelemetryMetricsPrometheus.Core.Registry do @moduledoc false use GenServer require Logger alias Telemetry.Metrics alias PromEx.TelemetryMetricsPrometheus.Core.{Counter, Distribution, LastValue, Sum} @type name :: atom() @type metric_exists_error() :: {:error, :already_exists, Metrics.t()} @type unsupported_metric_type_error() :: {:error, :unsupported_metric_type, :summary} # metric_name should be the validated and normalized prometheus # name - https://prometheus.io/docs/instrumenting/writing_exporters/#naming def start_link(opts) do case Keyword.get(opts, :metrics) do nil -> raise "no :metrics key defined in options" _ -> :ok end GenServer.start_link(__MODULE__, opts, name: opts[:name]) end @impl true def init(opts) do name = opts[:name] aggregates_table_id = create_table(name, :set) dist_table_id = create_table(String.to_atom("#{name}_dist"), :duplicate_bag) start_async = Keyword.get(opts, :start_async, true) Process.flag(:trap_exit, true) state = %{ config: %{aggregates_table_id: aggregates_table_id, dist_table_id: dist_table_id}, metrics: [] } if start_async do {:ok, state, {:continue, {:setup, opts}}} else registered = setup_registry(opts, state.config) {:ok, %{state | metrics: registered}} end end @spec register(Metrics.t(), atom()) :: :ok | metric_exists_error() | unsupported_metric_type_error() def register(metric, name \\ __MODULE__) do GenServer.call(name, {:register, metric}) end def validate_distribution_buckets!(%Metrics.Distribution{} = metric) do reporter_options = metric.reporter_options unless reporter_options != nil do raise ArgumentError, "reporter_options with a valid buckets property are required to be defined for Distribution metrics" end unless Keyword.get(reporter_options, :buckets) != nil do raise ArgumentError, "reporter_options is missing the required buckets property for Distribution metrics" end validate_distribution_buckets!(reporter_options[:buckets]) end @spec validate_distribution_buckets!(term()) :: Distribution.buckets() | no_return() def validate_distribution_buckets!([_ | _] = buckets) do unless Enum.all?(buckets, &is_number/1) do raise ArgumentError, "expected buckets list to contain only numbers, got #{inspect(buckets)}" end unless buckets == Enum.sort(buckets) do raise ArgumentError, "expected buckets to be ordered ascending, got #{inspect(buckets)}" end buckets end def validate_distribution_buckets!({first..last, step} = buckets) when is_integer(step) do if first >= last do raise ArgumentError, "expected buckets range to be ascending, got #{inspect(buckets)}" end if rem(last - first, step) != 0 do raise ArgumentError, "expected buckets range first and last to fall within all range steps " <> "(i.e. rem(last - first, step) == 0), got #{inspect(buckets)}" end first |> Stream.iterate(&(&1 + step)) |> Enum.take_while(&(&1 <= last)) end def validate_distribution_buckets!(term) do raise ArgumentError, "expected buckets to be a non-empty list or a {range, step} tuple, got #{inspect(term)}" end @spec config(name()) :: %{aggregates_table_id: atom(), dist_table_id: atom()} def config(name) do GenServer.call(name, :get_config) end @spec metrics(name()) :: [{Metrics.t(), :telemetry.handler_id()}] def metrics(name) do GenServer.call(name, :get_metrics) end @impl true def handle_continue({:setup, opts}, state) do registered = setup_registry(opts, state.config) {:noreply, %{state | metrics: registered}} end def handle_call(:get_config, _from, state) do {:reply, state.config, state} end def handle_call(:get_metrics, _from, state) do metrics = Enum.map(state.metrics, &elem(&1, 0)) {:reply, metrics, state} end @impl true @spec handle_call({:register, Metrics.t()}, GenServer.from(), map()) :: {:reply, :ok, map()} | {:reply, metric_exists_error() | unsupported_metric_type_error(), map()} def handle_call({:register, metric}, _from, state) do case register_metric(metric, state.config) do {:ok, metric} -> {:reply, :ok, %{state | metrics: [metric | state.metrics]}} other -> {:reply, other, state} end end @impl true def terminate(_reason, %{metrics: metrics, config: config} = _state) do with :ok <- Enum.each(metrics, &unregister_metric/1), true <- :ets.delete(config.aggregates_table_id), true <- :ets.delete(config.dist_table_id), do: :ok end defp setup_registry(opts, config) do opts |> Keyword.get(:metrics, []) |> register_metrics(config) end @spec create_table(name :: atom, type :: atom) :: :ets.tid() | atom defp create_table(name, type) do :ets.new(name, [:named_table, :public, type, {:write_concurrency, true}]) end @spec register_metrics([Metrics.t()], map()) :: [Metrics.t()] defp register_metrics(metrics, config) do metrics |> Enum.reduce([], fn metric, acc -> case register_metric(metric, config) do {:ok, metric} -> [metric | acc] {:error, :already_exists, metric_name} -> Logger.warn("Metric name already exists. Dropping measure. metric_name:=#{inspect(metric_name)}") acc {:error, :unsupported_metric_type, metric_type} -> Logger.warn( "Metric type #{metric_type} is unsupported. Dropping measure. metric_name:=#{inspect(metric.name)}" ) acc end end) end defp register_metric(%Metrics.Counter{} = metric, config) do case Counter.register(metric, config.aggregates_table_id, self()) do {:ok, handler_id} -> {:ok, {metric, handler_id}} {:error, :already_exists} -> {:error, :already_exists, metric.name} end end defp register_metric(%Metrics.LastValue{} = metric, config) do case LastValue.register(metric, config.aggregates_table_id, self()) do {:ok, handler_id} -> {:ok, {metric, handler_id}} {:error, :already_exists} -> {:error, :already_exists, metric.name} end end defp register_metric(%Metrics.Sum{} = metric, config) do case Sum.register(metric, config.aggregates_table_id, self()) do {:ok, handler_id} -> {:ok, {metric, handler_id}} {:error, :already_exists} -> {:error, :already_exists, metric.name} end end defp register_metric(%Metrics.Distribution{} = metric, config) do validate_distribution_buckets!(metric) case Distribution.register(metric, config.dist_table_id, self()) do {:ok, handler_id} -> reporter_options = Keyword.update!( metric.reporter_options, :buckets, &(&1 ++ ["+Inf"]) ) {:ok, {%{metric | reporter_options: reporter_options}, handler_id}} {:error, :already_exists} -> {:error, :already_exists, metric.name} end end defp register_metric(%Metrics.Summary{}, _config) do {:error, :unsupported_metric_type, :summary} end defp unregister_metric({_metric, handler_id}) do :telemetry.detach(handler_id) end end
31.51073
112
0.658268
73e8c3d8cf551275101f19205008e98d75b5ebf0
734
ex
Elixir
lib/phoenix_full_stack/util.ex
naymspace/phoenix-fullstack
289246584a9247d33b4fd3d28bea405d696a5270
[ "MIT" ]
2
2021-05-07T08:17:49.000Z
2021-05-07T08:39:39.000Z
lib/phoenix_full_stack/util.ex
naymspace/phoenix-fullstack
289246584a9247d33b4fd3d28bea405d696a5270
[ "MIT" ]
null
null
null
lib/phoenix_full_stack/util.ex
naymspace/phoenix-fullstack
289246584a9247d33b4fd3d28bea405d696a5270
[ "MIT" ]
1
2021-05-19T16:20:38.000Z
2021-05-19T16:20:38.000Z
defmodule PhoenixFullStack.Util do @moduledoc false @doc """ List all files in a directory tree and returns them as a list. """ def ls_r(path) do cond do File.regular?(path) -> [path] File.dir?(path) -> File.ls!(path) |> Stream.map(&Path.join(path, &1)) |> Stream.map(&ls_r/1) |> Enum.concat() true -> [] end end def temporary_directory(suffix \\ "") do dir = System.tmp_dir!() name = random_string() <> "_" <> suffix tmp_dir = Path.join(dir, name) File.mkdir_p!(tmp_dir) tmp_dir end def random_string(length \\ 8) do :crypto.strong_rand_bytes(length) |> Base.url_encode64() |> binary_part(0, length) end end
20.971429
86
0.580381
73e8e6f245334d1ebf6b48506808531ac3636875
125
ex
Elixir
lib/ueberauth_example/repo.ex
wribln/ueberauth_example
290d4023d647e058a3070453ec5482cf982e13da
[ "MIT" ]
1
2021-08-28T07:59:55.000Z
2021-08-28T07:59:55.000Z
lib/ueberauth_example/repo.ex
wribln/ueberauth_example
290d4023d647e058a3070453ec5482cf982e13da
[ "MIT" ]
null
null
null
lib/ueberauth_example/repo.ex
wribln/ueberauth_example
290d4023d647e058a3070453ec5482cf982e13da
[ "MIT" ]
null
null
null
defmodule UeberauthExample.Repo do use Ecto.Repo, otp_app: :ueberauth_example, adapter: Ecto.Adapters.Postgres end
20.833333
35
0.768
73e8e86c9bf68843b66eeb057e6ab92536790094
1,472
ex
Elixir
lib/phoenix/live_dashboard/pages/ets_page.ex
alexcastano/phoenix_live_dashboard
71579bb49d53a1dbf6eac017de3bb80e6b6c2d21
[ "MIT" ]
null
null
null
lib/phoenix/live_dashboard/pages/ets_page.ex
alexcastano/phoenix_live_dashboard
71579bb49d53a1dbf6eac017de3bb80e6b6c2d21
[ "MIT" ]
null
null
null
lib/phoenix/live_dashboard/pages/ets_page.ex
alexcastano/phoenix_live_dashboard
71579bb49d53a1dbf6eac017de3bb80e6b6c2d21
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveDashboard.EtsPage do @moduledoc false use Phoenix.LiveDashboard.PageBuilder alias Phoenix.LiveDashboard.SystemInfo @table_id :table @menu_text "ETS" @impl true def render_page(_assigns) do table( columns: columns(), id: @table_id, row_attrs: &row_attrs/1, row_fetcher: &fetch_ets/2, rows_name: "tables", title: "ETS" ) end defp fetch_ets(params, node) do %{search: search, sort_by: sort_by, sort_dir: sort_dir, limit: limit} = params SystemInfo.fetch_ets(node, search, sort_by, sort_dir, limit) end defp columns() do [ %{ field: :name, header: "Name or module", header_attrs: [class: "pl-4"], cell_attrs: [class: "tabular-column-name pl-4"] }, %{ field: :protection }, %{ field: :type }, %{ field: :size, cell_attrs: [class: "text-right"], sortable: true }, %{ field: :memory, cell_attrs: [class: "tabular-column-bytes"], format: &format_words(&1[:memory]), sortable: true }, %{ field: :owner, format: &encode_pid(&1[:owner]) } ] end defp row_attrs(table) do [ {"phx-click", "show_info"}, {"phx-value-info", encode_ets(table[:id])}, {"phx-page-loading", true} ] end @impl true def menu_link(_, _) do {:ok, @menu_text} end end
20.164384
82
0.554348
73e8eeae9203955b943e5c521255b9494d1d1a2e
845
exs
Elixir
mix.exs
ZennerIoT/casconf
949ecef6bc52f381a952c16b17fd876f3ba51975
[ "MIT" ]
2
2019-03-27T12:02:05.000Z
2019-05-22T03:08:57.000Z
mix.exs
ZennerIoT/casconf
949ecef6bc52f381a952c16b17fd876f3ba51975
[ "MIT" ]
null
null
null
mix.exs
ZennerIoT/casconf
949ecef6bc52f381a952c16b17fd876f3ba51975
[ "MIT" ]
null
null
null
defmodule Casconf.MixProject do use Mix.Project def project do [ app: :casconf, version: "1.0.0", elixir: "~> 1.8", start_permanent: Mix.env() == :prod, description: "Runtime config fed by static elixir expressions", deps: deps(), package: package(), source_url: "https://github.com/zenneriot/casconf" ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end def package() do [ name: "casconf", licenses: ["MIT"], links: %{"GitHub" => "https://github.com/zenneriot/casconf"} ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:ecto, "~> 3.0", only: :test}, {:ex_doc, ">= 0.0.0", only: :dev, runtime: false} ] end end
21.125
69
0.572781
73e9055b0fa0ef427e3e41ff6c80facb7d178453
776
ex
Elixir
apps/site/lib/site_web/controllers/schedule/offset.ex
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
42
2019-05-29T16:05:30.000Z
2021-08-09T16:03:37.000Z
apps/site/lib/site_web/controllers/schedule/offset.ex
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
872
2019-05-29T17:55:50.000Z
2022-03-30T09:28:43.000Z
apps/site/lib/site_web/controllers/schedule/offset.ex
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
12
2019-07-01T18:33:21.000Z
2022-03-10T02:13:57.000Z
defmodule SiteWeb.ScheduleController.Offset do @moduledoc """ Assigns the offset parameter to determine which scheduled trips to show. """ @behaviour Plug import Plug.Conn, only: [assign: 3] @impl true def init([]), do: [] @impl true def call(conn, []) do offset = find_offset(conn.assigns.timetable_schedules, conn.assigns.date_time) assign(conn, :offset, offset) end # find the index of the defp find_offset(timetable_schedules, date_time) do timetable_schedules |> last_stop_schedules |> Enum.find_index(&Timex.after?(&1.time, date_time)) |> Kernel.||(0) end defp last_stop_schedules(timetable_schedules) do timetable_schedules |> Enum.reverse() |> Enum.uniq_by(& &1.trip) |> Enum.reverse() end end
24.25
82
0.689433
73e93ab3a20afd408d265a5c6160c959ff6fe213
99
exs
Elixir
.formatter.exs
DNNX/badging
861c0d0e376c212bf27e59710fb21d00f734c715
[ "MIT" ]
4
2016-11-07T09:47:09.000Z
2020-10-19T20:39:03.000Z
.formatter.exs
DNNX/badging
861c0d0e376c212bf27e59710fb21d00f734c715
[ "MIT" ]
7
2016-11-07T13:02:36.000Z
2016-11-23T17:37:07.000Z
.formatter.exs
DNNX/badging
861c0d0e376c212bf27e59710fb21d00f734c715
[ "MIT" ]
3
2016-11-07T09:51:36.000Z
2019-06-18T12:26:38.000Z
[ inputs: [ "mix.exs", "config/*.exs", "lib/**/*.ex", "test/**/*.{ex,exs}" ] ]
11
24
0.353535
73e96463d24706bb7cf34905dce56ef50c8bac66
9,907
ex
Elixir
lib/glimesh/api/schema/chat_types.ex
MemoryLeakDeath/glimesh.tv
1462c4b939da899f5e3f67c3f28850025d59a10f
[ "MIT" ]
null
null
null
lib/glimesh/api/schema/chat_types.ex
MemoryLeakDeath/glimesh.tv
1462c4b939da899f5e3f67c3f28850025d59a10f
[ "MIT" ]
null
null
null
lib/glimesh/api/schema/chat_types.ex
MemoryLeakDeath/glimesh.tv
1462c4b939da899f5e3f67c3f28850025d59a10f
[ "MIT" ]
null
null
null
defmodule Glimesh.Api.ChatTypes do @moduledoc false use Absinthe.Schema.Notation use Absinthe.Relay.Schema.Notation, :modern import Absinthe.Resolution.Helpers alias Glimesh.Api.ChatResolver alias Glimesh.Repo alias Glimesh.Streams input_object :chat_message_input do field :message, :string end object :chat_mutations do @desc "Create a chat message" field :create_chat_message, type: :chat_message do arg(:channel_id, non_null(:id)) arg(:message, non_null(:chat_message_input)) resolve(&ChatResolver.create_chat_message/3) end @desc "Short timeout (5 minutes) a user from a chat channel." field :short_timeout_user, type: :channel_moderation_log do arg(:channel_id, non_null(:id)) arg(:user_id, non_null(:id)) resolve(&ChatResolver.short_timeout_user/3) end @desc "Long timeout (15 minutes) a user from a chat channel." field :long_timeout_user, type: :channel_moderation_log do arg(:channel_id, non_null(:id)) arg(:user_id, non_null(:id)) resolve(&ChatResolver.long_timeout_user/3) end @desc "Ban a user from a chat channel." field :ban_user, type: :channel_moderation_log do arg(:channel_id, non_null(:id)) arg(:user_id, non_null(:id)) resolve(&ChatResolver.ban_user/3) end @desc "Deletes a specific chat message from channel." field :delete_chat_message, type: :channel_moderation_log do arg(:channel_id, non_null(:id)) arg(:message_id, non_null(:id)) resolve(&ChatResolver.delete_chat_message/3) end @desc "Unban a user from a chat channel." field :unban_user, type: :channel_moderation_log do arg(:channel_id, non_null(:id)) arg(:user_id, non_null(:id)) resolve(&ChatResolver.unban_user/3) end end object :chat_subscriptions do field :chat_message, :chat_message do arg(:channel_id, :id) config(fn args, _ -> case Map.get(args, :channel_id) do nil -> {:ok, topic: [Streams.get_subscribe_topic(:chat)]} channel_id -> {:ok, topic: [Streams.get_subscribe_topic(:chat, channel_id)]} end end) end end @desc "Chat Message Token Interface" interface :chat_message_token do field :type, :string, description: "Token type" field :text, :string, description: "Token text" resolve_type(fn %{type: "text"}, _ -> :text_token %{type: "url"}, _ -> :url_token %{type: "emote"}, _ -> :emote_token _, _ -> nil end) end @desc "Chat Message Text Token" object :text_token do field :type, :string, description: "Token type" field :text, :string, description: "Token text" interface(:chat_message_token) end @desc "Chat Message URL Token" object :url_token do field :type, :string, description: "Token type" field :text, :string, description: "Token text" field :url, :string, description: "Token URL" interface(:chat_message_token) end @desc "Chat Message Emote Token" object :emote_token do field :type, :string, description: "Token type" field :text, :string, description: "Token text" # URL is no longer necessary, src will return the full URL. # field :url, :string field :src, :string, description: "Token src URL" interface(:chat_message_token) end @desc "A chat message sent to a channel by a user." object :chat_message do field :id, non_null(:id), description: "Unique chat message identifier" field :message, :string, description: "The chat message contents, be careful to sanitize because any user input is allowed" field :tokens, list_of(:chat_message_token), description: "List of chat message tokens used" field :metadata, :chat_message_metadata, description: "A collection of metadata attributed to the chat message" field :is_followed_message, :boolean, description: "Was this message generated by our system for a follow", deprecate: "We're going to replace this shortly after launch" field :is_subscription_message, :boolean, description: "Was this message generated by our system for a subscription", deprecate: "We're going to replace this shortly after launch" # Disabling isMod until we can figure out a performant way of storing the data # Re: https://github.com/Glimesh/glimesh.tv/issues/640 # field :is_mod, :boolean, description: "Is this user that posted this message a moderator" do # resolve(fn message, _, _ -> # message = # message # |> Repo.preload([:channel, :user]) # if message.user_id == message.channel.user_id do # {:ok, true} # else # {:ok, Glimesh.Chat.is_moderator?(message.channel, message.user)} # end # end) # end field :channel, non_null(:channel), resolve: dataloader(Repo), description: "Channel where the chat message occurs" field :user, non_null(:user), resolve: dataloader(Repo), description: "User who sent the chat message" field :inserted_at, non_null(:naive_datetime), description: "Chat message creation date" field :updated_at, non_null(:naive_datetime), description: "Chat message updated date" end @desc "Metadata attributed to the chat message" object :chat_message_metadata do field :admin, :boolean, description: "Was the user a admin at the time of this message" field :streamer, :boolean, description: "Was the user a streamer at the time of this message" field :moderator, :boolean, description: "Was the user a moderator at the time of this message" field :subscriber, :boolean, description: "Was the user a subscriber at the time of this message" field :platform_founder_subscriber, :boolean, description: "Was the user a platform_founder_subscriber at the time of this message" field :platform_supporter_subscriber, :boolean, description: "Was the user a platform_supporter_subscriber at the time of this message" end connection node_type: :chat_message do field :count, :integer do resolve(fn _, %{source: conn} -> {:ok, length(conn.edges)} end) end edge do field :node, :chat_message do resolve(fn %{node: message}, _args, _info -> {:ok, message} end) end end end @desc "A channel timeout or ban" object :channel_ban do field :id, non_null(:id), description: "Unique channel ban identifier" field :channel, non_null(:channel), resolve: dataloader(Repo), description: "Channel the ban affects" field :user, non_null(:user), resolve: dataloader(Repo), description: "User the ban affects" field :expires_at, :naive_datetime, description: "When the ban expires" field :reason, :string, description: "Reason for channel ban" field :inserted_at, non_null(:naive_datetime), description: "Channel ban creation date" field :updated_at, non_null(:naive_datetime), description: "Channel ban updated date" end connection node_type: :channel_ban do field :count, :integer do resolve(fn _, %{source: conn} -> {:ok, length(conn.edges)} end) end edge do field :node, :channel_ban do resolve(fn %{node: message}, _args, _info -> {:ok, message} end) end end end @desc "A channel moderator" object :channel_moderator do field :id, non_null(:id), description: "Unique channel moderator identifier" field :channel, non_null(:channel), resolve: dataloader(Repo), description: "Channel the moderator can moderate in" field :user, non_null(:user), resolve: dataloader(Repo), description: "Moderating User" field :can_short_timeout, :boolean, description: "Can perform a short timeout action" field :can_long_timeout, :boolean, description: "Can perform a long timeout action" field :can_un_timeout, :boolean, description: "Can untimeout a user" field :can_ban, :boolean, description: "Can ban a user" field :can_unban, :boolean, description: "Can unban a user" field :can_delete, :boolean, description: "Can delete a message" field :inserted_at, non_null(:naive_datetime), description: "Moderator creation date" field :updated_at, non_null(:naive_datetime), description: "Moderator updated date" end connection node_type: :channel_moderator do field :count, :integer do resolve(fn _, %{source: conn} -> {:ok, length(conn.edges)} end) end edge do field :node, :channel_moderator do resolve(fn %{node: message}, _args, _info -> {:ok, message} end) end end end @desc "A moderation event that happened" object :channel_moderation_log do field :id, non_null(:id), description: "Unique moderation event identifier" field :channel, non_null(:channel), resolve: dataloader(Repo), description: "Channel the event occurred in" field :moderator, non_null(:user), resolve: dataloader(Repo), description: "Moderator that performed the event" field :user, non_null(:user), resolve: dataloader(Repo), description: "Receiving user of the event" field :action, :string, description: "Action performed" field :inserted_at, non_null(:naive_datetime), description: "Event creation date" field :updated_at, non_null(:naive_datetime), description: "Event updated date" end connection node_type: :channel_moderation_log do field :count, :integer do resolve(fn _, %{source: conn} -> {:ok, length(conn.edges)} end) end edge do field :node, :channel_moderation_log do resolve(fn %{node: message}, _args, _info -> {:ok, message} end) end end end end
31.351266
98
0.67094
73e96cbc6c84af9b65c1263c314f79deffad5074
7,882
ex
Elixir
lib/siwapp/recurring_invoices.ex
peillis/siwapp
f8c11ad2660574395d636674aa449c959f0f87f1
[ "MIT" ]
4
2015-02-12T09:23:47.000Z
2022-03-09T18:11:06.000Z
lib/siwapp/recurring_invoices.ex
peillis/siwapp
f8c11ad2660574395d636674aa449c959f0f87f1
[ "MIT" ]
254
2021-12-09T14:40:41.000Z
2022-03-31T08:09:37.000Z
lib/siwapp/recurring_invoices.ex
peillis/siwapp
f8c11ad2660574395d636674aa449c959f0f87f1
[ "MIT" ]
1
2022-03-07T10:25:49.000Z
2022-03-07T10:25:49.000Z
defmodule Siwapp.RecurringInvoices do @moduledoc """ Recurring Invoices context. """ import Ecto.Query, warn: false alias Siwapp.InvoiceHelper alias Siwapp.Invoices alias Siwapp.Invoices.Invoice alias Siwapp.Invoices.InvoiceQuery alias Siwapp.Query alias Siwapp.RecurringInvoices.RecurringInvoice alias Siwapp.RecurringInvoices.RecurringInvoiceQuery alias Siwapp.Repo @doc """ Lists RecurringInvoices in database with options to select, preload, limit and offset (these two last default to 100 and 0 resp.). Limit can be removed setting limit: false """ @spec list(keyword()) :: [RecurringInvoice.t()] def list(options \\ []) do default = [limit: 100, offset: 0, preload: [], order_by: [desc: :id]] options = Keyword.merge(default, options) RecurringInvoice |> Query.list_preload(options[:preload]) |> maybe_limit_and_offset(options[:limit], options[:offset]) |> order_by(^options[:order_by]) |> maybe_select(options[:select]) |> Repo.all() end @spec get!(pos_integer()) :: RecurringInvoice.t() def get!(id), do: Repo.get!(RecurringInvoice, id) @spec get!(pos_integer(), :preload) :: RecurringInvoice.t() def get!(id, :preload) do RecurringInvoice |> Repo.get!(id) |> Repo.preload([:customer, :series]) end @spec create(map) :: {:ok, RecurringInvoice.t()} | {:error, Ecto.Changeset.t()} def create(attrs \\ %{}) do %RecurringInvoice{} |> RecurringInvoice.changeset(attrs) |> InvoiceHelper.maybe_find_customer_or_new() |> RecurringInvoice.untransform_items() |> Repo.insert() end @spec change(RecurringInvoice.t(), map) :: Ecto.Changeset.t() def change(%RecurringInvoice{} = recurring_invoice, attrs \\ %{}) do RecurringInvoice.changeset(recurring_invoice, attrs) end @spec update(RecurringInvoice.t(), map) :: {:ok, RecurringInvoice.t()} | {:error, Ecto.Changeset.t()} def update(recurring_invoice, attrs) do recurring_invoice |> RecurringInvoice.changeset(attrs) |> InvoiceHelper.maybe_find_customer_or_new() |> RecurringInvoice.untransform_items() |> Repo.update() end @spec delete(RecurringInvoice.t() | Ecto.Changeset.t()) :: {:ok, RecurringInvoice.t()} | {:error, Ecto.Changeset.t()} def delete(recurring_invoice) do Repo.delete(recurring_invoice) end @doc """ Generates invoices associated to each recurring_invoice in db using generate_invoices/1 """ @spec generate_invoices :: :ok def generate_invoices do [select: [:id], limit: false] |> list() |> Enum.each(&generate_invoices(&1.id)) end @doc """ Generates invoices given recurring_invoice_id, if this recurring_invoice is enabled. Also sends them by email if they are meant to (set in recurring_invoice send_by_email field) """ @spec generate_invoices(pos_integer()) :: :ok def generate_invoices(id) do rec_inv = get!(id) id |> invoices_to_generate() |> Range.new(1, -1) |> Enum.map(fn _ -> Invoices.create(build_invoice_attrs(rec_inv)) end) |> Enum.reject(&(elem(&1, 0) == :error)) |> Enum.each(fn {:ok, invoice} -> maybe_send_by_email(invoice, rec_inv.send_by_email) end) end @spec tax_in_any_recurring_invoice?(binary) :: boolean def tax_in_any_recurring_invoice?(tax_name) do RecurringInvoice |> RecurringInvoiceQuery.rec_inv_whose_items_have_tax(tax_name) |> Repo.exists?() end @spec build_invoice_attrs(RecurringInvoice.t()) :: map defp build_invoice_attrs(rec_inv) do rec_inv |> Map.from_struct() |> Map.put(:recurring_invoice_id, rec_inv.id) |> maybe_add_due_date(rec_inv.days_to_due) |> Map.put(:items, rec_inv.items) end @spec maybe_add_due_date(map, integer) :: map defp maybe_add_due_date(attrs, days_to_due) do if days_to_due do due_date = Date.add(Date.utc_today(), days_to_due) Map.put(attrs, :due_date, due_date) else attrs end end @spec maybe_send_by_email(Invoice.t(), boolean) :: {:ok, pos_integer} | {:error, binary} | nil defp maybe_send_by_email(invoice, true) do invoice |> Repo.preload([{:items, :taxes}, :series, :payments]) |> Invoices.send_email() end defp maybe_send_by_email(_invoice, _send_by_email), do: nil @spec maybe_limit_and_offset(Ecto.Query.t(), atom | integer, integer) :: Ecto.Query.t() defp maybe_limit_and_offset(query, false, _offset), do: query defp maybe_limit_and_offset(query, limit, offset) do query |> limit(^limit) |> offset(^offset) end @spec maybe_select(Ecto.Query.t(), nil | [atom]) :: Ecto.Query.t() defp maybe_select(query, nil), do: query defp maybe_select(query, fields), do: from(q in query, select: struct(q, ^fields)) @doc """ Given a recurring_invoice id, returns the amount of invoices that should be generated """ @spec invoices_to_generate(pos_integer()) :: integer def invoices_to_generate(id) do theoretical_number_of_inv_generated(id) - generated_invoices(id) end # Given a recurring_invoice id, returns the amount of invoices already generated related to that recurring_invoice @spec generated_invoices(pos_integer()) :: non_neg_integer() defp generated_invoices(id) do Invoice |> InvoiceQuery.number_of_invoices_associated_to_recurring_id(id) |> Repo.one() end # Given a recurring_invoice id, returns the amount of invoices that # should have been generated from starting_date until today, both included # if recurring_invoice is enabled. Otherwise returns 0 @spec theoretical_number_of_inv_generated(pos_integer()) :: non_neg_integer() defp theoretical_number_of_inv_generated(id) do rec_inv = get!(id) if rec_inv.enabled do today = Date.utc_today() max_date = [today, rec_inv.finishing_date] |> Enum.reject(&is_nil(&1)) |> Enum.sort(Date) |> List.first() number_using_dates = number_of_invoices_in_between_dates( rec_inv.starting_date, rec_inv.period, rec_inv.period_type, max_date ) if rec_inv.max_ocurrences, do: min(number_using_dates, rec_inv.max_ocurrences), else: number_using_dates else 0 end end # Returns the number of invoices that should have been generated from starting_date until max_date both included @spec number_of_invoices_in_between_dates(Date.t(), pos_integer(), binary, Date.t()) :: pos_integer() defp number_of_invoices_in_between_dates( %Date{} = starting_date, period, period_type, %Date{} = max_date ) do stream_iterate = Stream.iterate(starting_date, &next_date(&1, period, period_type)) stream_iterate |> Enum.take_while(&(Date.compare(&1, max_date) != :gt)) |> length() end # Returns the next date that invoices should be generated @spec next_date(Date.t(), pos_integer(), binary) :: Date.t() defp next_date(%Date{} = date, period, period_type), do: Date.add(date, days_to_sum_for_next(date, period, period_type)) # Returns the days that should be added to get to the following invoices generating date @spec days_to_sum_for_next(Date.t(), pos_integer(), binary) :: pos_integer defp days_to_sum_for_next(_date, 0, _period_type), do: 0 defp days_to_sum_for_next(_date, period, "Daily"), do: period defp days_to_sum_for_next(date, period, "Monthly") do days_this_month = :calendar.last_day_of_the_month(date.year, date.month) next_date = Date.add(date, days_this_month) days_this_month + days_to_sum_for_next(next_date, period - 1, "Monthly") end defp days_to_sum_for_next(date, period, "Yearly") do days_this_year = if Date.leap_year?(date), do: 366, else: 365 next_date = Date.add(date, days_this_year) days_this_year + days_to_sum_for_next(next_date, period - 1, "Yearly") end end
33.683761
116
0.697412
73e97f845c2b2ac454c55a8d613b631d7485dfb6
39
ex
Elixir
config/keys.js.ex
lawshe/boda
ebcb3af27bca294cb5d7e786a37b1d49f9af4b19
[ "MIT" ]
1
2018-02-03T21:37:43.000Z
2018-02-03T21:37:43.000Z
config/keys.js.ex
lawshe/boda
ebcb3af27bca294cb5d7e786a37b1d49f9af4b19
[ "MIT" ]
null
null
null
config/keys.js.ex
lawshe/boda
ebcb3af27bca294cb5d7e786a37b1d49f9af4b19
[ "MIT" ]
null
null
null
module.exports = { googleMaps: '' };
9.75
18
0.589744
73e997c84adc469bb7e2af01afaf17b03abcd605
1,649
exs
Elixir
mix.exs
axelson/lifx
9ac02474d181001efc6bc08d7d39a6f6e3bb0d2a
[ "Apache-2.0" ]
null
null
null
mix.exs
axelson/lifx
9ac02474d181001efc6bc08d7d39a6f6e3bb0d2a
[ "Apache-2.0" ]
null
null
null
mix.exs
axelson/lifx
9ac02474d181001efc6bc08d7d39a6f6e3bb0d2a
[ "Apache-2.0" ]
null
null
null
defmodule Lifx.Mixfile do use Mix.Project def project do [ app: :lifx, version: "0.1.8", elixir: "~> 1.3", build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, description: description(), package: package(), deps: deps(), aliases: aliases(), elixirc_paths: elixirc_paths(Mix.env()) ] end def application do [ applications: [:logger], mod: {Lifx, []}, env: [ multicast: {255, 255, 255, 255}, # Don't make this too small or the poller task will fall behind. poll_state_time: 5000, poll_discover_time: 10000, # Should be at least max_retries*wait_between_retry. max_api_timeout: 5000, max_retries: 3, wait_between_retry: 500, udp: Lifx.Udp ] ] end def description do """ A Client for Lifx LAN API """ end def package do [ name: :lifx, files: ["lib", "priv", "mix.exs", "README*", "LICENSE*"], maintainers: ["Christopher Steven Coté"], licenses: ["Apache License 2.0"], links: %{ "GitHub" => "https://github.com/NationalAssociationOfRealtors/lifx", "Docs" => "https://github.com/NationalAssociationOfRealtors/lifx" } ] end defp deps do [ {:ex_doc, ">= 0.0.0", only: :dev}, {:dialyxir, "~> 1.0.0-rc.3", only: [:dev], runtime: false}, {:mox, "~> 0.5", only: :test} ] end defp aliases do [ test: "test --no-start" ] end defp elixirc_paths(:test), do: ["test/support", "lib"] defp elixirc_paths(_), do: ["lib"] end
22.589041
76
0.548817
73e9d061b51821bed5dc01d253a2eb4120743b4a
2,050
exs
Elixir
mix.exs
andys8/stripcode
65a30d946ac20ad1b0e9635e6a3569b7a65e6270
[ "MIT" ]
281
2021-01-15T14:59:38.000Z
2022-01-06T23:13:33.000Z
mix.exs
andys8/stripcode
65a30d946ac20ad1b0e9635e6a3569b7a65e6270
[ "MIT" ]
12
2021-01-15T15:24:54.000Z
2021-07-31T17:36:39.000Z
mix.exs
andys8/stripcode
65a30d946ac20ad1b0e9635e6a3569b7a65e6270
[ "MIT" ]
11
2021-01-15T17:46:59.000Z
2021-09-22T13:24:19.000Z
defmodule OnlyCodes.MixProject do use Mix.Project def project do [ app: :only_codes, version: "0.1.0", elixir: "~> 1.7", elixirc_paths: elixirc_paths(Mix.env()), compilers: [:phoenix, :gettext] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps() ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {OnlyCodes.Application, []}, extra_applications: [:logger, :runtime_tools, :ueberauth_github, :os_mon] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [ {:phoenix, "~> 1.5.7"}, {:phoenix_ecto, "~> 4.1"}, {:ecto_sql, "~> 3.4"}, {:postgrex, ">= 0.0.0"}, {:phoenix_live_view, "~> 0.15.0"}, {:floki, ">= 0.27.0", only: :test}, {:phoenix_html, "~> 2.11"}, {:phoenix_live_reload, "~> 1.2", only: :dev}, {:phoenix_live_dashboard, "~> 0.4"}, {:telemetry_metrics, "~> 0.4"}, {:telemetry_poller, "~> 0.4"}, {:gettext, "~> 0.11"}, {:jason, "~> 1.0"}, {:plug_cowboy, "~> 2.0"}, {:ueberauth, "~> 0.6"}, {:ueberauth_github, "~> 0.7"}, {:ecto_psql_extras, "~> 0.2"} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to install project dependencies and perform other setup tasks, run: # # $ mix setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ setup: ["deps.get", "ecto.setup", "cmd npm install --prefix assets"], "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"] ] end end
28.873239
84
0.572683
73e9ee44368cccf26ea26d5da53490801ba15bd6
287
ex
Elixir
apps/language_server/test/support/uses_macro_a.ex
ihabunek/elixir-ls
a8bdf9304f04254160c9fc982ad314a50085c51a
[ "Apache-2.0" ]
865
2018-10-31T20:29:13.000Z
2022-03-29T11:13:39.000Z
apps/language_server/test/support/uses_macro_a.ex
ihabunek/elixir-ls
a8bdf9304f04254160c9fc982ad314a50085c51a
[ "Apache-2.0" ]
441
2019-01-05T02:33:52.000Z
2022-03-30T20:56:50.000Z
apps/language_server/test/support/uses_macro_a.ex
ihabunek/elixir-ls
a8bdf9304f04254160c9fc982ad314a50085c51a
[ "Apache-2.0" ]
126
2018-11-12T19:16:53.000Z
2022-03-26T13:27:50.000Z
defmodule ElixirLS.Test.UsesMacroA do use ElixirLS.Test.MacroA @inputs [1, 2, 3] def my_fun do macro_a_func() end def my_other_fun do macro_imported_fun() end for input <- @inputs do def gen_fun(unquote(input)) do unquote(input) + 1 end end end
14.35
37
0.658537
73ea0a579ce8520102c6aaa050ead1dd1106f517
451
exs
Elixir
test/chatbot_api_web/views/error_view_test.exs
GregoireLoens/chatbot_api
0a09ae821332b40d9b0fe1cec0b348fccb874613
[ "Apache-2.0" ]
null
null
null
test/chatbot_api_web/views/error_view_test.exs
GregoireLoens/chatbot_api
0a09ae821332b40d9b0fe1cec0b348fccb874613
[ "Apache-2.0" ]
null
null
null
test/chatbot_api_web/views/error_view_test.exs
GregoireLoens/chatbot_api
0a09ae821332b40d9b0fe1cec0b348fccb874613
[ "Apache-2.0" ]
null
null
null
defmodule ChatbotApiWeb.ErrorViewTest do use ChatbotApiWeb.ConnCase, async: true # Bring render/3 and render_to_string/3 for testing custom views import Phoenix.View test "renders 404.html" do assert render_to_string(ChatbotApiWeb.ErrorView, "404.html", []) == "Not Found" end test "renders 500.html" do assert render_to_string(ChatbotApiWeb.ErrorView, "500.html", []) == "Internal Server Error" end end
26.529412
71
0.7051
73ea5bc675ebf3f9de3de580d9dcfed62f0f5617
410
ex
Elixir
services/fc_inventory/lib/fc_inventory/aggregates/serial_number.ex
fleadope/freshcom
8d5944befaa6eea8d31e5f5995939be2a1a44262
[ "BSD-3-Clause" ]
46
2018-10-13T23:18:13.000Z
2021-08-07T07:46:51.000Z
services/fc_inventory/lib/fc_inventory/aggregates/serial_number.ex
fleadope/freshcom
8d5944befaa6eea8d31e5f5995939be2a1a44262
[ "BSD-3-Clause" ]
25
2018-10-14T00:56:07.000Z
2019-12-23T19:41:02.000Z
services/fc_inventory/lib/fc_inventory/aggregates/serial_number.ex
fleadope/freshcom
8d5944befaa6eea8d31e5f5995939be2a1a44262
[ "BSD-3-Clause" ]
5
2018-12-16T04:39:51.000Z
2020-10-01T12:17:03.000Z
defmodule FCInventory.SerialNumber do @moduledoc false use TypedStruct use FCBase, :aggregate alias FCInventory.{SerialNumberAdded} typedstruct do field :remove_at, DateTime.t() end def translatable_fields do [ :name, :caption, :description, :custom_data ] end def apply(%{} = state, %SerialNumberAdded{} = event) do merge(state, event) end end
15.769231
57
0.658537
73ea675c5da838822aae6dd05cb563c1787e1b51
256
ex
Elixir
apps/tai/lib/tai/commander/get_new_order_by_client_id.ex
yurikoval/tai
94254b45d22fa0307b01577ff7c629c7280c0295
[ "MIT" ]
null
null
null
apps/tai/lib/tai/commander/get_new_order_by_client_id.ex
yurikoval/tai
94254b45d22fa0307b01577ff7c629c7280c0295
[ "MIT" ]
78
2020-10-12T06:21:43.000Z
2022-03-28T09:02:00.000Z
apps/tai/lib/tai/commander/get_new_order_by_client_id.ex
yurikoval/tai
94254b45d22fa0307b01577ff7c629c7280c0295
[ "MIT" ]
null
null
null
defmodule Tai.Commander.GetNewOrderByClientId do @type client_id :: Tai.NewOrders.Order.client_id() @type order :: Tai.NewOrders.Order.t() @spec get(client_id) :: order def get(client_id) do Tai.NewOrders.get_by_client_id(client_id) end end
25.6
52
0.746094
73ea6b3ed6fe9b688c8a52e47f5308eb5775fafc
13,614
ex
Elixir
lib/phoenix/router/helpers.ex
mcrumm/phoenix
c3613cadec9ba7c45a8a36360ce8dde905f80ff3
[ "MIT" ]
null
null
null
lib/phoenix/router/helpers.ex
mcrumm/phoenix
c3613cadec9ba7c45a8a36360ce8dde905f80ff3
[ "MIT" ]
null
null
null
lib/phoenix/router/helpers.ex
mcrumm/phoenix
c3613cadec9ba7c45a8a36360ce8dde905f80ff3
[ "MIT" ]
null
null
null
defmodule Phoenix.Router.Helpers do # Module that generates the routing helpers. @moduledoc false alias Phoenix.Router.Route alias Plug.Conn @anno (if :erlang.system_info(:otp_release) >= '19' do [generated: true, unquote: false] else [line: -1, unquote: false] end) @doc """ Callback invoked by the url generated in each helper module. """ def url(_router, %Conn{private: private}) do case private do %{phoenix_router_url: %URI{} = uri} -> URI.to_string(uri) %{phoenix_router_url: url} when is_binary(url) -> url %{phoenix_endpoint: endpoint} -> endpoint.url() end end def url(_router, %_{endpoint: endpoint}) do endpoint.url() end def url(_router, %URI{} = uri) do URI.to_string(%{uri | path: nil}) end def url(_router, endpoint) when is_atom(endpoint) do endpoint.url() end def url(router, other) do raise ArgumentError, "expected a %Plug.Conn{}, a %Phoenix.Socket{}, a %URI{}, a struct with an :endpoint key, " <> "or a Phoenix.Endpoint when building url for #{inspect(router)}, got: #{inspect(other)}" end @doc """ Callback invoked by path generated in each helper module. """ def path(router, %Conn{} = conn, path) do conn |> build_own_forward_path(router, path) |> Kernel.||(build_conn_forward_path(conn, router, path)) |> Kernel.||(path_with_script(path, conn.script_name)) end def path(_router, %URI{} = uri, path) do (uri.path || "") <> path end def path(_router, %_{endpoint: endpoint}, path) do endpoint.path(path) end def path(_router, endpoint, path) when is_atom(endpoint) do endpoint.path(path) end def path(router, other, _path) do raise ArgumentError, "expected a %Plug.Conn{}, a %Phoenix.Socket{}, a %URI{}, a struct with an :endpoint key, " <> "or a Phoenix.Endpoint when building path for #{inspect(router)}, got: #{inspect(other)}" end ## Helpers defp build_own_forward_path(conn, router, path) do case Map.fetch(conn.private, router) do {:ok, {local_script, _}} -> path_with_script(path, local_script) :error -> nil end end defp build_conn_forward_path(%Conn{private: %{phoenix_router: phx_router}} = conn, router, path) do case Map.fetch(conn.private, phx_router) do {:ok, {script_name, forwards}} -> case Map.fetch(forwards, router) do {:ok, local_script} -> path_with_script(path, script_name ++ local_script) :error -> nil end :error -> nil end end defp build_conn_forward_path(_conn, _router, _path), do: nil defp path_with_script(path, []) do path end defp path_with_script(path, script) do "/" <> Enum.join(script, "/") <> path end @doc """ Generates the helper module for the given environment and routes. """ def define(env, routes, opts \\ []) do # Ignore any route without helper or forwards. routes = Enum.filter(routes, fn {route, _exprs} -> (not is_nil(route.helper) and not (route.kind == :forward)) end) groups = Enum.group_by(routes, fn {route, _exprs} -> route.helper end) impls = for {_helper, group} <- groups, {route, exprs} <- Enum.sort_by(group, fn {_, exprs} -> length(exprs.binding) end), do: defhelper(route, exprs) catch_all = Enum.map(groups, &defhelper_catch_all/1) defhelper = quote @anno do defhelper = fn helper, vars, opts, bins, segs, trailing_slash? -> def unquote(:"#{helper}_path")(conn_or_endpoint, unquote(Macro.escape(opts)), unquote_splicing(vars)) do unquote(:"#{helper}_path")(conn_or_endpoint, unquote(Macro.escape(opts)), unquote_splicing(vars), []) end def unquote(:"#{helper}_path")(conn_or_endpoint, unquote(Macro.escape(opts)), unquote_splicing(vars), params) when is_list(params) or is_map(params) do path(conn_or_endpoint, segments(unquote(segs), params, unquote(bins), unquote(Macro.escape(trailing_slash?)), {unquote(helper), unquote(Macro.escape(opts)), unquote(Enum.map(vars, &Macro.to_string/1))})) end def unquote(:"#{helper}_url")(conn_or_endpoint, unquote(Macro.escape(opts)), unquote_splicing(vars)) do unquote(:"#{helper}_url")(conn_or_endpoint, unquote(Macro.escape(opts)), unquote_splicing(vars), []) end def unquote(:"#{helper}_url")(conn_or_endpoint, unquote(Macro.escape(opts)), unquote_splicing(vars), params) when is_list(params) or is_map(params) do url(conn_or_endpoint) <> unquote(:"#{helper}_path")(conn_or_endpoint, unquote(Macro.escape(opts)), unquote_splicing(vars), params) end end end defcatch_all = quote @anno do defcatch_all = fn helper, lengths, routes -> for length <- lengths do binding = List.duplicate({:_, [], nil}, length) arity = length + 2 def unquote(:"#{helper}_path")(conn_or_endpoint, action, unquote_splicing(binding)) do path(conn_or_endpoint, "/") raise_route_error(unquote(helper), :path, unquote(arity), action, []) end def unquote(:"#{helper}_path")(conn_or_endpoint, action, unquote_splicing(binding), params) do path(conn_or_endpoint, "/") raise_route_error(unquote(helper), :path, unquote(arity + 1), action, params) end def unquote(:"#{helper}_url")(conn_or_endpoint, action, unquote_splicing(binding)) do url(conn_or_endpoint) raise_route_error(unquote(helper), :url, unquote(arity), action, []) end def unquote(:"#{helper}_url")(conn_or_endpoint, action, unquote_splicing(binding), params) do url(conn_or_endpoint) raise_route_error(unquote(helper), :url, unquote(arity + 1), action, params) end end defp raise_route_error(unquote(helper), suffix, arity, action, params) do Phoenix.Router.Helpers.raise_route_error(__MODULE__, "#{unquote(helper)}_#{suffix}", arity, action, unquote(Macro.escape(routes)), params) end end end docs = Keyword.get(opts, :docs, true) # It is in general bad practice to generate large chunks of code # inside quoted expressions. However, we can get away with this # here for two reasons: # # * Helper modules are quite uncommon, typically one per project. # # * We inline most of the code for performance, so it is specific # per helper module anyway. # code = quote do @moduledoc unquote(docs) && """ Module with named helpers generated from #{inspect unquote(env.module)}. """ unquote(defhelper) unquote(defcatch_all) unquote_splicing(impls) unquote_splicing(catch_all) @doc """ Generates the path information including any necessary prefix. """ def path(data, path) do Phoenix.Router.Helpers.path(unquote(env.module), data, path) end @doc """ Generates the connection/endpoint base URL without any path information. """ def url(data) do Phoenix.Router.Helpers.url(unquote(env.module), data) end @doc """ Generates path to a static asset given its file path. """ def static_path(%Conn{private: private} = conn, path) do private.phoenix_endpoint.static_path(path) end def static_path(%_{endpoint: endpoint} = conn, path) do endpoint.static_path(path) end def static_path(endpoint, path) when is_atom(endpoint) do endpoint.static_path(path) end @doc """ Generates url to a static asset given its file path. """ def static_url(%Conn{private: private}, path) do case private do %{phoenix_static_url: %URI{} = uri} -> URI.to_string(uri) <> path %{phoenix_static_url: url} when is_binary(url) -> url <> path %{phoenix_endpoint: endpoint} -> static_url(endpoint, path) end end def static_url(%_{endpoint: endpoint} = conn, path) do static_url(endpoint, path) end def static_url(endpoint, path) when is_atom(endpoint) do endpoint.static_url <> endpoint.static_path(path) end @doc """ Generates an integrity hash to a static asset given its file path. """ def static_integrity(%Conn{private: %{phoenix_endpoint: endpoint}}, path) do static_integrity(endpoint, path) end def static_integrity(%_{endpoint: endpoint}, path) do static_integrity(endpoint, path) end def static_integrity(endpoint, path) when is_atom(endpoint) do endpoint.static_integrity(path) end # Functions used by generated helpers # Those are inlined here for performance defp to_param(int) when is_integer(int), do: Integer.to_string(int) defp to_param(bin) when is_binary(bin), do: bin defp to_param(false), do: "false" defp to_param(true), do: "true" defp to_param(data), do: Phoenix.Param.to_param(data) defp segments(segments, [], _reserved, trailing_slash?, _opts) do maybe_append_slash(segments, trailing_slash?) end defp segments(segments, query, reserved, trailing_slash?, _opts) when is_list(query) or is_map(query) do dict = for {k, v} <- query, not ((k = to_string(k)) in reserved), do: {k, v} case Conn.Query.encode dict, &to_param/1 do "" -> maybe_append_slash(segments, trailing_slash?) o -> maybe_append_slash(segments, trailing_slash?) <> "?" <> o end end defp maybe_append_slash("/", _), do: "/" defp maybe_append_slash(path, _trailing_slash? = true), do: path <> "/" defp maybe_append_slash(path, _), do: path end Module.create(Module.concat(env.module, Helpers), code, line: env.line, file: env.file) end @doc """ Receives a route and returns the quoted definition for its helper function. In case a helper name was not given, or route is forwarded, returns nil. """ def defhelper(%Route{} = route, exprs) do helper = route.helper opts = route.plug_opts trailing_slash? = route.trailing_slash? {bins, vars} = :lists.unzip(exprs.binding) segs = expand_segments(exprs.path) quote do defhelper.( unquote(helper), unquote(Macro.escape(vars)), unquote(Macro.escape(opts)), unquote(Macro.escape(bins)), unquote(Macro.escape(segs)), unquote(Macro.escape(trailing_slash?)) ) end end def defhelper_catch_all({helper, routes_and_exprs}) do routes = routes_and_exprs |> Enum.map(fn {routes, exprs} -> {routes.plug_opts, Enum.map(exprs.binding, &elem(&1, 0))} end) |> Enum.sort() lengths = routes |> Enum.map(fn {_, bindings} -> length(bindings) end) |> Enum.uniq() quote do defcatch_all.( unquote(helper), unquote(lengths), unquote(Macro.escape(routes)) ) end end @doc """ Callback for generate router catch alls. """ def raise_route_error(mod, fun, arity, action, routes, params) do cond do not Keyword.has_key?(routes, action) -> "no action #{inspect action} for #{inspect mod}.#{fun}/#{arity}" |> invalid_route_error(fun, routes) is_list(params) or is_map(params) -> "no function clause for #{inspect mod}.#{fun}/#{arity} and action #{inspect action}" |> invalid_route_error(fun, routes) true -> invalid_param_error(mod, fun, arity, action, routes) end end defp invalid_route_error(prelude, fun, routes) do suggestions = for {action, bindings} <- routes do bindings = Enum.join([inspect(action) | bindings], ", ") "\n #{fun}(conn_or_endpoint, #{bindings}, params \\\\ [])" end raise ArgumentError, "#{prelude}. The following actions/clauses are supported:\n#{suggestions}" end defp invalid_param_error(mod, fun, arity, action, routes) do call_vars = Keyword.fetch!(routes, action) raise ArgumentError, """ #{inspect(mod)}.#{fun}/#{arity} called with invalid params. The last argument to this function should be a keyword list or a map. For example: #{fun}(#{Enum.join(["conn", ":#{action}" | call_vars], ", ")}, page: 5, per_page: 10) It is possible you have called this function without defining the proper number of path segments in your router. """ end @doc """ Callback for properly encoding parameters in routes. """ def encode_param(str), do: URI.encode(str, &URI.char_unreserved?/1) defp expand_segments([]), do: "/" defp expand_segments(segments) when is_list(segments) do expand_segments(segments, "") end defp expand_segments(segments) do quote(do: "/" <> Enum.map_join(unquote(segments), "/", &unquote(__MODULE__).encode_param/1)) end defp expand_segments([{:|, _, [h, t]}], acc), do: quote(do: unquote(expand_segments([h], acc)) <> "/" <> Enum.map_join(unquote(t), "/", fn(s) -> URI.encode(s, &URI.char_unreserved?/1) end)) defp expand_segments([h|t], acc) when is_binary(h), do: expand_segments(t, quote(do: unquote(acc) <> unquote("/" <> h))) defp expand_segments([h|t], acc), do: expand_segments(t, quote(do: unquote(acc) <> "/" <> URI.encode(to_param(unquote(h)), &URI.char_unreserved?/1))) defp expand_segments([], acc), do: acc end
33.614815
147
0.633172
73ea7862cd0b1df700b2e46ab3a26bd9cbf38354
3,149
ex
Elixir
clients/service_broker/lib/google_api/service_broker/v1/model/google_iam_v1__binding.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/service_broker/lib/google_api/service_broker/v1/model/google_iam_v1__binding.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/service_broker/lib/google_api/service_broker/v1/model/google_iam_v1__binding.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.ServiceBroker.V1.Model.GoogleIamV1Binding do @moduledoc """ Associates &#x60;members&#x60; with a &#x60;role&#x60;. ## Attributes - condition (GoogleTypeExpr): Unimplemented. The condition that is associated with this binding. NOTE: an unsatisfied condition will not allow user access via current binding. Different bindings, including their conditions, are examined independently. Defaults to: `null`. - members ([String.t]): Specifies the identities requesting access for a Cloud Platform resource. &#x60;members&#x60; can have the following values: * &#x60;allUsers&#x60;: A special identifier that represents anyone who is on the internet; with or without a Google account. * &#x60;allAuthenticatedUsers&#x60;: A special identifier that represents anyone who is authenticated with a Google account or a service account. * &#x60;user:{emailid}&#x60;: An email address that represents a specific Google account. For example, &#x60;[email protected]&#x60; . * &#x60;serviceAccount:{emailid}&#x60;: An email address that represents a service account. For example, &#x60;[email protected]&#x60;. * &#x60;group:{emailid}&#x60;: An email address that represents a Google group. For example, &#x60;[email protected]&#x60;. * &#x60;domain:{domain}&#x60;: A Google Apps domain name that represents all the users of that domain. For example, &#x60;google.com&#x60; or &#x60;example.com&#x60;. Defaults to: `null`. - role (String.t): Role that is assigned to &#x60;members&#x60;. For example, &#x60;roles/viewer&#x60;, &#x60;roles/editor&#x60;, or &#x60;roles/owner&#x60;. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :condition => GoogleApi.ServiceBroker.V1.Model.GoogleTypeExpr.t(), :members => list(any()), :role => any() } field(:condition, as: GoogleApi.ServiceBroker.V1.Model.GoogleTypeExpr) field(:members, type: :list) field(:role) end defimpl Poison.Decoder, for: GoogleApi.ServiceBroker.V1.Model.GoogleIamV1Binding do def decode(value, options) do GoogleApi.ServiceBroker.V1.Model.GoogleIamV1Binding.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceBroker.V1.Model.GoogleIamV1Binding do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
58.314815
1,055
0.736107
73ea79862d65e47698ea40ea90481d1b54786c1f
352
ex
Elixir
lib/ex_clubhouse/model/empty_template_task.ex
pootsbook/exclubhouse
3b93cded0124e4e5df489db4f9262a560595bb8e
[ "MIT" ]
4
2020-03-17T00:42:10.000Z
2021-04-11T16:39:52.000Z
lib/ex_clubhouse/model/empty_template_task.ex
pootsbook/exclubhouse
3b93cded0124e4e5df489db4f9262a560595bb8e
[ "MIT" ]
7
2020-03-21T20:22:13.000Z
2021-12-30T16:32:07.000Z
lib/ex_clubhouse/model/empty_template_task.ex
pootsbook/exclubhouse
3b93cded0124e4e5df489db4f9262a560595bb8e
[ "MIT" ]
4
2020-03-25T18:34:49.000Z
2021-09-13T16:44:00.000Z
defmodule ExClubhouse.Model.EmptyTemplateTask do @moduledoc """ Empty template task model """ @type t :: %__MODULE__{ complete: boolean(), description: binary(), external_id: binary(), owner_ids: list(binary()) } defstruct complete: nil, description: nil, external_id: nil, owner_ids: [] end
23.466667
76
0.619318
73ea9547c7fa2eae5d0e66927eef78ce3f781b25
2,528
ex
Elixir
clients/dataflow/lib/google_api/dataflow/v1b3/model/instruction_output.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/instruction_output.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/instruction_output.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Dataflow.V1b3.Model.InstructionOutput do @moduledoc """ An output of an instruction. ## Attributes - codec (%{optional(String.t) &#x3D;&gt; String.t}): The codec to use to encode data being written via this output. Defaults to: `null`. - name (String.t): The user-provided name of this output. Defaults to: `null`. - onlyCountKeyBytes (boolean()): For system-generated byte and mean byte metrics, certain instructions should only report the key size. Defaults to: `null`. - onlyCountValueBytes (boolean()): For system-generated byte and mean byte metrics, certain instructions should only report the value size. Defaults to: `null`. - originalName (String.t): System-defined name for this output in the original workflow graph. Outputs that do not contribute to an original instruction do not set this. Defaults to: `null`. - systemName (String.t): System-defined name of this output. Unique across the workflow. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :codec => map(), :name => any(), :onlyCountKeyBytes => any(), :onlyCountValueBytes => any(), :originalName => any(), :systemName => any() } field(:codec, type: :map) field(:name) field(:onlyCountKeyBytes) field(:onlyCountValueBytes) field(:originalName) field(:systemName) end defimpl Poison.Decoder, for: GoogleApi.Dataflow.V1b3.Model.InstructionOutput do def decode(value, options) do GoogleApi.Dataflow.V1b3.Model.InstructionOutput.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dataflow.V1b3.Model.InstructionOutput do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.126984
192
0.726266
73eacf2cd1c4b60a8416eb9e73789add9a284f67
4,687
exs
Elixir
test/plug/adapters/test/conn_test.exs
tomciopp/plug
af7fba19e8bce208129d858b924c7a49b93beef1
[ "Apache-2.0" ]
1
2020-09-01T12:50:36.000Z
2020-09-01T12:50:36.000Z
test/plug/adapters/test/conn_test.exs
tomciopp/plug
af7fba19e8bce208129d858b924c7a49b93beef1
[ "Apache-2.0" ]
null
null
null
test/plug/adapters/test/conn_test.exs
tomciopp/plug
af7fba19e8bce208129d858b924c7a49b93beef1
[ "Apache-2.0" ]
null
null
null
defmodule Plug.Adapters.Test.ConnTest do use ExUnit.Case, async: true import Plug.Test test "read_req_body/2" do conn = conn(:get, "/", "abcdefghij") {adapter, state} = conn.adapter assert {:more, "abcde", state} = adapter.read_req_body(state, length: 5) assert {:more, "f", state} = adapter.read_req_body(state, length: 1) assert {:more, "gh", state} = adapter.read_req_body(state, length: 2) assert {:ok, "ij", state} = adapter.read_req_body(state, length: 5) assert {:ok, "", _state} = adapter.read_req_body(state, length: 5) end test "custom params" do conn = conn(:get, "/", a: "b", c: [%{d: "e"}]) assert conn.body_params == %{"a" => "b", "c" => [%{"d" => "e"}]} assert conn.params == %{"a" => "b", "c" => [%{"d" => "e"}]} conn = conn(:get, "/", a: "b", c: [d: "e"]) assert conn.body_params == %{"a" => "b", "c" => %{"d" => "e"}} assert conn.params == %{"a" => "b", "c" => %{"d" => "e"}} conn = conn(:post, "/?foo=bar", %{foo: "baz"}) assert conn.body_params == %{"foo" => "baz"} assert conn.params == %{"foo" => "baz"} conn = conn(:post, "/?foo=bar", %{biz: "baz"}) assert conn.body_params == %{"biz" => "baz"} assert conn.params == %{"foo" => "bar", "biz" => "baz"} end test "custom struct params" do conn = conn(:get, "/", a: "b", file: %Plug.Upload{}) assert conn.params == %{ "a" => "b", "file" => %Plug.Upload{content_type: nil, filename: nil, path: nil} } conn = conn(:get, "/", a: "b", file: %{__struct__: "Foo"}) assert conn.params == %{"a" => "b", "file" => %{"__struct__" => "Foo"}} end test "no body or params" do conn = conn(:get, "/") {adapter, state} = conn.adapter assert conn.req_headers == [] assert {:ok, "", _state} = adapter.read_req_body(state, length: 10) end test "no path" do conn = conn(:get, "http://www.elixir-lang.org") assert conn.path_info == [] end test "custom params sets content-type to multipart/mixed when content-type is not set" do conn = conn(:get, "/", foo: "bar") assert conn.req_headers == [{"content-type", "multipart/mixed; boundary=plug_conn_test"}] end test "custom params does not change content-type when set" do conn = conn(:get, "/", foo: "bar") |> Plug.Conn.put_req_header("content-type", "application/vnd.api+json") |> Plug.Adapters.Test.Conn.conn(:get, "/", foo: "bar") assert conn.req_headers == [{"content-type", "application/vnd.api+json"}] end test "use existing conn.host if exists" do conn_with_host = conn(:get, "http://www.elixir-lang.org/") assert conn_with_host.host == "www.elixir-lang.org" child_conn = Plug.Adapters.Test.Conn.conn(conn_with_host, :get, "/getting-started/", nil) assert child_conn.host == "www.elixir-lang.org" end test "inform adds to the informational responses to the list" do conn = conn(:get, "/") |> Plug.Conn.inform(:early_hints, [{"link", "</style.css>; rel=preload; as=style"}]) |> Plug.Conn.inform(:early_hints, [{"link", "</script.js>; rel=preload; as=script"}]) informational_requests = Plug.Test.sent_informs(conn) assert {103, [{"link", "</style.css>; rel=preload; as=style"}]} in informational_requests assert {103, [{"link", "</script.js>; rel=preload; as=script"}]} in informational_requests end test "push adds to the pushes list" do conn = conn(:get, "/") |> Plug.Conn.push("/static/application.css", [{"accept", "text/css"}]) |> Plug.Conn.push("/static/application.js", [{"accept", "application/javascript"}]) pushes = Plug.Test.sent_pushes(conn) assert {"/static/application.css", [{"accept", "text/css"}]} in pushes assert {"/static/application.js", [{"accept", "application/javascript"}]} in pushes end test "full URL overrides existing conn.host" do conn_with_host = conn(:get, "http://www.elixir-lang.org/") assert conn_with_host.host == "www.elixir-lang.org" child_conn = Plug.Adapters.Test.Conn.conn(conn_with_host, :get, "http://www.example.org/", nil) assert child_conn.host == "www.example.org" end test "use existing conn.remote_ip if exists" do conn_with_remote_ip = %Plug.Conn{conn(:get, "/") | remote_ip: {151, 236, 219, 228}} child_conn = Plug.Adapters.Test.Conn.conn(conn_with_remote_ip, :get, "/", foo: "bar") assert child_conn.remote_ip == {151, 236, 219, 228} end test "use custom peer data" do peer_data = %{address: {127, 0, 0, 1}, port: 111_317} conn = conn(:get, "/") |> put_peer_data(peer_data) assert peer_data == Plug.Conn.get_peer_data(conn) end end
36.905512
94
0.603158
73eb3220e0e2e19d5b17716200fd578b7a83f31d
1,871
ex
Elixir
lib/gwf_gas-meter.ex
zolihorvath/element-parsers
dc9927db1c39b8f77e4c22f10dc38f29c6a41ab9
[ "MIT" ]
null
null
null
lib/gwf_gas-meter.ex
zolihorvath/element-parsers
dc9927db1c39b8f77e4c22f10dc38f29c6a41ab9
[ "MIT" ]
null
null
null
lib/gwf_gas-meter.ex
zolihorvath/element-parsers
dc9927db1c39b8f77e4c22f10dc38f29c6a41ab9
[ "MIT" ]
null
null
null
defmodule Parser do use Platform.Parsing.Behaviour # ELEMENT IoT Parser for GWF Gas meter with Elster module # According to documentation provided by GWF def parse(<<ptype::8, manu::integer-little-16, mid::integer-32, medium::8, state::8, accd::integer-little-16, vif::8, volume::integer-little-32, _::binary>>, _meta) do med = case medium do 3 -> "gas" 6 -> "warm water" 7 -> "water" _ -> "unknown" end decimalplaces = case vif do 0x16 -> 1 0x15 -> 10 0x14 -> 100 0x13 -> 1000 end s = case state do 0x00 -> "no error" 0x04 -> "battery error" 0x30 -> "no comm module <-> meter" 0x50 -> "jammed comm module <-> meter" 0x34 -> "no comms module <-> meter AND battery error" 0x55 -> "jammed comm module <-> meter AND batter error" _ -> "unknown error" end <<n1::integer-4,n0::integer-4,n3::integer-4,n2::integer-4,n5::integer-4,n4::integer-4,n7::4,n6::integer-4>> = <<mid::32>> %{ protocol_type: ptype, manufacturer_id: Base.encode16(<<manu::16>>), actuality_minutes: accd, meter_id: Integer.to_string(n7)<>Integer.to_string(n6)<>Integer.to_string(n5)<>Integer.to_string(n4)<>Integer.to_string(n3)<>Integer.to_string(n2)<>Integer.to_string(n1)<>Integer.to_string(n0), medium: med, state: s, volume: volume/decimalplaces, } end def fields do [ %{ "field" => "volume", "display" => "Volume", "unit" => "m³" } ] end def tests() do [ { :parse_hex, "01E61E1831062103000000141900000000D0982D", %{}, %{ protocol_type: 1, manufacturer_id: "1EE6", actuality_minutes: 0, meter_id: "21063118", medium: "gas", state: "no error", volume: 0.25 } } ] end end
25.986111
197
0.570818
73eb3b5c99f3b636fe8c703a4e2ade90b8c6a013
4,209
exs
Elixir
test/chat_api_web/controllers/company_controller_test.exs
wmnnd/papercups
1e6fdfaf343b95b8bd6853d1327d6123180d0ac7
[ "MIT" ]
null
null
null
test/chat_api_web/controllers/company_controller_test.exs
wmnnd/papercups
1e6fdfaf343b95b8bd6853d1327d6123180d0ac7
[ "MIT" ]
1
2021-01-17T10:42:34.000Z
2021-01-17T10:42:34.000Z
test/chat_api_web/controllers/company_controller_test.exs
BotCart/papercups
7e7533ac8a8becc114060ab5033376c6aab4b369
[ "MIT" ]
null
null
null
defmodule ChatApiWeb.CompanyControllerTest do use ChatApiWeb.ConnCase, async: true import ChatApi.Factory alias ChatApi.Companies.Company @update_attrs %{ description: "some updated description", external_id: "some updated external_id", industry: "some updated industry", logo_image_url: "some updated logo_image_url", metadata: %{}, name: "some updated name", slack_channel_id: "some updated slack_channel_id", slack_channel_name: "some updated slack_channel_name", website_url: "some updated website_url" } @invalid_attrs %{ description: nil, external_id: nil, industry: nil, logo_image_url: nil, metadata: nil, name: nil, slack_channel_id: nil, slack_channel_name: nil, website_url: nil } setup %{conn: conn} do account = insert(:account) user = insert(:user, account: account) company = insert(:company, account: account) conn = put_req_header(conn, "accept", "application/json") authed_conn = Pow.Plug.assign_current_user(conn, user, []) {:ok, conn: conn, authed_conn: authed_conn, account: account, company: company} end describe "index" do test "lists all companies", %{authed_conn: authed_conn, company: company} do resp = get(authed_conn, Routes.company_path(authed_conn, :index)) ids = json_response(resp, 200)["data"] |> Enum.map(& &1["id"]) assert ids == [company.id] end end describe "create company" do test "renders company when data is valid", %{ authed_conn: authed_conn, account: account } do resp = post(authed_conn, Routes.company_path(authed_conn, :create), company: params_for(:company, account: account, name: "Test Co") ) assert %{"id" => id} = json_response(resp, 201)["data"] resp = get(authed_conn, Routes.company_path(authed_conn, :show, id)) account_id = account.id assert %{ "id" => ^id, "account_id" => ^account_id, "object" => "company", "name" => "Test Co" } = json_response(resp, 200)["data"] end test "renders errors when data is invalid", %{authed_conn: authed_conn} do conn = post(authed_conn, Routes.company_path(authed_conn, :create), company: @invalid_attrs) assert json_response(conn, 422)["errors"] != %{} end end describe "update company" do test "renders company when data is valid", %{ authed_conn: authed_conn, company: %Company{id: id} = company } do conn = put(authed_conn, Routes.company_path(authed_conn, :update, company), company: @update_attrs ) assert %{"id" => ^id} = json_response(conn, 200)["data"] conn = get(authed_conn, Routes.company_path(authed_conn, :show, id)) account_id = company.account_id assert %{ "id" => ^id, "account_id" => ^account_id, "name" => "some updated name", "description" => "some updated description", "external_id" => "some updated external_id", "industry" => "some updated industry", "logo_image_url" => "some updated logo_image_url", "website_url" => "some updated website_url", "slack_channel_id" => "some updated slack_channel_id", "slack_channel_name" => "some updated slack_channel_name", "metadata" => %{} } = json_response(conn, 200)["data"] end test "renders errors when data is invalid", %{authed_conn: authed_conn, company: company} do conn = put(authed_conn, Routes.company_path(authed_conn, :update, company), company: @invalid_attrs ) assert json_response(conn, 422)["errors"] != %{} end end describe "delete company" do test "deletes chosen company", %{authed_conn: authed_conn, company: company} do conn = delete(authed_conn, Routes.company_path(authed_conn, :delete, company)) assert response(conn, 204) assert_error_sent 404, fn -> get(authed_conn, Routes.company_path(authed_conn, :show, company)) end end end end
32.627907
98
0.623901
73eb7627c6e2980dc2631d8783b3ff168d9dd3a0
474
ex
Elixir
exercises/concept/freelancer-rates/lib/freelancer_rates.ex
SaschaMann/elixir
2489747bba72a0ba5efa27e7e00441a428fdf987
[ "MIT" ]
1
2021-06-09T06:57:02.000Z
2021-06-09T06:57:02.000Z
exercises/concept/freelancer-rates/lib/freelancer_rates.ex
SaschaMann/elixir
2489747bba72a0ba5efa27e7e00441a428fdf987
[ "MIT" ]
6
2022-03-04T13:05:25.000Z
2022-03-30T18:36:49.000Z
exercises/concept/freelancer-rates/lib/freelancer_rates.ex
SaschaMann/elixir
2489747bba72a0ba5efa27e7e00441a428fdf987
[ "MIT" ]
null
null
null
defmodule FreelancerRates do def daily_rate(hourly_rate) do raise "Please implement the daily_rate/1 function" end def apply_discount(before_discount, discount) do raise "Please implement the apply_discount/2 function" end def monthly_rate(hourly_rate, discount) do raise "Please implement the monthly_rate/2 function" end def days_in_budget(budget, hourly_rate, discount) do raise "Please implement the days_in_budget/3 function" end end
26.333333
58
0.774262
73eb7693098ff9b42a84a3fece516ba04f313c9a
1,758
ex
Elixir
clients/android_management/lib/google_api/android_management/v1/model/api_level_condition.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/android_management/lib/google_api/android_management/v1/model/api_level_condition.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/android_management/lib/google_api/android_management/v1/model/api_level_condition.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.AndroidManagement.V1.Model.ApiLevelCondition do @moduledoc """ A compliance rule condition which is satisfied if the Android Framework API level on the device doesn't meet a minimum requirement. There can only be one rule with this type of condition per policy. ## Attributes * `minApiLevel` (*type:* `integer()`, *default:* `nil`) - The minimum desired Android Framework API level. If the device doesn't meet the minimum requirement, this condition is satisfied. Must be greater than zero. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :minApiLevel => integer() } field(:minApiLevel) end defimpl Poison.Decoder, for: GoogleApi.AndroidManagement.V1.Model.ApiLevelCondition do def decode(value, options) do GoogleApi.AndroidManagement.V1.Model.ApiLevelCondition.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AndroidManagement.V1.Model.ApiLevelCondition do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.404255
218
0.75711
73eb869763bb12e213fa206fbdbb4669284e6c90
58
ex
Elixir
lib/mockery/error.ex
kianmeng/mockery
ad843783e890000627c51b30b69a115e73617542
[ "Apache-2.0" ]
85
2017-07-29T22:03:54.000Z
2022-03-29T09:50:49.000Z
lib/mockery/error.ex
kianmeng/mockery
ad843783e890000627c51b30b69a115e73617542
[ "Apache-2.0" ]
36
2017-07-30T10:12:44.000Z
2021-12-23T12:25:42.000Z
lib/mockery/error.ex
kianmeng/mockery
ad843783e890000627c51b30b69a115e73617542
[ "Apache-2.0" ]
13
2017-07-29T09:06:47.000Z
2021-05-20T13:36:56.000Z
defmodule Mockery.Error do defexception message: "" end
14.5
26
0.775862
73eba219f3e12feb1d52eedb3d70e9067a38230b
1,119
exs
Elixir
markdown/config/config.exs
wkulikowski/homework
4def3bb3c7479953e859b84216b0848dba9c147c
[ "Apache-2.0" ]
69
2018-04-29T20:46:33.000Z
2022-03-11T04:12:40.000Z
markdown/config/config.exs
wkulikowski/homework
4def3bb3c7479953e859b84216b0848dba9c147c
[ "Apache-2.0" ]
5
2018-04-30T05:35:58.000Z
2020-08-24T19:13:36.000Z
markdown/config/config.exs
wkulikowski/homework
4def3bb3c7479953e859b84216b0848dba9c147c
[ "Apache-2.0" ]
18
2018-05-03T02:46:16.000Z
2021-05-01T17:46:55.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :markdown, key: :value # # And access this configuration in your application as: # # Application.get_env(:markdown, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
36.096774
73
0.751564
73ec1e6ebad920be5ddbcf6d90533836cc2e4c0f
2,946
exs
Elixir
test/calliope/integration_test.exs
Qqwy/calliope
f1f2a38e96f4f20b1ebe44f813b36df679434259
[ "Apache-2.0" ]
152
2015-01-13T15:39:04.000Z
2022-03-09T22:20:28.000Z
test/calliope/integration_test.exs
Qqwy/calliope
f1f2a38e96f4f20b1ebe44f813b36df679434259
[ "Apache-2.0" ]
43
2015-02-18T12:54:12.000Z
2018-06-26T20:48:16.000Z
test/calliope/integration_test.exs
Qqwy/calliope
f1f2a38e96f4f20b1ebe44f813b36df679434259
[ "Apache-2.0" ]
34
2015-02-16T23:35:45.000Z
2021-01-11T15:01:59.000Z
defmodule CalliopeIntegerationTest do use ExUnit.Case use Calliope.Render @haml """ - if false do %p true - else %p false """ test :else_result do actual = Regex.replace(~r/(^\s*)|(\s+$)|(\n)/m, EEx.eval_string(render(@haml), []), "") assert actual == "<p>false</p>" end @haml """ - if true do %p true - else %p false """ test :if_result_with_else do actual = Regex.replace(~r/(^\s*)|(\s+$)|(\n)/m, EEx.eval_string(render(@haml), []), "") assert actual == "<p>true</p>" end @haml """ - if true do %p true """ test :if_true_result do actual = Regex.replace(~r/(^\s*)|(\s+$)|(\n)/m, EEx.eval_string(render(@haml), []), "") assert actual == "<p>true</p>" end @haml """ - if false do %p true """ test :if_false_result do actual = Regex.replace(~r/(^\s*)|(\s+$)|(\n)/m, EEx.eval_string(render(@haml), []), "") assert actual == "" end @haml """ - unless false do %p true """ test :uneless_false_result do actual = Regex.replace(~r/(^\s*)|(\s+$)|(\n)/m, EEx.eval_string(render(@haml), []), "") assert actual == "<p>true</p>" end @haml ~S(- unless true do %p false - else %p true ) test :unless_result_with_else do actual = EEx.eval_string(render(@haml), []) assert actual == "\n<p>true</p>\n" end @haml ~S(- answer = "42" %p The answer is = " #{answer}" ) test :local_variable do actual = EEx.eval_string(render(@haml), []) assert actual == "<p>\n The answer is\n 42\n</p>\n" end @haml ~S( - for x <- [1,2] do %p= x ) test :for_evaluation do actual = Regex.replace(~r/(^\s*)|(\s+$)|(\n)/m, EEx.eval_string(render(@haml), []), "") assert actual == "<p>1</p><p>2</p>" end @haml ~S( - case 1 + 1 do - 1 -> %p Got one - 2 -> %p Got two - other -> %p= "Got other #{other}" ) test :case_evaluation do actual = Regex.replace(~r/(^\s*)|(\s+$)|(\n)/m, EEx.eval_string(render(@haml), []), "") assert actual == "<p>Got two</p>" end @haml ~S( .simple_div %b Label: Content Outside the div ) @expected ~S(<div class="simple_div"> <b>Label:</b> Content </div> Outside the div ) test :preserves_newlines do assert EEx.eval_string(render(@haml), []) == @expected end @haml ~s{!!! 5 %section.container %h1 = arg <!-- <h1>An important inline comment</h1> --> <!--[if IE]> <h2>An Elixir Haml Parser</h2> <![endif]--> #main.content Welcome to Calliope %br %section.container %img(src='#') } @expected ~s{<!DOCTYPE html> <section class="container"> <h1> <%= arg %> </h1> <!-- <h1>An important inline comment</h1> --> <!--[if IE]> <h2>An Elixir Haml Parser</h2> <![endif]--> <div id="main" class="content"> Welcome to Calliope <br> </div> </section> <section class="container"> <img src='#'> </section> } test :preserves_newlines_with_comments do assert render(@haml) == @expected end end
19.905405
91
0.56076
73ec46c9158ef076a93e09753d515747fed42bc4
916
ex
Elixir
lib/extreme/event_publisher.ex
Navneet-gupta01/commanded-extreme-adapter
daac1726573d4b979aaeddd0dae9aca0473a9446
[ "MIT" ]
null
null
null
lib/extreme/event_publisher.ex
Navneet-gupta01/commanded-extreme-adapter
daac1726573d4b979aaeddd0dae9aca0473a9446
[ "MIT" ]
null
null
null
lib/extreme/event_publisher.ex
Navneet-gupta01/commanded-extreme-adapter
daac1726573d4b979aaeddd0dae9aca0473a9446
[ "MIT" ]
null
null
null
defmodule Commanded.EventStore.Adapters.Extreme.EventPublisher do use Extreme.FanoutListener alias Commanded.EventStore.Adapters.Extreme.{Mapper, PubSub} alias Commanded.EventStore.RecordedEvent defp process_push(push) do push |> Mapper.to_recorded_event() |> publish() end defp publish(%RecordedEvent{} = recorded_event) do :ok = publish_to_all(recorded_event) :ok = publish_to_stream(recorded_event) end defp publish_to_all(%RecordedEvent{} = recorded_event) do Registry.dispatch(PubSub, "$all", fn entries -> for {pid, _} <- entries, do: send(pid, {:events, [recorded_event]}) end) end defp publish_to_stream(%RecordedEvent{} = recorded_event) do %RecordedEvent{stream_id: stream_id} = recorded_event Registry.dispatch(PubSub, stream_id, fn entries -> for {pid, _} <- entries, do: send(pid, {:events, [recorded_event]}) end) end end
28.625
73
0.712882
73ec4c4c1b179589f5ddaf79ed02131f7fdcc260
72
ex
Elixir
lib/slackmine/redmine.ex
avdgaag/slackmine
99a6964b190ff949088e75e76ce1f98b76b6a9b2
[ "MIT" ]
null
null
null
lib/slackmine/redmine.ex
avdgaag/slackmine
99a6964b190ff949088e75e76ce1f98b76b6a9b2
[ "MIT" ]
null
null
null
lib/slackmine/redmine.ex
avdgaag/slackmine
99a6964b190ff949088e75e76ce1f98b76b6a9b2
[ "MIT" ]
null
null
null
defmodule Slackmine.Redmine do @callback get_issue(binary) :: any end
18
36
0.777778
73ec7a0e76c9ac640c553b343d2e5aafc289a90e
327
ex
Elixir
backend/test/support/validation.ex
eeng/caffe
d85d0dd56a8204c715052ddaf3d990e47c5df0e9
[ "MIT" ]
7
2020-03-27T08:26:52.000Z
2021-08-29T09:50:31.000Z
backend/test/support/validation.ex
eeng/caffe
d85d0dd56a8204c715052ddaf3d990e47c5df0e9
[ "MIT" ]
null
null
null
backend/test/support/validation.ex
eeng/caffe
d85d0dd56a8204c715052ddaf3d990e47c5df0e9
[ "MIT" ]
null
null
null
defmodule Caffe.Support.Validation do def errors_on(module, params) do errors_on(module.changeset(struct(module), params)) end def errors_on(changeset) do Caffe.Middleware.Validator.transform_errors(changeset) end def error_fields_on(module, params) do errors_on(module, params) |> Map.keys() end end
23.357143
58
0.749235