hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
list
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
list
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
list
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
ff773a5c4c8dfff47670cedf619ee93acae7df54
2,804
exs
Elixir
test/css_test.exs
nathanjohnson320/elixir-css
5381cdb16ed6615bef6bfd905b978e3bc713be0e
[ "MIT" ]
null
null
null
test/css_test.exs
nathanjohnson320/elixir-css
5381cdb16ed6615bef6bfd905b978e3bc713be0e
[ "MIT" ]
null
null
null
test/css_test.exs
nathanjohnson320/elixir-css
5381cdb16ed6615bef6bfd905b978e3bc713be0e
[ "MIT" ]
null
null
null
defmodule CssTest do use ExUnit.Case import Css doctest Css test "hover" do styles = [ display_flex(), hover [background_color %CssColors.RGB{red: 32, green: 15, blue: 19}] ] {class, output} = styled(styles) assert class == "aoGhYVFwgcTVVW" assert output == "<style>\n .aoGhYVFwgcTVVW {\n display: flex;\n }\n</style><style>\n .aoGhYVFwgcTVVW:hover {\n background-color: #200F13;\n }\n</style>" end test "styled" do styles = [background_color %CssColors.RGB{red: 32, green: 15, blue: 19}] {class, output} = styled(styles) assert class == "FRVezCvCMuQPN" assert output == "<style>\n .FRVezCvCMuQPN {\n background-color: #200F13;\n }\n</style>" end test "rgb" do assert rgb("#200F13") == %CssColors.RGB{alpha: 1.0, blue: 19.0, green: 15.0, red: 32.0} end test "background_color" do assert background_color(%CssColors.RGB{red: 32, green: 15, blue: 19}) == "background-color: #200F13;" end test "color" do assert color(%CssColors.RGB{red: 32, green: 15, blue: 19}) == "color: #200F13;" end test "display_flex" do assert display_flex() == "display: flex;" end test "flex" do assert flex(3) == "flex: 3;" end test "width" do assert width(100 |> pct) == "width: 100%;" end test "margin" do assert margin(0) == "margin: 0;" end test "padding/2" do assert padding(10 |> px, 5 |> px) == "padding: 10px 5px;" end test "border/3" do assert border(1 |> px, "solid", "#bbc0c4" |> CssColors.parse!()) == "border: 1px solid #BBC0C4;" end test "border_top_color" do assert border_top_color("#bbc0c4" |> CssColors.parse!()) == "border-top-color: #BBC0C4;" end test "border_left_color" do assert border_left_color("#bbc0c4" |> CssColors.parse!()) == "border-left-color: #BBC0C4;" end test "border_bottom_color" do assert border_bottom_color("#bbc0c4" |> CssColors.parse!()) == "border-bottom-color: #BBC0C4;" end test "border_right_color" do assert border_right_color("#bbc0c4" |> CssColors.parse!()) == "border-right-color: #BBC0C4;" end test "border_color" do assert border_color("#bbc0c4" |> CssColors.parse!()) == "border-color: #BBC0C4;" end test "border_radius" do assert border_radius(3 |> px) == "border-radius: 3px;" end test "box_shadow/4" do assert box_shadow(0, 0, 0, rgb("#FFF")) == "box-shadow: 0 0 0 #FFFFFF;" end test "box_shadow" do assert box_shadow("none") == "box-shadow: none;" end test "font_size" do assert font_size(15 |> px) == "font-size: 15px;" end test "font_family" do assert font_family("inherit") == "font-family: inherit;" end test "line_height" do assert line_height(1.15384615) == "line-height: 1.15384615;" end end
25.724771
167
0.629458
ff777ad2693d4c3965d6e7f27eb5946beb0e8400
57
ex
Elixir
lib/kalbu_web/views/page_view.ex
KalvadTech/kalbu
a814aad1c276b44bc3366b758118795fb590d2df
[ "BSD-3-Clause" ]
null
null
null
lib/kalbu_web/views/page_view.ex
KalvadTech/kalbu
a814aad1c276b44bc3366b758118795fb590d2df
[ "BSD-3-Clause" ]
null
null
null
lib/kalbu_web/views/page_view.ex
KalvadTech/kalbu
a814aad1c276b44bc3366b758118795fb590d2df
[ "BSD-3-Clause" ]
null
null
null
defmodule KalbuWeb.PageView do use KalbuWeb, :view end
14.25
30
0.789474
ff77a78d0da9e46ec9cc5233c1572adb5c2c30a6
4,203
ex
Elixir
clients/cloud_tasks/lib/google_api/cloud_tasks/v2/model/binding.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
1
2021-10-01T09:20:41.000Z
2021-10-01T09:20:41.000Z
clients/cloud_tasks/lib/google_api/cloud_tasks/v2/model/binding.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/cloud_tasks/lib/google_api/cloud_tasks/v2/model/binding.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.CloudTasks.V2.Model.Binding do @moduledoc """ Associates `members` with a `role`. ## Attributes * `condition` (*type:* `GoogleApi.CloudTasks.V2.Model.Expr.t`, *default:* `nil`) - The condition that is associated with this binding. If the condition evaluates to `true`, then this binding applies to the current request. If the condition evaluates to `false`, then this binding does not apply to the current request. However, a different role binding might grant the same role to one or more of the members in this binding. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies). * `members` (*type:* `list(String.t)`, *default:* `nil`) - Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`: An email address that represents a Google group. For example, `admins@example.com`. * `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. * `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a service account that has been recently deleted. For example, `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted, this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`. If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that domain. For example, `google.com` or `example.com`. * `role` (*type:* `String.t`, *default:* `nil`) - Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :condition => GoogleApi.CloudTasks.V2.Model.Expr.t() | nil, :members => list(String.t()) | nil, :role => String.t() | nil } field(:condition, as: GoogleApi.CloudTasks.V2.Model.Expr) field(:members, type: :list) field(:role) end defimpl Poison.Decoder, for: GoogleApi.CloudTasks.V2.Model.Binding do def decode(value, options) do GoogleApi.CloudTasks.V2.Model.Binding.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudTasks.V2.Model.Binding do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
79.301887
1,972
0.75113
ff77c1d29aa70b77c786f5cdbbdf2724d6a5404f
2,631
exs
Elixir
lib/day13/brick_breaker2.exs
anamba/adventofcode2019
a5de43ddce8b40f67c3017f349d8563c73c94e20
[ "MIT" ]
null
null
null
lib/day13/brick_breaker2.exs
anamba/adventofcode2019
a5de43ddce8b40f67c3017f349d8563c73c94e20
[ "MIT" ]
null
null
null
lib/day13/brick_breaker2.exs
anamba/adventofcode2019
a5de43ddce8b40f67c3017f349d8563c73c94e20
[ "MIT" ]
null
null
null
# to run: # elixir -r lib/day11/intcode_interpreter.ex lib/day13/brick_breaker2.exs defmodule Day13.BrickBreaker2 do def part2 do pid = read_program() |> start_program clear_screen() {_vram, score} = iterate(pid) score end def read_program do "inputs/day13a.txt" |> File.stream!() |> Enum.map(fn line -> line |> String.trim() |> String.split(",") |> Enum.map(&String.to_integer/1) end) |> List.flatten() end def start_program(program) do spawn(Day11.IntcodeInterpreter, :start_program, [program, [], self()]) end def iterate(pid, ball_pos \\ nil, paddle_pos \\ nil, vram \\ %{}, buffer \\ [], score \\ 0) do receive do {:output, value} -> buffer = buffer ++ [value] if length(buffer) == 3 do case buffer do [-1, 0, new_score] -> iterate(pid, ball_pos, paddle_pos, vram, [], new_score) [x, y, tile] -> {ball_pos, paddle_pos} = case tile do 3 -> {ball_pos, {x, y}} 4 -> new_ball_pos = {x, y} if paddle_pos do {px, py} = paddle_pos cond do px < x -> send(pid, {:input, 1}) px > x -> send(pid, {:input, -1}) true -> nil end end {new_ball_pos, paddle_pos} _ -> {ball_pos, paddle_pos} end # interpret and draw to vram iterate(pid, ball_pos, paddle_pos, update_vram(vram, buffer), [], score) end else # carry on iterate(pid, ball_pos, paddle_pos, vram, buffer, score) end after 500 -> if Process.alive?(pid) do # give it an input to keep things moving send(pid, {:input, 0}) # continue iterate(pid, ball_pos, paddle_pos, vram, buffer, score) else # exit and display {vram, score} end end end def clear_screen, do: IO.write(IO.ANSI.clear()) def paint([x, y, tile]) do IO.write(IO.ANSI.cursor(y, x + 1)) case(tile) do 0 -> " " 1 -> "|" 2 -> "=" 3 -> "_" 4 -> "o" end |> IO.write() end def read_vram(vram, pos = {_x, _y}) do Map.get(vram, pos, 0) end def update_vram(vram, [x, y, tile]) do paint([x, y, tile]) Map.put(vram, {x, y}, tile) end end IO.puts(Day13.BrickBreaker2.part2())
24.137615
96
0.477765
ff77e04b81c04a5ec75162ce940ae3d84f95466d
574
exs
Elixir
examples/udp_example/mix.exs
shun159/brahman
dfa04d757c4e4422b00bdc97a694d2d6637708f9
[ "Beerware" ]
null
null
null
examples/udp_example/mix.exs
shun159/brahman
dfa04d757c4e4422b00bdc97a694d2d6637708f9
[ "Beerware" ]
null
null
null
examples/udp_example/mix.exs
shun159/brahman
dfa04d757c4e4422b00bdc97a694d2d6637708f9
[ "Beerware" ]
null
null
null
defmodule UdpExample.MixProject do use Mix.Project def project do [ app: :udp_example, version: "0.1.0", elixir: "~> 1.7", start_permanent: Mix.env() == :prod, deps: deps() ] end def application do [ extra_applications: [:logger, :brahman], mod: {UdpExample.Application, []} ] end defp deps do [ {:brahman, github: "shun159/brahman", branch: "develop"}, {:lager, ">= 3.5.2", override: true, manager: :rebar3}, {:bear, ">= 0.8.5", override: true, manger: :rebar3} ] end end
19.793103
63
0.554007
ff7842201668d69bbd79a7ad80d18433990aa8d6
1,423
exs
Elixir
test/bsv_p2p/util/services_test.exs
slashrsm/bsv_p2p
59e8971c0f107e71ba38a295f07a0a30699e0ed5
[ "MIT" ]
1
2021-12-07T13:28:54.000Z
2021-12-07T13:28:54.000Z
test/bsv_p2p/util/services_test.exs
slashrsm/bsv_p2p
59e8971c0f107e71ba38a295f07a0a30699e0ed5
[ "MIT" ]
null
null
null
test/bsv_p2p/util/services_test.exs
slashrsm/bsv_p2p
59e8971c0f107e71ba38a295f07a0a30699e0ed5
[ "MIT" ]
null
null
null
defmodule BsvP2p.Util.ServicesTest do use ExUnit.Case alias BsvP2p.Util.Services test "BsvP2p.Util.Services.get_payload/1" do assert <<1, 0, 0, 0, 0, 0, 0, 0>> == Services.get_payload([:node_network]) assert <<2, 0, 0, 0, 0, 0, 0, 0>> == Services.get_payload([:node_getutxo]) assert <<4, 0, 0, 0, 0, 0, 0, 0>> == Services.get_payload([:node_bloom]) assert <<0, 4, 0, 0, 0, 0, 0, 0>> == Services.get_payload([:node_network_limited]) assert <<7, 4, 0, 0, 0, 0, 0, 0>> == Services.get_payload([ :node_network, :node_getutxo, :node_bloom, :node_network_limited ]) assert_raise FunctionClauseError, fn -> Services.get_payload([:foo]) end end test "BsvP2p.Util.Services.from_payload/1" do assert [:node_network] == Services.from_payload(<<1, 0, 0, 0, 0, 0, 0, 0>>) assert [:node_getutxo] == Services.from_payload(<<2, 0, 0, 0, 0, 0, 0, 0>>) assert [:node_bloom] == Services.from_payload(<<4, 0, 0, 0, 0, 0, 0, 0>>) assert [:node_network_limited] == Services.from_payload(<<0, 4, 0, 0, 0, 0, 0, 0>>) assert [:node_network, :node_getutxo, :node_bloom, :node_network_limited] == Services.from_payload(<<7, 4, 0, 0, 0, 0, 0, 0>>) assert [:node_network, :node_getutxo, :node_bloom] == Services.from_payload(<<0xFF, 0, 0, 0, 0, 0, 0, 0>>) end end
38.459459
87
0.583978
ff786155d6a05365894ffc16602328321e19112f
8,554
ex
Elixir
deps/earmark/lib/earmark/html_renderer.ex
lgandersen/jocker_dist
b5e676f8d9e60bbc8bc7a82ccd1e05389f2cd5b5
[ "BSD-2-Clause" ]
null
null
null
deps/earmark/lib/earmark/html_renderer.ex
lgandersen/jocker_dist
b5e676f8d9e60bbc8bc7a82ccd1e05389f2cd5b5
[ "BSD-2-Clause" ]
null
null
null
deps/earmark/lib/earmark/html_renderer.ex
lgandersen/jocker_dist
b5e676f8d9e60bbc8bc7a82ccd1e05389f2cd5b5
[ "BSD-2-Clause" ]
null
null
null
defmodule Earmark.HtmlRenderer do @moduledoc false alias Earmark.Block alias Earmark.Context alias Earmark.Options import Earmark.Inline, only: [convert: 3] import Earmark.Helpers, only: [escape: 2] import Earmark.Helpers.HtmlHelpers import Earmark.Message, only: [add_messages_from: 2, get_messages: 1, set_messages: 2] import Earmark.Context, only: [append: 2, set_value: 2] import Earmark.Options, only: [get_mapper: 1] @doc false def render(blocks, context = %Context{options: %Options{}}) do messages = get_messages(context) {contexts, html} = get_mapper(context.options).( blocks, &render_block(&1, put_in(context.options.messages, [])) ) |> Enum.unzip() all_messages = contexts |> Enum.reduce(messages, fn ctx, messages1 -> messages1 ++ get_messages(ctx) end) {put_in(context.options.messages, all_messages), html |> IO.iodata_to_binary()} end ############# # Paragraph # ############# defp render_block(%Block.Para{lnb: lnb, lines: lines, attrs: attrs}, context) do lines = convert(lines, lnb, context) add_attrs(lines, "<p>#{lines.value}</p>\n", attrs, [], lnb) end ######## # Html # ######## defp render_block(%Block.Html{html: html}, context) do {context, Enum.intersperse(html, ?\n)} end defp render_block(%Block.HtmlComment{lines: lines}, context) do {context, Enum.intersperse(lines, ?\n)} end defp render_block(%Block.HtmlOneline{html: html}, context) do {context, Enum.intersperse(html, ?\n)} end ######### # Ruler # ######### defp render_block(%Block.Ruler{lnb: lnb, type: "-", attrs: attrs}, context) do add_attrs(context, "<hr />\n", attrs, [{"class", ["thin"]}], lnb) end defp render_block(%Block.Ruler{lnb: lnb, type: "_", attrs: attrs}, context) do add_attrs(context, "<hr />\n", attrs, [{"class", ["medium"]}], lnb) end defp render_block(%Block.Ruler{lnb: lnb, type: "*", attrs: attrs}, context) do add_attrs(context, "<hr />\n", attrs, [{"class", ["thick"]}], lnb) end ########### # Heading # ########### defp render_block( %Block.Heading{lnb: lnb, level: level, content: content, attrs: attrs}, context ) do converted = convert(content, lnb, context) html = "<h#{level}>#{converted.value}</h#{level}>\n" add_attrs(converted, html, attrs, [], lnb) end ############## # Blockquote # ############## defp render_block(%Block.BlockQuote{lnb: lnb, blocks: blocks, attrs: attrs}, context) do {context1, body} = render(blocks, context) html = "<blockquote>#{body}</blockquote>\n" add_attrs(context1, html, attrs, [], lnb) end ######### # Table # ######### defp render_block( %Block.Table{lnb: lnb, header: header, rows: rows, alignments: aligns, attrs: attrs}, context ) do {context1, html} = add_attrs(context, "<table>\n", attrs, [], lnb) context2 = set_value(context1, html) context3 = if header do append(add_trs(append(context2, "<thead>\n"), [header], "th", aligns, lnb), "</thead>\n") else # Maybe an error, needed append(context, html) context2 end context4 = append(add_trs(append(context3, "<tbody>\n"), rows, "td", aligns, lnb), "</tbody>\n") {context4, [context4.value, "</table>\n"]} end ######## # Code # ######## defp render_block( %Block.Code{lnb: lnb, language: language, attrs: attrs} = block, context = %Context{options: options} ) do class = if language, do: ~s{ class="#{code_classes(language, options.code_class_prefix)}"}, else: "" tag = ~s[<pre><code#{class}>] lines = options.render_code.(block) html = ~s[#{tag}#{lines}</code></pre>\n] add_attrs(context, html, attrs, [], lnb) end ######### # Lists # ######### defp render_block( %Block.List{lnb: lnb, type: type, blocks: items, attrs: attrs, start: start}, context ) do {context1, content} = render(items, context) html = "<#{type}#{start}>\n#{content}</#{type}>\n" add_attrs(context1, html, attrs, [], lnb) end # format a single paragraph list item, and remove the para tags defp render_block( %Block.ListItem{lnb: lnb, blocks: blocks, spaced: false, attrs: attrs}, context ) when length(blocks) == 1 do {context1, content} = render(blocks, context) content = Regex.replace(~r{</?p>}, content, "") html = "<li>#{content}</li>\n" add_attrs(context1, html, attrs, [], lnb) end # format a spaced list item defp render_block(%Block.ListItem{lnb: lnb, blocks: blocks, attrs: attrs}, context) do {context1, content} = render(blocks, context) html = "<li>#{content}</li>\n" add_attrs(context1, html, attrs, [], lnb) end ################## # Footnote Block # ################## defp render_block(%Block.FnList{blocks: footnotes}, context) do items = Enum.map(footnotes, fn note -> blocks = append_footnote_link(note) %Block.ListItem{attrs: "#fn:#{note.number}", type: :ol, blocks: blocks} end) {context1, html} = render_block(%Block.List{type: :ol, blocks: items}, context) {context1, Enum.join([~s[<div class="footnotes">], "<hr />", html, "</div>"], "\n")} end ####################################### # Isolated IALs are rendered as paras # ####################################### defp render_block(%Block.Ial{verbatim: verbatim}, context) do {context, "<p>{:#{verbatim}}</p>\n"} end #################### # IDDef is ignored # #################### defp render_block(%Block.IdDef{}, context), do: {context, ""} ##################################### # And here are the inline renderers # ##################################### def br, do: "<br />" def codespan(text), do: ~s[<code class="inline">#{text}</code>] def em(text), do: "<em>#{text}</em>" def strong(text), do: "<strong>#{text}</strong>" def strikethrough(text), do: "<del>#{text}</del>" def link(url, text), do: ~s[<a href="#{url}">#{text}</a>] def link(url, text, nil), do: ~s[<a href="#{url}">#{text}</a>] def link(url, text, title), do: ~s[<a href="#{url}" title="#{title}">#{text}</a>] def image(path, alt, nil) do ~s[<img src="#{path}" alt="#{alt}" />] end def image(path, alt, title) do ~s[<img src="#{path}" alt="#{alt}" title="#{title}" />] end def footnote_link(ref, backref, number), do: ~s[<a href="##{ref}" id="#{backref}" class="footnote" title="see footnote">#{number}</a>] # Table rows defp add_trs(context, rows, tag, aligns, lnb) do numbered_rows = rows |> Enum.zip(Stream.iterate(lnb, &(&1 + 1))) numbered_rows |> Enum.reduce(context, fn {row, lnb}, ctx -> append(add_tds(append(ctx, "<tr>\n"), row, tag, aligns, lnb), "\n</tr>\n") end) end defp add_tds(context, row, tag, aligns, lnb) do Enum.reduce(1..length(row), context, add_td_fn(row, tag, aligns, lnb)) end defp add_td_fn(row, tag, aligns, lnb) do fn n, ctx -> style = case Enum.at(aligns, n - 1, :default) do :default -> "" align -> " style=\"text-align: #{align}\"" end col = Enum.at(row, n - 1) converted = convert(col, lnb, set_messages(ctx, [])) append(add_messages_from(ctx, converted), "<#{tag}#{style}>#{converted.value}</#{tag}>") end end ############################### # Append Footnote Return Link # ############################### def append_footnote_link(note = %Block.FnDef{}) do fnlink = ~s[<a href="#fnref:#{note.number}" title="return to article" class="reversefootnote">&#x21A9;</a>] [last_block | blocks] = Enum.reverse(note.blocks) last_block = append_footnote_link(last_block, fnlink) Enum.reverse([last_block | blocks]) |> List.flatten() end def append_footnote_link(block = %Block.Para{lines: lines}, fnlink) do [last_line | lines] = Enum.reverse(lines) last_line = "#{last_line}&nbsp;#{fnlink}" [put_in(block.lines, Enum.reverse([last_line | lines]))] end def append_footnote_link(block, fnlink) do [block, %Block.Para{lines: fnlink}] end def render_code(%Block.Code{lines: lines}) do lines |> Enum.join("\n") |> escape(true) end defp code_classes(language, prefix) do ["" | String.split(prefix || "")] |> Enum.map(fn pfx -> "#{pfx}#{language}" end) |> Enum.join(" ") end end # SPDX-License-Identifier: Apache-2.0
29.804878
104
0.576572
ff7882ee7bd2c250064060fbfacc18afc798fac2
421
ex
Elixir
lib/hlcid/application.ex
davydog187/hlcid
1e7060676df22568e6b7dbe08be1716e25e8d58c
[ "MIT" ]
10
2019-08-25T16:07:40.000Z
2021-07-13T19:08:48.000Z
lib/hlcid/application.ex
davydog187/hlcid
1e7060676df22568e6b7dbe08be1716e25e8d58c
[ "MIT" ]
6
2021-11-22T10:23:01.000Z
2022-03-23T11:07:00.000Z
lib/hlcid/application.ex
elixir-toniq/hlcid
3761b7641feb419e4c4ede4adeb946645ecbb23b
[ "MIT" ]
2
2020-09-10T22:57:59.000Z
2021-05-19T21:34:15.000Z
defmodule HLCID.Application do @moduledoc false use Application def start(_type, _args) do node_id = gen_node_id() children = [ {HLClock, name: HLCID.Clock, node_id: node_id} ] opts = [strategy: :one_for_one, name: HLCID.Supervisor] Supervisor.start_link(children, opts) end defp gen_node_id do 8 |> :crypto.strong_rand_bytes() |> :crypto.bytes_to_integer() end end
18.304348
59
0.669834
ff78a19099b7a2abb1627c09277bbbdc8f51e619
11,064
exs
Elixir
test/taglet_test.exs
GoCorus/taglet
eddc781f1ddff16e43ddbc97d94fe8976a135923
[ "Apache-2.0" ]
null
null
null
test/taglet_test.exs
GoCorus/taglet
eddc781f1ddff16e43ddbc97d94fe8976a135923
[ "Apache-2.0" ]
null
null
null
test/taglet_test.exs
GoCorus/taglet
eddc781f1ddff16e43ddbc97d94fe8976a135923
[ "Apache-2.0" ]
null
null
null
defmodule TagletTest do alias Ecto.Adapters.SQL alias TagletPost, as: Post alias Taglet.{Tagging, Tag} import Ecto.Query import Ecto.Query import Mix.Ecto, only: [build_repo_priv: 1] use ExUnit.Case @repo Taglet.RepoClient.repo() @tenant_id "example_tenant" doctest Taglet setup do # Regular test @repo.delete_all(Post) @repo.delete_all(Tagging) @repo.delete_all(Tag) # Multi tenant test setup_tenant() on_exit(fn -> # Regular test @repo.delete_all(Post) @repo.delete_all(Tagging) @repo.delete_all(Tag) # Multi tenant test setup_tenant() end) :ok end # Regular test test "add/4 with a tag returns the struct with the new tag" do post = @repo.insert!(%Post{title: "hello world"}) Taglet.add(post, "mytag") result = Taglet.add(post, "tag1") assert result.tags == ["mytag", "tag1"] end test "add/4 with a tag list returns the struct with the new tags" do post = @repo.insert!(%Post{title: "hello world"}) Taglet.add(post, "mytag") result = Taglet.add(post, ["tag1", "tag2"]) assert result.tags == ["mytag", "tag1", "tag2"] end test "add/4 with context returns a diferent list for every context" do post = @repo.insert!(%Post{title: "hello world"}) result1 = Taglet.add(post, "mytag1", "context1") result2 = Taglet.add(post, "mytag2", "context2") assert result1.context1 == ["mytag1"] assert result2.context2 == ["mytag2"] end test "add/4 with repeated tag returns the same tags" do post = @repo.insert!(%Post{title: "hello world"}) Taglet.add(post, "mytag") result = Taglet.add(post, "mytag") assert result.tags == ["mytag"] end test "add/4 with nil tag returns the same struct" do post = @repo.insert!(%Post{title: "hello world"}) result = Taglet.add(post, nil) assert result == post end test "remove/4 deletes a tag and returns a list of associated tags" do post = @repo.insert!(%Post{title: "hello world"}) Taglet.add(post, "mytag") Taglet.add(post, "mytag2") Taglet.add(post, "mytag3") result = Taglet.remove(post, "mytag2") assert result.tags == ["mytag", "mytag3"] end test "remove/4 deletes a tag for a specific context and returns a list of associated tags" do post = @repo.insert!(%Post{title: "hello world"}) Taglet.add(post, "mytag", "context1") Taglet.add(post, "mytag2", "context1") Taglet.add(post, "mytag3", "context2") result = Taglet.remove(post, "mytag2", "context1") assert result.context1 == ["mytag"] end test "remove/4 does nothing for an unexistent tag" do post = @repo.insert!(%Post{title: "hello world"}) Taglet.add(post, "mytag") Taglet.add(post, "mytag2") Taglet.add(post, "mytag3") result = Taglet.remove(post, "my2") assert result.tags == ["mytag", "mytag2", "mytag3"] end test "tag_list/2 with struct as param returns a list of associated tags" do post = @repo.insert!(%Post{title: "hello world"}) Taglet.add(post, "mytag") Taglet.add(post, "mytag2") result = Taglet.tag_list(post) assert result == ["mytag", "mytag2"] end test "tag_list/2 with struct returns a list of associated tags for a specific context" do post = @repo.insert!(%Post{title: "hello world"}) Taglet.add(post, "mytag", "context") Taglet.add(post, "mytag2", "context") result = Taglet.tag_list(post, "context") assert result == ["mytag", "mytag2"] end test "tag_list/2 with module as param returns a list of tags related with one context and module" do post1 = @repo.insert!(%Post{title: "hello world"}) post2 = @repo.insert!(%Post{title: "hello world2"}) Taglet.add(post1, ["tag1", "tag2"]) Taglet.add(post2, ["tag2", "tag3"]) result = Taglet.tag_list(Post) assert result == ["tag1", "tag2", "tag3"] end test "tagged_with/4 returns a list of structs associated to a tag" do post1 = @repo.insert!(%Post{title: "hello world1"}) post2 = @repo.insert!(%Post{title: "hello world2"}) post3 = @repo.insert!(%Post{title: "hello world3"}) Taglet.add(post1, "tagged1") Taglet.add(post2, "tagged1") Taglet.add(post3, "tagged2") result = Taglet.tagged_with("tagged1", Post) assert result == [post1, post2] end test "tagged_with_query/4 returns a query of structs associated to a tag" do post1 = @repo.insert!(%Post{title: "hello world1"}) post2 = @repo.insert!(%Post{title: "hello world2"}) post3 = @repo.insert!(%Post{title: "hello world3"}) Taglet.add(post1, "tagged1") Taglet.add(post2, ["tagged1", "tagged2"]) Taglet.add(post3, "tagged2") query = Post |> where(title: "hello world2") result = Taglet.tagged_with_query(query, ["tagged1", "tagged2"]) |> @repo.all assert result == [post2] end # Multi tenant test test "[multi tenant] add/4 with a tag returns the struct with the new tag" do post = @repo.insert!(%Post{title: "hello world"}) Taglet.add(post, "mytag") result = Taglet.add(post, "tag1") assert result.tags == ["mytag", "tag1"] end test "[multi tenant] add/4 with a tag list returns the struct with the new tags" do post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id) Taglet.add(post, "mytag", prefix: @tenant_id) result = Taglet.add(post, ["tag1", "tag2"], prefix: @tenant_id) assert result.tags == ["mytag", "tag1", "tag2"] end test "[multi tenant] add/4 with context returns a diferent list for every context" do post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id) result1 = Taglet.add(post, "mytag1", "context1", prefix: @tenant_id) result2 = Taglet.add(post, "mytag2", "context2", prefix: @tenant_id) assert result1.context1 == ["mytag1"] assert result2.context2 == ["mytag2"] end test "[multi tenant] add/4 with repeated tag returns the same tags" do post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id) Taglet.add(post, "mytag", prefix: @tenant_id) result = Taglet.add(post, "mytag", prefix: @tenant_id) assert result.tags == ["mytag"] end test "[multi tenant] add/4 with nil tag returns the same struct" do post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id) result = Taglet.add(post, nil, prefix: @tenant_id) assert result == post end test "[multi tenant] remove/4 deletes a tag and returns a list of associated tags" do post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id) Taglet.add(post, "mytag", "tags", prefix: @tenant_id) Taglet.add(post, "mytag2", "tags", prefix: @tenant_id) Taglet.add(post, "mytag3", "tags", prefix: @tenant_id) result = Taglet.remove(post, "mytag2", "tags", prefix: @tenant_id) assert result.tags == ["mytag", "mytag3"] end test "[multi tenant] remove/4 deletes a tag for a specific context and returns a list of associated tags" do post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id) Taglet.add(post, "mytag", "context1", prefix: @tenant_id) Taglet.add(post, "mytag2", "context1", prefix: @tenant_id) Taglet.add(post, "mytag3", "context2", prefix: @tenant_id) result = Taglet.remove(post, "mytag2", "context1", prefix: @tenant_id) assert result.context1 == ["mytag"] end test "[multi tenant] remove/4 does nothing for an unexistent tag" do post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id) Taglet.add(post, "mytag", "tags", prefix: @tenant_id) Taglet.add(post, "mytag2", "tags", prefix: @tenant_id) Taglet.add(post, "mytag3", "tags", prefix: @tenant_id) result = Taglet.remove(post, "my2", "tags", prefix: @tenant_id) assert result.tags() == ["mytag", "mytag2", "mytag3"] end test "[multi tenant] tag_list/2 with struct as param returns a list of associated tags" do post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id) Taglet.add(post, "mytag", "tags", prefix: @tenant_id) Taglet.add(post, "mytag2", "tags", prefix: @tenant_id) result = Taglet.tag_list(post, "tags", prefix: @tenant_id) assert result == ["mytag", "mytag2"] end test "[multi tenant] tag_list/2 with struct returns a list of associated tags for a specific context" do post = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id) Taglet.add(post, "mytag", "context", prefix: @tenant_id) Taglet.add(post, "mytag2", "context", prefix: @tenant_id) result = Taglet.tag_list(post, "context", prefix: @tenant_id) assert result == ["mytag", "mytag2"] end test "[multi tenant] tag_list/2 with module as param returns a list of tags related with one context and module" do post1 = @repo.insert!(%Post{title: "hello world"}, prefix: @tenant_id) post2 = @repo.insert!(%Post{title: "hello world2"}, prefix: @tenant_id) Taglet.add(post1, ["tag1", "tag2"], "tags", prefix: @tenant_id) Taglet.add(post2, ["tag2", "tag3"], "tags", prefix: @tenant_id) result = Taglet.tag_list(Post, "tags", prefix: @tenant_id) assert result == ["tag1", "tag2", "tag3"] end test "[multi tenant] tagged_with/4 returns a list of structs associated to a tag" do post1 = @repo.insert!(%Post{title: "hello world1"}, prefix: @tenant_id) post2 = @repo.insert!(%Post{title: "hello world2"}, prefix: @tenant_id) post3 = @repo.insert!(%Post{title: "hello world3"}, prefix: @tenant_id) Taglet.add(post1, "tagged1", "tags", prefix: @tenant_id) Taglet.add(post2, "tagged1", "tags", prefix: @tenant_id) Taglet.add(post3, "tagged2", "tags", prefix: @tenant_id) post1 = @repo.get(Post, 1, prefix: @tenant_id) post2 = @repo.get(Post, 2, prefix: @tenant_id) result = Taglet.tagged_with("tagged1", Post, "tags", prefix: @tenant_id) assert result == [post1, post2] end test "[multi tenant] tagged_with_query/4 returns a query of structs associated to a tag" do post1 = @repo.insert!(%Post{title: "hello world1"}, prefix: @tenant_id) post2 = @repo.insert!(%Post{title: "hello world2"}, prefix: @tenant_id) post3 = @repo.insert!(%Post{title: "hello world3"}, prefix: @tenant_id) Taglet.add(post1, "tagged1", "tags", prefix: @tenant_id) Taglet.add(post2, ["tagged1", "tagged2"], "tags", prefix: @tenant_id) Taglet.add(post3, "tagged2", "tags", prefix: @tenant_id) query = Post |> where(title: "hello world2") post2 = @repo.get(Post, 2, prefix: @tenant_id) result = Taglet.tagged_with_query(query, ["tagged1", "tagged2"]) |> @repo.all(prefix: @tenant_id) assert result == [post2] end # Aux functions defp setup_tenant do migrations_path = Path.join(build_repo_priv(@repo), "migrations") # Drop the previous tenant to reset the data SQL.query(@repo, "DROP SCHEMA \"#{@tenant_id}\" CASCADE", []) # Create new tenant SQL.query(@repo, "CREATE SCHEMA \"#{@tenant_id}\"", []) Ecto.Migrator.run(@repo, migrations_path, :up, prefix: @tenant_id, all: true) end end
33.93865
117
0.652205
ff78d14cff479b7f5cadef29ee9328216349b337
12,545
ex
Elixir
lib/radiator/directory/editor/manager.ex
bhtabor/radiator
39c137a18d36d6f418f9d1ffb7aa2c99011d66cf
[ "MIT" ]
92
2019-01-03T11:46:23.000Z
2022-02-19T21:28:44.000Z
lib/radiator/directory/editor/manager.ex
bhtabor/radiator
39c137a18d36d6f418f9d1ffb7aa2c99011d66cf
[ "MIT" ]
350
2019-04-11T07:55:51.000Z
2021-08-03T11:19:05.000Z
lib/radiator/directory/editor/manager.ex
bhtabor/radiator
39c137a18d36d6f418f9d1ffb7aa2c99011d66cf
[ "MIT" ]
10
2019-04-18T12:47:27.000Z
2022-01-25T20:49:15.000Z
defmodule Radiator.Directory.Editor.Manager do @moduledoc """ Manipulation of data with the assumption that the user has the :manage permission to the entity. """ import Ecto.Query, warn: false alias Ecto.Multi alias Radiator.Repo alias Radiator.Support alias Radiator.Media.AudioFile alias Radiator.Directory.{ Network, Podcast, Episode, Audio, AudioPublication, Publication } alias Radiator.Contribution.{ AudioContribution, PodcastContribution, Person } @doc """ Creates a podcast. Makes the creator the sole owner. ## Examples iex> create_podcast(current_user, %Network{} = network, %{field: value}) {:ok, %Podcast{}} iex> create_podcast(current_user, %Network{} = network, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ require Logger def create_podcast(%Network{} = network, attrs) do Logger.debug("creating podcast --- #{inspect(attrs)}") # we need the podcast to have an id before we can save the image {update_attrs, insert_attrs} = Map.split(attrs, [:image, "image"]) insert = %Podcast{network_id: network.id} |> Podcast.changeset(insert_attrs) Multi.new() |> Multi.insert(:podcast, insert) |> Multi.update(:podcast_updated, fn %{podcast: podcast} -> Podcast.changeset(podcast, update_attrs) end) |> Repo.transaction() # translate the multi result in a regular result |> case do {:ok, %{podcast_updated: podcast}} -> {:ok, podcast} {:error, :podcast, changeset, _map} -> {:error, changeset} {:error, :podcast_updates, changeset, _map} -> {:error, changeset} something -> something end end def list_audio_publications(network = %Network{}) do network |> Ecto.assoc(:audio_publications) |> order_by(desc_nulls_first: :published_at) |> Repo.all() |> Repo.preload(:audio) |> (&{:ok, &1}).() end def update_audio_publication(%AudioPublication{} = audio_publication, attrs) do audio_publication |> AudioPublication.changeset(attrs) |> Repo.update() end @spec create_audio(Episode.t() | Network.t(), map, map) :: {:error, any} | {:ok, Audio.t()} def create_audio(subject, audio_attrs, subject_attrs \\ %{}) # todo: this raises if used on an episode that already has an associated audio. # we need to define a way, maybe even a separate API, # to remove or replace an episode audio. def create_audio(episode = %Episode{}, audio_attrs, episode_attrs) do # we need the audio to have an id before we can save the image {update_attrs, insert_attrs} = Map.split(audio_attrs, [:image, "image"]) Multi.new() |> Multi.insert(:audio, fn _ -> %Audio{} |> Audio.changeset(insert_attrs) end) |> Multi.update(:audio_updated, fn %{audio: audio} -> audio |> Audio.changeset(update_attrs) end) |> Multi.update(:episode, fn %{audio_updated: audio} -> episode |> Repo.preload(:audio) |> Ecto.Changeset.change() |> Ecto.Changeset.put_assoc(:audio, audio) |> Episode.changeset(episode_attrs) end) |> Repo.transaction() |> case do {:ok, %{audio_updated: audio}} -> {:ok, audio} something -> something end end def create_audio(network = %Network{}, audio_attrs, audio_publication_attrs) do Multi.new() |> Multi.insert(:audio_publication, fn _ -> Ecto.build_assoc(network, :audio_publications) |> AudioPublication.changeset(audio_publication_attrs) end) |> Multi.insert(:audio, fn %{audio_publication: audio_publication} -> Ecto.build_assoc(audio_publication, :audio) |> Audio.changeset(audio_attrs) end) |> Multi.update(:audio_publication_with_audio, fn %{ audio_publication: audio_publication, audio: audio } -> AudioPublication.changeset(audio_publication, %{audio_id: audio.id}) end) |> Repo.transaction() |> case do {:ok, %{audio: audio}} -> {:ok, audio |> Repo.preload(:audio_publication)} something -> something end end def list_audio_files(audio = %Audio{}) do audio |> Ecto.assoc(:audio_files) |> Repo.all() |> (&{:ok, &1}).() end def create_audio_file(audio, %{"file" => file} = attrs) do with {:ok, audio_file} <- Radiator.Media.AudioFileUpload.upload(file, audio) do audio_file |> AudioFile.metadata_update_changeset(attrs) |> Repo.update() end end def update_audio(%Audio{} = audio, attrs) do audio |> Audio.changeset(attrs) |> Repo.update() end def delete_audio(%Audio{} = audio) do Repo.delete(audio) end def create_audio_publication(network = %Network{}, attrs) do Ecto.build_assoc(network, :audio_publications) |> AudioPublication.changeset(attrs) |> Repo.insert() end @doc """ Creates an episode. ## Examples iex> create_episode(%Podcast{}, %{field: value}) {:ok, %Episode{}} iex> create_episode(%Podcast{}, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ def create_episode(%Podcast{} = podcast, attrs \\ %{}) do # todo: keys are sometimes atoms, sometimes binaries? why? can/should we enforce atoms? {update_attrs, insert_attrs} = Map.split(attrs, [:image, "image", :enclosure, "enclosure"]) insert = Ecto.build_assoc(podcast, :episodes) |> Episode.changeset(insert_attrs) Multi.new() |> Multi.insert(:episode, insert) |> Multi.update(:episode_updated, fn %{episode: episode} -> Episode.changeset(episode, update_attrs) end) |> Repo.transaction() |> case do {:ok, %{episode_updated: episode}} -> if Publication.published?(episode) do refresh_feed_cache(podcast) end {:ok, episode} {:error, :episode, changeset, _map} -> {:error, changeset} {:error, :episode_updates, changeset, _map} -> {:error, changeset} something -> something end end @doc """ Deletes an Episode. ## Examples iex> delete_episode(episode) {:ok, %Episode{}} iex> delete_episode(episode) {:error, %Ecto.Changeset{}} """ def delete_episode(%Episode{} = episode) do result = Repo.delete(episode) refresh_feed_cache(episode) result end @doc """ Updates an Episode. ## Examples iex> update_episode(episode, %{field: new_value}) {:ok, %Episode{}} iex> update_episode(episode, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ def update_episode(%Episode{} = episode, attrs) do result = episode |> Episode.changeset(attrs) |> Repo.update() refresh_feed_cache(episode) result end defp refresh_feed_cache(%Episode{podcast_id: podcast_id}) do Radiator.Feed.Worker.enqueue(%{"podcast_id" => podcast_id}) end defp refresh_feed_cache(%Podcast{id: podcast_id}) do Radiator.Feed.Worker.enqueue(%{"podcast_id" => podcast_id}) end defp refresh_feed_cache(_) do nil end def regenerate_episode_guid(episode) do episode |> change_episode() |> Episode.regenerate_guid() |> Repo.update() end @doc """ Returns an `%Ecto.Changeset{}` for tracking episode changes. ## Examples iex> change_episode(episode) %Ecto.Changeset{source: %Episode{}} """ def change_episode(%Episode{} = episode) do Episode.changeset(episode, %{}) end @doc """ Publishes a `Podcast`, `Episode` or `AudioPublication`, sets `publication_date` to now if not set. ## Examples iex> publish(episode) {:ok, %Episode{}} iex> publish(bad_value) {:error, %Ecto.Changeset{}} """ def publish(subject = %type{}) when type in [Podcast, Episode, AudioPublication] do result = subject |> type.publication_changeset(%{publish_state: :published}) |> Repo.update() refresh_feed_cache(subject) result end @doc """ Depublishes a `Podcast`, `Episode` or `AudioPublication`. ## Examples iex> depublish(episode) {:ok, %Episode{}} iex> depublish(bad_value) {:error, %Ecto.Changeset{}} """ def depublish(subject = %type{}) when type in [Podcast, Episode, AudioPublication] do result = subject |> type.publication_changeset(%{publish_state: :depublished}) |> Repo.update() refresh_feed_cache(subject) result end @doc """ Shedules `Podcast`, `Episode` or `AudioPublication` for publication by giving it a future `published_at` date. ## Examples iex> schedule(episode, datetime) {:ok, %Episode{}} iex> schedule(bad_value, datetime) {:error, %Ecto.Changeset{}} """ def schedule(subject = %type{}, datetime = %DateTime{}) when type in [Podcast, Episode, AudioPublication] do if Support.DateTime.after_utc_now?(datetime) do subject |> type.changeset(%{publish_state: :scheduled, published_at: datetime}) |> Repo.update() else {:error, :datetime_not_future} end end @doc """ Updates a podcast. ## Examples iex> update_podcast(podcast, %{field: new_value}) {:ok, %Podcast{}} iex> update_podcast(podcast, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ def update_podcast(%Podcast{} = podcast, attrs) do result = podcast |> Podcast.changeset(attrs) |> Repo.update() refresh_feed_cache(podcast) result end @doc """ Deletes a Podcast. ## Examples iex> delete_podcast(podcast) {:ok, %Podcast{}} iex> delete_podcast(podcast) {:error, %Ecto.Changeset{}} """ def delete_podcast(%Podcast{} = podcast) do result = Repo.delete(podcast) refresh_feed_cache(podcast) result end @doc """ Returns an `%Ecto.Changeset{}` for tracking podcast changes. ## Examples iex> change_podcast(podcast) %Ecto.Changeset{source: %Podcast{}} """ def change_podcast(%Podcast{} = podcast) do Podcast.changeset(podcast, %{}) end @doc """ Make person contributor for podcast. """ def add_podcast_contribution(%Podcast{} = podcast, %Person{} = person, role \\ nil) do position = determine_new_podcast_contribution_position(podcast) %PodcastContribution{} |> Ecto.Changeset.change(%{position: position}) |> Ecto.Changeset.put_assoc(:podcast, podcast) |> Ecto.Changeset.put_assoc(:person, person) |> Ecto.Changeset.put_assoc(:role, role) |> Repo.insert!() end @doc """ Make person contributor for audio. """ def add_audio_contribution(%Audio{} = audio, %Person{} = person, role \\ nil) do position = determine_new_audio_contribution_position(audio) %AudioContribution{} |> Ecto.Changeset.change(%{position: position}) |> Ecto.Changeset.put_assoc(:audio, audio) |> Ecto.Changeset.put_assoc(:person, person) |> Ecto.Changeset.put_assoc(:role, role) |> Repo.insert!() end defp determine_new_podcast_contribution_position(podcast) do get_max_contribution_position(podcast, PodcastContribution, :podcast_id) + 1 end defp determine_new_audio_contribution_position(audio) do get_max_contribution_position(audio, AudioContribution, :audio_id) + 1 end @spec get_max_contribution_position(Podcast.t() | Audio.t(), atom(), :audio_id | :podcast_id) :: integer() defp get_max_contribution_position(entity, schema, id_field) do entity_id = entity.id filters = [{id_field, entity_id}] from(c in schema, where: ^filters, select: max(c.position)) |> Repo.one() |> case do nil -> 0 value -> value end end def delete_person(%Person{} = subject) do subject |> Repo.delete() end # TODO # def add_podcast_contribution(%Podcast{} = podcast, %Person{} = person, role \\ nil) # def move_podcast_contribution(contribution, position) # def delete_podcast_contribution(contribution) # # def move_audio_contribution(contribution, position) # def delete_audio_contribution(contribution) def propagate_short_id(%Podcast{} = podcast) do Repo.transaction(fn -> Repo.all(Ecto.assoc(podcast, :episodes)) |> Enum.each(fn episode -> short_id = Episode.construct_short_id(episode, podcast) Repo.update(Episode.changeset(episode, %{short_id: short_id})) end) end) end end
25.919421
112
0.637465
ff7913598e6904d5357bb618eb480788c9023099
33,844
exs
Elixir
test/phoenix_live_view/html_engine_test.exs
nickolaich/phoenix_live_view
2e9db09b11d42fabfd5a388980ff2b15d11da527
[ "MIT" ]
null
null
null
test/phoenix_live_view/html_engine_test.exs
nickolaich/phoenix_live_view
2e9db09b11d42fabfd5a388980ff2b15d11da527
[ "MIT" ]
null
null
null
test/phoenix_live_view/html_engine_test.exs
nickolaich/phoenix_live_view
2e9db09b11d42fabfd5a388980ff2b15d11da527
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveView.HTMLEngineTest do use ExUnit.Case, async: true import Phoenix.LiveView.Helpers, only: [sigil_H: 2, render_slot: 1, render_slot: 2] alias Phoenix.LiveView.HTMLEngine alias Phoenix.LiveView.HTMLTokenizer.ParseError defp eval(string, assigns \\ %{}, opts \\ []) do opts = Keyword.merge(opts, file: __ENV__.file, engine: HTMLEngine, subengine: Phoenix.LiveView.Engine ) EEx.eval_string(string, [assigns: assigns], opts) end defp render(string, assigns \\ %{}) do string |> eval(assigns) |> Phoenix.HTML.Safe.to_iodata() |> IO.iodata_to_binary() end defmacrop compile(string) do quote do unquote(EEx.compile_string(string, file: __ENV__.file, engine: HTMLEngine)) |> Phoenix.HTML.Safe.to_iodata() |> IO.iodata_to_binary() end end def assigns_component(assigns) do ~H"<%= inspect(Map.delete(assigns, :__changed__)) %>" end def remote_function_component(assigns) do ~H"REMOTE COMPONENT: Value: <%= @value %>" end def remote_function_component_with_inner_block(assigns) do ~H"REMOTE COMPONENT: Value: <%= @value %>, Content: <%= render_slot(@inner_block) %>" end def remote_function_component_with_inner_block_args(assigns) do ~H""" REMOTE COMPONENT WITH ARGS: Value: <%= @value %> <%= render_slot(@inner_block, %{ downcase: String.downcase(@value), upcase: String.upcase(@value) }) %> """ end defp local_function_component(assigns) do ~H"LOCAL COMPONENT: Value: <%= @value %>" end defp local_function_component_with_inner_block(assigns) do ~H"LOCAL COMPONENT: Value: <%= @value %>, Content: <%= render_slot(@inner_block) %>" end defp local_function_component_with_inner_block_args(assigns) do ~H""" LOCAL COMPONENT WITH ARGS: Value: <%= @value %> <%= render_slot(@inner_block, %{ downcase: String.downcase(@value), upcase: String.upcase(@value) }) %> """ end test "handles text" do assert render("Hello") == "Hello" end test "handles regular blocks" do assert render(""" Hello <%= if true do %>world!<% end %> """) == "Hello world!" end test "handles html blocks with regular blocks" do assert render(""" Hello <div>w<%= if true do %>orld<% end %>!</div> """) == "Hello <div>world!</div>" end test "handles string attributes" do assert render(""" Hello <div name="my name" phone="111">text</div> """) == "Hello <div name=\"my name\" phone=\"111\">text</div>" end test "handles string attribute value keeping special chars unchanged" do assert render("<div name='1 < 2'/>") == "<div name='1 < 2'></div>" end test "handles boolean attributes" do assert render(""" Hello <div hidden>text</div> """) == "Hello <div hidden>text</div>" end test "handles interpolated attributes" do assert render(""" Hello <div name={to_string(123)} phone={to_string(456)}>text</div> """) == "Hello <div name=\"123\" phone=\"456\">text</div>" end test "handles interpolated attribute value containing special chars" do assert render("<div name={@val}/>", %{val: "1 < 2"}) == "<div name=\"1 &lt; 2\"></div>" end test "handles interpolated attributes with strings" do assert render(""" <div name={String.upcase("abc")}>text</div> """) == "<div name=\"ABC\">text</div>" end test "handles interpolated attributes with curly braces" do assert render(""" <div name={elem({"abc"}, 0)}>text</div> """) == "<div name=\"abc\">text</div>" end test "handles dynamic attributes" do assert render("Hello <div {@attrs}>text</div>", %{attrs: [name: "1", phone: to_string(2)]}) == "Hello <div name=\"1\" phone=\"2\">text</div>" end test "keeps attribute ordering" do assigns = %{attrs1: [d1: "1"], attrs2: [d2: "2"]} template = ~S(<div {@attrs1} sd1={1} s1="1" {@attrs2} s2="2" sd2={2} />) assert render(template, assigns) == ~S(<div d1="1" sd1="1" s1="1" d2="2" s2="2" sd2="2"></div>) assert %Phoenix.LiveView.Rendered{static: ["<div", "", " s1=\"1\"", " s2=\"2\"", "></div>"]} = eval(template, assigns) end test "optimizes attributes with literal string values" do assigns = %{unsafe: "<foo>", safe: {:safe, "<foo>"}} # binaries are extracted out template = ~S(<div id={"<foo>"} />) assert render(template, assigns) == ~S(<div id="&lt;foo&gt;"></div>) assert %Phoenix.LiveView.Rendered{static: ["<div id=\"&lt;foo&gt;\"></div>"]} = eval(template, assigns) # binary concatenation is extracted out template = ~S(<div id={"pre-" <> @unsafe} />) assert render(template, assigns) == ~S(<div id="pre-&lt;foo&gt;"></div>) assert %Phoenix.LiveView.Rendered{static: ["<div id=\"pre-", "\"></div>"]} = eval(template, assigns) template = ~S(<div id={"pre-" <> @unsafe <> "-pos"} />) assert render(template, assigns) == ~S(<div id="pre-&lt;foo&gt;-pos"></div>) assert %Phoenix.LiveView.Rendered{static: ["<div id=\"pre-", "-pos\"></div>"]} = eval(template, assigns) # interpolation is extracted out template = ~S(<div id={"pre-#{@unsafe}-pos"} />) assert render(template, assigns) == ~S(<div id="pre-&lt;foo&gt;-pos"></div>) assert %Phoenix.LiveView.Rendered{static: ["<div id=\"pre-", "-pos\"></div>"]} = eval(template, assigns) # mixture of interpolation and binary concatenation is extracted out template = ~S(<div id={"pre-" <> "#{@unsafe}-pos"} />) assert render(template, assigns) == ~S(<div id="pre-&lt;foo&gt;-pos"></div>) assert %Phoenix.LiveView.Rendered{static: ["<div id=\"pre-", "-pos\"></div>"]} = eval(template, assigns) # raises if not a binary assert_raise ArgumentError, "expected a binary in <>, got: {:safe, \"<foo>\"}", fn -> render(~S(<div id={"pre-" <> @safe} />), assigns) end end def do_block(do: block), do: block test "handles do blocks with expressions" do assigns = %{not_text: "not text", text: "text"} template = ~S""" <%= @text %> <%= Phoenix.LiveView.HTMLEngineTest.do_block do %><%= assigns[:not_text] %><% end %> """ # A bug made it so "not text" appeared inside @text. assert render(template, assigns) == "text\nnot text" template = ~S""" <%= for i <- 1..3 do %> <div id={i}> <%= Phoenix.LiveView.HTMLEngineTest.do_block do %> <%= i %> <% end %> </div> <% end %> """ # A bug made it so "id=1" was not handled properly assert render(template, assigns) =~ ~s'<div id="1">' end test "optimizes class attributes" do assigns = %{ nil_assign: nil, true_assign: true, false_assign: false, unsafe: "<foo>", safe: {:safe, "<foo>"}, list: ["safe", false, nil, "<unsafe>"] } assert %Phoenix.LiveView.Rendered{static: ["<div class=\"", "\"></div>"]} = eval(~S(<div class={@safe} />), assigns) template = ~S(<div class={@nil_assign} />) assert render(template, assigns) == ~S(<div class=""></div>) template = ~S(<div class={@false_assign} />) assert render(template, assigns) == ~S(<div class=""></div>) template = ~S(<div class={@true_assign} />) assert render(template, assigns) == ~S(<div class=""></div>) template = ~S(<div class={@unsafe} />) assert render(template, assigns) == ~S(<div class="&lt;foo&gt;"></div>) template = ~S(<div class={@safe} />) assert render(template, assigns) == ~S(<div class="<foo>"></div>) template = ~S(<div class={@list} />) assert render(template, assigns) == ~S(<div class="safe &lt;unsafe&gt;"></div>) end test "optimizes attributes that can be empty" do assigns = %{ nil_assign: nil, true_assign: true, false_assign: false, unsafe: "<foo>", safe: {:safe, "<foo>"}, list: ["safe", false, nil, "<unsafe>"] } assert %Phoenix.LiveView.Rendered{static: ["<div style=\"", "\"></div>"]} = eval(~S(<div style={@safe} />), assigns) template = ~S(<div style={@nil_assign} />) assert render(template, assigns) == ~S(<div style=""></div>) template = ~S(<div style={@false_assign} />) assert render(template, assigns) == ~S(<div style=""></div>) template = ~S(<div style={@true_assign} />) assert render(template, assigns) == ~S(<div style=""></div>) template = ~S(<div style={@unsafe} />) assert render(template, assigns) == ~S(<div style="&lt;foo&gt;"></div>) template = ~S(<div style={@safe} />) assert render(template, assigns) == ~S(<div style="<foo>"></div>) end test "handle void elements" do assert render(""" <div><br></div>\ """) == "<div><br></div>" end test "handle void elements with attributes" do assert render(""" <div><br attr='1'></div>\ """) == "<div><br attr='1'></div>" end test "handle self close void elements" do assert render("<hr/>") == "<hr>" end test "handle self close void elements with attributes" do assert render(~S(<hr id="1"/>)) == ~S(<hr id="1">) end test "handle self close elements" do assert render("<div/>") == "<div></div>" end test "handle self close elements with attributes" do assert render("<div attr='1'/>") == "<div attr='1'></div>" end describe "handle function components" do test "remote call (self close)" do assigns = %{} assert compile("<Phoenix.LiveView.HTMLEngineTest.remote_function_component value='1'/>") == "REMOTE COMPONENT: Value: 1" end test "remote call from alias (self close)" do alias Phoenix.LiveView.HTMLEngineTest assigns = %{} assert compile("<HTMLEngineTest.remote_function_component value='1'/>") == "REMOTE COMPONENT: Value: 1" end test "remote call with inner content" do assigns = %{} assert compile(""" <Phoenix.LiveView.HTMLEngineTest.remote_function_component_with_inner_block value='1'> The inner content </Phoenix.LiveView.HTMLEngineTest.remote_function_component_with_inner_block> """) == "REMOTE COMPONENT: Value: 1, Content: \n The inner content\n" end test "remote call with inner content with args" do expected = """ REMOTE COMPONENT WITH ARGS: Value: aBcD Upcase: ABCD Downcase: abcd """ assigns = %{} assert compile(""" <Phoenix.LiveView.HTMLEngineTest.remote_function_component_with_inner_block_args value="aBcD" let={%{upcase: upcase, downcase: downcase}} > Upcase: <%= upcase %> Downcase: <%= downcase %> </Phoenix.LiveView.HTMLEngineTest.remote_function_component_with_inner_block_args> """) =~ expected end test "raise on remote call with inner content passing non-matching args" do message = ~r""" cannot match arguments sent from `render_slot/2` against the pattern in `let`. Expected a value matching `%{wrong: _}`, got: `%{downcase: "abcd", upcase: "ABCD"}`. """ assigns = %{} assert_raise(RuntimeError, message, fn -> compile(""" <Phoenix.LiveView.HTMLEngineTest.remote_function_component_with_inner_block_args {[value: "aBcD"]} let={%{wrong: _}} > ... </Phoenix.LiveView.HTMLEngineTest.remote_function_component_with_inner_block_args> """) end) end test "raise on remote call passing args to self close components" do message = ~r".exs:2: cannot use `let` on a component without inner content" assert_raise(CompileError, message, fn -> eval(""" <br> <Phoenix.LiveView.HTMLEngineTest.remote_function_component value='1' let={var}/> """) end) end test "local call (self close)" do assigns = %{} assert compile("<.local_function_component value='1'/>") == "LOCAL COMPONENT: Value: 1" end test "local call with inner content" do assigns = %{} assert compile(""" <.local_function_component_with_inner_block value='1'> The inner content </.local_function_component_with_inner_block> """) == "LOCAL COMPONENT: Value: 1, Content: \n The inner content\n" end test "local call with inner content with args" do expected = """ LOCAL COMPONENT WITH ARGS: Value: aBcD Upcase: ABCD Downcase: abcd """ assigns = %{} assert compile(""" <.local_function_component_with_inner_block_args value="aBcD" let={%{upcase: upcase, downcase: downcase}} > Upcase: <%= upcase %> Downcase: <%= downcase %> </.local_function_component_with_inner_block_args> """) =~ expected assert compile(""" <.local_function_component_with_inner_block_args {[value: "aBcD"]} let={%{upcase: upcase, downcase: downcase}} > Upcase: <%= upcase %> Downcase: <%= downcase %> </.local_function_component_with_inner_block_args> """) =~ expected end test "raise on local call with inner content passing non-matching args" do message = ~r""" cannot match arguments sent from `render_slot/2` against the pattern in `let`. Expected a value matching `%{wrong: _}`, got: `%{downcase: "abcd", upcase: "ABCD"}`. """ assigns = %{} assert_raise(RuntimeError, message, fn -> compile(""" <.local_function_component_with_inner_block_args {[value: "aBcD"]} let={%{wrong: _}} > ... </.local_function_component_with_inner_block_args> """) end) end test "raise on local call passing args to self close components" do message = ~r".exs:2: cannot use `let` on a component without inner content" assert_raise(CompileError, message, fn -> eval(""" <br> <.local_function_component value='1' let={var}/> """) end) end test "raise on duplicated `let`" do message = ~r".exs:4:(8:)? cannot define multiple `let` attributes. Another `let` has already been defined at line 3" assert_raise(ParseError, message, fn -> eval(""" <br> <Phoenix.LiveView.HTMLEngineTest.remote_function_component value='1' let={var1} let={var2} /> """) end) assert_raise(ParseError, message, fn -> eval(""" <br> <.local_function_component value='1' let={var1} let={var2} /> """) end) end test "empty attributes" do assigns = %{} assert compile("<.assigns_component />") == "%{}" end test "dynamic attributes" do assigns = %{attrs: [name: "1", phone: true]} assert compile("<.assigns_component {@attrs} />") == "%{name: &quot;1&quot;, phone: true}" end test "sorts attributes by group: static + dynamic" do assigns = %{attrs1: [d1: "1"], attrs2: [d2: "2", d3: "3"]} assert compile( "<.assigns_component d1=\"one\" {@attrs1} d=\"middle\" {@attrs2} d2=\"two\" />" ) == "%{d: &quot;middle&quot;, d1: &quot;one&quot;, d2: &quot;two&quot;, d3: &quot;3&quot;}" end end describe "named slots" do def function_component_with_single_slot(assigns) do ~H""" BEFORE SLOT <%= render_slot(@sample) %> AFTER SLOT """ end def function_component_with_slots(assigns) do ~H""" BEFORE HEADER <%= render_slot(@header) %> TEXT <%= render_slot(@footer) %> AFTER FOOTER """ end def function_component_with_slots_and_default(assigns) do ~H""" BEFORE HEADER <%= render_slot(@header) %> TEXT:<%= render_slot(@inner_block) %>:TEXT <%= render_slot(@footer) %> AFTER FOOTER """ end def function_component_with_slots_and_args(assigns) do ~H""" BEFORE SLOT <%= render_slot(@sample, 1) %> AFTER SLOT """ end def function_component_with_slot_props(assigns) do ~H""" <%= for entry <- @sample do %> <%= entry.a %> <%= render_slot(entry) %> <%= entry.b %> <% end %> """ end def function_component_with_multiple_slots_entries(assigns) do ~H""" <%= for entry <- @sample do %> <%= entry.id %>: <%= render_slot(entry, %{}) %> <% end %> """ end def function_component_with_self_close_slots(assigns) do ~H""" <%= for entry <- @sample do %> <%= entry.id %> <% end %> """ end def render_slot_name(assigns) do ~H"<%= for entry <- @sample do %>[<%= entry.__slot__ %>]<% end %>" end def render_inner_block_slot_name(assigns) do ~H"<%= for entry <- @inner_block do %>[<%= entry.__slot__ %>]<% end %>" end test "single slot" do assigns = %{} expected = """ COMPONENT WITH SLOTS: BEFORE SLOT The sample slot \ AFTER SLOT """ assert compile(""" COMPONENT WITH SLOTS: <.function_component_with_single_slot> <:sample> The sample slot </:sample> </.function_component_with_single_slot> """) == expected assert compile(""" COMPONENT WITH SLOTS: <Phoenix.LiveView.HTMLEngineTest.function_component_with_single_slot> <:sample> The sample slot </:sample> </Phoenix.LiveView.HTMLEngineTest.function_component_with_single_slot> """) == expected end test "raise when calling render_slot/2 on a slot without inner content" do message = ~r"attempted to render slot <:sample> but the slot has no inner content" assigns = %{} assert_raise(RuntimeError, message, fn -> compile(""" <.function_component_with_single_slot> <:sample/> </.function_component_with_single_slot> """) end) assert_raise(RuntimeError, message, fn -> compile(""" <.function_component_with_single_slot> <:sample/> <:sample/> </.function_component_with_single_slot> """) end) end test "multiple slot entries randered by a single rende_slot/2 call" do assigns = %{} expected = """ COMPONENT WITH SLOTS: BEFORE SLOT entry 1 \ entry 2 \ AFTER SLOT """ assert compile(""" COMPONENT WITH SLOTS: <.function_component_with_single_slot> <:sample> entry 1 </:sample> <:sample> entry 2 </:sample> </.function_component_with_single_slot> """) == expected assert compile(""" COMPONENT WITH SLOTS: <Phoenix.LiveView.HTMLEngineTest.function_component_with_single_slot> <:sample> entry 1 </:sample> <:sample> entry 2 </:sample> </Phoenix.LiveView.HTMLEngineTest.function_component_with_single_slot> """) == expected end test "multiple slot entries handled by an explicit for comprehension" do assigns = %{} expected = """ 1: one 2: two """ assert compile(""" <.function_component_with_multiple_slots_entries> <:sample id="1">one</:sample> <:sample id="2">two</:sample> </.function_component_with_multiple_slots_entries> """) == expected assert compile(""" <Phoenix.LiveView.HTMLEngineTest.function_component_with_multiple_slots_entries> <:sample id="1">one</:sample> <:sample id="2">two</:sample> </Phoenix.LiveView.HTMLEngineTest.function_component_with_multiple_slots_entries> """) == expected end test "slot props" do assigns = %{a: "A"} expected = "\nA\n and \nB\n" assert compile(""" <.function_component_with_slot_props> <:sample a={@a} b="B"> and </:sample> </.function_component_with_slot_props> """) == expected assert compile(""" <Phoenix.LiveView.HTMLEngineTest.function_component_with_slot_props> <:sample a={@a} b="B"> and </:sample> </Phoenix.LiveView.HTMLEngineTest.function_component_with_slot_props> """) == expected end test "multiple slots" do assigns = %{} expected = """ BEFORE COMPONENT BEFORE HEADER The header content \ TEXT The footer content \ AFTER FOOTER AFTER COMPONENT """ assert compile(""" BEFORE COMPONENT <.function_component_with_slots> <:header> The header content </:header> <:footer> The footer content </:footer> </.function_component_with_slots> AFTER COMPONENT """) == expected assert compile(""" BEFORE COMPONENT <Phoenix.LiveView.HTMLEngineTest.function_component_with_slots> <:header> The header content </:header> <:footer> The footer content </:footer> </Phoenix.LiveView.HTMLEngineTest.function_component_with_slots> AFTER COMPONENT """) == expected end test "multiple slots with default" do assigns = %{middle: "middle"} expected = """ BEFORE COMPONENT BEFORE HEADER The header content \ TEXT: top foo middle bar bot :TEXT The footer content \ AFTER FOOTER AFTER COMPONENT """ assert compile(""" BEFORE COMPONENT <.function_component_with_slots_and_default> top <:header> The header content </:header> foo <%= @middle %> bar <:footer> The footer content </:footer> bot </.function_component_with_slots_and_default> AFTER COMPONENT """) == expected assert compile(""" BEFORE COMPONENT <Phoenix.LiveView.HTMLEngineTest.function_component_with_slots_and_default> top <:header> The header content </:header> foo <%= @middle %> bar <:footer> The footer content </:footer> bot </Phoenix.LiveView.HTMLEngineTest.function_component_with_slots_and_default> AFTER COMPONENT """) == expected end test "slots with args" do assigns = %{} expected = """ COMPONENT WITH SLOTS: BEFORE SLOT The sample slot Arg: 1 \ AFTER SLOT """ assert compile(""" COMPONENT WITH SLOTS: <.function_component_with_slots_and_args> <:sample let={arg}> The sample slot Arg: <%= arg %> </:sample> </.function_component_with_slots_and_args> """) == expected assert compile(""" COMPONENT WITH SLOTS: <Phoenix.LiveView.HTMLEngineTest.function_component_with_slots_and_args> <:sample let={arg}> The sample slot Arg: <%= arg %> </:sample> </Phoenix.LiveView.HTMLEngineTest.function_component_with_slots_and_args> """) == expected end test "nested calls with slots" do assigns = %{} expected = """ BEFORE SLOT The outer slot BEFORE SLOT The inner slot \ AFTER SLOT \ AFTER SLOT """ assert compile(""" <Phoenix.LiveView.HTMLEngineTest.function_component_with_single_slot> <:sample> The outer slot <.function_component_with_single_slot> <:sample> The inner slot </:sample> </.function_component_with_single_slot> </:sample> </Phoenix.LiveView.HTMLEngineTest.function_component_with_single_slot> """) == expected assert compile(""" <.function_component_with_single_slot> <:sample> The outer slot <.function_component_with_single_slot> <:sample> The inner slot </:sample> </.function_component_with_single_slot> </:sample> </.function_component_with_single_slot> """) == expected end test "self close slots" do assigns = %{} expected = """ 1 2 """ assert compile(""" <.function_component_with_self_close_slots> <:sample id="1"/> <:sample id="2"/> </.function_component_with_self_close_slots> """) == expected assert compile(""" <Phoenix.LiveView.HTMLEngineTest.function_component_with_self_close_slots> <:sample id="1"/> <:sample id="2"/> </Phoenix.LiveView.HTMLEngineTest.function_component_with_self_close_slots> """) == expected end test "raise if self close slot uses let" do message = ~r".exs:2:(24:)? cannot use `let` on a slot without inner content" assert_raise(ParseError, message, fn -> eval(""" <.function_component_with_self_close_slots> <:sample id="1" let={var}/> </.function_component_with_self_close_slots> """) end) end test "store the slot name in __slot__" do assigns = %{} assert compile(""" <.render_slot_name> <:sample> The sample slot </:sample> </.render_slot_name> """) == "[sample]" assert compile(""" <.render_slot_name> <:sample/> <:sample/> </.render_slot_name> """) == "[sample][sample]" end test "store the inner_block slot name in __slot__" do assigns = %{} assert compile(""" <.render_inner_block_slot_name> The content </.render_inner_block_slot_name> """) == "[inner_block]" end test "raise if the slot entry is not a direct child of a component" do message = ~r".exs:2:(3:)? invalid slot entry <:sample>. A slot entry must be a direct child of a component" assert_raise(ParseError, message, fn -> eval(""" <div> <:sample> Content </:sample> </div> """) end) message = ~r".exs:3:(5:)? invalid slot entry <:footer>. A slot entry must be a direct child of a component" assert_raise(ParseError, message, fn -> eval(""" <div> <:sample> <:footer> Content </:footer> </:sample> </div> """) end) message = ~r".exs:1:(1:)? invalid slot entry <:sample>. A slot entry must be a direct child of a component" assert_raise(ParseError, message, fn -> eval(""" <:sample> Content </:sample> """) end) end end describe "tracks root" do test "valid cases" do assert eval("<foo></foo>").root == true assert eval("<foo><%= 123 %></foo>").root == true assert eval("<foo><bar></bar></foo>").root == true assert eval("<foo><br /></foo>").root == true assert eval("<foo />").root == true assert eval("<br />").root == true assert eval("<br>").root == true assert eval(" <foo></foo> ").root == true assert eval("\n\n<foo></foo>\n").root == true end test "invalid cases" do assert eval("").root == false assert eval("<foo></foo><bar></bar>").root == false assert eval("<foo></foo><bar></bar>").root == false assert eval("<br /><br />").root == false assert eval("<%= 123 %>").root == false assert eval("<foo></foo><%= 123 %>").root == false assert eval("<%= 123 %><foo></foo>").root == false assert eval("123<foo></foo>").root == false assert eval("<foo></foo>123").root == false assert eval("<.to_string />").root == false assert eval("<.to_string></.to_string>").root == false assert eval("<Kernel.to_string />").root == false assert eval("<Kernel.to_string></Kernel.to_string>").root == false end end describe "tag validations" do test "handles script" do assert render("<script>a = '<a>';<%= :b %> = '<b>';</script>") == "<script>a = '<a>';b = '<b>';</script>" end test "handles comments" do assert render("Begin<!-- <%= 123 %> -->End") == "Begin<!-- 123 -->End" end test "unmatched comment" do message = ~r".exs:1:(11:)? expected closing `-->` for comment" assert_raise(ParseError, message, fn -> eval("Begin<!-- <%= 123 %>") end) end test "unmatched open/close tags" do message = ~r".exs:4:(1:)? unmatched closing tag. Expected </div> for <div> at line 2, got: </span>" assert_raise(ParseError, message, fn -> eval(""" <br> <div> text </span> """) end) end test "unmatched open/close tags with nested tags" do message = ~r".exs:6:(1:)? unmatched closing tag. Expected </div> for <div> at line 2, got: </span>" assert_raise(ParseError, message, fn -> eval(""" <br> <div> <p> text </p> </span> """) end) end test "invalid remote tag" do message = ~r".exs:1:(1:)? invalid tag <Foo>" assert_raise(ParseError, message, fn -> eval(""" <Foo foo="bar" /> """) end) end test "missing open tag" do message = ~r".exs:2:(3:)? missing opening tag for </span>" assert_raise(ParseError, message, fn -> eval(""" text </span> """) end) end test "missing closing tag" do message = ~r/.exs:2:(1:)? end of file reached without closing tag for <div>/ assert_raise(ParseError, message, fn -> eval(""" <br> <div foo={@foo}> """) end) message = ~r/.exs:2:(3:)? end of file reached without closing tag for <span>/ assert_raise(ParseError, message, fn -> eval(""" text <span foo={@foo}> text """) end) end test "invalid tag name" do message = ~r/.exs:2:(3:)? invalid tag <Oops>/ assert_raise(ParseError, message, fn -> eval(""" <br> <Oops foo={@foo}> Bar </Oops> """) end) end test "invalid tag" do message = ~r/.exs:1:(11:)? expected closing `}` for expression/ assert_raise(ParseError, message, fn -> eval(""" <div foo={<%= @foo %>}>bar</div> """) end) end end describe "handle errors in expressions" do if Version.match?(System.version(), ">= 1.12.0") do test "inside attribute values" do assert_raise(SyntaxError, ~r"test/phoenix_live_view/html_engine_test.exs:12:22: syntax error before: ','", fn -> opts = [line: 10, indentation: 8] eval( """ text <%= "interpolation" %> <div class={[,]}/> """, [], opts ) end) end test "inside root attribute value" do assert_raise(SyntaxError, ~r"test/phoenix_live_view/html_engine_test.exs:12:16: syntax error before: ','", fn -> opts = [line: 10, indentation: 8] eval( """ text <%= "interpolation" %> <div {[,]}/> """, [], opts ) end) end else test "older versions cannot provide correct line on errors" do assert_raise(SyntaxError, ~r"test/phoenix_live_view/html_engine_test.exs:2", fn -> opts = [line: 10, indentation: 8] eval( """ text <%= "interpolation" %> <div class={[,]}/> """, [], opts ) end) end end end end
28.016556
120
0.53262
ff7913b2c3c32a7872c8fa5ad223bb0df96a0ba0
205
exs
Elixir
elixir/phoenix_socket/test/controllers/page_controller_test.exs
BStudent/SPANC-websocket-shootout
44353f1b9bf87ba7017b2788d876e732b410b4c4
[ "MIT" ]
421
2016-09-01T14:16:04.000Z
2022-03-11T14:22:29.000Z
elixir/phoenix_socket/test/controllers/page_controller_test.exs
BStudent/SPANC-websocket-shootout
44353f1b9bf87ba7017b2788d876e732b410b4c4
[ "MIT" ]
48
2016-09-01T23:10:37.000Z
2020-10-28T14:34:47.000Z
elixir/phoenix_socket/test/controllers/page_controller_test.exs
thewillhuang/websocket-shootout
d9046f341dc2a1ed54be5e734a546b392db09b05
[ "MIT" ]
84
2016-09-01T14:37:39.000Z
2021-11-10T16:46:13.000Z
defmodule PhoenixSocket.PageControllerTest do use PhoenixSocket.ConnCase test "GET /", %{conn: conn} do conn = get conn, "/" assert html_response(conn, 200) =~ "Welcome to Phoenix!" end end
22.777778
60
0.692683
ff7927462cd21819a4c2dbdc3b19250af9d423aa
1,496
ex
Elixir
clients/sheets/lib/google_api/sheets/v4/model/add_chart_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/sheets/lib/google_api/sheets/v4/model/add_chart_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/sheets/lib/google_api/sheets/v4/model/add_chart_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Sheets.V4.Model.AddChartResponse do @moduledoc """ The result of adding a chart to a spreadsheet. ## Attributes * `chart` (*type:* `GoogleApi.Sheets.V4.Model.EmbeddedChart.t`, *default:* `nil`) - The newly added chart. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :chart => GoogleApi.Sheets.V4.Model.EmbeddedChart.t() } field(:chart, as: GoogleApi.Sheets.V4.Model.EmbeddedChart) end defimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.AddChartResponse do def decode(value, options) do GoogleApi.Sheets.V4.Model.AddChartResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.AddChartResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.829787
110
0.740642
ff795e413f393943aa07d67e60b88594f41113d7
267
exs
Elixir
priv/repo/migrations/20201204003445_add_interview_discontinue_columns_to_exposures.exs
geometricservices/epi-viewpoin
ecb5316ea0f3f7299d5ff63e2de588539005ac1c
[ "Apache-2.0" ]
5
2021-02-25T18:43:09.000Z
2021-02-27T06:00:35.000Z
priv/repo/migrations/20201204003445_add_interview_discontinue_columns_to_exposures.exs
geometricservices/epi-viewpoint
ecb5316ea0f3f7299d5ff63e2de588539005ac1c
[ "Apache-2.0" ]
3
2021-12-13T17:52:47.000Z
2021-12-17T01:35:31.000Z
priv/repo/migrations/20201204003445_add_interview_discontinue_columns_to_exposures.exs
geometricservices/epi-viewpoint
ecb5316ea0f3f7299d5ff63e2de588539005ac1c
[ "Apache-2.0" ]
1
2022-01-27T23:26:38.000Z
2022-01-27T23:26:38.000Z
defmodule Epicenter.Repo.Migrations.AddInterviewDiscontinueColumnsToExposures do use Ecto.Migration def change do alter table(:exposures) do add :interview_discontinued_at, :utc_datetime add :interview_discontinue_reason, :text end end end
24.272727
80
0.775281
ff7967aa7aa11e4ab6fc9bd99e32fa894f825e69
406
ex
Elixir
webrtc/auth/lib/auth/user_manager/guardian.ex
membraneframework/videoroom_advanced
d5bfbcec7558bb7ddd4f74742c0d842e5d759b21
[ "Apache-2.0" ]
84
2020-08-01T14:57:29.000Z
2022-03-27T13:28:23.000Z
webrtc/auth/lib/auth/user_manager/guardian.ex
membraneframework/videoroom_advanced
d5bfbcec7558bb7ddd4f74742c0d842e5d759b21
[ "Apache-2.0" ]
75
2020-08-24T08:01:53.000Z
2022-03-17T10:41:22.000Z
webrtc/auth/lib/auth/user_manager/guardian.ex
membraneframework/videoroom_advanced
d5bfbcec7558bb7ddd4f74742c0d842e5d759b21
[ "Apache-2.0" ]
17
2020-09-15T21:04:23.000Z
2022-03-31T07:43:48.000Z
defmodule Example.Auth.UserManager.Guardian do @moduledoc false use Guardian, otp_app: :example_auth alias Example.Auth.UserManager def subject_for_token(user, _claims) do {:ok, to_string(user.id)} end def resource_from_claims(%{"sub" => id}) do case UserManager.get_user(id) do nil -> {:error, :resource_not_found} user -> {:ok, user} end end end
19.333333
46
0.657635
ff7988e1c9330956a63a23308e96b97b937f8d21
4,499
ex
Elixir
lib/peluquero/utils.ex
facundokantox/peluquero
16e54ad00016858b925313fa20eb38310b18718f
[ "MIT" ]
12
2017-06-22T16:41:17.000Z
2022-01-08T09:52:40.000Z
lib/peluquero/utils.ex
facundokantox/peluquero
16e54ad00016858b925313fa20eb38310b18718f
[ "MIT" ]
4
2017-11-24T05:03:31.000Z
2020-11-03T11:41:12.000Z
lib/peluquero/utils.ex
facundokantox/peluquero
16e54ad00016858b925313fa20eb38310b18718f
[ "MIT" ]
1
2020-11-02T17:26:14.000Z
2020-11-02T17:26:14.000Z
defmodule Peluquero.Utils do @moduledoc "Plain utilities for the project" require Logger @joiner "/" @max_match 20 @doc ~S""" Quick check for the consul key. ## Examples iex> Peluquero.Utils.consul_key_type("a/b/c/") {:nested, :bag, "a"} iex> Peluquero.Utils.consul_key_type("a/b/c") {:nested, :item, "a"} iex> Peluquero.Utils.consul_key_type("a/") {:plain, :bag, "a"} iex> Peluquero.Utils.consul_key_type("a") {:plain, :item, "a"} """ @spec consul_key_type(String.t()) :: {:plain | :nested, :bag | :item, String.t()} def consul_key_type(key) 0..@max_match |> Enum.each(fn n -> @n n def consul_key_type(<< key::binary-size(unquote(@n)), unquote(@joiner)::binary, rest::binary >>) do case String.reverse(rest) do "" -> {:plain, :bag, key} <<@joiner::binary, _::binary>> -> {:nested, :bag, key} _ -> {:nested, :item, key} end end def consul_key_type(<<rest::binary-size(unquote(@n + 1))>>), do: {:plain, :item, rest} end) def consul_key_type(key) when is_binary(key) do {type, rest} = case String.reverse(key) do <<@joiner::binary, rest::binary>> -> {:bag, String.reverse(rest)} _ -> {:item, key} end {if(String.contains?(rest, @joiner), do: :nested, else: :plain), type, rest} end ############################################################################## def safe(value) when is_nil(value), do: "" def safe(false), do: "false" def safe(true), do: "true" def safe(value) when is_binary(value), do: value def safe(value) when is_integer(value), do: Integer.to_string(value) def safe(value) when is_float(value), do: Float.to_string(value) def safe(value) when is_atom(value), do: Atom.to_string(value) def safe(value), do: Jason.encode!(value) ############################################################################## if Code.ensure_compiled?(Consul.Kv) do def consul(root, path) when is_list(path), do: consul(root, Enum.join(path, @joiner)) def consul(root, path) when is_atom(path), do: consul(root, Atom.to_string(path)) def consul(root, path) when is_binary(path) do path = [root, path] |> Enum.join(@joiner) |> String.trim_trailing(@joiner) size = String.length(path) case apply(Consul.Kv, :keys, [path]) do {:ok, %HTTPoison.Response{body: keys}} when is_list(keys) -> keys |> Enum.map(fn <<_::binary-size(size), @joiner::binary, key::binary>> -> key end) |> Enum.filter(&(&1 != "")) |> Enum.map(fn key -> case Peluquero.Utils.consul_key_type(key) do {:nested, _, _} -> nil {:plain, :bag, rest} -> {String.to_atom(rest), consul(path, key)} {:plain, :item, _} -> with %HTTPoison.Response{body: [%{"Value" => value}]} <- apply(Consul.Kv, :fetch!, ["#{path}#{@joiner}#{key}"]), do: {String.to_atom(key), value} end end) |> Enum.filter(&(not is_nil(&1))) |> Enum.into([]) {:error, %HTTPoison.Error{id: _, reason: :econnrefused}} -> Logger.error("Connection to consul refused for path [#{path}], check settings") [] any -> Logger.error("Unexpected error while connecting to consul: [#{inspect(any)}]") [] end end end ############################################################################## defmacro safe_method(name, id, param, do: block) do if Application.get_env(:peluquero, :safe_peinados, false) do quote do def unquote(name)(unquote(id) \\ nil, unquote(param)) do if child?(unquote(id)), do: unquote(block) end end else quote do def unquote(name)(unquote(id) \\ nil, unquote(param)), do: unquote(block) end end end defmacro safe_method(name, id, param1, param2, do: block) do if Application.get_env(:peluquero, :safe_peinados, false) do quote do def unquote(name)(unquote(id) \\ nil, unquote(param1), unquote(param2)) do if child?(unquote(id)), do: unquote(block) end end else quote do def unquote(name)(unquote(id) \\ nil, unquote(param1), unquote(param2)), do: unquote(block) end end end end
31.683099
91
0.533452
ff79924a8b43cfb7a60e6f1c4e956bb4c5423800
671
exs
Elixir
config/test.exs
evanbattaglia/livewords
c1324cde64e6d7873942e24a473feb16482c9fbb
[ "MIT" ]
null
null
null
config/test.exs
evanbattaglia/livewords
c1324cde64e6d7873942e24a473feb16482c9fbb
[ "MIT" ]
null
null
null
config/test.exs
evanbattaglia/livewords
c1324cde64e6d7873942e24a473feb16482c9fbb
[ "MIT" ]
null
null
null
use Mix.Config # Configure your database # # The MIX_TEST_PARTITION environment variable can be used # to provide built-in test partitioning in CI environment. # Run `mix help test` for more information. config :livewords, Livewords.Repo, username: "postgres", password: "postgres", database: "livewords_test#{System.get_env("MIX_TEST_PARTITION")}", hostname: "localhost", pool: Ecto.Adapters.SQL.Sandbox # We don't run a server during test. If one is required, # you can enable the server option below. config :livewords, LivewordsWeb.Endpoint, http: [port: 4002], server: false # Print only warnings and errors during test config :logger, level: :warn
29.173913
68
0.752608
ff79a8a0480bdac1a6d49eba5855ca7b28e83d97
2,810
ex
Elixir
web/views/admin/checkout_view.ex
harry-gao/ex-cart
573e7f977bb3b710d11618dd215d4ddd8f819fb3
[ "Apache-2.0" ]
356
2016-03-16T12:37:28.000Z
2021-12-18T03:22:39.000Z
web/views/admin/checkout_view.ex
harry-gao/ex-cart
573e7f977bb3b710d11618dd215d4ddd8f819fb3
[ "Apache-2.0" ]
30
2016-03-16T09:19:10.000Z
2021-01-12T08:10:52.000Z
web/views/admin/checkout_view.ex
harry-gao/ex-cart
573e7f977bb3b710d11618dd215d4ddd8f819fb3
[ "Apache-2.0" ]
72
2016-03-16T13:32:14.000Z
2021-03-23T11:27:43.000Z
defmodule Nectar.Admin.CheckoutView do use Nectar.Web, :view alias Nectar.Repo alias Nectar.CheckoutManager import Ecto.Query def country_names_and_ids do [{"--Select Country--", ""} | Repo.all(from c in Nectar.Country, select: {c.name, c.id})] end def state_names_and_ids do [{"--Select State--", ""} | Repo.all(from c in Nectar.State, select: {c.name, c.id})] end def adjustment_row(%Nectar.Adjustment{shipment_id: shipment_id} = adjustment) when not is_nil(shipment_id) do content_tag :tr do [content_tag :td do to_string(adjustment.amount) end, content_tag :td do "shipping: #{adjustment.shipment.shipping_method.name}" end] end end def adjustment_row(%Nectar.Adjustment{tax_id: tax_id} = adjustment) when not is_nil(tax_id) do content_tag :tr do [content_tag :td do to_string(adjustment.amount) end, content_tag :td do "tax: #{adjustment.tax.name}" end] end end def braintree_client_token do Nectar.Gateway.Braintree.client_token end def next_step(%Nectar.Order{state: state, confirmation_status: true} = order) do next_state = CheckoutManager.next_state(order) # cannot move forward therefore must be in confirmed state. if next_state == state do "confirmed.html" else "#{next_state}.form.html" end end def next_step(%Nectar.Order{confirmation_status: false}) do "cancelled.html" end def error_in_payment_method?(changeset, payment_method_id) do (!changeset.valid?) && changeset.params["payment"]["payment_method_id"] == to_string(payment_method_id) end def back_link(conn, %Nectar.Order{state: "cart"} = order) do link "Back", to: admin_cart_path(conn, :edit, order), class: "btn btn-xs" end def back_link(_conn, %Nectar.Order{state: "confirmation"} = _order) do "" end def back_link(conn, %Nectar.Order{} = order) do link "Back", to: admin_order_checkout_path(conn, :back, order), method: "put", class: "btn btn-xs" end def shipment_details(%Nectar.ShipmentUnit{} = shipment_unit) do Enum.reduce(shipment_unit.line_items, "", fn (line_item, acc) -> acc <> line_item.variant.product.name <> "," end) end def shipping_method_selection(data, id), do: shipping_method_selection(data.proposed_shipping_methods[id]) def shipping_method_selection(proposed_shipments) do Enum.map(proposed_shipments, &({&1.shipping_method_name <> " (+#{&1.shipping_cost})", &1.shipping_method_id})) end def has_shipping_method?(data, shipment_unit_id) do not is_nil(data.proposed_shipping_methods[shipment_unit_id] ) end def payment_methods_available?(%{applicable_payment_methods: []}), do: false def payment_methods_available?(%{}), do: true end
29.578947
114
0.695374
ff79d5b8afae75afd4fbb0291476da948fa4efee
66
exs
Elixir
learning/programming_elixir/appendix_2/simple/test/simple_test.exs
Mdlkxzmcp/various_elixir
c87527b7118a0c74a042073c04d2228025888ddf
[ "MIT" ]
2
2020-01-20T20:15:20.000Z
2020-02-27T11:08:42.000Z
learning/programming_elixir/appendix_2/simple/test/simple_test.exs
Mdlkxzmcp/various_elixir
c87527b7118a0c74a042073c04d2228025888ddf
[ "MIT" ]
null
null
null
learning/programming_elixir/appendix_2/simple/test/simple_test.exs
Mdlkxzmcp/various_elixir
c87527b7118a0c74a042073c04d2228025888ddf
[ "MIT" ]
null
null
null
defmodule SimpleTest do use ExUnit.Case doctest Simple end
11
23
0.757576
ff7a3415510bb1b717fe59e3b5cdd0358151ea65
510
ex
Elixir
lib/segment/http.ex
joshsmith/segment_elixir
0cf5548b805cdfcaf547b9d213173388a7ea2005
[ "MIT" ]
2
2019-05-10T13:20:39.000Z
2019-05-10T15:08:21.000Z
lib/segment/http.ex
joshsmith/segment_elixir
0cf5548b805cdfcaf547b9d213173388a7ea2005
[ "MIT" ]
7
2019-05-10T15:28:18.000Z
2019-06-13T16:44:59.000Z
lib/segment/http.ex
joshsmith/segment_elixir
0cf5548b805cdfcaf547b9d213173388a7ea2005
[ "MIT" ]
1
2019-05-24T18:41:57.000Z
2019-05-24T18:41:57.000Z
defmodule Segment.Http do use HTTPoison.Base @base_url "https://api.segment.io/v1/" def process_url(url) do @base_url <> url end def process_request_options(options) do Keyword.merge(options, [hackney: [basic_auth: {write_key(), ""}]]) end def process_request_headers(headers) do headers |> Keyword.put(:"Content-Type", "application/json") |> Keyword.put(:accept, "application/json") end defp write_key() do Application.fetch_env!(:segment, :write_key) end end
21.25
70
0.686275
ff7a49460d473fd408b9cf6a08b1e491ec652984
907
ex
Elixir
lib/metrics/adapter/memory.ex
cloud8421/gig
a2bc5d004ae8b11a92e971c043de3e544fcfbfcf
[ "MIT" ]
null
null
null
lib/metrics/adapter/memory.ex
cloud8421/gig
a2bc5d004ae8b11a92e971c043de3e544fcfbfcf
[ "MIT" ]
null
null
null
lib/metrics/adapter/memory.ex
cloud8421/gig
a2bc5d004ae8b11a92e971c043de3e544fcfbfcf
[ "MIT" ]
null
null
null
defmodule Metrics.Adapter.Memory do @moduledoc false @behaviour Metrics.Adapter def state do Agent.get(__MODULE__, fn(s) -> s end) end def start_link(state) do Agent.start_link(fn() -> state end, name: __MODULE__) end def child_spec(state) do %{id: __MODULE__, start: {__MODULE__, :start_link, [state]}} end def inc(name) do Agent.update(__MODULE__, fn(state) -> Map.update(state, name, 1, fn(current) -> current + 1 end) end) end def counter(name, value) do Agent.update(__MODULE__, fn(state) -> Map.put(state, name, value) end) end def gauge(name, value) do Agent.update(__MODULE__, fn(state) -> Map.update(state, name, [value], fn(current) -> [value | current] end) end) end end
20.155556
57
0.546858
ff7a8545140f47c078ff79e46f3711d1ecbe275b
2,091
ex
Elixir
clients/sql_admin/lib/google_api/sql_admin/v1/model/generate_ephemeral_cert_request.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/sql_admin/lib/google_api/sql_admin/v1/model/generate_ephemeral_cert_request.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/sql_admin/lib/google_api/sql_admin/v1/model/generate_ephemeral_cert_request.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.SQLAdmin.V1.Model.GenerateEphemeralCertRequest do @moduledoc """ Ephemeral certificate creation request. ## Attributes * `access_token` (*type:* `String.t`, *default:* `nil`) - Optional. Access token to include in the signed certificate. * `public_key` (*type:* `String.t`, *default:* `nil`) - PEM encoded public key to include in the signed certificate. * `readTime` (*type:* `DateTime.t`, *default:* `nil`) - Optional. Optional snapshot read timestamp to trade freshness for performance. * `validDuration` (*type:* `String.t`, *default:* `nil`) - Optional. If set, it will contain the cert valid duration. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :access_token => String.t() | nil, :public_key => String.t() | nil, :readTime => DateTime.t() | nil, :validDuration => String.t() | nil } field(:access_token) field(:public_key) field(:readTime, as: DateTime) field(:validDuration) end defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1.Model.GenerateEphemeralCertRequest do def decode(value, options) do GoogleApi.SQLAdmin.V1.Model.GenerateEphemeralCertRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1.Model.GenerateEphemeralCertRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.339286
138
0.717838
ff7aaa5649e3b948512457ca48781a05eb01f2d8
1,722
exs
Elixir
test/bow/exec_test.exs
kianmeng/bow
d0b2ad564b0ccd06eb7d4582b94177877559d4af
[ "MIT" ]
25
2017-10-06T14:22:13.000Z
2022-01-14T20:59:59.000Z
test/bow/exec_test.exs
kianmeng/bow
d0b2ad564b0ccd06eb7d4582b94177877559d4af
[ "MIT" ]
9
2017-10-30T06:02:22.000Z
2022-01-03T13:57:57.000Z
test/bow/exec_test.exs
kianmeng/bow
d0b2ad564b0ccd06eb7d4582b94177877559d4af
[ "MIT" ]
4
2018-03-29T12:59:10.000Z
2021-09-19T09:10:01.000Z
defmodule Bow.ExecTest do use ExUnit.Case @file_cat "test/files/cat.jpg" import Bow.Exec, only: [exec: 3, exec: 4] setup do source = Bow.new(path: @file_cat) target = Bow.set(source, :name, "thumb_#{source.name}") {:ok, source: source, target: target} end test "successful command", %{source: source, target: target} do assert {:ok, %Bow{path: path}} = exec(source, target, ["test/scripts/copy.sh", :input, :output]) assert path != nil assert File.exists?(path) end test "command not found", %{source: source, target: target} do assert {:error, reason} = exec(source, target, ["test/scripts/notfound", :input, :output]) assert reason[:output] =~ ~r/No such file/u end test "failing command", %{source: source, target: target} do assert {:error, reason} = exec(source, target, ["test/scripts/fail.sh", :input, :output]) assert reason[:exit_code] != 0 end test "timout", %{source: source, target: target} do assert {:error, reason} = exec(source, target, ["test/scripts/sleep.sh", :input, :output], timeout: 500) assert reason[:exit_code] == :timeout end test "file name with quotes" do file = "tmp/asdf'weird$name.pdf" File.write!(file, "data") source = Bow.new(path: file) target = Bow.set(source, :name, "thumb_#{source.name}") assert {:ok, %Bow{path: path}} = exec(source, target, ["test/scripts/copy.sh", :input, :output]) assert path != nil assert File.exists?(path) end test "append extension to target file", %{source: source, target: target} do assert {:ok, _} = exec(source, target, ["test/scripts/assert-ext.sh", :input, :output, "jpg"]) end end
30.210526
98
0.629501
ff7ac35c0ea3b97f60c32bd7ae9c588a9d5f414e
1,619
exs
Elixir
test/farside_test.exs
TrueMysterious/farside
3c0d560007d29605875fe0d754a84aea042b1164
[ "MIT" ]
null
null
null
test/farside_test.exs
TrueMysterious/farside
3c0d560007d29605875fe0d754a84aea042b1164
[ "MIT" ]
null
null
null
test/farside_test.exs
TrueMysterious/farside
3c0d560007d29605875fe0d754a84aea042b1164
[ "MIT" ]
null
null
null
defmodule FarsideTest do @services_json Application.fetch_env!(:farside, :services_json) use ExUnit.Case use Plug.Test alias Farside.Router @opts Router.init([]) def test_conn(path) do :timer.sleep(1000) :get |> conn(path, "") |> Router.call(@opts) end test "throttle" do :get |> conn("/", "") |> Router.call(@opts) throttled_conn = :get |> conn("/", "") |> Router.call(@opts) assert throttled_conn.state == :sent assert throttled_conn.status == 403 end test "/" do conn = test_conn("/") assert conn.state == :sent assert conn.status == 200 end test "/ping" do conn = test_conn("/ping") assert conn.state == :sent assert conn.status == 200 assert conn.resp_body == "PONG" end test "/:service" do {:ok, file} = File.read(@services_json) {:ok, service_list} = Jason.decode(file) service_names = Enum.map( service_list, fn service -> service["type"] end ) IO.puts("") Enum.map(service_names, fn service_name -> conn = test_conn("/#{service_name}") first_redirect = elem(List.last(conn.resp_headers), 1) IO.puts(" /#{service_name} (#1) -- #{first_redirect}") assert conn.state == :set assert conn.status == 302 conn = test_conn("/#{service_name}") second_redirect = elem(List.last(conn.resp_headers), 1) IO.puts(" /#{service_name} (#2) -- #{second_redirect}") assert conn.state == :set assert conn.status == 302 assert first_redirect != second_redirect end) end end
21.302632
65
0.592341
ff7ac62abdd65ccc7a83be84e0002e3e4c5c5d1c
1,513
ex
Elixir
elixir/lib/astrum/domains/auth/auth.ex
explore-astrum/astrum
868fa6d28e1c44d0a99a72edc7f6b5b7d818da07
[ "MIT" ]
2
2019-01-21T17:49:19.000Z
2019-06-20T03:01:06.000Z
elixir/lib/astrum/domains/auth/auth.ex
explore-astrum/astrum
868fa6d28e1c44d0a99a72edc7f6b5b7d818da07
[ "MIT" ]
1
2022-01-27T16:05:47.000Z
2022-01-27T16:05:47.000Z
elixir/lib/astrum/domains/auth/auth.ex
explore-astrum/astrum
868fa6d28e1c44d0a99a72edc7f6b5b7d818da07
[ "MIT" ]
null
null
null
defmodule Astrum.Auth do use Kora.Interceptor def validate(data, user, path, history) when is_map(data) do data |> Enum.flat_map(fn {key, value} -> next_path = path ++ [key] case validate_merge(next_path, value, user) do res = {:error, _err} -> [res] nil -> validate(value, user, next_path, history) res -> validate(value, user, next_path, res) end end) |> Stream.map(fn [] -> {:error, :not_allowed} res -> res end) |> Enum.to_list() end def validate(_, _, _, history) do [history] end def validate_merge(["plot:activity", _plot, _activity], %{"type" => type}, _user) when type in ["plot.offer"], do: :ok def validate_merge(["plot:activity", _plot, _activity], _, _user) do {:error, :plot_activity_bad} end def validate_merge(["plot:info", _plot, field | rest], _value, _user) when [field | rest] not in [ ["name"], ["prices", "list"] ] do {:error, {:unmodifiable_field, field}} end def validate_merge(["plot:info", plot], _value, user) do ["plot:info", plot, "owner"] |> Kora.query_path!() |> case do ^user -> :ok _ -> {:error, :plot_unowned} end end def validate_merge(_, _, _), do: nil def require_owner(root, entity, user) do [root, entity, "owner"] |> Kora.query_path!() |> case do ^user -> :ok _ -> {:error, :plot_unowned} end end end
22.58209
83
0.555188
ff7ac78591cf807a49d2061f14abb9d6f37a21bb
2,072
exs
Elixir
example/config/dev.exs
JohnKacz/phoenix_datatables
747b184972614d87aeb0cd644593951703d718db
[ "MIT" ]
null
null
null
example/config/dev.exs
JohnKacz/phoenix_datatables
747b184972614d87aeb0cd644593951703d718db
[ "MIT" ]
null
null
null
example/config/dev.exs
JohnKacz/phoenix_datatables
747b184972614d87aeb0cd644593951703d718db
[ "MIT" ]
null
null
null
use Mix.Config # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with brunch.io to recompile .js and .css sources. config :phoenix_datatables_example, PhoenixDatatablesExampleWeb.Endpoint, http: [port: System.get_env("PORT") || 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin", cd: Path.expand("../assets", __DIR__)]] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # command from your terminal: # # openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem # # The `http:` config above can be replaced with: # # https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :phoenix_datatables_example, PhoenixDatatablesExampleWeb.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{priv/gettext/.*(po)$}, ~r{lib/phoenix_datatables_example_web/views/.*(ex)$}, ~r{lib/phoenix_datatables_example_web/templates/.*(eex)$} ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Configure your database config :phoenix_datatables_example, PhoenixDatatablesExample.Repo, adapter: Ecto.Adapters.Postgres, database: "phoenix_datatables_example_dev", hostname: "localhost", pool_size: 10
36.350877
170
0.726834
ff7aca5abd4c5337be7d8c01a089d16d6c0ce48c
67
exs
Elixir
test/test_helper.exs
abotkit/teddy
72f1c7015a278d4fd1b2c90daeaeb49d0d8ef142
[ "MIT" ]
1
2022-02-03T19:41:52.000Z
2022-02-03T19:41:52.000Z
test/test_helper.exs
abotkit/teddy
72f1c7015a278d4fd1b2c90daeaeb49d0d8ef142
[ "MIT" ]
null
null
null
test/test_helper.exs
abotkit/teddy
72f1c7015a278d4fd1b2c90daeaeb49d0d8ef142
[ "MIT" ]
null
null
null
ExUnit.start() Ecto.Adapters.SQL.Sandbox.mode(Teddy.Repo, :manual)
22.333333
51
0.776119
ff7ae3d258fdaad347015e0a8af560e9df1b4093
1,080
exs
Elixir
test/four_lucha/platform_test.exs
Thomas-Jean/four_lucha
591627059c02edc3315b5cac2c35eacb821108ff
[ "Apache-2.0" ]
1
2021-02-21T19:15:27.000Z
2021-02-21T19:15:27.000Z
test/four_lucha/platform_test.exs
Thomas-Jean/four_lucha
591627059c02edc3315b5cac2c35eacb821108ff
[ "Apache-2.0" ]
null
null
null
test/four_lucha/platform_test.exs
Thomas-Jean/four_lucha
591627059c02edc3315b5cac2c35eacb821108ff
[ "Apache-2.0" ]
null
null
null
defmodule FourLucha.PlatformTest do use ExUnit.Case, async: true use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney, options: [clear_mock: true] ExVCR.Config.filter_url_params(true) setup_all do HTTPoison.start() end setup do {status, _cleared} = Cachex.clear(:gb_cache) status end test "responses with a Game and Response struct" do use_cassette "gb_get_platform" do response = FourLucha.Platform.get(1) assert elem(response, 0) == :ok assert elem(response, 1).__struct__ == FourLucha.Resource.Platform assert elem(response, 1).name == "Amiga" assert elem(response, 2).__struct__ == FourLucha.Resource.Response end end test "responses with a list of Games when given query parameters as a map" do use_cassette "gb_get_commodores" do {status, commodores, req} = FourLucha.Platform.get(%{filter: %{name: "commodore"}}) assert status == :ok assert is_list(commodores) assert length(commodores) == 5 assert req.error == "OK" assert req.status_code == 1 end end end
28.421053
89
0.685185
ff7b3be64a29674f8a2902aa82aa756cb279bb8c
6,057
ex
Elixir
lib/couch_gears/database.ex
Zatvobor/couch_gears
5ebfdec4d79fb3734d7d2cb36e495b6e408eac21
[ "Apache-2.0" ]
1
2015-09-29T03:07:04.000Z
2015-09-29T03:07:04.000Z
lib/couch_gears/database.ex
Zatvobor/couch_gears
5ebfdec4d79fb3734d7d2cb36e495b6e408eac21
[ "Apache-2.0" ]
null
null
null
lib/couch_gears/database.ex
Zatvobor/couch_gears
5ebfdec4d79fb3734d7d2cb36e495b6e408eac21
[ "Apache-2.0" ]
null
null
null
defmodule CouchGears.Database do @moduledoc """ This module provides CRUD functions for managing either databases or documents. The main important thing is a `database` module designed to be a 'instance' for certain DB (see examples below). ## Examples: db = CouchGears.Database.open("db") db.find("x") db.close() Is an equivalent to: CouchGears.Database.find("db", "x") also you can use a `database` module from pure Erlang environment: Db = 'Elixir-CouchGears-Database':open(<<"db">>), Db:find(<<"x">>), DB:close(). 'Elixir-CouchGears-Database':find(<<"db">>, <<"x">>). """ alias CouchGears.Database.Helpers, as: Helpers alias CouchGears.Records, as: Records Code.prepend_path("include") defrecord Db, Record.extract(:db, from: "couch_db.hrl") defrecordp :database, [:raw_db, :db] @doc """ Gets associated `db` record. Check a `include/couch_db.hrl` for details. """ def db(database(db: db)), do: db @doc """ Gets associated raw `db` record which has been returned from `couch_db:open_int/2`. """ def raw_db(database(raw_db: raw_db)), do: raw_db @doc """ Opens a `db` and returns a `database` instance or `:no_db_file` atom in case it doesn't exist. """ def open(db_name) do db = do_open(db_name) unless db == :no_db_file do db = database(raw_db: db, db: Db.new(db)) end db end @doc """ Opens a `db` and returns a `database` instance or exception in case it doesn't exist. """ def open!(db_name) do db = open(db_name) if db == :no_db_file do raise "No db file" end db end @doc """ Closes associated `db`. """ def close(database(raw_db: raw_db)) do :couch_db.close(raw_db) database() end @doc """ Creates a `db`. """ def create_db(db_name, opts // []) do :couch_server.create(db_name, opts) end @doc """ Deletes a `db`. """ def delete_db(db_name, opts // []) do :couch_server.delete(db_name, opts) end @doc """ Returns a `document` as a raw `list` or either `:no_db_file`/`:missing` atom. """ def find(_doc_id, :no_db_file), do: :no_db_file def find(doc_id, db) when is_record(db, CouchGears.Database) do find(doc_id, [], db) end def find(db_name, doc_id), do: find(doc_id, [], open(db_name)) @doc """ Returns a `document` as a raw `list` or either `:no_db_file`/`:missing` atom. An `opts` is a convenience for filtering ## Options * `except:` - The list of fields which should be cut from a document body * `only:` - The strict list of fields which should have a returned document ## Examples Database.find("db", "doc_id", [only: ["_id"]]) # => [{"_id", "doc_id"}] Database.find("db", "doc_id", [except: ["_id"]]) # => [{"_rev", "1-41f7a51b6f7002e9a41ad4fc466838e4"}] """ def find(_doc_id, _opts, :no_db_file), do: :no_db_file def find(doc_id, opts, db) when is_record(db, CouchGears.Database) do { _, doc } = do_find(doc_id, db) do_filter(doc, opts) end def find(db_name, doc_id, opts), do: find(doc_id, opts, open(db_name)) @doc """ Returns a `document` as a raw `list` or either `:no_db_file`/`:missing` atom. """ def find_with_rev(_doc_id, _rev, :no_db_file), do: :no_db_file def find_with_rev(doc_id, rev, database(raw_db: raw_db)) do case :couch_db.open_doc_revs(raw_db, doc_id, [make_rev(rev)], []) do {:ok, [{:ok, doc}]} -> {body} = :couch_doc.to_json_obj(doc, []) body _ -> :missing end end def find_with_rev(db_name, doc_id, rev), do: find_with_rev(doc_id, rev, open(db_name)) @doc """ Creates a `document` and return the `rev` as string or either `:conflict`/`:no_db_file` atom. """ def create_doc(_doc, :no_db_file), do: :no_db_file def create_doc(db_name, doc) when is_list(doc) do create_doc(doc, open(db_name)) end def create_doc(doc, db) when is_list(doc) and is_record(db, CouchGears.Database) do update(doc, db) end @doc """ Updates a particular `document` and return a `rev` string or either `:conflict`/`:no_db_file` atom. """ def update(_doc, :no_db_file), do: :no_db_file def update(doc, database(raw_db: raw_db)) when is_list(doc) do json_doc = :couch_doc.from_json_obj({doc}) {:ok, rev} = :couch_db.update_doc(raw_db, json_doc, []) :couch_doc.rev_to_str(rev) end def update(db_name, doc) when is_list(doc), do: update(doc, open(db_name)) @doc """ Enumerates through particular `db` and pass arguments such a `FullDocInfo` record, something like `reds` and execution accumulator as a second argument to `callback` function. Check a `couch_db:enum_docs/4` function usage example for more information. """ def enum_docs(db, callback, opts) when is_record(db, CouchGears.Database) and is_function(callback, 3) do function = fn(raw_full_doc_info, reds, acc) -> callback.(Records.FullDocInfo.new(raw_full_doc_info), reds, acc) end :couch_db.enum_docs(db.raw_db, function, [], opts || []) end def enum_docs(db_name, callback, opts), do: enum_docs(open(db_name), callback, opts) def enum_docs(db_name, callback), do: enum_docs(db_name, callback, []) # Internal stuff defp do_open(name) do case :couch_db.open_int(to_binary(name), []) do { :not_found, :no_db_file } -> :no_db_file { _, db } -> db end end defp do_find(ddoc, database(raw_db: raw_db)) do case :couch_db.open_doc(raw_db, ddoc) do {:ok, doc} -> {body} = :couch_doc.to_json_obj(doc, []) {:ok, body } _ -> {:not_found, :missing} end end defp do_filter(missing, _opts) when is_atom(missing), do: missing defp do_filter(doc, []), do: doc defp do_filter(doc, opts) do fun = case opts do [except: fields] -> fn({k,_}) -> !List.member?(fields, k) end [only: fields] -> fn({k,_}) -> List.member?(fields, k) end end Enum.filter(doc, fun) end defp make_rev(rev), do: :couch_doc.parse_rev(rev) end
26.92
114
0.641076
ff7b9b7dab58f48878f7333d3a3b24e448c2a4e9
243
ex
Elixir
lib/tnd/dice/dice_roll_result.ex
tndrpg/tnd
a9a348ed7ce2f3d8f55046559f9551e2607f3236
[ "0BSD" ]
null
null
null
lib/tnd/dice/dice_roll_result.ex
tndrpg/tnd
a9a348ed7ce2f3d8f55046559f9551e2607f3236
[ "0BSD" ]
1
2021-05-11T14:31:58.000Z
2021-05-11T14:31:58.000Z
lib/tnd/dice/dice_roll_result.ex
tndrpg/tnd
a9a348ed7ce2f3d8f55046559f9551e2607f3236
[ "0BSD" ]
null
null
null
defmodule Tnd.Dice.DiceRollResult do alias Tnd.Dice.DicePool defstruct pool: %DicePool{}, success: 0, advantage: 0, triumph: 0, failure: 0, threat: 0, despair: 0 end
20.25
36
0.514403
ff7b9d338ac8468beab4d2eb0220163607772b12
1,353
exs
Elixir
test/let/let_ok_and_let_error_test.exs
bblaszkow06/espec
4d9819ca5c68c6eb70276c7d9c9630ded01ba778
[ "Apache-2.0" ]
null
null
null
test/let/let_ok_and_let_error_test.exs
bblaszkow06/espec
4d9819ca5c68c6eb70276c7d9c9630ded01ba778
[ "Apache-2.0" ]
null
null
null
test/let/let_ok_and_let_error_test.exs
bblaszkow06/espec
4d9819ca5c68c6eb70276c7d9c9630ded01ba778
[ "Apache-2.0" ]
null
null
null
defmodule LetOkAndLetErrorTest do use ExUnit.Case, async: true defmodule SomeSpec do use ESpec def ok_fun, do: {:ok, 10} def error_fun, do: {:error, 20} context "let_ok and let_ok!" do let_ok :ok_result, do: ok_fun() let_ok! :ok_result!, do: ok_fun() it do: expect(ok_result()).to(eq(10)) it do: expect(ok_result!()).to(eq(10)) end context "let_error and let_error!" do let_error :error_result, do: error_fun() let_error! :error_result!, do: error_fun() it do: expect(error_result()).to(eq(20)) it do: expect(error_result!()).to(eq(20)) end end setup_all do {:ok, ex1: Enum.at(SomeSpec.examples(), 0), ex2: Enum.at(SomeSpec.examples(), 1), ex3: Enum.at(SomeSpec.examples(), 2), ex4: Enum.at(SomeSpec.examples(), 3)} end test "run ex1", context do example = ESpec.ExampleRunner.run(context[:ex1]) assert(example.status == :success) end test "run ex2", context do example = ESpec.ExampleRunner.run(context[:ex2]) assert(example.status == :success) end test "run ex3", context do example = ESpec.ExampleRunner.run(context[:ex3]) assert(example.status == :success) end test "run ex5", context do example = ESpec.ExampleRunner.run(context[:ex4]) assert(example.status == :success) end end
24.6
52
0.637103
ff7ba638b2c7f482fa32a63b4038d3048ce0c8a4
1,069
ex
Elixir
clients/elixir/generated/lib/cloud_manager_api/model/repository__links.ex
shinesolutions/cloudmanager-api-clients
d73a25878f6cc57af954362ba8dccc90d54e6131
[ "Apache-2.0" ]
3
2020-06-23T05:31:52.000Z
2020-11-26T05:34:57.000Z
clients/elixir/generated/lib/cloud_manager_api/model/repository__links.ex
shinesolutions/cloudmanager-api-clients
d73a25878f6cc57af954362ba8dccc90d54e6131
[ "Apache-2.0" ]
2
2021-01-21T01:19:54.000Z
2021-12-09T22:30:22.000Z
clients/elixir/generated/lib/cloud_manager_api/model/repository__links.ex
shinesolutions/cloudmanager-api-clients
d73a25878f6cc57af954362ba8dccc90d54e6131
[ "Apache-2.0" ]
1
2020-11-18T11:48:13.000Z
2020-11-18T11:48:13.000Z
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule CloudManagerAPI.Model.RepositoryLinks do @moduledoc """ """ @derive [Poison.Encoder] defstruct [ :"http://ns.adobe.com/adobecloud/rel/program", :"http://ns.adobe.com/adobecloud/rel/branches", :"self" ] @type t :: %__MODULE__{ :"http://ns.adobe.com/adobecloud/rel/program" => HalLink | nil, :"http://ns.adobe.com/adobecloud/rel/branches" => HalLink | nil, :"self" => HalLink | nil } end defimpl Poison.Decoder, for: CloudManagerAPI.Model.RepositoryLinks do import CloudManagerAPI.Deserializer def decode(value, options) do value |> deserialize(:"http://ns.adobe.com/adobecloud/rel/program", :struct, CloudManagerAPI.Model.HalLink, options) |> deserialize(:"http://ns.adobe.com/adobecloud/rel/branches", :struct, CloudManagerAPI.Model.HalLink, options) |> deserialize(:"self", :struct, CloudManagerAPI.Model.HalLink, options) end end
31.441176
115
0.702526
ff7be3bd913249171adb1dc0090af2e9451627e2
3,262
exs
Elixir
config/runtime.exs
TiagoDanin/Aquamarine-Monitor
432e50f0bddc6c04689a65e1dd25843f0efe2cce
[ "MIT" ]
1
2022-01-25T22:07:43.000Z
2022-01-25T22:07:43.000Z
config/runtime.exs
TiagoDanin/Aquamarine-Monitor
432e50f0bddc6c04689a65e1dd25843f0efe2cce
[ "MIT" ]
null
null
null
config/runtime.exs
TiagoDanin/Aquamarine-Monitor
432e50f0bddc6c04689a65e1dd25843f0efe2cce
[ "MIT" ]
null
null
null
import Config # config/runtime.exs is executed for all environments, including # during releases. It is executed after compilation and before the # system starts, so it is typically used to load production configuration # and secrets from environment variables or elsewhere. Do not define # any compile-time configuration in here, as it won't be applied. # The block below contains prod specific runtime configuration. # Start the phoenix server if environment is set and running in a release if System.get_env("PHX_SERVER") && System.get_env("RELEASE_NAME") do config :aquamarine, AquamarineWeb.Endpoint, server: true end if config_env() == :prod do database_url = System.get_env("DATABASE_URL") || raise """ environment variable DATABASE_URL is missing. For example: ecto://USER:PASS@HOST/DATABASE """ maybe_ipv6 = if System.get_env("ECTO_IPV6"), do: [:inet6], else: [] config :aquamarine, Aquamarine.Repo, # ssl: true, url: database_url, pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"), socket_options: maybe_ipv6 # The secret key base is used to sign/encrypt cookies and other secrets. # A default value is used in config/dev.exs and config/test.exs but you # want to use a different value for prod and you most likely don't want # to check this value into version control, so we use an environment # variable instead. secret_key_base = System.get_env("SECRET_KEY_BASE") || raise """ environment variable SECRET_KEY_BASE is missing. You can generate one by calling: mix phx.gen.secret """ host = System.get_env("PHX_HOST") || "example.com" port = String.to_integer(System.get_env("PORT") || "4000") config :aquamarine, AquamarineWeb.Endpoint, url: [host: host, port: 443], http: [ # Enable IPv6 and bind on all interfaces. # Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access. # See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html # for details about using IPv6 vs IPv4 and loopback vs public addresses. ip: {0, 0, 0, 0, 0, 0, 0, 0}, port: port ], secret_key_base: secret_key_base # ## Using releases # # If you are doing OTP releases, you need to instruct Phoenix # to start each relevant endpoint: # # config :aquamarine, AquamarineWeb.Endpoint, server: true # # Then you can assemble a release by calling `mix release`. # See `mix help release` for more information. # ## Configuring the mailer # # In production you need to configure the mailer to use a different adapter. # Also, you may need to configure the Swoosh API client of your choice if you # are not using SMTP. Here is an example of the configuration: # # config :aquamarine, Aquamarine.Mailer, # adapter: Swoosh.Adapters.Mailgun, # api_key: System.get_env("MAILGUN_API_KEY"), # domain: System.get_env("MAILGUN_DOMAIN") # # For this example you need include a HTTP client required by Swoosh API client. # Swoosh supports Hackney and Finch out of the box: # # config :swoosh, :api_client, Swoosh.ApiClient.Hackney # # See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details. end
37.930233
82
0.70141
ff7bf9e9e79e2fbdda643d2654735c33b707d0fe
399
exs
Elixir
test/pummpcomm/history/delete_other_device_id_test.exs
infinity-aps/pummpcomm
7380585ecd110ab1c19d2aea3880e51e3f433050
[ "MIT" ]
15
2017-08-31T00:58:47.000Z
2020-01-12T03:53:13.000Z
test/pummpcomm/history/delete_other_device_id_test.exs
vladhj38/pummpcomm
7380585ecd110ab1c19d2aea3880e51e3f433050
[ "MIT" ]
1
2017-09-15T02:09:31.000Z
2017-09-15T02:09:31.000Z
test/pummpcomm/history/delete_other_device_id_test.exs
vladhj38/pummpcomm
7380585ecd110ab1c19d2aea3880e51e3f433050
[ "MIT" ]
3
2017-09-10T17:24:59.000Z
2019-09-10T19:41:49.000Z
defmodule Pummpcomm.History.DeleteOtherDeviceIDTest do use ExUnit.Case test "Delete Other Device ID" do {:ok, history_page} = Base.decode16("820100400081080000000000") decoded_events = Pummpcomm.History.decode_records(history_page, %{}) assert {:delete_other_device_id, %{timestamp: ~N[2008-01-01 00:00:00], raw: ^history_page}} = Enum.at(decoded_events, 0) end end
33.25
97
0.721805
ff7c17b1241dcbe84b4faaebb8c31a4e8ff1a010
75
ex
Elixir
lib/events_tools_web/views/user_view.ex
community-tools/community-tools
40b0e6cc9234b44593d2ab60bb2303d7224deb30
[ "Apache-2.0" ]
2
2017-10-06T01:14:35.000Z
2017-11-18T16:44:44.000Z
lib/events_tools_web/views/user_view.ex
community-tools/community-tools
40b0e6cc9234b44593d2ab60bb2303d7224deb30
[ "Apache-2.0" ]
6
2017-10-06T00:04:59.000Z
2017-10-06T00:09:27.000Z
lib/events_tools_web/views/user_view.ex
apps-team/community-tools
40b0e6cc9234b44593d2ab60bb2303d7224deb30
[ "Apache-2.0" ]
1
2017-10-06T01:17:35.000Z
2017-10-06T01:17:35.000Z
defmodule CommunityToolsWeb.UserView do use CommunityToolsWeb, :view end
18.75
39
0.84
ff7c237cb4bd742f9fd42da3d877bb4e5bb1b142
370
ex
Elixir
lib/cforum/messages/tag_auditing_protocol.ex
campingrider/cforum_ex
cf27684c47d6dc26c9c37a946f1c729a79d27c70
[ "MIT" ]
null
null
null
lib/cforum/messages/tag_auditing_protocol.ex
campingrider/cforum_ex
cf27684c47d6dc26c9c37a946f1c729a79d27c70
[ "MIT" ]
null
null
null
lib/cforum/messages/tag_auditing_protocol.ex
campingrider/cforum_ex
cf27684c47d6dc26c9c37a946f1c729a79d27c70
[ "MIT" ]
null
null
null
defimpl Cforum.System.AuditingProtocol, for: Cforum.Messages.Tag do def audit_json(tag) do tag_synonyms = Cforum.Messages.Tags.list_tag_synonyms(tag) synonyms = Enum.map(tag_synonyms, &Cforum.System.AuditingProtocol.audit_json(&1)) tag |> Map.from_struct() |> Map.drop([:forum, :messages, :__meta__]) |> Map.put(:synonyms, synonyms) end end
30.833333
85
0.713514
ff7c46e6afe0682f7a3e30877a536a6dd217c68a
28,308
ex
Elixir
lib/elixir/lib/code/fragment.ex
tnascimento/elixir
9a4d10e702f33d2fa47718cde05375b506b4a3d6
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/code/fragment.ex
tnascimento/elixir
9a4d10e702f33d2fa47718cde05375b506b4a3d6
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/code/fragment.ex
tnascimento/elixir
9a4d10e702f33d2fa47718cde05375b506b4a3d6
[ "Apache-2.0" ]
null
null
null
defmodule Code.Fragment do @moduledoc """ This module provides conveniences for analyzing fragments of textual code and extract available information whenever possible. Most of the functions in this module provide a best-effort and may not be accurate under all circumstances. Read each documentation for more information. This module should be considered experimental. """ @type position :: {line :: pos_integer(), column :: pos_integer()} @doc """ Receives a string and returns the cursor context. This function receives a string with an Elixir code fragment, representing a cursor position, and based on the string, it provides contextual information about said position. The return of this function can then be used to provide tips, suggestions, and autocompletion functionality. This function provides a best-effort detection and may not be accurate under all circumstances. See the "Limitations" section below. Consider adding a catch-all clause when handling the return type of this function as new cursor information may be added in future releases. ## Examples iex> Code.Fragment.cursor_context("") :expr iex> Code.Fragment.cursor_context("hello_wor") {:local_or_var, 'hello_wor'} ## Return values * `{:alias, charlist}` - the context is an alias, potentially a nested one, such as `Hello.Wor` or `HelloWor` * `{:dot, inside_dot, charlist}` - the context is a dot where `inside_dot` is either a `{:var, charlist}`, `{:alias, charlist}`, `{:module_attribute, charlist}`, `{:unquoted_atom, charlist}` or a `dot` itself. If a var is given, this may either be a remote call or a map field access. Examples are `Hello.wor`, `:hello.wor`, `hello.wor`, `Hello.nested.wor`, `hello.nested.wor`, and `@hello.world` * `{:dot_arity, inside_dot, charlist}` - the context is a dot arity where `inside_dot` is either a `{:var, charlist}`, `{:alias, charlist}`, `{:module_attribute, charlist}`, `{:unquoted_atom, charlist}` or a `dot` itself. If a var is given, it must be a remote arity. Examples are `Hello.world/`, `:hello.world/`, `hello.world/2`, and `@hello.world/2` * `{:dot_call, inside_dot, charlist}` - the context is a dot call. This means parentheses or space have been added after the expression. where `inside_dot` is either a `{:var, charlist}`, `{:alias, charlist}`, `{:module_attribute, charlist}`, `{:unquoted_atom, charlist}` or a `dot` itself. If a var is given, it must be a remote call. Examples are `Hello.world(`, `:hello.world(`, `Hello.world `, `hello.world(`, `hello.world `, and `@hello.world(` * `:expr` - may be any expression. Autocompletion may suggest an alias, local or var * `{:local_or_var, charlist}` - the context is a variable or a local (import or local) call, such as `hello_wor` * `{:local_arity, charlist}` - the context is a local (import or local) arity, such as `hello_world/` * `{:local_call, charlist}` - the context is a local (import or local) call, such as `hello_world(` and `hello_world ` * `{:module_attribute, charlist}` - the context is a module attribute, such as `@hello_wor` * `{:operator, charlist}` - the context is an operator, such as `+` or `==`. Note textual operators, such as `when` do not appear as operators but rather as `:local_or_var`. `@` is never an `:operator` and always a `:module_attribute` * `{:operator_arity, charlist}` - the context is an operator arity, which is an operator followed by /, such as `+/`, `not/` or `when/` * `{:operator_call, charlist}` - the context is an operator call, which is an operator followed by space, such as `left + `, `not ` or `x when ` * `:none` - no context possible * `{:sigil, charlist}` - the context is a sigil. It may be either the beginning of a sigil, such as `~` or `~s`, or an operator starting with `~`, such as `~>` and `~>>` * `{:struct, charlist}` - the context is a struct, such as `%`, `%UR` or `%URI` * `{:unquoted_atom, charlist}` - the context is an unquoted atom. This can be any atom or an atom representing a module ## Limitations The current algorithm only considers the last line of the input. This means it will also show suggestions inside strings, heredocs, etc, which is intentional as it helps with doctests, references, and more. """ @doc since: "1.13.0" @spec cursor_context(List.Chars.t(), keyword()) :: {:alias, charlist} | {:dot, inside_dot, charlist} | {:dot_arity, inside_dot, charlist} | {:dot_call, inside_dot, charlist} | :expr | {:local_or_var, charlist} | {:local_arity, charlist} | {:local_call, charlist} | {:module_attribute, charlist} | {:operator, charlist} | {:operator_arity, charlist} | {:operator_call, charlist} | :none | {:sigil, charlist} | {:struct, charlist} | {:unquoted_atom, charlist} when inside_dot: {:alias, charlist} | {:dot, inside_dot, charlist} | {:module_attribute, charlist} | {:unquoted_atom, charlist} | {:var, charlist} def cursor_context(fragment, opts \\ []) def cursor_context(binary, opts) when is_binary(binary) and is_list(opts) do binary = case :binary.matches(binary, "\n") do [] -> binary matches -> {position, _} = List.last(matches) binary_part(binary, position + 1, byte_size(binary) - position - 1) end binary |> String.to_charlist() |> :lists.reverse() |> codepoint_cursor_context(opts) |> elem(0) end def cursor_context(charlist, opts) when is_list(charlist) and is_list(opts) do charlist = case charlist |> Enum.chunk_by(&(&1 == ?\n)) |> List.last([]) do [?\n | _] -> [] rest -> rest end charlist |> :lists.reverse() |> codepoint_cursor_context(opts) |> elem(0) end def cursor_context(other, opts) when is_list(opts) do cursor_context(to_charlist(other), opts) end @operators '\\<>+-*/:=|&~^%!' @starter_punctuation ',([{;' @non_starter_punctuation ')]}"\'.$' @space '\t\s' @trailing_identifier '?!' @tilde_op_prefix '<=~' @non_identifier @trailing_identifier ++ @operators ++ @starter_punctuation ++ @non_starter_punctuation ++ @space @textual_operators ~w(when not and or in)c defp codepoint_cursor_context(reverse, _opts) do {stripped, spaces} = strip_spaces(reverse, 0) case stripped do # It is empty [] -> {:expr, 0} # Structs [?%, ?:, ?: | _] -> {{:struct, ''}, 1} [?%, ?: | _] -> {{:unquoted_atom, '%'}, 2} [?% | _] -> {{:struct, ''}, 1} # Token/AST only operators [?>, ?= | rest] when rest == [] or hd(rest) != ?: -> {:expr, 0} [?>, ?- | rest] when rest == [] or hd(rest) != ?: -> {:expr, 0} # Two-digit containers [?<, ?< | rest] when rest == [] or hd(rest) != ?< -> {:expr, 0} # Ambiguity around : [?: | rest] when rest == [] or hd(rest) != ?: -> unquoted_atom_or_expr(spaces) # Dots [?.] -> {:none, 0} [?. | rest] when hd(rest) not in '.:' -> dot(rest, spaces + 1, '') # It is a local or remote call with parens [?( | rest] -> call_to_cursor_context(strip_spaces(rest, spaces + 1)) # A local arity definition [?/ | rest] -> arity_to_cursor_context(strip_spaces(rest, spaces + 1)) # Starting a new expression [h | _] when h in @starter_punctuation -> {:expr, 0} # It is a local or remote call without parens rest when spaces > 0 -> call_to_cursor_context({rest, spaces}) # It is an identifier _ -> identifier_to_cursor_context(reverse, 0, false) end end defp strip_spaces([h | rest], count) when h in @space, do: strip_spaces(rest, count + 1) defp strip_spaces(rest, count), do: {rest, count} defp unquoted_atom_or_expr(0), do: {{:unquoted_atom, ''}, 1} defp unquoted_atom_or_expr(_), do: {:expr, 0} defp arity_to_cursor_context({reverse, spaces}) do case identifier_to_cursor_context(reverse, spaces, true) do {{:local_or_var, acc}, count} -> {{:local_arity, acc}, count} {{:dot, base, acc}, count} -> {{:dot_arity, base, acc}, count} {{:operator, acc}, count} -> {{:operator_arity, acc}, count} {_, _} -> {:none, 0} end end defp call_to_cursor_context({reverse, spaces}) do case identifier_to_cursor_context(reverse, spaces, true) do {{:local_or_var, acc}, count} -> {{:local_call, acc}, count} {{:dot, base, acc}, count} -> {{:dot_call, base, acc}, count} {{:operator, acc}, count} -> {{:operator_call, acc}, count} {_, _} -> {:none, 0} end end defp identifier_to_cursor_context([?., ?., ?: | _], n, _), do: {{:unquoted_atom, '..'}, n + 3} defp identifier_to_cursor_context([?., ?., ?. | _], n, _), do: {{:local_or_var, '...'}, n + 3} defp identifier_to_cursor_context([?., ?: | _], n, _), do: {{:unquoted_atom, '.'}, n + 2} defp identifier_to_cursor_context([?., ?. | _], n, _), do: {{:operator, '..'}, n + 2} defp identifier_to_cursor_context(reverse, count, call_op?) do case identifier(reverse, count) do :none -> {:none, 0} :operator -> operator(reverse, count, [], call_op?) {:module_attribute, acc, count} -> {{:module_attribute, acc}, count} {:sigil, acc, count} -> {{:sigil, acc}, count} {:unquoted_atom, acc, count} -> {{:unquoted_atom, acc}, count} {:alias, rest, acc, count} -> case strip_spaces(rest, count) do {'.' ++ rest, count} when rest == [] or hd(rest) != ?. -> nested_alias(rest, count + 1, acc) {'%' ++ _, count} -> {{:struct, acc}, count + 1} _ -> {{:alias, acc}, count} end {:identifier, _, acc, count} when call_op? and acc in @textual_operators -> {{:operator, acc}, count} {:identifier, rest, acc, count} -> case strip_spaces(rest, count) do {'.' ++ rest, count} when rest == [] or hd(rest) != ?. -> dot(rest, count + 1, acc) _ -> {{:local_or_var, acc}, count} end end end defp identifier([?? | rest], count), do: check_identifier(rest, count + 1, [??]) defp identifier([?! | rest], count), do: check_identifier(rest, count + 1, [?!]) defp identifier(rest, count), do: check_identifier(rest, count, []) defp check_identifier([h | t], count, acc) when h not in @non_identifier, do: rest_identifier(t, count + 1, [h | acc]) defp check_identifier(_, _, _), do: :operator defp rest_identifier([h | rest], count, acc) when h not in @non_identifier do rest_identifier(rest, count + 1, [h | acc]) end defp rest_identifier(rest, count, [?@ | acc]) do case tokenize_identifier(rest, count, acc) do {:identifier, _rest, acc, count} -> {:module_attribute, acc, count} :none when acc == [] -> {:module_attribute, '', count} _ -> :none end end defp rest_identifier([?~ | rest], count, [letter]) when (letter in ?A..?Z or letter in ?a..?z) and (rest == [] or hd(rest) not in @tilde_op_prefix) do {:sigil, [letter], count + 1} end defp rest_identifier([?: | rest], count, acc) when rest == [] or hd(rest) != ?: do case String.Tokenizer.tokenize(acc) do {_, _, [], _, _, _} -> {:unquoted_atom, acc, count + 1} _ -> :none end end defp rest_identifier([?? | _], _count, _acc) do :none end defp rest_identifier(rest, count, acc) do tokenize_identifier(rest, count, acc) end defp tokenize_identifier(rest, count, acc) do case String.Tokenizer.tokenize(acc) do # Not actually an atom cause rest is not a : {:atom, _, _, _, _, _} -> :none # Aliases must be ascii only {:alias, _, _, _, false, _} -> :none {kind, _, [], _, _, extra} -> if :at in extra do :none else {kind, rest, acc, count} end _ -> :none end end defp nested_alias(rest, count, acc) do {rest, count} = strip_spaces(rest, count) case identifier_to_cursor_context(rest, count, true) do {{:struct, prev}, count} -> {{:struct, prev ++ '.' ++ acc}, count} {{:alias, prev}, count} -> {{:alias, prev ++ '.' ++ acc}, count} _ -> {:none, 0} end end defp dot(rest, count, acc) do {rest, count} = strip_spaces(rest, count) case identifier_to_cursor_context(rest, count, true) do {{:local_or_var, var}, count} -> {{:dot, {:var, var}, acc}, count} {{:unquoted_atom, _} = prev, count} -> {{:dot, prev, acc}, count} {{:alias, _} = prev, count} -> {{:dot, prev, acc}, count} {{:dot, _, _} = prev, count} -> {{:dot, prev, acc}, count} {{:module_attribute, _} = prev, count} -> {{:dot, prev, acc}, count} {{:struct, acc}, count} -> {{:struct, acc ++ '.'}, count} {_, _} -> {:none, 0} end end defp operator([h | rest], count, acc, call_op?) when h in @operators do operator(rest, count + 1, [h | acc], call_op?) end # If we are opening a sigil, ignore the operator. defp operator([letter, ?~ | rest], _count, [op], _call_op?) when op in '<|/' and (letter in ?A..?Z or letter in ?a..?z) and (rest == [] or hd(rest) not in @tilde_op_prefix) do {:none, 0} end defp operator(rest, count, '~', call_op?) do {rest, _} = strip_spaces(rest, count) if call_op? or match?([?. | rest] when rest == [] or hd(rest) != ?., rest) do {:none, 0} else {{:sigil, ''}, count} end end defp operator(rest, count, acc, _call_op?) do case :elixir_tokenizer.tokenize(acc, 1, 1, []) do {:ok, _, _, _, [{:atom, _, _}]} -> {{:unquoted_atom, tl(acc)}, count} {:ok, _, _, _, [{_, _, op}]} -> {rest, dot_count} = strip_spaces(rest, count) cond do Code.Identifier.unary_op(op) == :error and Code.Identifier.binary_op(op) == :error -> :none match?([?. | rest] when rest == [] or hd(rest) != ?., rest) -> dot(tl(rest), dot_count + 1, acc) true -> {{:operator, acc}, count} end _ -> {:none, 0} end end @doc """ Receives a string and returns the surround context. This function receives a string with an Elixir code fragment and a `position`. It returns a map containing the beginning and ending of the identifier alongside its context, or `:none` if there is nothing with a known context. The difference between `cursor_context/2` and `surround_context/3` is that the former assumes the expression in the code fragment is incomplete. For example, `do` in `cursor_context/2` may be a keyword or a variable or a local call, while `surround_context/3` assumes the expression in the code fragment is complete, therefore `do` would always be a keyword. The `position` contains both the `line` and `column`, both starting with the index of 1. The column must precede the surrounding expression. For example, the expression `foo`, will return something for the columns 1, 2, and 3, but not 4: foo ^ column 1 foo ^ column 2 foo ^ column 3 foo ^ column 4 The returned map contains the column the expression starts and the first column after the expression ends. Similar to `cursor_context/2`, this function also provides a best-effort detection and may not be accurate under all circumstances. See the "Return values" and "Limitations" section under `cursor_context/2` for more information. ## Examples iex> Code.Fragment.surround_context("foo", {1, 1}) %{begin: {1, 1}, context: {:local_or_var, 'foo'}, end: {1, 4}} ## Differences to `cursor_context/2` Because `surround_context/3` deals with complete code, it has some difference to `cursor_context/2`: * `dot_call`/`dot_arity` and `operator_call`/`operator_arity` are collapsed into `dot` and `operator` contexts respectively as there aren't any meaningful distinctions between them * On the other hand, this function still makes a distinction between `local_call`/`local_arity` and `local_or_var`, since the latter can be a local or variable * `@` when not followed by any identifier is returned as `{:operator, '@'}` (in contrast to `{:module_attribute, ''}` in `cursor_context/2` * This function never returns empty sigils `{:sigil, ''}` or empty structs `{:struct, ''}` as context * This function never returns `:expr` """ @doc since: "1.13.0" @spec surround_context(List.Chars.t(), position(), keyword()) :: %{begin: position, end: position, context: context} | :none when context: {:alias, charlist} | {:dot, inside_dot, charlist} | {:local_or_var, charlist} | {:local_arity, charlist} | {:local_call, charlist} | {:module_attribute, charlist} | {:operator, charlist} | {:sigil, charlist} | {:struct, charlist} | {:unquoted_atom, charlist}, inside_dot: {:alias, charlist} | {:dot, inside_dot, charlist} | {:module_attribute, charlist} | {:unquoted_atom, charlist} | {:var, charlist} def surround_context(fragment, position, options \\ []) def surround_context(binary, {line, column}, opts) when is_binary(binary) do binary |> String.split("\n") |> Enum.at(line - 1, '') |> String.to_charlist() |> position_surround_context(line, column, opts) end def surround_context(charlist, {line, column}, opts) when is_list(charlist) do charlist |> :string.split('\n', :all) |> Enum.at(line - 1, '') |> position_surround_context(line, column, opts) end def surround_context(other, {_, _} = position, opts) do surround_context(to_charlist(other), position, opts) end defp position_surround_context(charlist, line, column, opts) when is_integer(line) and line >= 1 and is_integer(column) and column >= 1 do {reversed_pre, post} = string_reverse_at(charlist, column - 1, []) {reversed_pre, post} = adjust_position(reversed_pre, post) case take_identifier(post, []) do {_, [], _} -> maybe_operator(reversed_pre, post, line, opts) {:identifier, reversed_post, rest} -> {rest, _} = strip_spaces(rest, 0) reversed = reversed_post ++ reversed_pre case codepoint_cursor_context(reversed, opts) do {{:struct, acc}, offset} -> build_surround({:struct, acc}, reversed, line, offset) {{:alias, acc}, offset} -> build_surround({:alias, acc}, reversed, line, offset) {{:dot, _, [_ | _]} = dot, offset} -> build_surround(dot, reversed, line, offset) {{:local_or_var, acc}, offset} when hd(rest) == ?( -> build_surround({:local_call, acc}, reversed, line, offset) {{:local_or_var, acc}, offset} when hd(rest) == ?/ -> build_surround({:local_arity, acc}, reversed, line, offset) {{:local_or_var, acc}, offset} when acc in @textual_operators -> build_surround({:operator, acc}, reversed, line, offset) {{:local_or_var, acc}, offset} when acc not in ~w(do end after else catch rescue)c -> build_surround({:local_or_var, acc}, reversed, line, offset) {{:module_attribute, ''}, offset} -> build_surround({:operator, '@'}, reversed, line, offset) {{:module_attribute, acc}, offset} -> build_surround({:module_attribute, acc}, reversed, line, offset) {{:sigil, acc}, offset} -> build_surround({:sigil, acc}, reversed, line, offset) {{:unquoted_atom, acc}, offset} -> build_surround({:unquoted_atom, acc}, reversed, line, offset) _ -> maybe_operator(reversed_pre, post, line, opts) end {:alias, reversed_post, _rest} -> reversed = reversed_post ++ reversed_pre case codepoint_cursor_context(reversed, opts) do {{:alias, acc}, offset} -> build_surround({:alias, acc}, reversed, line, offset) {{:struct, acc}, offset} -> build_surround({:struct, acc}, reversed, line, offset) _ -> :none end end end defp maybe_operator(reversed_pre, post, line, opts) do case take_operator(post, []) do {[], _rest} -> :none {reversed_post, rest} -> reversed = reversed_post ++ reversed_pre case codepoint_cursor_context(reversed, opts) do {{:operator, acc}, offset} -> build_surround({:operator, acc}, reversed, line, offset) {{:sigil, ''}, offset} when hd(rest) in ?A..?Z or hd(rest) in ?a..?z -> build_surround({:sigil, [hd(rest)]}, [hd(rest) | reversed], line, offset + 1) {{:dot, _, [_ | _]} = dot, offset} -> build_surround(dot, reversed, line, offset) _ -> :none end end end defp build_surround(context, reversed, line, offset) do {post, reversed_pre} = enum_reverse_at(reversed, offset, []) pre = :lists.reverse(reversed_pre) pre_length = :string.length(pre) + 1 %{ context: context, begin: {line, pre_length}, end: {line, pre_length + :string.length(post)} } end defp take_identifier([h | t], acc) when h in @trailing_identifier, do: {:identifier, [h | acc], t} defp take_identifier([h | t], acc) when h not in @non_identifier, do: take_identifier(t, [h | acc]) defp take_identifier(rest, acc) do with {[?. | t], _} <- strip_spaces(rest, 0), {[h | _], _} when h in ?A..?Z <- strip_spaces(t, 0) do take_alias(rest, acc) else _ -> {:identifier, acc, rest} end end defp take_alias([h | t], acc) when h not in @non_identifier, do: take_alias(t, [h | acc]) defp take_alias(rest, acc) do with {[?. | t], acc} <- move_spaces(rest, acc), {[h | t], acc} when h in ?A..?Z <- move_spaces(t, [?. | acc]) do take_alias(t, [h | acc]) else _ -> {:alias, acc, rest} end end defp take_operator([h | t], acc) when h in @operators, do: take_operator(t, [h | acc]) defp take_operator([h | t], acc) when h == ?., do: take_operator(t, [h | acc]) defp take_operator(rest, acc), do: {acc, rest} # Unquoted atom handling defp adjust_position(reversed_pre, [?: | post]) when hd(post) != ?: and (reversed_pre == [] or hd(reversed_pre) != ?:) do {[?: | reversed_pre], post} end defp adjust_position(reversed_pre, [?% | post]) do adjust_position([?% | reversed_pre], post) end # Dot/struct handling defp adjust_position(reversed_pre, post) do case move_spaces(post, reversed_pre) do # If we are between spaces and a dot, move past the dot {[?. | post], reversed_pre} when hd(post) != ?. and hd(reversed_pre) != ?. -> {post, reversed_pre} = move_spaces(post, [?. | reversed_pre]) {reversed_pre, post} _ -> case strip_spaces(reversed_pre, 0) do # If there is a dot to our left, make sure to move to the first character {[?. | rest], _} when rest == [] or hd(rest) not in '.:' -> {post, reversed_pre} = move_spaces(post, reversed_pre) {reversed_pre, post} # If there is a % to our left, make sure to move to the first character {[?% | _], _} -> case move_spaces(post, reversed_pre) do {[h | _] = post, reversed_pre} when h in ?A..?Z -> {reversed_pre, post} _ -> {reversed_pre, post} end _ -> {reversed_pre, post} end end end defp move_spaces([h | t], acc) when h in @space, do: move_spaces(t, [h | acc]) defp move_spaces(t, acc), do: {t, acc} defp string_reverse_at(charlist, 0, acc), do: {acc, charlist} defp string_reverse_at(charlist, n, acc) do case :unicode_util.gc(charlist) do [gc | cont] when is_integer(gc) -> string_reverse_at(cont, n - 1, [gc | acc]) [gc | cont] when is_list(gc) -> string_reverse_at(cont, n - 1, :lists.reverse(gc, acc)) [] -> {acc, []} end end defp enum_reverse_at([h | t], n, acc) when n > 0, do: enum_reverse_at(t, n - 1, [h | acc]) defp enum_reverse_at(rest, _, acc), do: {acc, rest} @doc """ Receives a code fragment and returns a quoted expression with a cursor at the nearest argument position. A container is any Elixir expression starting with `(`, `{`, and `[`. This includes function calls, tuples, lists, maps, and so on. For example, take this code, which would be given as input: max(some_value, This function will return the AST equivalent to: max(some_value, __cursor__()) In other words, this function is capable of closing any open brackets and insert the cursor position. Any content at the cursor position that is after a comma or an opening bracket is discarded. For example, if this is given as input: max(some_value, another_val It will return the same AST: max(some_value, __cursor__()) Similarly, if only this is given: max(some_va Then it returns: max(__cursor__()) Calls without parenthesis are also supported, as we assume the brackets are implicit. Operators and anonymous functions are not containers, and therefore will be discarded. The following will all return the same AST: max(some_value, max(some_value, fn x -> x end max(some_value, 1 + another_val max(some_value, 1 |> some_fun() |> another_fun On the other hand, tuples, lists, maps, etc all retain the cursor position: max(some_value, [1, 2, Returns the following AST: max(some_value, [1, 2, __cursor__()]) Keyword lists (and do-end blocks) are also retained. The following: if(some_value, do: if(some_value, do: :token if(some_value, do: 1 + val all return: if(some_value, do: __cursor__()) The AST returned by this function is not safe to evaluate but it can be analyzed and expanded. ## Examples iex> Code.Fragment.container_cursor_to_quoted("max(some_value, ") {:ok, {:max, [line: 1], [{:some_value, [line: 1], nil}, {:__cursor__, [line: 1], []}]}} ## Options * `:file` - the filename to be reported in case of parsing errors. Defaults to `"nofile"`. * `:line` - the starting line of the string being parsed. Defaults to 1. * `:column` - the starting column of the string being parsed. Defaults to 1. * `:columns` - when `true`, attach a `:column` key to the quoted metadata. Defaults to `false`. * `:token_metadata` - when `true`, includes token-related metadata in the expression AST, such as metadata for `do` and `end` tokens, for closing tokens, end of expressions, as well as delimiters for sigils. See `t:Macro.metadata/0`. Defaults to `false`. """ @doc since: "1.13.0" @spec container_cursor_to_quoted(List.Chars.t(), keyword()) :: {:ok, Macro.t()} | {:error, {location :: keyword, binary | {binary, binary}, binary}} def container_cursor_to_quoted(fragment, opts \\ []) do file = Keyword.get(opts, :file, "nofile") line = Keyword.get(opts, :line, 1) column = Keyword.get(opts, :column, 1) columns = Keyword.get(opts, :columns, false) token_metadata = Keyword.get(opts, :token_metadata, false) Code.string_to_quoted(fragment, file: file, line: line, column: column, columns: columns, token_metadata: token_metadata, cursor_completion: true, emit_warnings: false ) end end
34.024038
96
0.600042
ff7c5ba4d9c4e2d8f6ff34f7619d6786ff636f31
867
ex
Elixir
web/workflows/move_back_to_cart_state.ex
harry-gao/ex-cart
573e7f977bb3b710d11618dd215d4ddd8f819fb3
[ "Apache-2.0" ]
356
2016-03-16T12:37:28.000Z
2021-12-18T03:22:39.000Z
web/workflows/move_back_to_cart_state.ex
harry-gao/ex-cart
573e7f977bb3b710d11618dd215d4ddd8f819fb3
[ "Apache-2.0" ]
30
2016-03-16T09:19:10.000Z
2021-01-12T08:10:52.000Z
web/workflows/move_back_to_cart_state.ex
harry-gao/ex-cart
573e7f977bb3b710d11618dd215d4ddd8f819fb3
[ "Apache-2.0" ]
72
2016-03-16T13:32:14.000Z
2021-03-23T11:27:43.000Z
defmodule Nectar.Workflow.MoveBackToCartState do alias Ecto.Multi def run(repo, order), do: repo.transaction(steps(order)) def steps(order) do Multi.new() |> Multi.delete_all(:delete_payment, Nectar.Query.Payment.for_order(order)) |> Multi.delete_all(:delete_tax_adjustments, Nectar.Query.Adjustment.tax_adjustments_for_order(order)) |> Multi.delete_all(:delete_shipment_adjustments, Nectar.Query.Adjustment.shipment_adjustments_for_order(order)) |> Multi.delete_all(:delete_shipment_units, Nectar.Query.ShipmentUnit.for_order(order)) |> Multi.delete_all(:delete_shipping_address, Nectar.Query.OrderShippingAddress.for_order(order)) |> Multi.delete_all(:delete_billing_address, Nectar.Query.OrderBillingAddress.for_order(order)) |> Multi.update(:update_state, Nectar.Order.state_changeset(order, %{state: "cart"})) end end
45.631579
116
0.7797
ff7c634ce438a88d770b97748c5652195d61e524
848
ex
Elixir
apps/snitch_core/lib/core/data/model/state.ex
gridgentoo/avia
139b68f4b3ccd830c4db296d81132680e253b731
[ "MIT" ]
null
null
null
apps/snitch_core/lib/core/data/model/state.ex
gridgentoo/avia
139b68f4b3ccd830c4db296d81132680e253b731
[ "MIT" ]
null
null
null
apps/snitch_core/lib/core/data/model/state.ex
gridgentoo/avia
139b68f4b3ccd830c4db296d81132680e253b731
[ "MIT" ]
null
null
null
defmodule Snitch.Data.Model.State do @moduledoc """ State CRUD and helpers """ use Snitch.Data.Model alias Snitch.Data.Schema.State @spec get(map | non_neg_integer) :: State.t() | nil def get(query_fields_or_primary_key) do QH.get(State, query_fields_or_primary_key, Repo) end @spec get_all() :: [State.t()] def get_all() do Repo.all(State) end @spec formatted_list() :: [{String.t(), non_neg_integer}] def formatted_list do State |> order_by([s], asc: s.name) |> select([s], {s.name, s.id}) |> Repo.all() end @spec formatted_state_list(integer) :: [{String.t(), non_neg_integer}] def formatted_state_list(country_id) do State |> where([s], s.country_id == ^country_id) |> order_by([s], asc: s.name) |> select([s], %{text: s.name, id: s.id}) |> Repo.all() end end
22.918919
72
0.633255
ff7c662fcb04587d4ebbcbbb7c9f4ac5eb8f62f0
448
ex
Elixir
lib/cayenne/lpp/type/temperature.ex
janpieper/cayenne_lpp
432003d00553cc05a4faa80dddaa2429e2cf5b6b
[ "MIT" ]
1
2020-08-24T08:14:09.000Z
2020-08-24T08:14:09.000Z
lib/cayenne/lpp/type/temperature.ex
janpieper/cayenne_lpp
432003d00553cc05a4faa80dddaa2429e2cf5b6b
[ "MIT" ]
null
null
null
lib/cayenne/lpp/type/temperature.ex
janpieper/cayenne_lpp
432003d00553cc05a4faa80dddaa2429e2cf5b6b
[ "MIT" ]
null
null
null
defmodule Cayenne.LPP.Type.Temperature do @moduledoc """ Cayenne LPP type for temperature ### Example ```elixir alias Cayenne.LPP.{Buffer, Encoder} alias Cayenne.LPP.Type.Temperature buffer = 28.3 |> Temperature.new() |> Encoder.encode(temperature) Buffer.to_string(buffer) # "67011B" Buffer.size(buffer) # 3 ``` """ use Cayenne.LPP.Type, id: 0x67, size: 2, multiplier: 10, signed: true end
16.592593
41
0.642857
ff7ca46ab3b526c63502c430a0a905e078bcf25f
101
ex
Elixir
test/examples/contract_supertype.ex
staring-frog/dialyxir
b78735f75b325238b7db20d9eed22f018cca5f26
[ "Apache-2.0" ]
1,455
2015-01-03T02:53:19.000Z
2022-03-12T00:31:25.000Z
test/examples/contract_supertype.ex
staring-frog/dialyxir
b78735f75b325238b7db20d9eed22f018cca5f26
[ "Apache-2.0" ]
330
2015-05-14T13:53:13.000Z
2022-03-29T17:12:23.000Z
test/examples/contract_supertype.ex
staring-frog/dialyxir
b78735f75b325238b7db20d9eed22f018cca5f26
[ "Apache-2.0" ]
146
2015-02-03T18:19:43.000Z
2022-03-07T10:05:20.000Z
defmodule Dialyxir.Examples.ContractSuperType do @spec ok() :: any def ok() do :ok end end
14.428571
48
0.673267
ff7cb92788f1c05d3fb38c280d4cf1ccb5df306a
1,651
ex
Elixir
lib/mix/tasks/routes.ex
davidenko87/maru
62b6ca0e42dd550683af8743f50e67048c4027d0
[ "BSD-3-Clause" ]
819
2016-11-25T07:12:04.000Z
2022-03-16T06:59:36.000Z
lib/mix/tasks/routes.ex
davidenko87/maru
62b6ca0e42dd550683af8743f50e67048c4027d0
[ "BSD-3-Clause" ]
71
2016-11-24T20:19:09.000Z
2021-06-09T10:12:23.000Z
lib/mix/tasks/routes.ex
davidenko87/maru
62b6ca0e42dd550683af8743f50e67048c4027d0
[ "BSD-3-Clause" ]
56
2015-01-10T23:34:12.000Z
2016-11-17T00:13:56.000Z
defmodule Mix.Tasks.Maru.Routes do @moduledoc """ Print routes for a `Maru.Router` module. $ mix maru.routes $ mix maru.routes MyApp.API """ use Mix.Task def run(args) do unless System.get_env("MIX_ENV") do Mix.env(:dev) end Mix.Task.run("compile", args) cond do module = List.first(args) -> Module.concat("Elixir", module) |> generate_module([]) (servers = Mix.Maru.servers()) != [] -> for module <- servers do generate_module(module.__plug__, []) end true -> nil end end defp generate_module(module, prefix) do config = (Application.get_env(:maru, module) || [])[:versioning] || [] adapter = Maru.Builder.Versioning.get_adapter(config[:using]) module.__routes__ |> Enum.sort_by(fn route -> route.version end) |> Enum.map(&generate_route(&1, adapter, prefix)) |> Enum.map(&IO.puts/1) end defp generate_route(route, adapter, prefix) do path = adapter.path_for_params(route.path, route.version) format_version(route.version) <> format_method(route.method) <> format_path(prefix ++ path) <> " " <> (route.desc[:summary] || "") end defp format_version(nil), do: "nil" |> format_version defp format_version(version) do version |> String.pad_trailing(5) end defp format_method(method) do method |> to_string() |> String.upcase() |> String.pad_trailing(7) end defp format_path([]), do: "/" defp format_path(p) do func = fn i when is_atom(i) -> ":#{i}" i -> i end ["" | p] |> Enum.map(func) |> Enum.join("/") end end
22.013333
74
0.601454
ff7ce5240cf57e9ed9c2f197ce3741abfaba37ae
990
ex
Elixir
lib/mix/tasks/compile.phoenix.ex
bhicks/phoenix
2c43d798c184f6085cd2765d6cb2b463c87edac7
[ "MIT" ]
null
null
null
lib/mix/tasks/compile.phoenix.ex
bhicks/phoenix
2c43d798c184f6085cd2765d6cb2b463c87edac7
[ "MIT" ]
1
2021-11-17T12:10:06.000Z
2021-11-24T12:53:45.000Z
lib/mix/tasks/compile.phoenix.ex
bhicks/phoenix
2c43d798c184f6085cd2765d6cb2b463c87edac7
[ "MIT" ]
null
null
null
defmodule Mix.Tasks.Compile.Phoenix do use Mix.Task @recursive true @moduledoc """ Compiles Phoenix source files that support code reloading. """ @doc false def run(_args) do {:ok, _} = Application.ensure_all_started(:phoenix) case touch() do [] -> {:noop, []} _ -> {:ok, []} end end @doc false def touch do Mix.Phoenix.modules |> modules_for_recompilation |> modules_to_file_paths |> Stream.map(&touch_if_exists(&1)) |> Stream.filter(&(&1 == :ok)) |> Enum.to_list() end defp touch_if_exists(path) do :file.change_time(path, :calendar.local_time()) end defp modules_for_recompilation(modules) do Stream.filter modules, fn mod -> Code.ensure_loaded?(mod) and function_exported?(mod, :__phoenix_recompile__?, 0) and mod.__phoenix_recompile__? end end defp modules_to_file_paths(modules) do Stream.map(modules, fn mod -> mod.__info__(:compile)[:source] end) end end
22.5
70
0.653535
ff7cfb5c928334efb3bd53dd16c9d5a2750bc039
1,985
exs
Elixir
src/033/problem033.exs
fredericojordan/project-euler
75c3f519d5a6ad610362b6904f8fa4d1cde05448
[ "MIT" ]
9
2018-05-06T04:43:08.000Z
2020-12-01T20:51:34.000Z
src/033/problem033.exs
fredericojordan/project-euler
75c3f519d5a6ad610362b6904f8fa4d1cde05448
[ "MIT" ]
null
null
null
src/033/problem033.exs
fredericojordan/project-euler
75c3f519d5a6ad610362b6904f8fa4d1cde05448
[ "MIT" ]
null
null
null
#!/usr/bin/env elixir defmodule Problem033 do @moduledoc """ The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. We shall consider fractions like, 30/50 = 3/5, to be trivial examples. There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator. If the product of these four fractions is given in its lowest common terms, find the value of the denominator. """ @empty MapSet.new defp empty?(some_map_set) when some_map_set == @empty, do: true defp empty?(%MapSet{}), do: false defp has_same_digit?([num, den]), do: !empty?(MapSet.intersection(MapSet.new(Integer.digits(num)), MapSet.new(Integer.digits(den)))) defp matching_sub_unit_fractions do for den <- 10..99, num <- 10..den-1, has_same_digit?([num, den]) do [num, den] end end defp equals_cancelled?([num, den]) do culprit = MapSet.intersection(MapSet.new(Integer.digits(num)), MapSet.new(Integer.digits(den))) n = Integer.digits(num) |> MapSet.new() |> MapSet.difference(culprit) |> MapSet.to_list() |> List.first() d = Integer.digits(den) |> MapSet.new() |> MapSet.difference(culprit) |> MapSet.to_list() |> List.first() case [n,d] do [_,0] -> false [_,nil] -> false [nil,_] -> false _ -> num/den == n/d end end defp simplify_fraction([num,den]), do: div(den, num) # FIXME: Lazy "hack" def solve do matching_sub_unit_fractions() |> Stream.filter(&equals_cancelled?/1) |> Stream.filter(&(rem(List.first(&1), 10) != 0)) # Removes trivial examples (e.g. 10/20) |> Enum.reduce(&([List.first(&1)*List.first(&2), List.last(&1)*List.last(&2)])) |> simplify_fraction() end end IO.puts Problem033.solve
37.45283
201
0.653904
ff7d06336fd2f9bc161db5434e52d7d8cc72656c
9,411
ex
Elixir
lib/bamboo/phoenix.ex
ymtszw/bamboo
8c5780319c5e2c936d04a2e1d9594be20a525c9b
[ "MIT" ]
null
null
null
lib/bamboo/phoenix.ex
ymtszw/bamboo
8c5780319c5e2c936d04a2e1d9594be20a525c9b
[ "MIT" ]
1
2021-02-23T18:44:13.000Z
2021-02-23T18:44:13.000Z
lib/bamboo/phoenix.ex
ymtszw/bamboo
8c5780319c5e2c936d04a2e1d9594be20a525c9b
[ "MIT" ]
null
null
null
defmodule Bamboo.Phoenix do @moduledoc """ Render emails with Phoenix templates and layouts. This module allows rendering emails with Phoenix layouts and views. Pass an atom (e.g. `:welcome_email`) as the template name to render both HTML and plain text emails. Use a string if you only want to render one type, e.g. `"welcome_email.text"` or `"welcome_email.html"`. ## Examples _Set the text and HTML layout for an email._ defmodule MyApp.Email do use Bamboo.Phoenix, view: MyApp.EmailView def welcome_email do new_email() |> put_text_layout({MyApp.LayoutView, "email.text"}) |> put_html_layout({MyApp.LayoutView, "email.html"}) |> render(:welcome) # Pass atom to render html AND plain text templates end end _Set both the text and HTML layout at the same time for an email._ defmodule MyApp.Email do use Bamboo.Phoenix, view: MyApp.EmailView def welcome_email do new_email() |> put_layout({MyApp.LayoutView, :email}) |> render(:welcome) end end _Render both text and html emails without layouts._ defmodule MyApp.Email do use Bamboo.Phoenix, view: MyApp.EmailView def welcome_email do new_email() |> render(:welcome) end end _Make assigns available to a template._ defmodule MyApp.Email do use Bamboo.Phoenix, view: MyApp.EmailView def welcome_email(user) do new_email() |> assign(:user, user) |> render(:welcome) end end _Make assigns available to a template during render call._ defmodule MyApp.Email do use Bamboo.Phoenix, view: MyApp.EmailView def welcome_email(user) do new_email() |> put_html_layout({MyApp.LayoutView, "email.html"}) |> render(:welcome, user: user) end end _Render an email by passing the template string to render._ defmodule MyApp.Email do use Bamboo.Phoenix, view: MyApp.EmailView def html_email do new_email |> render("html_email.html") end def text_email do new_email |> render("text_email.text") end end ## HTML Layout Example # web/email.ex defmodule Myapp.Email do use Bamboo.Phoenix, view: Myapp.EmailView def sign_in_email(person) do base_email() |> to(person) |> subject("Your Sign In Link") |> assign(:person, person) |> render(:sign_in) end defp base_email do new_email |> from("Rob Ot<robot@changelog.com>") |> put_header("Reply-To", "editors@changelog.com") # This will use the "email.html.eex" file as a layout when rendering html emails. # Plain text emails will not use a layout unless you use `put_text_layout` |> put_html_layout({Myapp.LayoutView, "email.html"}) end end # web/views/email_view.ex defmodule Myapp.EmailView do use Myapp.Web, :view end # web/templates/layout/email.html.eex <html> <head> <link rel="stylesheet" href="<%= static_url(Myapp.Endpoint, "/css/email.css") %>"> </head> <body> <%= render @view_module, @view_template, assigns %> </body> </html> # web/templates/email/sign_in.html.eex <p><%= link "Sign In", to: sign_in_url(Myapp.Endpoint, :create, @person) %></p> # web/templates/email/sign_in.text.eex # This will not be rendered within a layout because `put_text_layout` was not used. Sign In: <%= sign_in_url(Myapp.Endpoint, :create, @person) %> """ import Bamboo.Email, only: [put_private: 3] defmacro __using__(view: view_module) do verify_phoenix_dep() quote do import Bamboo.Email import Bamboo.Phoenix, except: [render: 3] @doc """ Render an Phoenix template and set the body on the email. Pass an atom as the template name (:welcome_email) to render HTML *and* plain text emails. Use a string if you only want to render one type, e.g. "welcome_email.text" or "welcome_email.html". Scroll to the top for more examples. """ def render(email, template, assigns \\ []) do Bamboo.Phoenix.render_email(unquote(view_module), email, template, assigns) end end end defmacro __using__(opts) do raise ArgumentError, """ expected Bamboo.Phoenix to have a view set, instead got: #{inspect(opts)}. Please set a view e.g. use Bamboo.Phoenix, view: MyApp.MyView """ end defp verify_phoenix_dep do unless Code.ensure_loaded?(Phoenix) do raise "You tried to use Bamboo.Phoenix, but Phoenix module is not loaded. " <> "Please add phoenix to your dependencies." end end @doc """ Render a Phoenix template and set the body on the email. Pass an atom as the template name to render HTML *and* plain text emails, e.g. `:welcome_email`. Use a string if you only want to render one type, e.g. `"welcome_email.text"` or `"welcome_email.html"`. Scroll to the top for more examples. """ def render(_email, _template_name, _assigns) do raise "function implemented for documentation only, please call: use Bamboo.Phoenix" end @doc """ Sets the layout when rendering HTML templates. ## Example def html_email_layout do new_email # Will use MyApp.LayoutView with email.html template when rendering html emails |> put_html_layout({MyApp.LayoutView, "email.html"}) end """ def put_html_layout(email, layout) do email |> put_private(:html_layout, layout) end @doc """ Sets the layout when rendering plain text templates. ## Example def text_email_layout do new_email # Will use MyApp.LayoutView with email.text template when rendering text emails |> put_text_layout({MyApp.LayoutView, "email.text"}) end """ def put_text_layout(email, layout) do email |> put_private(:text_layout, layout) end @doc """ Sets the layout for rendering plain text and HTML templates. ## Example def text_and_html_email_layout do new_email # Will use MyApp.LayoutView with the email.html template for html emails # and MyApp.LayoutView with the email.text template for text emails |> put_layout({MyApp.LayoutView, :email}) end """ def put_layout(email, {layout, template}) do email |> put_text_layout({layout, to_string(template) <> ".text"}) |> put_html_layout({layout, to_string(template) <> ".html"}) end @doc """ Sets an assign for the email. These will be available when rendering the email """ def assign(%{assigns: assigns} = email, key, value) do %{email | assigns: Map.put(assigns, key, value)} end @doc false def render_email(view, email, template, assigns) do email |> put_default_layouts |> merge_assigns(assigns) |> put_view(view) |> put_template(template) |> render end defp put_default_layouts(%{private: private} = email) do private = private |> Map.put_new(:html_layout, false) |> Map.put_new(:text_layout, false) %{email | private: private} end defp merge_assigns(%{assigns: email_assigns} = email, assigns) do assigns = email_assigns |> Map.merge(Enum.into(assigns, %{})) email |> Map.put(:assigns, assigns) end defp put_view(email, view_module) do email |> put_private(:view_module, view_module) end defp put_template(email, view_template) do email |> put_private(:view_template, view_template) end defp render(%{private: %{view_template: template}} = email) when is_atom(template) do render_html_and_text_emails(email) end defp render(email) do render_text_or_html_email(email) end defp render_html_and_text_emails(email) do view_template = Atom.to_string(email.private.view_template) email |> Map.put(:html_body, render_html(email, view_template <> ".html")) |> Map.put(:text_body, render_text(email, view_template <> ".text")) end defp render_text_or_html_email(email) do template = email.private.view_template cond do String.ends_with?(template, ".html") -> email |> Map.put(:html_body, render_html(email, template)) String.ends_with?(template, ".text") -> email |> Map.put(:text_body, render_text(email, template)) true -> raise ArgumentError, """ Template name must end in either ".html" or ".text". Template name was #{ inspect(template) } If you would like to render both and html and text template, use an atom without an extension instead. """ end end defp render_html(email, template) do # Phoenix uses the assigns.layout to determine what layout to use assigns = Map.put(email.assigns, :layout, email.private.html_layout) Phoenix.View.render_to_string( email.private.view_module, template, assigns ) end defp render_text(email, template) do assigns = Map.put(email.assigns, :layout, email.private.text_layout) Phoenix.View.render_to_string( email.private.view_module, template, assigns ) end end
28.604863
92
0.643927
ff7d07ef72f6e73320e46a6acd331b336679e2eb
2,100
exs
Elixir
implements/wordy/wordy_test.exs
MickeyOoh/Exercises
3b34e7fdab4a09e0269d20c68531b4fb75bb7f16
[ "MIT" ]
null
null
null
implements/wordy/wordy_test.exs
MickeyOoh/Exercises
3b34e7fdab4a09e0269d20c68531b4fb75bb7f16
[ "MIT" ]
1
2018-06-19T18:59:41.000Z
2018-06-19T18:59:41.000Z
implements/wordy/wordy_test.exs
MickeyOoh/Exercises
3b34e7fdab4a09e0269d20c68531b4fb75bb7f16
[ "MIT" ]
null
null
null
#if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("wordy.exs", __DIR__) #end ExUnit.start() #ExUnit.configure(exclude: :pending, trace: true) defmodule WordyTest do use ExUnit.Case test "addition" do assert Wordy.answer("What is 1 plus 1?") == 2 end @tag :pending test "more addition" do assert Wordy.answer("What is 53 plus 2?") == 55 end @tag :pending test "addition with negative numbers" do assert Wordy.answer("What is -1 plus -10?") == -11 end @tag :pending test "large addition" do assert Wordy.answer("What is 123 plus 45678?") == 45801 end @tag :pending test "subtraction" do assert Wordy.answer("What is 4 minus -12?") == 16 end @tag :pending test "multiplication" do assert Wordy.answer("What is -3 multiplied by 25?") == -75 end @tag :pending test "division" do assert Wordy.answer("What is 33 divided by -3?") == -11 end @tag :pending test "multiple additions" do assert Wordy.answer("What is 1 plus 1 plus 1?") == 3 end @tag :pending test "addition and subtraction" do assert Wordy.answer("What is 1 plus 5 minus -2?") == 8 end @tag :pending test "multiple subtraction" do assert Wordy.answer("What is 20 minus 4 minus 13?") == 3 end @tag :pending test "subtraction then addition" do assert Wordy.answer("What is 17 minus 6 plus 3?") == 14 end @tag :pending test "multiple multiplication" do assert Wordy.answer("What is 2 multiplied by -2 multiplied by 3?") == -12 end @tag :pending test "addition and multiplication" do assert Wordy.answer("What is -3 plus 7 multiplied by -2?") == -8 end @tag :pending test "multiple division" do assert Wordy.answer("What is -12 divided by 2 divided by -3?") == 2 end @tag :pending test "unknown operation" do assert_raise ArgumentError, fn -> Wordy.answer("What is 52 cubed?") end end @tag :pending test "Non math question" do assert_raise ArgumentError, fn -> Wordy.answer("Who is the President of the United States?") end end end
22.340426
77
0.656667
ff7d11ec0dcf1aed626bf3e621b99c8b16cecb92
2,030
ex
Elixir
lib/elixirdo/base/undetermined.ex
slepher/elixirdo
9417f275f1c908f9144e93325e6c52717896058f
[ "Xnet", "X11" ]
null
null
null
lib/elixirdo/base/undetermined.ex
slepher/elixirdo
9417f275f1c908f9144e93325e6c52717896058f
[ "Xnet", "X11" ]
5
2018-07-20T12:36:25.000Z
2018-08-01T04:55:46.000Z
lib/elixirdo/base/undetermined.ex
slepher/elixirdo
9417f275f1c908f9144e93325e6c52717896058f
[ "Xnet", "X11" ]
null
null
null
defmodule Elixirdo.Base.Undetermined do alias Elixirdo.Base.Undetermined alias Elixirdo.Base.Generated defstruct [:required_typeclass, :typeclass, :inner_function] def new(f, required_typeclass) do new(f, required_typeclass, required_typeclass) end def new(f, required_typeclass, typeclass) do case(Generated.is_typeclass(required_typeclass)) do true -> %Undetermined{required_typeclass: required_typeclass, typeclass: typeclass, inner_function: f} false -> f.(required_typeclass) end end def type(undetermined_a, typeclass) do case guess_type([undetermined_a], typeclass) do nil -> typeclass type -> type end end def run(%Undetermined{inner_function: f} = undetermined_a, typeclass) do case Generated.is_typeclass(typeclass) do true -> undetermined_a false -> f.(typeclass) end end def run(a, _typeclass) do a end def map(f, undetermined_a, typeclass) do map(f, undetermined_a, typeclass, typeclass) end def map(f, undetermined_a, typeclass, return_type) do map_list(fn [a], type -> f.(a, type) end, [undetermined_a], typeclass, return_type) end def map_list(f, values, typeclass, return_type, new \\ true) do case guess_type(values, typeclass) do nil -> case new do true -> new(fn type -> map_list(f, values, type, return_type) end, typeclass, return_type) false -> f.(values, typeclass) end type -> f.(map_type(values, type), type) end end def guess_type(as, type_or_typeclass) do case Generated.is_typeclass(type_or_typeclass) do true -> guess_type(as) false -> type_or_typeclass end end defp guess_type([%Undetermined{} | t]) do guess_type(t) end defp guess_type([h | _]) do Generated.type(h) end defp guess_type([]) do nil end defp map_type(values, type) do Enum.map(values, fn value -> run(value, type) end) end end
23.068182
102
0.657143
ff7d1b7365733f50d8cb80c159e2698db8e04204
478
exs
Elixir
bench/breaker_timeout_request_bench.exs
awochna/breaker
84a7855939b1350376bac555fb1ee1475a842e9a
[ "MIT" ]
33
2017-01-26T23:37:00.000Z
2021-05-17T16:39:35.000Z
bench/breaker_timeout_request_bench.exs
awochna/breaker
84a7855939b1350376bac555fb1ee1475a842e9a
[ "MIT" ]
9
2017-02-14T22:12:02.000Z
2019-08-06T20:46:41.000Z
bench/breaker_timeout_request_bench.exs
awochna/breaker
84a7855939b1350376bac555fb1ee1475a842e9a
[ "MIT" ]
4
2018-01-23T02:36:14.000Z
2019-08-06T15:42:01.000Z
defmodule BreakerTimeoutRequestBench do use Benchfella setup_all do HTTPotion.start Breaker.start_link([url: "http://localhost:8080/", timeout: 500]) end bench "get request with breaker", [breaker: bench_context] do task = Breaker.get(breaker, "/delay/1") Breaker.error?(Task.await(task)) end bench "get request without breaker" do response = HTTPotion.get("http://localhost:8080/delay/1", timeout: 500) Breaker.error?(response) end end
25.157895
75
0.707113
ff7d525e6df07c1c747366301b462a0e21ed93d1
2,378
ex
Elixir
lib/mix/tasks/ecto.migrate.ex
cnsa/ecto
a6e0eaaa5da1032fad571308c338eca1b5f77738
[ "Apache-2.0" ]
null
null
null
lib/mix/tasks/ecto.migrate.ex
cnsa/ecto
a6e0eaaa5da1032fad571308c338eca1b5f77738
[ "Apache-2.0" ]
null
null
null
lib/mix/tasks/ecto.migrate.ex
cnsa/ecto
a6e0eaaa5da1032fad571308c338eca1b5f77738
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Ecto.Migrate do use Mix.Task import Mix.Ecto @shortdoc "Runs the repository migrations" @recursive true @moduledoc """ Runs the pending migrations for the given repository. The repository must be set under `:ecto_repos` in the current app configuration or given via the `-r` option. By default, migrations are expected at "priv/YOUR_REPO/migrations" directory of the current application but it can be configured to be any subdirectory of `priv` by specifying the `:priv` key under the repository configuration. Runs all pending migrations by default. To migrate up to a version number, supply `--to version_number`. To migrate up a specific number of times, use `--step n`. If the repository has not been started yet, one will be started outside our application supervision tree and shutdown afterwards. ## Examples mix ecto.migrate mix ecto.migrate -r Custom.Repo mix ecto.migrate -n 3 mix ecto.migrate --step 3 mix ecto.migrate -v 20080906120000 mix ecto.migrate --to 20080906120000 ## Command line options * `-r`, `--repo` - the repo to migrate * `--all` - run all pending migrations * `--step` / `-n` - run n number of pending migrations * `--to` / `-v` - run all migrations up to and including version * `--quiet` - do not log migration commands * `--prefix` - the prefix to run migrations on * `--pool-size` - the pool size if the repository is started only for the task (defaults to 1) """ @doc false def run(args, migrator \\ &Ecto.Migrator.run/4) do repos = parse_repo(args) {opts, _, _} = OptionParser.parse args, switches: [all: :boolean, step: :integer, to: :integer, quiet: :boolean, prefix: :string, pool_size: :integer], aliases: [n: :step, v: :to] opts = if opts[:to] || opts[:step] || opts[:all], do: opts, else: Keyword.put(opts, :all, true) opts = if opts[:quiet], do: Keyword.put(opts, :log, false), else: opts Enum.each repos, fn repo -> ensure_repo(repo, args) ensure_migrations_path(repo) {:ok, pid, apps} = ensure_started(repo, opts) migrated = migrator.(repo, migrations_path(repo), :up, opts) pid && repo.stop(pid) restart_apps_if_migrated(apps, migrated) end end end
29.725
98
0.653911
ff7d6d56a5fcc4ec3fca20507eb79a7016618553
18,318
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v35/api/creatives.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v35/api/creatives.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v35/api/creatives.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DFAReporting.V35.Api.Creatives do @moduledoc """ API calls for all endpoints tagged `Creatives`. """ alias GoogleApi.DFAReporting.V35.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Gets one creative by ID. ## Parameters * `connection` (*type:* `GoogleApi.DFAReporting.V35.Connection.t`) - Connection to server * `profile_id` (*type:* `String.t`) - User profile ID associated with this request. * `id` (*type:* `String.t`) - Creative ID. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.DFAReporting.V35.Model.Creative{}}` on success * `{:error, info}` on failure """ @spec dfareporting_creatives_get( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.DFAReporting.V35.Model.Creative.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def dfareporting_creatives_get(connection, profile_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/dfareporting/v3.5/userprofiles/{profileId}/creatives/{id}", %{ "profileId" => URI.encode(profile_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V35.Model.Creative{}]) end @doc """ Inserts a new creative. ## Parameters * `connection` (*type:* `GoogleApi.DFAReporting.V35.Connection.t`) - Connection to server * `profile_id` (*type:* `String.t`) - User profile ID associated with this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.DFAReporting.V35.Model.Creative.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.DFAReporting.V35.Model.Creative{}}` on success * `{:error, info}` on failure """ @spec dfareporting_creatives_insert(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.DFAReporting.V35.Model.Creative.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def dfareporting_creatives_insert(connection, profile_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/dfareporting/v3.5/userprofiles/{profileId}/creatives", %{ "profileId" => URI.encode(profile_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V35.Model.Creative{}]) end @doc """ Retrieves a list of creatives, possibly filtered. This method supports paging. ## Parameters * `connection` (*type:* `GoogleApi.DFAReporting.V35.Connection.t`) - Connection to server * `profile_id` (*type:* `String.t`) - User profile ID associated with this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:active` (*type:* `boolean()`) - Select only active creatives. Leave blank to select active and inactive creatives. * `:advertiserId` (*type:* `String.t`) - Select only creatives with this advertiser ID. * `:archived` (*type:* `boolean()`) - Select only archived creatives. Leave blank to select archived and unarchived creatives. * `:campaignId` (*type:* `String.t`) - Select only creatives with this campaign ID. * `:companionCreativeIds` (*type:* `list(String.t)`) - Select only in-stream video creatives with these companion IDs. * `:creativeFieldIds` (*type:* `list(String.t)`) - Select only creatives with these creative field IDs. * `:ids` (*type:* `list(String.t)`) - Select only creatives with these IDs. * `:maxResults` (*type:* `integer()`) - Maximum number of results to return. * `:pageToken` (*type:* `String.t`) - Value of the nextPageToken from the previous result page. * `:renderingIds` (*type:* `list(String.t)`) - Select only creatives with these rendering IDs. * `:searchString` (*type:* `String.t`) - Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "creative*2015" will return objects with names like "creative June 2015", "creative April 2015", or simply "creative 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "creative" will match objects with name "my creative", "creative 2015", or simply "creative". * `:sizeIds` (*type:* `list(String.t)`) - Select only creatives with these size IDs. * `:sortField` (*type:* `String.t`) - Field by which to sort the list. * `:sortOrder` (*type:* `String.t`) - Order of sorted results. * `:studioCreativeId` (*type:* `String.t`) - Select only creatives corresponding to this Studio creative ID. * `:types` (*type:* `list(String.t)`) - Select only creatives with these creative types. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.DFAReporting.V35.Model.CreativesListResponse{}}` on success * `{:error, info}` on failure """ @spec dfareporting_creatives_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.DFAReporting.V35.Model.CreativesListResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def dfareporting_creatives_list(connection, profile_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :active => :query, :advertiserId => :query, :archived => :query, :campaignId => :query, :companionCreativeIds => :query, :creativeFieldIds => :query, :ids => :query, :maxResults => :query, :pageToken => :query, :renderingIds => :query, :searchString => :query, :sizeIds => :query, :sortField => :query, :sortOrder => :query, :studioCreativeId => :query, :types => :query } request = Request.new() |> Request.method(:get) |> Request.url("/dfareporting/v3.5/userprofiles/{profileId}/creatives", %{ "profileId" => URI.encode(profile_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.DFAReporting.V35.Model.CreativesListResponse{}] ) end @doc """ Updates an existing creative. This method supports patch semantics. ## Parameters * `connection` (*type:* `GoogleApi.DFAReporting.V35.Connection.t`) - Connection to server * `profile_id` (*type:* `String.t`) - User profile ID associated with this request. * `id` (*type:* `String.t`) - Creative ID. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.DFAReporting.V35.Model.Creative.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.DFAReporting.V35.Model.Creative{}}` on success * `{:error, info}` on failure """ @spec dfareporting_creatives_patch( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.DFAReporting.V35.Model.Creative.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def dfareporting_creatives_patch(connection, profile_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/dfareporting/v3.5/userprofiles/{profileId}/creatives", %{ "profileId" => URI.encode(profile_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :id, id) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V35.Model.Creative{}]) end @doc """ Updates an existing creative. ## Parameters * `connection` (*type:* `GoogleApi.DFAReporting.V35.Connection.t`) - Connection to server * `profile_id` (*type:* `String.t`) - User profile ID associated with this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.DFAReporting.V35.Model.Creative.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.DFAReporting.V35.Model.Creative{}}` on success * `{:error, info}` on failure """ @spec dfareporting_creatives_update(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.DFAReporting.V35.Model.Creative.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def dfareporting_creatives_update(connection, profile_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/dfareporting/v3.5/userprofiles/{profileId}/creatives", %{ "profileId" => URI.encode(profile_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.DFAReporting.V35.Model.Creative{}]) end end
47.703125
480
0.620428
ff7d8c808b9c8aee5582f7cd0c09857f803741df
3,376
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/user_role.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/user_role.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/user_role.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.DFAReporting.V33.Model.UserRole do @moduledoc """ Contains properties of auser role, which is used to manage user access. ## Attributes * `accountId` (*type:* `String.t`, *default:* `nil`) - Account ID of this user role. This is a read-only field that can be left blank. * `defaultUserRole` (*type:* `boolean()`, *default:* `nil`) - Whether this is a default user role. Default user roles are created by the system for the account/subaccount and cannot be modified or deleted. Each default user role comes with a basic set of preassigned permissions. * `id` (*type:* `String.t`, *default:* `nil`) - ID of this user role. This is a read-only, auto-generated field. * `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRole". * `name` (*type:* `String.t`, *default:* `nil`) - Name of this user role. This is a required field. Must be less than 256 characters long. If this user role is under a subaccount, the name must be unique among sites of the same subaccount. Otherwise, this user role is a top-level user role, and the name must be unique among top-level user roles of the same account. * `parentUserRoleId` (*type:* `String.t`, *default:* `nil`) - ID of the user role that this user role is based on or copied from. This is a required field. * `permissions` (*type:* `list(GoogleApi.DFAReporting.V33.Model.UserRolePermission.t)`, *default:* `nil`) - List of permissions associated with this user role. * `subaccountId` (*type:* `String.t`, *default:* `nil`) - Subaccount ID of this user role. This is a read-only field that can be left blank. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :accountId => String.t(), :defaultUserRole => boolean(), :id => String.t(), :kind => String.t(), :name => String.t(), :parentUserRoleId => String.t(), :permissions => list(GoogleApi.DFAReporting.V33.Model.UserRolePermission.t()), :subaccountId => String.t() } field(:accountId) field(:defaultUserRole) field(:id) field(:kind) field(:name) field(:parentUserRoleId) field(:permissions, as: GoogleApi.DFAReporting.V33.Model.UserRolePermission, type: :list) field(:subaccountId) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.UserRole do def decode(value, options) do GoogleApi.DFAReporting.V33.Model.UserRole.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.UserRole do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
49.647059
371
0.705865
ff7d9e79c17e0e4d1c8df0b6a90fa54feab26001
14,645
ex
Elixir
lib/plug/ssl.ex
adrianomitre/plug
9bf2f611f766e59adf4f238ea679e13d6ff6da75
[ "Apache-2.0" ]
null
null
null
lib/plug/ssl.ex
adrianomitre/plug
9bf2f611f766e59adf4f238ea679e13d6ff6da75
[ "Apache-2.0" ]
null
null
null
lib/plug/ssl.ex
adrianomitre/plug
9bf2f611f766e59adf4f238ea679e13d6ff6da75
[ "Apache-2.0" ]
null
null
null
defmodule Plug.SSL do @moduledoc """ A plug to force SSL connections and enable HSTS. If the scheme of a request is `https`, it'll add a `strict-transport-security` header to enable HTTP Strict Transport Security by default. Otherwise, the request will be redirected to a corresponding location with the `https` scheme by setting the `location` header of the response. The status code will be 301 if the method of `conn` is `GET` or `HEAD`, or 307 in other situations. Besides being a Plug, this module also provides conveniences for configuring SSL. See `configure/1`. ## x-forwarded-* If your Plug application is behind a proxy that handles HTTPS, you may need to tell Plug to parse the proper protocol from the `x-forwarded-*` header. This can be done using the `:rewrite_on` option: plug Plug.SSL, rewrite_on: [:x_forwarded_proto, :x_forwarded_host, :x_forwarded_port] The supported values are: * `:x_forwarded_host` - to override the host based on on the "x-forwarded-host" header * `:x_forwarded_port` - to override the port based on on the "x-forwarded-port" header * `:x_forwarded_proto` - to override the protocol based on on the "x-forwarded-proto" header Since rewriting the scheme based on `x-forwarded-*` headers can open up security vulnerabilities, only provide the option above if: * your app is behind a proxy * your proxy strips the given `x-forwarded-*` headers from all incoming requests * your proxy sets the `x-forwarded-*` headers and sends it to Plug ## Plug Options * `:rewrite_on` - rewrites the given connection information based on the given headers * `:hsts` - a boolean on enabling HSTS or not, defaults to `true` * `:expires` - seconds to expires for HSTS, defaults to `31_536_000` (1 year) * `:preload` - a boolean to request inclusion on the HSTS preload list (for full set of required flags, see: [Chromium HSTS submission site](https://hstspreload.org)), defaults to `false` * `:subdomains` - a boolean on including subdomains or not in HSTS, defaults to `false` * `:exclude` - exclude the given hosts from redirecting to the `https` scheme. Defaults to `["localhost"]`. It may be set to a list of binaries or a tuple [`{module, function, args}`](#module-excluded-hosts-tuple). * `:host` - a new host to redirect to if the request's scheme is `http`, defaults to `conn.host`. It may be set to a binary or a tuple `{module, function, args}` that will be invoked on demand * `:log` - The log level at which this plug should log its request info. Default is `:info`. Can be `false` to disable logging. ## Port It is not possible to directly configure the port in `Plug.SSL` because HSTS expects the port to be 443 for SSL. If you are not using HSTS and want to redirect to HTTPS on another port, you can sneak it alongside the host, for example: `host: "example.com:443"`. ## Excluded hosts tuple Tuple `{module, function, args}` can be passed to be invoked each time the plug is checking whether to redirect host. Provided function needs to receive at least one argument (`host`). For example, you may define it as: plug Plug.SSL, rewrite_on: [:x_forwarded_proto], exclude: {__MODULE__, :excluded_host?, []} where: def excluded_host?(host) do # Custom logic end """ @behaviour Plug require Logger import Plug.Conn @strong_tls_ciphers [ 'ECDHE-RSA-AES256-GCM-SHA384', 'ECDHE-ECDSA-AES256-GCM-SHA384', 'ECDHE-RSA-AES128-GCM-SHA256', 'ECDHE-ECDSA-AES128-GCM-SHA256', 'DHE-RSA-AES256-GCM-SHA384', 'DHE-RSA-AES128-GCM-SHA256' ] @compatible_tls_ciphers [ 'ECDHE-RSA-AES256-GCM-SHA384', 'ECDHE-ECDSA-AES256-GCM-SHA384', 'ECDHE-RSA-AES128-GCM-SHA256', 'ECDHE-ECDSA-AES128-GCM-SHA256', 'DHE-RSA-AES256-GCM-SHA384', 'DHE-RSA-AES128-GCM-SHA256', 'ECDHE-RSA-AES256-SHA384', 'ECDHE-ECDSA-AES256-SHA384', 'ECDHE-RSA-AES128-SHA256', 'ECDHE-ECDSA-AES128-SHA256', 'DHE-RSA-AES256-SHA256', 'DHE-RSA-AES128-SHA256', 'ECDHE-RSA-AES256-SHA', 'ECDHE-ECDSA-AES256-SHA', 'ECDHE-RSA-AES128-SHA', 'ECDHE-ECDSA-AES128-SHA' ] @eccs [ :secp256r1, :secp384r1, :secp521r1 ] @doc """ Configures and validates the options given to the `:ssl` application. This function is often called internally by adapters, such as Cowboy, to validate and set reasonable defaults for SSL handling. Therefore Plug users are not expected to invoke it directly, rather you pass the relevant SSL options to your adapter which then invokes this. ## Options This function accepts all options defined [in Erlang/OTP `:ssl` documentation](http://erlang.org/doc/man/ssl.html). Besides the options from `:ssl`, this function adds on extra option: * `:cypher_suite` - it may be `:strong` or `:compatible`, as outlined in the following section Furthermore, it sets the following defaults: * `secure_renegotiate: true` - to avoid certain types of man-in-the-middle attacks * `reuse_sessions: true` - for improved handshake performance of recurring connections For a complete guide on HTTPS and best pratices, see [our Plug HTTPS Guide](https.html). ## Cipher Suites To simplify configuration of TLS defaults, this function provides two preconfigured options: `cipher_suite: :strong` and `cipher_suite: :compatible`. The Ciphers chosen and related configuration come from the [OWASP Cipher String Cheat Sheet](https://www.owasp.org/index.php/TLS_Cipher_String_Cheat_Sheet) We've made two modifications to the suggested config from the OWASP recommendations. First we include ECDSA certificates which are excluded from their configuration. Second we have changed the order of the ciphers to deprioritize DHE because of performance implications noted within the OWASP post itself. As the article notes "...the TLS handshake with DHE hinders the CPU about 2.4 times more than ECDHE". The **Strong** cipher suite only supports tlsv1.2. Ciphers were based on the OWASP Group A+ and includes support for RSA or ECDSA certificates. The intention of this configuration is to provide as secure as possible defaults knowing that it will not be fully compatible with older browsers and operating systems. The **Compatible** cipher suite supports tlsv1, tlsv1.1 and tlsv1.2. Ciphers were based on the OWASP Group B and includes support for RSA or ECDSA certificates. The intention of this configuration is to provide as secure as possible defaults that still maintain support for older browsers and Android versions 4.3 and earlier For both suites we've specified certificate curves secp256r1, ecp384r1 and secp521r1. Since OWASP doesn't prescribe curves we've based the selection on [Mozilla's recommendations](https://wiki.mozilla.org/Security/Server_Side_TLS#Cipher_names_correspondence_table) **The cipher suites were last updated on 2018-JUN-14.** """ @spec configure(Keyword.t()) :: {:ok, Keyword.t()} | {:error, String.t()} def configure(options) do options |> check_for_missing_keys() |> validate_ciphers() |> normalize_ssl_files() |> convert_to_charlist() |> set_secure_defaults() |> configure_managed_tls() catch {:configure, message} -> {:error, message} else options -> {:ok, options} end defp check_for_missing_keys(options) do has_sni? = Keyword.has_key?(options, :sni_hosts) or Keyword.has_key?(options, :sni_fun) has_key? = Keyword.has_key?(options, :key) or Keyword.has_key?(options, :keyfile) has_cert? = Keyword.has_key?(options, :cert) or Keyword.has_key?(options, :certfile) cond do has_sni? -> options not has_key? -> fail("missing option :key/:keyfile") not has_cert? -> fail("missing option :cert/:certfile") true -> options end end defp normalize_ssl_files(options) do ssl_files = [:keyfile, :certfile, :cacertfile, :dhfile] Enum.reduce(ssl_files, options, &normalize_ssl_file(&1, &2)) end defp normalize_ssl_file(key, options) do value = options[key] cond do is_nil(value) -> options Path.type(value) == :absolute -> put_ssl_file(options, key, value) true -> put_ssl_file(options, key, Path.expand(value, otp_app(options))) end end defp put_ssl_file(options, key, value) do value = to_charlist(value) unless File.exists?(value) do message = "the file #{value} required by SSL's #{inspect(key)} either does not exist, " <> "or the application does not have permission to access it" fail(message) end Keyword.put(options, key, value) end defp otp_app(options) do if app = options[:otp_app] do Application.app_dir(app) else fail("the :otp_app option is required when setting relative SSL certfiles") end end defp convert_to_charlist(options) do Enum.reduce([:password], options, fn key, acc -> if value = acc[key] do Keyword.put(acc, key, to_charlist(value)) else acc end end) end defp set_secure_defaults(options) do options |> Keyword.put_new(:secure_renegotiate, true) |> Keyword.put_new(:reuse_sessions, true) end defp configure_managed_tls(options) do {cipher_suite, options} = Keyword.pop(options, :cipher_suite) case cipher_suite do :strong -> set_strong_tls_defaults(options) :compatible -> set_compatible_tls_defaults(options) nil -> options _ -> fail("unknown :cipher_suite named #{inspect(cipher_suite)}") end end defp set_managed_tls_defaults(options) do options |> Keyword.put_new(:honor_cipher_order, true) |> Keyword.put_new(:eccs, @eccs) end defp set_strong_tls_defaults(options) do options |> set_managed_tls_defaults |> Keyword.put_new(:ciphers, @strong_tls_ciphers) |> Keyword.put_new(:versions, [:"tlsv1.2"]) end defp set_compatible_tls_defaults(options) do options |> set_managed_tls_defaults |> Keyword.put_new(:ciphers, @compatible_tls_ciphers) |> Keyword.put_new(:versions, [:"tlsv1.2", :"tlsv1.1", :tlsv1]) end defp validate_ciphers(options) do options |> Keyword.get(:ciphers, []) |> Enum.each(&validate_cipher/1) options end defp validate_cipher(cipher) do if is_binary(cipher) do message = "invalid cipher #{inspect(cipher)} in cipher list. " <> "Strings (double-quoted) are not allowed in ciphers. " <> "Ciphers must be either charlists (single-quoted) or tuples. " <> "See the ssl application docs for reference" fail(message) end end defp fail(message) when is_binary(message) do throw({:configure, message}) end @impl true def init(opts) do host = Keyword.get(opts, :host) rewrite_on = List.wrap(Keyword.get(opts, :rewrite_on)) log = Keyword.get(opts, :log, :info) exclude = Keyword.get(opts, :exclude, ["localhost"]) {hsts_header(opts), exclude, host, rewrite_on, log} end @impl true def call(conn, {hsts, exclude, host, rewrite_on, log_level}) do conn = rewrite_on(conn, rewrite_on) cond do excluded?(conn.host, exclude) -> conn conn.scheme == :https -> put_hsts_header(conn, hsts) true -> redirect_to_https(conn, host, log_level) end end defp excluded?(host, list) when is_list(list), do: :lists.member(host, list) defp excluded?(host, {mod, fun, args}), do: apply(mod, fun, [host | args]) defp rewrite_on(conn, [:x_forwarded_proto | rewrite_on]) do conn |> put_scheme(get_req_header(conn, "x-forwarded-proto")) |> rewrite_on(rewrite_on) end defp rewrite_on(conn, [:x_forwarded_port | rewrite_on]) do conn |> put_port(get_req_header(conn, "x-forwarded-port")) |> rewrite_on(rewrite_on) end defp rewrite_on(conn, [:x_forwarded_host | rewrite_on]) do conn |> put_host(get_req_header(conn, "x-forwarded-host")) |> rewrite_on(rewrite_on) end defp rewrite_on(_conn, [other | _rewrite_on]) do raise "unknown rewrite: #{inspect(other)}" end defp rewrite_on(conn, []) do conn end defp put_scheme(%{scheme: :http, port: 80} = conn, ["https"]), do: %{conn | scheme: :https, port: 443} defp put_scheme(conn, ["https"]), do: %{conn | scheme: :https} defp put_scheme(%{scheme: :https, port: 443} = conn, ["http"]), do: %{conn | scheme: :http, port: 80} defp put_scheme(conn, ["http"]), do: %{conn | scheme: :http} defp put_scheme(conn, _scheme), do: conn defp put_host(conn, [proper_host]), do: %{conn | host: proper_host} defp put_host(conn, _), do: conn defp put_port(conn, headers) do with [header] <- headers, {port, ""} <- Integer.parse(header) do %{conn | port: port} else _ -> conn end end # http://tools.ietf.org/html/draft-hodges-strict-transport-sec-02 defp hsts_header(opts) do if Keyword.get(opts, :hsts, true) do expires = Keyword.get(opts, :expires, 31_536_000) preload = Keyword.get(opts, :preload, false) subdomains = Keyword.get(opts, :subdomains, false) "max-age=#{expires}" <> if(preload, do: "; preload", else: "") <> if(subdomains, do: "; includeSubDomains", else: "") end end defp put_hsts_header(conn, hsts_header) when is_binary(hsts_header) do put_resp_header(conn, "strict-transport-security", hsts_header) end defp put_hsts_header(conn, nil), do: conn defp redirect_to_https(%{host: host} = conn, custom_host, log_level) do status = if conn.method in ~w(HEAD GET), do: 301, else: 307 scheme_and_host = "https://" <> host(custom_host, host) location = scheme_and_host <> conn.request_path <> qs(conn.query_string) log_level && Logger.log(log_level, fn -> [ "Plug.SSL is redirecting ", conn.method, ?\s, conn.request_path, " to ", scheme_and_host, " with status ", Integer.to_string(status) ] end) conn |> put_resp_header("location", location) |> send_resp(status, "") |> halt end defp host(nil, host), do: host defp host(host, _) when is_binary(host), do: host defp host({mod, fun, args}, host), do: host(apply(mod, fun, args), host) # TODO: Deprecate this format defp host({:system, env}, host), do: host(System.get_env(env), host) defp qs(""), do: "" defp qs(qs), do: "?" <> qs end
32.616927
103
0.679344
ff7db472f350511a08a48242f04931121d16e11f
619
exs
Elixir
priv/repo/seeds.exs
cabol/rps
813028c4b7bb18f8c7cbcf4422249a81ccb9f059
[ "MIT" ]
3
2018-05-28T15:10:11.000Z
2020-08-02T21:14:25.000Z
priv/repo/seeds.exs
cabol/rps
813028c4b7bb18f8c7cbcf4422249a81ccb9f059
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
cabol/rps
813028c4b7bb18f8c7cbcf4422249a81ccb9f059
[ "MIT" ]
null
null
null
# Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # Rps.Repo.insert!(%Rps.SomeSchema{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong. alias Rps.Repo alias Rps.Accounts.User users = [ %User{ username: "admin", password: "admin" }, %User{ username: "user1", password: "user1" }, %User{ username: "user2", password: "user2" } ] for user <- users do Repo.insert!(user) end
18.205882
61
0.642973
ff7dbd433b93be01274cfc62baeb1c0d3ed686c8
1,739
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/platform_type.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/platform_type.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/platform_type.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.DFAReporting.V33.Model.PlatformType do @moduledoc """ Contains information about a platform type that can be targeted by ads. ## Attributes * `id` (*type:* `String.t`, *default:* `nil`) - ID of this platform type. * `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#platformType". * `name` (*type:* `String.t`, *default:* `nil`) - Name of this platform type. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :id => String.t(), :kind => String.t(), :name => String.t() } field(:id) field(:kind) field(:name) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.PlatformType do def decode(value, options) do GoogleApi.DFAReporting.V33.Model.PlatformType.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.PlatformType do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.811321
148
0.706728
ff7dc1aca5dc7d0bdb8a700e65362cd93a2f544d
5,196
ex
Elixir
phoenix/lib/mehr_schulferien/collect_data.ex
komlanvi/www.mehr-schulferien.de
fe74772f2cc8ce430e04adf6e66023971456ce57
[ "MIT" ]
null
null
null
phoenix/lib/mehr_schulferien/collect_data.ex
komlanvi/www.mehr-schulferien.de
fe74772f2cc8ce430e04adf6e66023971456ce57
[ "MIT" ]
null
null
null
phoenix/lib/mehr_schulferien/collect_data.ex
komlanvi/www.mehr-schulferien.de
fe74772f2cc8ce430e04adf6e66023971456ce57
[ "MIT" ]
null
null
null
defmodule MehrSchulferien.CollectData do alias MehrSchulferien.Timetables alias MehrSchulferien.Locations alias MehrSchulferien.Repo alias MehrSchulferien.Timetables.Day alias MehrSchulferien.Timetables.Slot alias MehrSchulferien.Timetables.Period alias MehrSchulferien.Locations.Country alias MehrSchulferien.Locations.FederalState alias MehrSchulferien.Locations.City alias MehrSchulferien.Locations.School alias MehrSchulferien.Timetables.Category import Ecto.Query def list_days(locations, opts \\ []) do country_ids = for %MehrSchulferien.Locations.Country{id: id} <- locations, do: id federal_state_ids = for %MehrSchulferien.Locations.FederalState{id: id} <- locations, do: id city_ids = for %MehrSchulferien.Locations.City{id: id} <- locations, do: id school_ids = for %MehrSchulferien.Locations.School{id: id} <- locations, do: id if opts[:starts_on] do starts_on = opts[:starts_on] else {:ok, starts_on} = Date.from_erl({Date.utc_today.year, 1, 1}) end if opts[:ends_on] do ends_on = opts[:ends_on] else {:ok, ends_on} = Date.from_erl({starts_on.year, 12, 31}) end if opts[:categories] do categories = opts[:categories] else query = from(categories in Category, where: categories.for_students == true and categories.needs_exeat == false) categories = Repo.all(query) end category_ids = for %MehrSchulferien.Timetables.Category{id: id} <- categories, do: id if opts[:additional_categories] do additional_categories = opts[:additional_categories] else additional_categories = [] end additional_categories_ids = for %MehrSchulferien.Timetables.Category{id: id} <- additional_categories, do: id category_ids = category_ids ++ additional_categories_ids query = from( days in Day, left_join: slots in Slot, on: days.id == slots.day_id, left_join: periods in Period, on: slots.period_id == periods.id and (periods.country_id in ^country_ids or periods.federal_state_id in ^federal_state_ids or periods.city_id in ^city_ids or periods.school_id in ^school_ids) and periods.category_id in ^category_ids, left_join: country in Country, on: periods.country_id == country.id, left_join: federal_state in FederalState, on: periods.federal_state_id == federal_state.id, left_join: city in City, on: periods.city_id == city.id, left_join: school in School, on: periods.school_id == school.id, left_join: category in Category, on: periods.category_id == category.id, where: days.value >= ^starts_on and days.value <= ^ends_on, order_by: days.value, select: {days, periods, category, country, federal_state, city, school} ) Repo.all(query) |> Enum.group_by(fn {date, _, _, _, _, _, _} -> date end, fn {_, period, category, country, federal_state, city, school} -> {period, category, country, federal_state, city, school} end) |> Enum.map(fn {date, periods} -> date |> Map.put(:periods, Enum.reject(periods, fn(x) -> x == {nil, nil, nil, nil, nil, nil} end)) end) |> Enum.sort_by(fn x -> x.slug end) end def test_foobar do country = MehrSchulferien.Locations.get_country!(1) federal_state = MehrSchulferien.Locations.get_federal_state!("hessen") days = MehrSchulferien.CollectData.list_days([country, federal_state], starts_on: ~D[2017-01-01], ends_on: ~D[2017-01-02]) end def ramp_up_to_full_months(starts_on, ends_on) do {:ok, starts_on} = Date.from_erl({starts_on.year, starts_on.month, 1}) {:ok, ends_on} = case {ends_on.month, Date.leap_year?(ends_on)} do {1, _} -> Date.from_erl({ends_on.year, ends_on.month, 31}) {2, false} -> Date.from_erl({ends_on.year, ends_on.month, 28}) {2, true} -> Date.from_erl({ends_on.year, ends_on.month, 29}) {3, _} -> Date.from_erl({ends_on.year, ends_on.month, 31}) {4, _} -> Date.from_erl({ends_on.year, ends_on.month, 30}) {5, _} -> Date.from_erl({ends_on.year, ends_on.month, 31}) {6, _} -> Date.from_erl({ends_on.year, ends_on.month, 30}) {7, _} -> Date.from_erl({ends_on.year, ends_on.month, 31}) {8, _} -> Date.from_erl({ends_on.year, ends_on.month, 31}) {9, _} -> Date.from_erl({ends_on.year, ends_on.month, 30}) {10, _} -> Date.from_erl({ends_on.year, ends_on.month, 31}) {11, _} -> Date.from_erl({ends_on.year, ends_on.month, 30}) {12, _} -> Date.from_erl({ends_on.year, ends_on.month, 31}) end {starts_on, ends_on} end def count_inset_day_quantity(days) do length(for day <- days do for {_, %MehrSchulferien.Timetables.Category{name: "Beweglicher Ferientag"}, _, _, _, _} <- day.periods do 1 end end |> List.flatten) end end
44.033898
190
0.632794
ff7df1ab4cc895e31e94d13e713619f5a49e8e49
326
ex
Elixir
lib/pkg_core/logger.ex
jnylen/pkg_core
a8575c5202615f671b450b9aad17f0b70ed88d09
[ "MIT" ]
null
null
null
lib/pkg_core/logger.ex
jnylen/pkg_core
a8575c5202615f671b450b9aad17f0b70ed88d09
[ "MIT" ]
10
2020-07-18T10:39:03.000Z
2022-03-24T04:03:27.000Z
lib/pkg_core/logger.ex
jnylen/pkg_core
a8575c5202615f671b450b9aad17f0b70ed88d09
[ "MIT" ]
null
null
null
defmodule PkgCore.Logger do @doc """ `debug/1` outputs in a shell a green text with the following string. """ def debug(_, string), do: Mix.shell().info([:green, "* ", :reset, string]) @doc """ `error/1` raises an error in case of an error. """ def error(app, string), do: Mix.raise("[#{app}] #{string}") end
27.166667
76
0.616564
ff7df4bac9677fc9e57aa0da4a600dd52056f0be
972
ex
Elixir
lib/opencov.ex
ramkrishna70/opencov
7a3415f8eebb797ad1f7b6c832daa4f04d70af8d
[ "MIT" ]
null
null
null
lib/opencov.ex
ramkrishna70/opencov
7a3415f8eebb797ad1f7b6c832daa4f04d70af8d
[ "MIT" ]
null
null
null
lib/opencov.ex
ramkrishna70/opencov
7a3415f8eebb797ad1f7b6c832daa4f04d70af8d
[ "MIT" ]
null
null
null
defmodule Opencov do use Application # See http://elixir-lang.org/docs/stable/elixir/Application.html # for more information on OTP Applications def start(_type, _args) do import Supervisor.Spec, warn: false children = [ # Start the endpoint when the application starts supervisor(Opencov.Endpoint, []), # Start the Ecto repository worker(Opencov.Repo, []), # Here you could define other workers and supervisors as children # worker(Opencov.Worker, [arg1, arg2, arg3]), ] # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Opencov.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do Opencov.Endpoint.config_change(changed, removed) :ok end end
31.354839
71
0.709877
ff7e09ddbc2fdc1e74468587b445a4279347cf18
259
ex
Elixir
lib/rfxi_web/channels/rfx_channel.ex
andyl/rfxi
9007c75693d643555c45a20e9634dd4b3867deba
[ "MIT" ]
1
2021-08-10T14:46:10.000Z
2021-08-10T14:46:10.000Z
lib/rfxi_web/channels/rfx_channel.ex
andyl/rfxi
9007c75693d643555c45a20e9634dd4b3867deba
[ "MIT" ]
2
2021-06-22T14:12:37.000Z
2021-06-28T05:06:23.000Z
lib/rfxi_web/channels/rfx_channel.ex
andyl/rfxi
9007c75693d643555c45a20e9634dd4b3867deba
[ "MIT" ]
null
null
null
defmodule RfxiWeb.RfxChannel do use Phoenix.Channel def join(_topic, _payload, socket) do {:ok, socket} end def handle_in("rfx", payload, socket) do IO.inspect payload, label: "PAYLOAD" {:reply, {:ok, %{echo: "PONG"}}, socket} end end
19.923077
44
0.656371
ff7e22d6324ec387dc43775f46d7b7bb36bea4d5
926
ex
Elixir
safe-indexer-ex/lib/rpc_client/rpc_client.ex
gnosis/simple-indexer
573484c0b9253d97883a51fe430519d718345b10
[ "MIT" ]
1
2022-01-30T02:15:03.000Z
2022-01-30T02:15:03.000Z
safe-indexer-ex/lib/rpc_client/rpc_client.ex
gnosis/safe-indexer
573484c0b9253d97883a51fe430519d718345b10
[ "MIT" ]
4
2021-08-31T10:02:21.000Z
2021-12-03T15:05:53.000Z
safe-indexer-ex/lib/rpc_client/rpc_client.ex
gnosis/simple-tracer
573484c0b9253d97883a51fe430519d718345b10
[ "MIT" ]
2
2021-12-19T01:56:44.000Z
2022-03-28T15:12:37.000Z
defmodule RpcClient do use Tesla plug Tesla.Middleware.BaseUrl, System.get_env("RPC_NODE_URL") plug Tesla.Middleware.JSON @topics %{ IncomingEth: "0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d", ExecutionSuccess: "0x442e715f626346e8c54381002da614f62bee8d27386535b2521ec8540898556e", ExecutionFailure: "0x23428b18acfb3ea64b08dc0c1d296ea9c09702c09083ca5272e64d115b687d23", SafeMultisigTransaction: "0x19e764001f2cb3b0a6315f2efccf09084fbfcda01b50198d7d093a91e491f34b" } def topics , do: @topics def rpc_method(method, params \\ []) do {:ok , body} = Jason.encode( %RpcClient.Request{method: method, params: params}); IO.inspect(body); {:ok, response} = post("", body, headers: [{"content-type", "application/json"}]); response.body["result"] # |> SafeIndexer.HexUtils.from_string end end
38.583333
101
0.709503
ff7e485b41631d218506daf4c6f60297ab435cf3
642
ex
Elixir
lib/exrush/csv.ex
xaviRodri/exrush
43dfa9e1364c87d77b16739c03215d3ba2abb5bc
[ "MIT" ]
null
null
null
lib/exrush/csv.ex
xaviRodri/exrush
43dfa9e1364c87d77b16739c03215d3ba2abb5bc
[ "MIT" ]
null
null
null
lib/exrush/csv.ex
xaviRodri/exrush
43dfa9e1364c87d77b16739c03215d3ba2abb5bc
[ "MIT" ]
null
null
null
defmodule Exrush.Csv do @moduledoc """ This module is in charge of all operations related to CSV files management. """ @csv_path "priv/csv/" @doc """ Writes a list of rushing data into a CSV file. """ @spec write(list()) :: binary() def write(data_list) do file_name = Enum.join([@csv_path, DateTime.utc_now() |> DateTime.to_iso8601(), ".csv"]) maybe_create_dir() file = File.open!(file_name, [:write, :utf8]) data_list |> CSV.encode(headers: true) |> Enum.each(&IO.write(file, &1)) file_name end defp maybe_create_dir, do: unless(File.dir?(@csv_path), do: File.mkdir!(@csv_path)) end
23.777778
91
0.647975
ff7e4f9553725c84ef28f7436fb18904e7cea125
60
exs
Elixir
lib/mix/test/fixtures/escripttest/config/config.exs
mk/elixir
2b2c66ecf7b1cc2167cae9cc3e88f950994223f1
[ "Apache-2.0" ]
4
2015-12-22T02:46:39.000Z
2016-04-26T06:11:09.000Z
lib/mix/test/fixtures/escripttest/config/config.exs
mk/elixir
2b2c66ecf7b1cc2167cae9cc3e88f950994223f1
[ "Apache-2.0" ]
null
null
null
lib/mix/test/fixtures/escripttest/config/config.exs
mk/elixir
2b2c66ecf7b1cc2167cae9cc3e88f950994223f1
[ "Apache-2.0" ]
null
null
null
use Mix.Config config :escripttest, erlval: "Erlang value"
15
43
0.766667
ff7e62acd1c27b47f9949c095430a60d45fad7c4
1,637
exs
Elixir
elixir/roman-numerals/roman_numerals_test.exs
codebay/exercism
f6ed549d473892f2c21f44a8f171480494eb59ad
[ "Apache-2.0" ]
null
null
null
elixir/roman-numerals/roman_numerals_test.exs
codebay/exercism
f6ed549d473892f2c21f44a8f171480494eb59ad
[ "Apache-2.0" ]
null
null
null
elixir/roman-numerals/roman_numerals_test.exs
codebay/exercism
f6ed549d473892f2c21f44a8f171480494eb59ad
[ "Apache-2.0" ]
null
null
null
if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("roman.exs", __DIR__) end ExUnit.start() ExUnit.configure(exclude: :pending, trace: true) defmodule RomanTest do use ExUnit.Case # @tag :pending test "1" do assert Roman.numerals(1) == "I" end # @tag :pending test "2" do assert Roman.numerals(2) == "II" end # @tag :pending test "3" do assert Roman.numerals(3) == "III" end # @tag :pending test "4" do assert Roman.numerals(4) == "IV" end # @tag :pending test "5" do assert Roman.numerals(5) == "V" end # @tag :pending test "6" do assert Roman.numerals(6) == "VI" end # @tag :pending test "9" do assert Roman.numerals(9) == "IX" end # @tag :pending test "27" do assert Roman.numerals(27) == "XXVII" end # @tag :pending test "48" do assert Roman.numerals(48) == "XLVIII" end # @tag :pending test "59" do assert Roman.numerals(59) == "LIX" end # @tag :pending test "93" do assert Roman.numerals(93) == "XCIII" end # @tag :pending test "141" do assert Roman.numerals(141) == "CXLI" end # @tag :pending test "163" do assert Roman.numerals(163) == "CLXIII" end # @tag :pending test "402" do assert Roman.numerals(402) == "CDII" end # @tag :pending test "575" do assert Roman.numerals(575) == "DLXXV" end # @tag :pending test "911" do assert Roman.numerals(911) == "CMXI" end # @tag :pending test "1024" do assert Roman.numerals(1024) == "MXXIV" end # @tag :pending test "3000" do assert Roman.numerals(3000) == "MMM" end end
16.207921
48
0.597434
ff7e70e4c9f8cfca7b972013f5bb9508bc6e30c1
445
ex
Elixir
lib/geolix/adapter/mmdb2/result/anonymous_ip.ex
coladarci/geolix
0a0508db410732fa8a24cbcd28e44f89b1b30afa
[ "Apache-2.0" ]
null
null
null
lib/geolix/adapter/mmdb2/result/anonymous_ip.ex
coladarci/geolix
0a0508db410732fa8a24cbcd28e44f89b1b30afa
[ "Apache-2.0" ]
null
null
null
lib/geolix/adapter/mmdb2/result/anonymous_ip.ex
coladarci/geolix
0a0508db410732fa8a24cbcd28e44f89b1b30afa
[ "Apache-2.0" ]
null
null
null
defmodule Geolix.Adapter.MMDB2.Result.AnonymousIP do @moduledoc """ Result for `GeoIP2 Anonymous IP` databases. """ alias Geolix.Adapter.MMDB2.Model defstruct ip_address: nil, is_anonymous: false, is_anonymous_vpn: false, is_hosting_provider: false, is_public_proxy: false, is_tor_exit_node: false @behaviour Model def from(data, _), do: struct(__MODULE__, data) end
23.421053
52
0.660674
ff7ee83ebb8862ea6d64d6400f9cd540103f84e3
24,666
ex
Elixir
lib/codes/codes_s58.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_s58.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_s58.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_S58 do alias IcdCode.ICDCode def _S58011A do %ICDCode{full_code: "S58011A", category_code: "S58", short_code: "011A", full_name: "Complete traumatic amputation at elbow level, right arm, initial encounter", short_name: "Complete traumatic amputation at elbow level, right arm, initial encounter", category_name: "Complete traumatic amputation at elbow level, right arm, initial encounter" } end def _S58011D do %ICDCode{full_code: "S58011D", category_code: "S58", short_code: "011D", full_name: "Complete traumatic amputation at elbow level, right arm, subsequent encounter", short_name: "Complete traumatic amputation at elbow level, right arm, subsequent encounter", category_name: "Complete traumatic amputation at elbow level, right arm, subsequent encounter" } end def _S58011S do %ICDCode{full_code: "S58011S", category_code: "S58", short_code: "011S", full_name: "Complete traumatic amputation at elbow level, right arm, sequela", short_name: "Complete traumatic amputation at elbow level, right arm, sequela", category_name: "Complete traumatic amputation at elbow level, right arm, sequela" } end def _S58012A do %ICDCode{full_code: "S58012A", category_code: "S58", short_code: "012A", full_name: "Complete traumatic amputation at elbow level, left arm, initial encounter", short_name: "Complete traumatic amputation at elbow level, left arm, initial encounter", category_name: "Complete traumatic amputation at elbow level, left arm, initial encounter" } end def _S58012D do %ICDCode{full_code: "S58012D", category_code: "S58", short_code: "012D", full_name: "Complete traumatic amputation at elbow level, left arm, subsequent encounter", short_name: "Complete traumatic amputation at elbow level, left arm, subsequent encounter", category_name: "Complete traumatic amputation at elbow level, left arm, subsequent encounter" } end def _S58012S do %ICDCode{full_code: "S58012S", category_code: "S58", short_code: "012S", full_name: "Complete traumatic amputation at elbow level, left arm, sequela", short_name: "Complete traumatic amputation at elbow level, left arm, sequela", category_name: "Complete traumatic amputation at elbow level, left arm, sequela" } end def _S58019A do %ICDCode{full_code: "S58019A", category_code: "S58", short_code: "019A", full_name: "Complete traumatic amputation at elbow level, unspecified arm, initial encounter", short_name: "Complete traumatic amputation at elbow level, unspecified arm, initial encounter", category_name: "Complete traumatic amputation at elbow level, unspecified arm, initial encounter" } end def _S58019D do %ICDCode{full_code: "S58019D", category_code: "S58", short_code: "019D", full_name: "Complete traumatic amputation at elbow level, unspecified arm, subsequent encounter", short_name: "Complete traumatic amputation at elbow level, unspecified arm, subsequent encounter", category_name: "Complete traumatic amputation at elbow level, unspecified arm, subsequent encounter" } end def _S58019S do %ICDCode{full_code: "S58019S", category_code: "S58", short_code: "019S", full_name: "Complete traumatic amputation at elbow level, unspecified arm, sequela", short_name: "Complete traumatic amputation at elbow level, unspecified arm, sequela", category_name: "Complete traumatic amputation at elbow level, unspecified arm, sequela" } end def _S58021A do %ICDCode{full_code: "S58021A", category_code: "S58", short_code: "021A", full_name: "Partial traumatic amputation at elbow level, right arm, initial encounter", short_name: "Partial traumatic amputation at elbow level, right arm, initial encounter", category_name: "Partial traumatic amputation at elbow level, right arm, initial encounter" } end def _S58021D do %ICDCode{full_code: "S58021D", category_code: "S58", short_code: "021D", full_name: "Partial traumatic amputation at elbow level, right arm, subsequent encounter", short_name: "Partial traumatic amputation at elbow level, right arm, subsequent encounter", category_name: "Partial traumatic amputation at elbow level, right arm, subsequent encounter" } end def _S58021S do %ICDCode{full_code: "S58021S", category_code: "S58", short_code: "021S", full_name: "Partial traumatic amputation at elbow level, right arm, sequela", short_name: "Partial traumatic amputation at elbow level, right arm, sequela", category_name: "Partial traumatic amputation at elbow level, right arm, sequela" } end def _S58022A do %ICDCode{full_code: "S58022A", category_code: "S58", short_code: "022A", full_name: "Partial traumatic amputation at elbow level, left arm, initial encounter", short_name: "Partial traumatic amputation at elbow level, left arm, initial encounter", category_name: "Partial traumatic amputation at elbow level, left arm, initial encounter" } end def _S58022D do %ICDCode{full_code: "S58022D", category_code: "S58", short_code: "022D", full_name: "Partial traumatic amputation at elbow level, left arm, subsequent encounter", short_name: "Partial traumatic amputation at elbow level, left arm, subsequent encounter", category_name: "Partial traumatic amputation at elbow level, left arm, subsequent encounter" } end def _S58022S do %ICDCode{full_code: "S58022S", category_code: "S58", short_code: "022S", full_name: "Partial traumatic amputation at elbow level, left arm, sequela", short_name: "Partial traumatic amputation at elbow level, left arm, sequela", category_name: "Partial traumatic amputation at elbow level, left arm, sequela" } end def _S58029A do %ICDCode{full_code: "S58029A", category_code: "S58", short_code: "029A", full_name: "Partial traumatic amputation at elbow level, unspecified arm, initial encounter", short_name: "Partial traumatic amputation at elbow level, unspecified arm, initial encounter", category_name: "Partial traumatic amputation at elbow level, unspecified arm, initial encounter" } end def _S58029D do %ICDCode{full_code: "S58029D", category_code: "S58", short_code: "029D", full_name: "Partial traumatic amputation at elbow level, unspecified arm, subsequent encounter", short_name: "Partial traumatic amputation at elbow level, unspecified arm, subsequent encounter", category_name: "Partial traumatic amputation at elbow level, unspecified arm, subsequent encounter" } end def _S58029S do %ICDCode{full_code: "S58029S", category_code: "S58", short_code: "029S", full_name: "Partial traumatic amputation at elbow level, unspecified arm, sequela", short_name: "Partial traumatic amputation at elbow level, unspecified arm, sequela", category_name: "Partial traumatic amputation at elbow level, unspecified arm, sequela" } end def _S58111A do %ICDCode{full_code: "S58111A", category_code: "S58", short_code: "111A", full_name: "Complete traumatic amputation at level between elbow and wrist, right arm, initial encounter", short_name: "Complete traumatic amputation at level between elbow and wrist, right arm, initial encounter", category_name: "Complete traumatic amputation at level between elbow and wrist, right arm, initial encounter" } end def _S58111D do %ICDCode{full_code: "S58111D", category_code: "S58", short_code: "111D", full_name: "Complete traumatic amputation at level between elbow and wrist, right arm, subsequent encounter", short_name: "Complete traumatic amputation at level between elbow and wrist, right arm, subsequent encounter", category_name: "Complete traumatic amputation at level between elbow and wrist, right arm, subsequent encounter" } end def _S58111S do %ICDCode{full_code: "S58111S", category_code: "S58", short_code: "111S", full_name: "Complete traumatic amputation at level between elbow and wrist, right arm, sequela", short_name: "Complete traumatic amputation at level between elbow and wrist, right arm, sequela", category_name: "Complete traumatic amputation at level between elbow and wrist, right arm, sequela" } end def _S58112A do %ICDCode{full_code: "S58112A", category_code: "S58", short_code: "112A", full_name: "Complete traumatic amputation at level between elbow and wrist, left arm, initial encounter", short_name: "Complete traumatic amputation at level between elbow and wrist, left arm, initial encounter", category_name: "Complete traumatic amputation at level between elbow and wrist, left arm, initial encounter" } end def _S58112D do %ICDCode{full_code: "S58112D", category_code: "S58", short_code: "112D", full_name: "Complete traumatic amputation at level between elbow and wrist, left arm, subsequent encounter", short_name: "Complete traumatic amputation at level between elbow and wrist, left arm, subsequent encounter", category_name: "Complete traumatic amputation at level between elbow and wrist, left arm, subsequent encounter" } end def _S58112S do %ICDCode{full_code: "S58112S", category_code: "S58", short_code: "112S", full_name: "Complete traumatic amputation at level between elbow and wrist, left arm, sequela", short_name: "Complete traumatic amputation at level between elbow and wrist, left arm, sequela", category_name: "Complete traumatic amputation at level between elbow and wrist, left arm, sequela" } end def _S58119A do %ICDCode{full_code: "S58119A", category_code: "S58", short_code: "119A", full_name: "Complete traumatic amputation at level between elbow and wrist, unspecified arm, initial encounter", short_name: "Complete traumatic amputation at level between elbow and wrist, unspecified arm, initial encounter", category_name: "Complete traumatic amputation at level between elbow and wrist, unspecified arm, initial encounter" } end def _S58119D do %ICDCode{full_code: "S58119D", category_code: "S58", short_code: "119D", full_name: "Complete traumatic amputation at level between elbow and wrist, unspecified arm, subsequent encounter", short_name: "Complete traumatic amputation at level between elbow and wrist, unspecified arm, subsequent encounter", category_name: "Complete traumatic amputation at level between elbow and wrist, unspecified arm, subsequent encounter" } end def _S58119S do %ICDCode{full_code: "S58119S", category_code: "S58", short_code: "119S", full_name: "Complete traumatic amputation at level between elbow and wrist, unspecified arm, sequela", short_name: "Complete traumatic amputation at level between elbow and wrist, unspecified arm, sequela", category_name: "Complete traumatic amputation at level between elbow and wrist, unspecified arm, sequela" } end def _S58121A do %ICDCode{full_code: "S58121A", category_code: "S58", short_code: "121A", full_name: "Partial traumatic amputation at level between elbow and wrist, right arm, initial encounter", short_name: "Partial traumatic amputation at level between elbow and wrist, right arm, initial encounter", category_name: "Partial traumatic amputation at level between elbow and wrist, right arm, initial encounter" } end def _S58121D do %ICDCode{full_code: "S58121D", category_code: "S58", short_code: "121D", full_name: "Partial traumatic amputation at level between elbow and wrist, right arm, subsequent encounter", short_name: "Partial traumatic amputation at level between elbow and wrist, right arm, subsequent encounter", category_name: "Partial traumatic amputation at level between elbow and wrist, right arm, subsequent encounter" } end def _S58121S do %ICDCode{full_code: "S58121S", category_code: "S58", short_code: "121S", full_name: "Partial traumatic amputation at level between elbow and wrist, right arm, sequela", short_name: "Partial traumatic amputation at level between elbow and wrist, right arm, sequela", category_name: "Partial traumatic amputation at level between elbow and wrist, right arm, sequela" } end def _S58122A do %ICDCode{full_code: "S58122A", category_code: "S58", short_code: "122A", full_name: "Partial traumatic amputation at level between elbow and wrist, left arm, initial encounter", short_name: "Partial traumatic amputation at level between elbow and wrist, left arm, initial encounter", category_name: "Partial traumatic amputation at level between elbow and wrist, left arm, initial encounter" } end def _S58122D do %ICDCode{full_code: "S58122D", category_code: "S58", short_code: "122D", full_name: "Partial traumatic amputation at level between elbow and wrist, left arm, subsequent encounter", short_name: "Partial traumatic amputation at level between elbow and wrist, left arm, subsequent encounter", category_name: "Partial traumatic amputation at level between elbow and wrist, left arm, subsequent encounter" } end def _S58122S do %ICDCode{full_code: "S58122S", category_code: "S58", short_code: "122S", full_name: "Partial traumatic amputation at level between elbow and wrist, left arm, sequela", short_name: "Partial traumatic amputation at level between elbow and wrist, left arm, sequela", category_name: "Partial traumatic amputation at level between elbow and wrist, left arm, sequela" } end def _S58129A do %ICDCode{full_code: "S58129A", category_code: "S58", short_code: "129A", full_name: "Partial traumatic amputation at level between elbow and wrist, unspecified arm, initial encounter", short_name: "Partial traumatic amputation at level between elbow and wrist, unspecified arm, initial encounter", category_name: "Partial traumatic amputation at level between elbow and wrist, unspecified arm, initial encounter" } end def _S58129D do %ICDCode{full_code: "S58129D", category_code: "S58", short_code: "129D", full_name: "Partial traumatic amputation at level between elbow and wrist, unspecified arm, subsequent encounter", short_name: "Partial traumatic amputation at level between elbow and wrist, unspecified arm, subsequent encounter", category_name: "Partial traumatic amputation at level between elbow and wrist, unspecified arm, subsequent encounter" } end def _S58129S do %ICDCode{full_code: "S58129S", category_code: "S58", short_code: "129S", full_name: "Partial traumatic amputation at level between elbow and wrist, unspecified arm, sequela", short_name: "Partial traumatic amputation at level between elbow and wrist, unspecified arm, sequela", category_name: "Partial traumatic amputation at level between elbow and wrist, unspecified arm, sequela" } end def _S58911A do %ICDCode{full_code: "S58911A", category_code: "S58", short_code: "911A", full_name: "Complete traumatic amputation of right forearm, level unspecified, initial encounter", short_name: "Complete traumatic amputation of right forearm, level unspecified, initial encounter", category_name: "Complete traumatic amputation of right forearm, level unspecified, initial encounter" } end def _S58911D do %ICDCode{full_code: "S58911D", category_code: "S58", short_code: "911D", full_name: "Complete traumatic amputation of right forearm, level unspecified, subsequent encounter", short_name: "Complete traumatic amputation of right forearm, level unspecified, subsequent encounter", category_name: "Complete traumatic amputation of right forearm, level unspecified, subsequent encounter" } end def _S58911S do %ICDCode{full_code: "S58911S", category_code: "S58", short_code: "911S", full_name: "Complete traumatic amputation of right forearm, level unspecified, sequela", short_name: "Complete traumatic amputation of right forearm, level unspecified, sequela", category_name: "Complete traumatic amputation of right forearm, level unspecified, sequela" } end def _S58912A do %ICDCode{full_code: "S58912A", category_code: "S58", short_code: "912A", full_name: "Complete traumatic amputation of left forearm, level unspecified, initial encounter", short_name: "Complete traumatic amputation of left forearm, level unspecified, initial encounter", category_name: "Complete traumatic amputation of left forearm, level unspecified, initial encounter" } end def _S58912D do %ICDCode{full_code: "S58912D", category_code: "S58", short_code: "912D", full_name: "Complete traumatic amputation of left forearm, level unspecified, subsequent encounter", short_name: "Complete traumatic amputation of left forearm, level unspecified, subsequent encounter", category_name: "Complete traumatic amputation of left forearm, level unspecified, subsequent encounter" } end def _S58912S do %ICDCode{full_code: "S58912S", category_code: "S58", short_code: "912S", full_name: "Complete traumatic amputation of left forearm, level unspecified, sequela", short_name: "Complete traumatic amputation of left forearm, level unspecified, sequela", category_name: "Complete traumatic amputation of left forearm, level unspecified, sequela" } end def _S58919A do %ICDCode{full_code: "S58919A", category_code: "S58", short_code: "919A", full_name: "Complete traumatic amputation of unspecified forearm, level unspecified, initial encounter", short_name: "Complete traumatic amputation of unspecified forearm, level unspecified, initial encounter", category_name: "Complete traumatic amputation of unspecified forearm, level unspecified, initial encounter" } end def _S58919D do %ICDCode{full_code: "S58919D", category_code: "S58", short_code: "919D", full_name: "Complete traumatic amputation of unspecified forearm, level unspecified, subsequent encounter", short_name: "Complete traumatic amputation of unspecified forearm, level unspecified, subsequent encounter", category_name: "Complete traumatic amputation of unspecified forearm, level unspecified, subsequent encounter" } end def _S58919S do %ICDCode{full_code: "S58919S", category_code: "S58", short_code: "919S", full_name: "Complete traumatic amputation of unspecified forearm, level unspecified, sequela", short_name: "Complete traumatic amputation of unspecified forearm, level unspecified, sequela", category_name: "Complete traumatic amputation of unspecified forearm, level unspecified, sequela" } end def _S58921A do %ICDCode{full_code: "S58921A", category_code: "S58", short_code: "921A", full_name: "Partial traumatic amputation of right forearm, level unspecified, initial encounter", short_name: "Partial traumatic amputation of right forearm, level unspecified, initial encounter", category_name: "Partial traumatic amputation of right forearm, level unspecified, initial encounter" } end def _S58921D do %ICDCode{full_code: "S58921D", category_code: "S58", short_code: "921D", full_name: "Partial traumatic amputation of right forearm, level unspecified, subsequent encounter", short_name: "Partial traumatic amputation of right forearm, level unspecified, subsequent encounter", category_name: "Partial traumatic amputation of right forearm, level unspecified, subsequent encounter" } end def _S58921S do %ICDCode{full_code: "S58921S", category_code: "S58", short_code: "921S", full_name: "Partial traumatic amputation of right forearm, level unspecified, sequela", short_name: "Partial traumatic amputation of right forearm, level unspecified, sequela", category_name: "Partial traumatic amputation of right forearm, level unspecified, sequela" } end def _S58922A do %ICDCode{full_code: "S58922A", category_code: "S58", short_code: "922A", full_name: "Partial traumatic amputation of left forearm, level unspecified, initial encounter", short_name: "Partial traumatic amputation of left forearm, level unspecified, initial encounter", category_name: "Partial traumatic amputation of left forearm, level unspecified, initial encounter" } end def _S58922D do %ICDCode{full_code: "S58922D", category_code: "S58", short_code: "922D", full_name: "Partial traumatic amputation of left forearm, level unspecified, subsequent encounter", short_name: "Partial traumatic amputation of left forearm, level unspecified, subsequent encounter", category_name: "Partial traumatic amputation of left forearm, level unspecified, subsequent encounter" } end def _S58922S do %ICDCode{full_code: "S58922S", category_code: "S58", short_code: "922S", full_name: "Partial traumatic amputation of left forearm, level unspecified, sequela", short_name: "Partial traumatic amputation of left forearm, level unspecified, sequela", category_name: "Partial traumatic amputation of left forearm, level unspecified, sequela" } end def _S58929A do %ICDCode{full_code: "S58929A", category_code: "S58", short_code: "929A", full_name: "Partial traumatic amputation of unspecified forearm, level unspecified, initial encounter", short_name: "Partial traumatic amputation of unspecified forearm, level unspecified, initial encounter", category_name: "Partial traumatic amputation of unspecified forearm, level unspecified, initial encounter" } end def _S58929D do %ICDCode{full_code: "S58929D", category_code: "S58", short_code: "929D", full_name: "Partial traumatic amputation of unspecified forearm, level unspecified, subsequent encounter", short_name: "Partial traumatic amputation of unspecified forearm, level unspecified, subsequent encounter", category_name: "Partial traumatic amputation of unspecified forearm, level unspecified, subsequent encounter" } end def _S58929S do %ICDCode{full_code: "S58929S", category_code: "S58", short_code: "929S", full_name: "Partial traumatic amputation of unspecified forearm, level unspecified, sequela", short_name: "Partial traumatic amputation of unspecified forearm, level unspecified, sequela", category_name: "Partial traumatic amputation of unspecified forearm, level unspecified, sequela" } end end
50.032454
128
0.68641
ff7eef24060a25e345fa4848821718396b200c46
2,233
ex
Elixir
lib/hexpm/repository/owners.ex
lau/hexpm
beee80f5358a356530debfea35ee65c3a0aa9b25
[ "Apache-2.0" ]
null
null
null
lib/hexpm/repository/owners.ex
lau/hexpm
beee80f5358a356530debfea35ee65c3a0aa9b25
[ "Apache-2.0" ]
null
null
null
lib/hexpm/repository/owners.ex
lau/hexpm
beee80f5358a356530debfea35ee65c3a0aa9b25
[ "Apache-2.0" ]
null
null
null
defmodule Hexpm.Repository.Owners do use Hexpm.Web, :context def all(package, preload \\ []) do assoc(package, :package_owners) |> Repo.all() |> Repo.preload(preload) end def get(package, user) do if owner = Repo.get_by(PackageOwner, package_id: package.id, user_id: user.id) do %{owner | package: package, user: user} end end def add(package, user, params, audit: audit_data) do organization = package.organization owners = all(package, user: :emails) owner = Enum.find(owners, &(&1.user_id == user.id)) owner = owner || %PackageOwner{package_id: package.id, user_id: user.id} changeset = PackageOwner.changeset(owner, params) if organization.public or Organizations.access?(organization, user, "read") do multi = Multi.new() |> Multi.insert_or_update(:owner, changeset) |> audit(audit_data, "owner.add", fn %{owner: owner} -> {package, owner.level, user} end) case Repo.transaction(multi) do {:ok, %{owner: owner}} -> # TODO: Separate email for the affected person owners = Enum.map(owners, & &1.user) Emails.owner_added(package, [user | owners], user) |> Mailer.deliver_now_throttled() {:ok, %{owner | user: user}} {:error, :owner, changeset, _} -> {:error, changeset} end else {:error, :not_member} end end def remove(package, user, audit: audit_data) do owners = all(package, user: :emails) owner = Enum.find(owners, &(&1.user_id == user.id)) cond do !owner -> {:error, :not_owner} length(owners) == 1 and package.organization.public -> {:error, :last_owner} true -> multi = Multi.new() |> Multi.delete(:owner, owner) |> audit(audit_data, "owner.remove", fn %{owner: owner} -> {package, owner.level, owner.user} end) {:ok, _} = Repo.transaction(multi) # TODO: Separate email for the affected person owners = Enum.map(owners, & &1.user) Emails.owner_removed(package, owners, owner.user) |> Mailer.deliver_now_throttled() :ok end end end
27.9125
85
0.592029
ff7efc1ef2cde7db55e96ef639967d448d66885f
1,988
ex
Elixir
clients/iam/lib/google_api/iam/v1/model/set_iam_policy_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/iam/lib/google_api/iam/v1/model/set_iam_policy_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/iam/lib/google_api/iam/v1/model/set_iam_policy_request.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.IAM.V1.Model.SetIamPolicyRequest do @moduledoc """ Request message for `SetIamPolicy` method. ## Attributes * `policy` (*type:* `GoogleApi.IAM.V1.Model.Policy.t`, *default:* `nil`) - REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. * `updateMask` (*type:* `String.t`, *default:* `nil`) - OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be modified. If no mask is provided, the following default mask is used: `paths: "bindings, etag"` """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :policy => GoogleApi.IAM.V1.Model.Policy.t(), :updateMask => String.t() } field(:policy, as: GoogleApi.IAM.V1.Model.Policy) field(:updateMask) end defimpl Poison.Decoder, for: GoogleApi.IAM.V1.Model.SetIamPolicyRequest do def decode(value, options) do GoogleApi.IAM.V1.Model.SetIamPolicyRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.IAM.V1.Model.SetIamPolicyRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.76
303
0.7334
ff7f418195c1daf8489b66654e347f5f90c2cb63
5,232
exs
Elixir
test/nostrum/struct/guild/member_test.exs
jos-b/nostrum
baf5c9de9f17c3bd99c5c06a454e03cc448aad1c
[ "MIT" ]
2
2020-03-03T02:51:57.000Z
2021-01-18T02:24:42.000Z
test/nostrum/struct/guild/member_test.exs
jos-b/nostrum
baf5c9de9f17c3bd99c5c06a454e03cc448aad1c
[ "MIT" ]
null
null
null
test/nostrum/struct/guild/member_test.exs
jos-b/nostrum
baf5c9de9f17c3bd99c5c06a454e03cc448aad1c
[ "MIT" ]
1
2020-09-03T13:55:55.000Z
2020-09-03T13:55:55.000Z
defmodule Nostrum.Struct.MemberTest do use ExUnit.Case, async: true alias Nostrum.Permission alias Nostrum.Struct.{Channel, Guild, User, Overwrite} alias Nostrum.Struct.Guild.{Member, Role} doctest Member describe "mention/1" do test "matches `Nostrum.Struct.User.mention/1`" do member = %Member{user: %User{id: 150_061_853_001_777_154}} assert(Member.mention(member) === User.mention(member.user)) end end describe "guild_permissions/2" do test "returns all perms if admin" do member = %Member{roles: [10]} role = %Role{id: 10, permissions: Permission.to_bitset([:administrator])} guild = %Guild{roles: %{role.id => role}} result = Member.guild_permissions(member, guild) assert(result === Permission.all()) end test "returns all perms if owner" do member = %Member{user: %User{id: 200}} guild = %Guild{owner_id: 200} result = Member.guild_permissions(member, guild) assert(result === Permission.all()) end test "returns permissions otherwise" do member = %Member{roles: [10]} role_perms = [:create_instant_invite, :manage_guild] role = %Role{id: 10, permissions: Permission.to_bitset(role_perms)} guild = %Guild{ roles: %{role.id => role} } result = Member.guild_permissions(member, guild) assert(result === Permission.from_bitset(0x00000021)) end end describe "guild_channel_permissions/3" do setup do [ channel_id: 300, everyone_role_id: 100, guild_id: 100, member_id: 500, role_id: 200 ] end test "returns all perms if member is admin", context do member = %Member{user: %User{id: context[:member_id]}, roles: [context[:role_id]]} role = %Role{id: context[:role_id], permissions: 0x00000008} channel = %Channel{id: context[:channel_id]} guild = %Guild{ channels: %{channel.id => channel}, members: %{member.user.id => member}, roles: %{role.id => role} } result = Member.guild_channel_permissions(member, guild, context[:channel_id]) assert(result === Permission.all()) end test "role overwrites have priority over @everyone overwrites", context do test_perm_bits = 0x00000040 member = %Member{ user: %User{id: context[:member_id]}, roles: [context[:everyone_role_id], context[:role_id]] } everyone_role = %Role{id: context[:everyone_role_id], permissions: 0} role = %Role{id: context[:role_id], permissions: 0} channel = %Channel{ id: context[:channel_id], permission_overwrites: [ %Overwrite{id: context[:role_id], allow: test_perm_bits, deny: 0}, %Overwrite{id: context[:everyone_role_id], deny: test_perm_bits, allow: 0} ] } guild = %Guild{ id: context[:guild_id], channels: %{channel.id => channel}, roles: %{everyone_role.id => everyone_role, role.id => role} } result = Member.guild_channel_permissions(member, guild, context[:channel_id]) assert(result === Permission.from_bitset(0x00000040)) end test "member overwrites have priority over role overwrites", context do test_perm_bits = 0x00000040 member = %Member{user: %User{id: context[:member_id]}, roles: [context[:role_id]]} everyone_role = %Role{id: context[:everyone_role_id], permissions: 0} role = %Role{id: context[:role_id], permissions: 0} channel = %Channel{ id: context[:channel_id], permission_overwrites: [ %Overwrite{id: context[:role_id], allow: 0, deny: test_perm_bits}, %Overwrite{id: context[:member_id], allow: test_perm_bits, deny: 0} ] } guild = %Guild{ id: context[:guild_id], channels: %{channel.id => channel}, roles: %{everyone_role.id => everyone_role, role.id => role} } result = Member.guild_channel_permissions(member, guild, context[:channel_id]) assert(result === Permission.from_bitset(0x00000040)) end test "returns empty list when there are no matching ids between channel overrides and member roles", context do member = %Member{user: %User{id: context[:member_id]}, roles: [context[:role_id]]} everyone_role = %Role{id: context[:everyone_role_id], permissions: 0} role = %Role{id: context[:role_id], permissions: 0} channel = %Channel{ id: context[:channel_id], permission_overwrites: [ %Overwrite{id: context[:role_id], allow: 0, deny: 0}, %Overwrite{id: context[:member_id], allow: 0, deny: 0} ] } guild = %Guild{ id: context[:guild_id], channels: %{channel.id => channel}, roles: %{everyone_role.id => everyone_role, role.id => role} } result = Member.guild_channel_permissions(member, guild, context[:channel_id]) assert(result == []) end end describe "String.Chars" do test "matches `mention/1`" do member = %Member{user: %User{id: 150_061_853_001_777_154}} assert(to_string(member) === Member.mention(member)) end end end
30.418605
104
0.629014
ff7f7687234c4e3b813d73a56cf660e630ab71cb
4,799
ex
Elixir
lib/glue/feed/api_wrappers/tmdb_api_wrapper.ex
seanbreckenridge/glue
60cbe6478be27572de6c6d5276a806b5940ffcbc
[ "Apache-2.0" ]
5
2020-07-04T12:18:58.000Z
2022-01-13T22:35:40.000Z
lib/glue/feed/api_wrappers/tmdb_api_wrapper.ex
seanbreckenridge/glue
60cbe6478be27572de6c6d5276a806b5940ffcbc
[ "Apache-2.0" ]
37
2020-07-20T23:35:56.000Z
2022-03-19T02:13:16.000Z
lib/glue/feed/api_wrappers/tmdb_api_wrapper.ex
seanbreckenridge/glue
60cbe6478be27572de6c6d5276a806b5940ffcbc
[ "Apache-2.0" ]
null
null
null
defmodule Glue.TMDB_API do require Logger use Tesla, only: [:get] @api_key Application.get_env(:glue, :tmdb_api_key) plug(Tesla.Middleware.JSON) plug(Tesla.Middleware.BaseUrl, "https://api.themoviedb.org/3") plug Tesla.Middleware.Retry, delay: 2_000, max_retries: 3, max_delay: 4_000, should_retry: fn {:ok, %{status: status}} when status >= 400 -> true {:ok, _} -> false {:error, _} -> true end def image_from_trakt_movie(meta_info) do slug = meta_info["ids"]["slug"] Logger.debug("Requesting Trakt movie #{slug}") case meta_info["ids"]["tmdb"] do nil -> Logger.warn("No tmdb entry for #{slug}, cant get image.") # can send another message to check the next item in cache in 1 second, since no request was made Process.whereis(Glue.Feed.ImageCache.Server) |> Process.send_after(:cache_images, :timer.seconds(1)) nil tmdb_id -> get_movie_image(tmdb_id) end end def get_movie_image(non_string) when not is_bitstring(non_string), do: nil def get_movie_image(tmdb_id) do case movie(tmdb_id) do {:ok, resp} -> poster_path = resp |> Map.get("poster_path", "") "https://image.tmdb.org/t/p/w400" <> poster_path {:err, _err} -> nil end end def movie(tmdb_id) do case get("/movie/#{tmdb_id}", query: [api_key: @api_key]) do {:ok, %{body: json_body}} -> {:ok, json_body} {:error, err} -> Logger.warn("Request to TMDB #{tmdb_id} failed") IO.inspect(err) {:error, err} end end def episode(tv_show_id, season, episode) do req_url = "/tv/#{tv_show_id}/season/#{season}/episode/#{episode}" case get(req_url, query: [api_key: @api_key]) do {:ok, %{body: json_body}} -> {:ok, json_body} {:error, err} -> Logger.warn("Request to TMDB #{req_url} failed") IO.inspect(err) {:error, err} end end def season(tv_show_id, season) do req_url = "/tv/#{tv_show_id}/season/#{season}" case get(req_url, query: [api_key: @api_key]) do {:ok, %{body: json_body}} -> {:ok, json_body} {:error, err} -> Logger.warn("Request to TMDB #{req_url} failed") IO.inspect(err) {:error, err} end end def tv(tv_show_id) do req_url = "/tv/#{tv_show_id}" case get(req_url, query: [api_key: @api_key]) do {:ok, %{body: json_body}} -> {:ok, json_body} {:error, err} -> Logger.warn("Request to TMDB #{req_url} failed") IO.inspect(err) {:error, err} end end # RSS feed returns something like https://trakt.tv/episodes/4101234 def image_from_trakt_episode(meta_info) do slug = meta_info["show"]["ids"]["slug"] info = get_tmdb_info(meta_info) if is_nil(info[:tmdb]) do Logger.warn("No TMDB info for #{slug}") # can send another message to check the next item in cache in 1 second, since no request was made Process.whereis(Glue.Feed.ImageCache.Server) |> Process.send_after(:cache_images, :timer.seconds(1)) nil else path = case episode(info[:tmdb], info[:season], info[:episode]) do {:ok, episode_resp} -> still_path = Map.get(episode_resp, "still_path") if is_nil(still_path) do Logger.warn( "Couldn't get episode still for #{info[:tmdb]} #{slug}, trying season poster..." ) :timer.sleep(:timer.seconds(2)) case season(info[:tmdb], info[:season]) do {:ok, season_resp} -> poster_path = Map.get(season_resp, "poster_path") if is_nil(poster_path) do Logger.warn( "Couldn't get season poster for #{info[:tmdb]} #{slug}, trying show poster..." ) :timer.sleep(:timer.seconds(2)) case tv(info[:tmdb]) do {:ok, tv_resp} -> Map.get(tv_resp, "poster_path") {:error, _err} -> nil end else poster_path end {:error, _err} -> nil end else still_path end {:error, _err} -> nil end if not is_nil(path) do "https://image.tmdb.org/t/p/w400" <> path else nil end end end defp get_tmdb_info(meta_info) do %{ tmdb: meta_info["show"]["ids"]["tmdb"], season: meta_info["episode"]["season"], episode: meta_info["episode"]["number"] } end end
26.224044
105
0.542405
ff7f9bb0dbb70d7f4598cc0eb8dc072b4d134139
811
ex
Elixir
lib/game/actions/heal.ex
kevinmartiniano/ex_mon
d86f090046a86e00794d7e974d468d0fb3121aa8
[ "Apache-2.0" ]
null
null
null
lib/game/actions/heal.ex
kevinmartiniano/ex_mon
d86f090046a86e00794d7e974d468d0fb3121aa8
[ "Apache-2.0" ]
null
null
null
lib/game/actions/heal.ex
kevinmartiniano/ex_mon
d86f090046a86e00794d7e974d468d0fb3121aa8
[ "Apache-2.0" ]
null
null
null
defmodule ExMon.Game.Actions.Heal do alias ExMon.Game alias ExMon.Game.Status @heal_power 18..25 def heal_life(player) do player |> Game.fetch_player() |> Map.get(:life) |> calculate_total_life() |> set_life(player) end defp calculate_total_life(life), do: Enum.random(@heal_power) + life defp set_life(life, player) when life > 100, do: update_player_life(player, 100) defp set_life(life, player), do: update_player_life(player, life) defp update_player_life(player, life) do player |> Game.fetch_player() |> Map.put(:life, life) |> update_game(player, life) end defp update_game(player_data, player, life) do Game.info() |> Map.put(player, player_data) |> Game.update() Status.print_move_message(player, :heal, life) end end
22.527778
82
0.681874
ff7f9e10587d32ebddef4e931d69d0e3f860f9b9
83
ex
Elixir
lib/ucx_ucc_web/views/coherence/password_view.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
lib/ucx_ucc_web/views/coherence/password_view.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
lib/ucx_ucc_web/views/coherence/password_view.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
defmodule UcxUccWeb.Coherence.PasswordView do use UcxUccWeb.Coherence, :view end
20.75
45
0.831325
ff7fd032ed57e1a454d0d41cf92e53b33fb45802
2,811
ex
Elixir
apps/ewallet_api/lib/ewallet_api/v1/router.ex
Macavirus/ewallet
ce62177b8bd3f7e72156930d384a1c4c047a3b5b
[ "Apache-2.0" ]
null
null
null
apps/ewallet_api/lib/ewallet_api/v1/router.ex
Macavirus/ewallet
ce62177b8bd3f7e72156930d384a1c4c047a3b5b
[ "Apache-2.0" ]
null
null
null
apps/ewallet_api/lib/ewallet_api/v1/router.ex
Macavirus/ewallet
ce62177b8bd3f7e72156930d384a1c4c047a3b5b
[ "Apache-2.0" ]
null
null
null
# Copyright 2018-2019 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule EWalletAPI.V1.Router do @moduledoc """ Routes for the eWallet API endpoints. """ use EWalletAPI, :router alias EWalletAPI.V1.ClientAuthPlug alias EWalletAPI.V1.StandalonePlug pipeline :client_api do plug(ClientAuthPlug) end pipeline :standalone do plug(StandalonePlug) end pipeline :api do plug(:accepts, ["json"]) end # Client endpoints scope "/", EWalletAPI.V1 do pipe_through([:api, :client_api]) post("/me.get", SelfController, :get) post("/me.get_settings", SelfController, :get_settings) post("/me.get_wallets", SelfController, :get_wallets) post("/me.get_transactions", TransactionController, :get_transactions) post("/me.create_transaction_request", TransactionRequestController, :create_for_user) post("/me.get_transaction_request", TransactionRequestController, :get) post("/me.create_transaction", TransactionController, :create) post( "/me.approve_transaction_consumption", TransactionConsumptionController, :approve_for_user ) post("/me.reject_transaction_consumption", TransactionConsumptionController, :reject_for_user) post("/me.cancel_transaction_consumption", TransactionConsumptionController, :cancel_for_user) post("/me.consume_transaction_request", TransactionConsumptionController, :consume_for_user) post("/me.logout", AuthController, :logout) # Simulate a server error. Useful for testing the internal server error response # and error reporting. Locked behind authentication to prevent spamming. post("/status.server_error", StatusController, :server_error) end # Standalone endpoints scope "/", EWalletAPI.V1 do pipe_through([:api, :standalone]) post("/user.signup", SignupController, :signup) post("/user.verify_email", SignupController, :verify_email) post("/user.login", AuthController, :login) post("/user.reset_password", ResetPasswordController, :reset) post("/user.update_password", ResetPasswordController, :update) end # Public endpoints scope "/", EWalletAPI.V1 do pipe_through([:api]) post("/status", StatusController, :index) match(:*, "/*path", FallbackController, :not_found) end end
32.686047
98
0.737816
ff8002abe48bc1b474bac14dfddb2ce82542ddc6
4,053
exs
Elixir
test/support/repo.exs
aleDsz/ecto-polymorphic
4e29780602fc0028bfb42a4e56efd48b205b7861
[ "MIT" ]
1
2020-10-02T00:26:38.000Z
2020-10-02T00:26:38.000Z
test/support/repo.exs
aleDsz/ecto-polymorphic
4e29780602fc0028bfb42a4e56efd48b205b7861
[ "MIT" ]
null
null
null
test/support/repo.exs
aleDsz/ecto-polymorphic
4e29780602fc0028bfb42a4e56efd48b205b7861
[ "MIT" ]
null
null
null
defmodule EctoPolymorphic.Support.Adapter do @behaviour Ecto.Adapter @behaviour Ecto.Adapter.Queryable @behaviour Ecto.Adapter.Schema @behaviour Ecto.Adapter.Transaction defmacro __before_compile__(_opts), do: :ok def ensure_all_started(_, _) do {:ok, []} end def init(opts) do :ecto = opts[:otp_app] "user" = opts[:username] "pass" = opts[:password] "hello" = opts[:database] "local" = opts[:hostname] {:ok, Supervisor.child_spec({Task, fn -> :timer.sleep(:infinity) end}, []), %{meta: :meta}} end def checkout(_mod, _opts, fun) do send(self(), {:checkout, fun}) fun.() end ## Types def loaders(:binary_id, type), do: [Ecto.UUID, type] def loaders(_primitive, type), do: [type] def dumpers(:binary_id, type), do: [type, Ecto.UUID] def dumpers(_primitive, type), do: [type] def autogenerate(:id), do: nil def autogenerate(:embed_id), do: Ecto.UUID.autogenerate() def autogenerate(:binary_id), do: Ecto.UUID.bingenerate() ## Queryable def prepare(operation, query), do: {:nocache, {operation, query}} def execute(_, _, {:nocache, {:all, query}}, _, _) do send(self(), {:all, query}) Process.get(:test_repo_all_results) || results_for_all_query(query) end def execute(_, _meta, {:nocache, {op, query}}, _params, _opts) do send(self(), {op, query}) {1, nil} end def stream(_, _meta, {:nocache, {:all, query}}, _params, _opts) do Stream.map([:execute], fn :execute -> send(self(), {:stream, query}) results_for_all_query(query) end) end defp results_for_all_query(%{select: %{fields: [_ | _] = fields}}) do values = List.duplicate(nil, length(fields) - 1) {1, [[1 | values]]} end defp results_for_all_query(%{select: %{fields: []}}) do {1, [[]]} end ## Schema def insert_all(_, meta, header, rows, on_conflict, returning, _opts) do meta = Map.merge(meta, %{header: header, on_conflict: on_conflict, returning: returning}) send(self(), {:insert_all, meta, rows}) {1, nil} end def insert(_, %{context: nil} = meta, fields, on_conflict, returning, _opts) do meta = Map.merge(meta, %{fields: fields, on_conflict: on_conflict, returning: returning}) send(self(), {:insert, meta}) {:ok, Enum.zip(returning, 1..length(returning))} end def insert(_, %{context: context}, _fields, _on_conflict, _returning, _opts) do context end # Notice the list of changes is never empty. def update(_, %{context: nil} = meta, [_ | _] = changes, filters, returning, _opts) do meta = Map.merge(meta, %{changes: changes, filters: filters, returning: returning}) send(self(), {:update, meta}) {:ok, Enum.zip(returning, 1..length(returning))} end def update(_, %{context: context}, [_ | _], _filters, _returning, _opts) do context end def delete(_, %{context: nil} = meta, filters, _opts) do meta = Map.merge(meta, %{filters: filters}) send(self(), {:delete, meta}) {:ok, []} end def delete(_, %{context: context}, _filters, _opts) do context end ## Transactions def transaction(mod, _opts, fun) do # Makes transactions "trackable" in tests Process.put({mod, :in_transaction?}, true) send(self(), {:transaction, fun}) try do {:ok, fun.()} catch :throw, {:ecto_rollback, value} -> {:error, value} after Process.delete({mod, :in_transaction?}) end end def in_transaction?(mod) do Process.get({mod, :in_transaction?}) || false end def rollback(_, value) do send(self(), {:rollback, value}) throw({:ecto_rollback, value}) end end Application.put_env(:ecto, EctoPolymorphic.Support.Repo, user: "invalid") defmodule EctoPolymorphic.Support.Repo do use Ecto.Repo, otp_app: :ecto, adapter: EctoPolymorphic.Support.Adapter def init(type, opts) do opts = [url: "ecto://user:pass@local/hello"] ++ opts opts[:parent] && send(opts[:parent], {__MODULE__, type, opts}) {:ok, opts} end end EctoPolymorphic.Support.Repo.start_link()
27.201342
95
0.642734
ff8018ce7755c4000c151113fa5cf2142ed33984
1,523
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/metric.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/metric.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/metric.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.DFAReporting.V33.Model.Metric do @moduledoc """ Represents a metric. ## Attributes * `kind` (*type:* `String.t`, *default:* `nil`) - The kind of resource this is, in this case dfareporting#metric. * `name` (*type:* `String.t`, *default:* `nil`) - The metric name, e.g. dfa:impressions """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :kind => String.t(), :name => String.t() } field(:kind) field(:name) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.Metric do def decode(value, options) do GoogleApi.DFAReporting.V33.Model.Metric.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.Metric do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
30.46
117
0.71241
ff80391f7c185b43e23e2aaf188d9925510a25e9
4,145
ex
Elixir
clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_input_audio_config.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_input_audio_config.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_input_audio_config.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3InputAudioConfig do @moduledoc """ Instructs the speech recognizer on how to process the audio content. ## Attributes * `audioEncoding` (*type:* `String.t`, *default:* `nil`) - Required. Audio encoding of the audio content to process. * `enableWordInfo` (*type:* `boolean()`, *default:* `nil`) - Optional. If `true`, Dialogflow returns SpeechWordInfo in StreamingRecognitionResult with information about the recognized speech words, e.g. start and end time offsets. If false or unspecified, Speech doesn't return any word-level information. * `model` (*type:* `String.t`, *default:* `nil`) - Optional. Which Speech model to select for the given request. Select the model best suited to your domain to get best results. If a model is not explicitly specified, then we auto-select a model based on the parameters in the InputAudioConfig. If enhanced speech model is enabled for the agent and an enhanced version of the specified model for the language does not exist, then the speech is recognized using the standard version of the specified model. Refer to [Cloud Speech API documentation](https://cloud.google.com/speech-to-text/docs/basics#select-model) for more details. * `modelVariant` (*type:* `String.t`, *default:* `nil`) - Optional. Which variant of the Speech model to use. * `phraseHints` (*type:* `list(String.t)`, *default:* `nil`) - Optional. A list of strings containing words and phrases that the speech recognizer should recognize with higher likelihood. See [the Cloud Speech documentation](https://cloud.google.com/speech-to-text/docs/basics#phrase-hints) for more details. * `sampleRateHertz` (*type:* `integer()`, *default:* `nil`) - Sample rate (in Hertz) of the audio content sent in the query. Refer to [Cloud Speech API documentation](https://cloud.google.com/speech-to-text/docs/basics) for more details. * `singleUtterance` (*type:* `boolean()`, *default:* `nil`) - Optional. If `false` (default), recognition does not cease until the client closes the stream. If `true`, the recognizer will detect a single spoken utterance in input audio. Recognition ceases when it detects the audio's voice has stopped or paused. In this case, once a detected intent is received, the client should close the stream and start a new request with a new stream as needed. Note: This setting is relevant only for streaming methods. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :audioEncoding => String.t() | nil, :enableWordInfo => boolean() | nil, :model => String.t() | nil, :modelVariant => String.t() | nil, :phraseHints => list(String.t()) | nil, :sampleRateHertz => integer() | nil, :singleUtterance => boolean() | nil } field(:audioEncoding) field(:enableWordInfo) field(:model) field(:modelVariant) field(:phraseHints, type: :list) field(:sampleRateHertz) field(:singleUtterance) end defimpl Poison.Decoder, for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3InputAudioConfig do def decode(value, options) do GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3InputAudioConfig.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3InputAudioConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
61.865672
635
0.738239
ff80431ebfad71e158e263f218bcb5267472ce94
2,374
exs
Elixir
{{cookiecutter.project_underscored}}/config/dev.exs
ijcd/cookiecutter-screaming-phoenix
f34ca6704f8f8b0581e91b4f6e3e75239fb79cb1
[ "Apache-2.0" ]
null
null
null
{{cookiecutter.project_underscored}}/config/dev.exs
ijcd/cookiecutter-screaming-phoenix
f34ca6704f8f8b0581e91b4f6e3e75239fb79cb1
[ "Apache-2.0" ]
null
null
null
{{cookiecutter.project_underscored}}/config/dev.exs
ijcd/cookiecutter-screaming-phoenix
f34ca6704f8f8b0581e91b4f6e3e75239fb79cb1
[ "Apache-2.0" ]
null
null
null
use Mix.Config # General application configuration config :{{cookiecutter.project_underscored}}, include_debug_routes: :true # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with brunch.io to recompile .js and .css sources. config :{{cookiecutter.project_underscored}}, {{cookiecutter.project_module}}.Web.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin", cd: Path.expand("../assets", __DIR__)]] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # command from your terminal: # # openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem # # The `http:` config above can be replaced with: # # https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :{{cookiecutter.project_underscored}}, {{cookiecutter.project_module}}.Web.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{priv/gettext/.*(po)$}, ~r{lib/{{cookiecutter.project_underscored}}_web/views/.*(ex)$}, ~r{lib/{{cookiecutter.project_underscored}}_web/templates/.*(eex)$} ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Configure your database config :{{cookiecutter.project_underscored}}, {{cookiecutter.project_module}}.Repo, adapter: Ecto.Adapters.Postgres, username: "postgres", password: "postgres", database: "{{cookiecutter.project_underscored}}_dev", hostname: "localhost", pool_size: 10 config :mix_test_watch, tasks: [ "test", # "dialyzer", # "credo", ]
34.405797
170
0.7123
ff806204d7c8603ce19ca3681572efe48ea8b055
1,541
ex
Elixir
lib/dingo_web/endpoint.ex
madclaws/Dingo
f277671b7e0a33c6b9a181f1444175f1171e9ce6
[ "MIT" ]
null
null
null
lib/dingo_web/endpoint.ex
madclaws/Dingo
f277671b7e0a33c6b9a181f1444175f1171e9ce6
[ "MIT" ]
null
null
null
lib/dingo_web/endpoint.ex
madclaws/Dingo
f277671b7e0a33c6b9a181f1444175f1171e9ce6
[ "MIT" ]
null
null
null
defmodule DingoWeb.Endpoint do use Phoenix.Endpoint, otp_app: :dingo # 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: "_dingo_key", signing_salt: "lEUjEV8/" ] socket "/socket", DingoWeb.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: :dingo, 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 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 DingoWeb.Router end
28.537037
97
0.713822
ff806c0c863483132b275a3008c389cbc58d1879
2,500
ex
Elixir
lib/codes/codes_d64.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_d64.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_d64.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_D64 do alias IcdCode.ICDCode def _D640 do %ICDCode{full_code: "D640", category_code: "D64", short_code: "0", full_name: "Hereditary sideroblastic anemia", short_name: "Hereditary sideroblastic anemia", category_name: "Hereditary sideroblastic anemia" } end def _D641 do %ICDCode{full_code: "D641", category_code: "D64", short_code: "1", full_name: "Secondary sideroblastic anemia due to disease", short_name: "Secondary sideroblastic anemia due to disease", category_name: "Secondary sideroblastic anemia due to disease" } end def _D642 do %ICDCode{full_code: "D642", category_code: "D64", short_code: "2", full_name: "Secondary sideroblastic anemia due to drugs and toxins", short_name: "Secondary sideroblastic anemia due to drugs and toxins", category_name: "Secondary sideroblastic anemia due to drugs and toxins" } end def _D643 do %ICDCode{full_code: "D643", category_code: "D64", short_code: "3", full_name: "Other sideroblastic anemias", short_name: "Other sideroblastic anemias", category_name: "Other sideroblastic anemias" } end def _D644 do %ICDCode{full_code: "D644", category_code: "D64", short_code: "4", full_name: "Congenital dyserythropoietic anemia", short_name: "Congenital dyserythropoietic anemia", category_name: "Congenital dyserythropoietic anemia" } end def _D6481 do %ICDCode{full_code: "D6481", category_code: "D64", short_code: "81", full_name: "Anemia due to antineoplastic chemotherapy", short_name: "Anemia due to antineoplastic chemotherapy", category_name: "Anemia due to antineoplastic chemotherapy" } end def _D6489 do %ICDCode{full_code: "D6489", category_code: "D64", short_code: "89", full_name: "Other specified anemias", short_name: "Other specified anemias", category_name: "Other specified anemias" } end def _D649 do %ICDCode{full_code: "D649", category_code: "D64", short_code: "9", full_name: "Anemia, unspecified", short_name: "Anemia, unspecified", category_name: "Anemia, unspecified" } end end
31.64557
81
0.618
ff80719c5e8fe234176dbdd9e2e9a81394bc1fb0
1,001
ex
Elixir
lib/hasher/application.ex
enlego/hasher
43b528059119971ffbca6538ffb6713fb78e077f
[ "MIT" ]
null
null
null
lib/hasher/application.ex
enlego/hasher
43b528059119971ffbca6538ffb6713fb78e077f
[ "MIT" ]
null
null
null
lib/hasher/application.ex
enlego/hasher
43b528059119971ffbca6538ffb6713fb78e077f
[ "MIT" ]
null
null
null
defmodule Hasher.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do children = [ # Start the Ecto repository Hasher.Repo, # Start the Telemetry supervisor HasherWeb.Telemetry, # Start the PubSub system {Phoenix.PubSub, name: Hasher.PubSub}, # Start the Endpoint (http/https) HasherWeb.Endpoint # Start a worker by calling: Hasher.Worker.start_link(arg) # {Hasher.Worker, arg} ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Hasher.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do HasherWeb.Endpoint.config_change(changed, removed) :ok end end
28.6
64
0.699301
ff80828aeae100a42f843738855e5a4d42cbed2d
2,049
ex
Elixir
lib/sbom_poc/mqtt.ex
TraceyOnim/SbomPoc-sFractal
bac895a7eda61c47c00b8bbe682a6fda4dd7255c
[ "MIT" ]
2
2020-10-04T12:41:58.000Z
2021-03-11T20:51:26.000Z
lib/sbom_poc/mqtt.ex
TraceyOnim/SbomPoc-sFractal
bac895a7eda61c47c00b8bbe682a6fda4dd7255c
[ "MIT" ]
113
2020-07-25T02:29:33.000Z
2022-03-01T01:07:23.000Z
lib/sbom_poc/mqtt.ex
TraceyOnim/SbomPoc-sFractal
bac895a7eda61c47c00b8bbe682a6fda4dd7255c
[ "MIT" ]
5
2020-07-10T09:57:58.000Z
2021-03-11T20:51:29.000Z
defmodule SbomPoc.Mqtt do @moduledoc """ `Mqtt` is main module for handling mqtt mqtt.start initializes the system and starts the Tortoise mqtt client using mqtt.handler """ require Logger @doc """ Start initializes system variables and starts supervisor of mqtt client """ def start do client_id = System.get_env("CLIENT_ID") || raise """ environment variable CLIENT_ID is missing. For example: export CLIENT_ID=:mqttlogger """ Logger.info("client_id is #{client_id}") mqtt_host = System.get_env("MQTT_HOST") || raise """ environment variable HOST is missing. Examples: export MQTT_HOST="34.86.117.113" export MQTT_HOST="mqtt.sfractal.com" """ Logger.info("mqtt_host is #{mqtt_host}") mqtt_port = String.to_integer( System.get_env("MQTT_PORT") || raise(""" environment variable MQTT_PORT is missing. Example: export MQTT_PORT=1883 """) ) Logger.info("mqtt_port is #{mqtt_port}") server = {Tortoise.Transport.Tcp, host: mqtt_host, port: mqtt_port} user_name = System.get_env("USER_NAME") || raise """ environment variable USER_NAME is missing. Examples: export USER_NAME="plug" """ Logger.info("user_name is #{user_name}") password = System.get_env("PASSWORD") || raise """ environment variable PASSWORD is missing. Example: export PASSWORD="fest" """ Logger.info("password set") Logger.info("Creating events table...") :events_table = SbomPoc.Mqtt.Handler.create_events_table() {:ok, _} = Tortoise.Supervisor.start_child( Oc2Mqtt.Connection.Supervisor, client_id: client_id, handler: {SbomPoc.Mqtt.Handler, [name: client_id]}, server: server, user_name: user_name, password: password, subscriptions: [{"#", 0}] ) end end
24.105882
71
0.598341
ff808fde32409c7646281f6c4ed148cc51985c49
305
ex
Elixir
lib/idService_web/auth_pipeline.ex
dougalcorn/id-server
a699cdc05a484faf498846d7d428921dfaecb978
[ "MIT" ]
null
null
null
lib/idService_web/auth_pipeline.ex
dougalcorn/id-server
a699cdc05a484faf498846d7d428921dfaecb978
[ "MIT" ]
null
null
null
lib/idService_web/auth_pipeline.ex
dougalcorn/id-server
a699cdc05a484faf498846d7d428921dfaecb978
[ "MIT" ]
null
null
null
defmodule IdService.Guardian.AuthPipeline do use Guardian.Plug.Pipeline, otp_app: :idService, module: IdService.Guardian, error_handler: IdService.AuthErrorHandler plug Guardian.Plug.VerifyHeader, realm: "Bearer" plug Guardian.Plug.EnsureAuthenticated plug Guardian.Plug.LoadResource end
30.5
50
0.803279
ff80d84a00f35f294bbcd93a9230c92d2bf9b7bb
886
exs
Elixir
test/splitwise/oauth2/client_test.exs
nathanbegbie/ex_splitwise
6de8b9f59db9834b342b86dfcd5c41354f349e5d
[ "MIT" ]
3
2019-09-29T04:15:29.000Z
2021-04-02T14:52:04.000Z
test/splitwise/oauth2/client_test.exs
nathanbegbie/ex_splitwise
6de8b9f59db9834b342b86dfcd5c41354f349e5d
[ "MIT" ]
null
null
null
test/splitwise/oauth2/client_test.exs
nathanbegbie/ex_splitwise
6de8b9f59db9834b342b86dfcd5c41354f349e5d
[ "MIT" ]
1
2022-02-22T15:32:16.000Z
2022-02-22T15:32:16.000Z
defmodule Splitwise.OAuth2.ClientTest do use ExUnit.Case, async: true import Mox setup :verify_on_exit! describe "authorize_url!/0" do test "it calls the authorize_url! from the OAuth client" do result = "authorize url" ExSplitwise.OAuth2Mock |> expect(:authorize_url!, fn _client -> result end) assert ExSplitwise.OAuth2.Client.authorize_url!() == result end end describe "get_token!/1" do test "it calls the get_token! from the OAuth client" do code = "code" access_token = "access_token" result = %{token: %{access_token: "{ \"access_token\": \"#{access_token}\", \"token_type\": \"bearer\" }"}} ExSplitwise.OAuth2Mock |> expect(:get_token!, fn _client, [code: ^code, client_secret: _] -> result end) assert {:ok, access_token} == ExSplitwise.OAuth2.Client.get_token!(code) end end end
28.580645
113
0.6614
ff80e346aa63f96210d4193f71d8b9450845164a
1,185
exs
Elixir
config/config.exs
wbotelhos/i18n-with-phoenix
6a7dd5a4454e9ea1d83d9a42938180cb019936bf
[ "MIT" ]
null
null
null
config/config.exs
wbotelhos/i18n-with-phoenix
6a7dd5a4454e9ea1d83d9a42938180cb019936bf
[ "MIT" ]
null
null
null
config/config.exs
wbotelhos/i18n-with-phoenix
6a7dd5a4454e9ea1d83d9a42938180cb019936bf
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. # General application configuration use Mix.Config config :i18n_with_phoenix, ecto_repos: [I18nWithPhoenix.Repo] # Configures the endpoint config :i18n_with_phoenix, I18nWithPhoenixWeb.Endpoint, url: [host: "localhost"], secret_key_base: "VykRzKYCB7sdl9K72ZuQN3GbGowvut5MFBmGBnXy6kl+7MLFcfIw8pSjaT8Oe1hd", render_errors: [view: I18nWithPhoenixWeb.ErrorView, accepts: ~w(html json), layout: false], pubsub_server: I18nWithPhoenix.PubSub, live_view: [signing_salt: "KZwXCJ/I"] # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # Use Jason for JSON parsing in Phoenix config :phoenix, :json_library, Jason config :i18n_with_phoenix, I18nWithPhoenix.Gettext, default_locale: "pt_BR", locales: ~w(pt_BR en) # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{Mix.env()}.exs"
34.852941
98
0.781435
ff80fb7dd0c2a1f17980c78cc7f52e76cfcd9b61
1,214
exs
Elixir
test/mix/tasks/absinthe.schema.sdl_test.exs
TheRealReal/absinthe
6eae5bc36283e58f42d032b8afd90de3ad64f97b
[ "MIT" ]
1
2019-10-10T02:57:52.000Z
2019-10-10T02:57:52.000Z
test/mix/tasks/absinthe.schema.sdl_test.exs
TheRealReal/absinthe
6eae5bc36283e58f42d032b8afd90de3ad64f97b
[ "MIT" ]
1
2019-09-23T21:26:01.000Z
2019-09-23T21:26:01.000Z
test/mix/tasks/absinthe.schema.sdl_test.exs
TheRealReal/absinthe
6eae5bc36283e58f42d032b8afd90de3ad64f97b
[ "MIT" ]
null
null
null
defmodule Mix.Tasks.Absinthe.Schema.SdlTest do use Absinthe.Case, async: true alias Mix.Tasks.Absinthe.Schema.Sdl, as: Task defmodule TestSchema do use Absinthe.Schema """ schema { query: Query } type Query { helloWorld(name: String!): String } """ |> import_sdl end @test_schema "Mix.Tasks.Absinthe.Schema.SdlTest.TestSchema" describe "absinthe.schema.sdl" do test "parses options" do argv = ["output.graphql", "--schema", @test_schema] opts = Task.parse_options(argv) assert opts.filename == "output.graphql" assert opts.schema == TestSchema end test "provides default options" do argv = ["--schema", @test_schema] opts = Task.parse_options(argv) assert opts.filename == "./schema.graphql" assert opts.schema == TestSchema end test "fails if no schema arg is provided" do argv = [] catch_error(Task.parse_options(argv)) end test "Generate schema" do argv = ["--schema", @test_schema] opts = Task.parse_options(argv) {:ok, schema} = Task.generate_schema(opts) assert schema =~ "helloWorld(name: String!): String" end end end
21.678571
61
0.632619
ff811386227e79bcf00e53b45761655e61ce4654
122
exs
Elixir
lib/mix/test/fixtures/deps_status/deps/invalidapp/mix.exs
mk/elixir
2b2c66ecf7b1cc2167cae9cc3e88f950994223f1
[ "Apache-2.0" ]
4
2015-12-22T02:46:39.000Z
2016-04-26T06:11:09.000Z
lib/mix/test/fixtures/deps_status/deps/invalidapp/mix.exs
mk/elixir
2b2c66ecf7b1cc2167cae9cc3e88f950994223f1
[ "Apache-2.0" ]
null
null
null
lib/mix/test/fixtures/deps_status/deps/invalidapp/mix.exs
mk/elixir
2b2c66ecf7b1cc2167cae9cc3e88f950994223f1
[ "Apache-2.0" ]
1
2017-07-25T21:46:48.000Z
2017-07-25T21:46:48.000Z
defmodule InvalidApp.Mixfile do use Mix.Project def project do [app: :invalidapp, version: "1.0"] end end
13.555556
31
0.663934
ff81211aaf3238674576e8c13c8d01fd415ed3ab
363
exs
Elixir
priv/repo/migrations/20170609220534_create_blogs_post.exs
myobie/post_register
924a832d7fa1693d655c34b0295affa8b3275f26
[ "MIT" ]
null
null
null
priv/repo/migrations/20170609220534_create_blogs_post.exs
myobie/post_register
924a832d7fa1693d655c34b0295affa8b3275f26
[ "MIT" ]
null
null
null
priv/repo/migrations/20170609220534_create_blogs_post.exs
myobie/post_register
924a832d7fa1693d655c34b0295affa8b3275f26
[ "MIT" ]
null
null
null
defmodule PostRegister.Repo.Migrations.CreatePostRegister.Blogs.Post do use Ecto.Migration def change do create table(:posts) do add :log_id, references(:logs, on_delete: :delete_all) add :subject, :string, size: 999, null: false add :from, :string, null: false add :html, :text, null: false timestamps() end end end
24.2
71
0.672176
ff8140837e5476ad65b3f2e7a269cbf17a6d55df
197
exs
Elixir
priv/repo/migrations/20190216140810_make_albums_apple_photos_id_optional.exs
allen-garvey/photog-phoenix
69cbcffbba905e623fe9c9c236e3be27b678ec75
[ "MIT" ]
4
2019-10-04T16:11:15.000Z
2021-08-18T21:00:13.000Z
apps/photog/priv/repo/migrations/20190216140810_make_albums_apple_photos_id_optional.exs
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
5
2020-03-16T23:52:25.000Z
2021-09-03T16:52:17.000Z
apps/photog/priv/repo/migrations/20190216140810_make_albums_apple_photos_id_optional.exs
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
null
null
null
defmodule Photog.Repo.Migrations.MakeAlbumsApplePhotosIdOptional do use Ecto.Migration def change do alter table(:albums) do modify :apple_photos_id, :integer, null: true end end end
19.7
67
0.771574
ff8147bab693d08d0afefcccdb03d29ca7c01b99
3,931
exs
Elixir
test/controllers/session_controller_test.exs
dipth/coherence
64ad450c5d8d020172875c4bf52f2bbdaa6e59de
[ "MIT" ]
null
null
null
test/controllers/session_controller_test.exs
dipth/coherence
64ad450c5d8d020172875c4bf52f2bbdaa6e59de
[ "MIT" ]
null
null
null
test/controllers/session_controller_test.exs
dipth/coherence
64ad450c5d8d020172875c4bf52f2bbdaa6e59de
[ "MIT" ]
null
null
null
defmodule CoherenceTest.SessionController do use TestCoherence.ConnCase import TestCoherenceWeb.Router.Helpers alias Coherence.Controller alias TestCoherence.Coherence.Trackable import Ecto.Query alias TestCoherence.User def setup_trackable_table %{conn: conn} do Application.put_env :coherence, :opts, [:authenticatable, :recoverable, :lockable, :trackable_table, :unlockable_with_token, :invitable, :registerable] Application.put_env(:coherence, :max_failed_login_attempts, 2) user = insert_user() conn = assign conn, :current_user, user {:ok, conn: conn, user: user} end describe "trackable table" do setup [:setup_trackable_table] test "track login", %{conn: conn, user: user} do conn = assign conn, :current_user, nil params = %{"session" => %{"email" => user.email, "password" => "supersecret"}} conn = post conn, session_path(conn, :create), params assert html_response(conn, 302) [t1] = Trackable |> order_by(asc: :id) |> Repo.all assert t1.action == "login" end test "mass asignment not allowed", %{conn: conn, user: user} do conn = assign conn, :current_user, nil params = %{"remember" => "on", "session" => %{"email" => user.email, "password" => "supersecret", "current_sign_in_ip" => "mass_asignment"}} conn = post conn, session_path(conn, :create), params assert html_response(conn, 302) %{:current_sign_in_ip => current_sign_in_ip} = get_user_by_email(user.email) refute current_sign_in_ip == params["session"]["current_sign_in_ip"] end test "track logout", %{conn: conn, user: user} do conn = assign conn, :current_user, nil params = %{"session" => %{"email" => user.email, "password" => "supersecret"}} conn = post conn, session_path(conn, :create), params conn = delete conn, session_path(conn, :delete) assert html_response(conn, 302) [t1, t2] = Trackable |> order_by(asc: :id) |> Repo.all assert t1.action == "login" assert t2.action == "logout" end test "failed login", %{conn: conn, user: user} do conn = assign conn, :current_user, nil params = %{"session" => %{"email" => user.email, "password" => "wrong"}} conn = post conn, session_path(conn, :create), params assert html_response(conn, 401) [t1] = Trackable |> order_by(asc: :id) |> Repo.all assert t1.action == "failed_login" end test "lock", %{conn: conn, user: user} do conn = assign conn, :current_user, nil params = %{"session" => %{"email" => user.email, "password" => "wrong"}} conn = post conn, session_path(conn, :create), params conn = post conn, session_path(conn, :create), params assert html_response(conn, 401) trackables = Trackable |> order_by(asc: :id) |> Repo.all assert Enum.at(trackables, 0).action == "failed_login" assert Enum.at(trackables, 1).action == "failed_login" assert Enum.at(trackables, 2).action == "lock" end test "unlock", %{conn: conn, user: user} do conn = assign conn, :current_user, nil params = %{"session" => %{"email" => user.email, "password" => "wrong"}} conn = post conn, session_path(conn, :create), params conn = post conn, session_path(conn, :create), params assert html_response(conn, 401) user = Repo.get(User, user.id) locked_at = user.locked_at |> Controller.shift(days: -10) User.changeset(user, %{locked_at: locked_at}) |> Repo.update! params = put_in params, ["session", "password"], "supersecret" post conn, session_path(conn, :create), params trackables = Trackable |> order_by(asc: :id) |> Repo.all assert Enum.count(trackables) == 5 assert Enum.at(trackables, 2).action == "lock" assert Enum.at(trackables, 3).action == "unlock" assert Enum.at(trackables, 4).action == "login" end end end
45.709302
146
0.644874
ff817667c2c00888ac510e8c8b247cfa0c2fae14
4,568
ex
Elixir
lib/commands/outfit.ex
Bentheburrito/caibot
301720992d668b02f308343c60f53ae050b5481b
[ "MIT" ]
2
2020-07-23T07:41:25.000Z
2020-08-10T22:03:25.000Z
lib/commands/outfit.ex
Bentheburrito/caibot
301720992d668b02f308343c60f53ae050b5481b
[ "MIT" ]
null
null
null
lib/commands/outfit.ex
Bentheburrito/caibot
301720992d668b02f308343c60f53ae050b5481b
[ "MIT" ]
null
null
null
defmodule CAIBot.Commands.PlanetSide.Outfit do @behaviour Nosedrum.Command require Logger alias Nostrum.Api alias Nostrum.Struct.Embed alias PS2.API.{Query, Join, QueryResult} # import Predicates, only: [ps2_outfit_name?: 1] import PS2.API.QueryBuilder import Utils, only: [safe_div: 2] @impl true def usage, do: ["outfit name <outfit name>", "outfit tag <outfit tag>"] @impl true def description, do: "View an outfit's general info. Searches by outfit tag by default (See usage examples.)" @impl true def parse_args(args), do: Enum.join(args, " ") @impl true def predicates, do: [] # outfit_identifier = an outfit name or tag @impl true def command(message, "name " <> outfit_identifier), do: do_command( message, query_outfit_with_identifier("name_lower", String.downcase(outfit_identifier)) ) @impl true def command(message, "tag " <> outfit_identifier), do: command(message, outfit_identifier) @impl true def command(message, outfit_identifier), do: do_command( message, query_outfit_with_identifier("alias_lower", String.downcase(outfit_identifier)) ) defp do_command(message, %Query{} = query) do with {:ok, %QueryResult{data: %{"name" => name, "alias" => tag, "members" => members} = outfit}} <- PS2.API.query_one(query) do faction_id = List.first(members)["character"]["faction_id"] {faction_name, faction_color, faction_logo} = CAIData.API.get_info(:faction)[faction_id] %{"kills" => outfit_kills, "deaths" => outfit_deaths} = outfit_members_stats(members) outfit_kdr = safe_div(outfit_kills, outfit_deaths) online_member_cards = Enum.filter(members, fn member -> member["character"]["status"]["online_status"] not in ["0", nil] end) |> Enum.map_join("\n", fn member -> "**#{member["character"]["name"]["first"]}** / *#{member["rank"]}* (#{ member["rank_ordinal"] })" end) |> String.slice(0..1023) embed = %Embed{} |> Embed.put_field( "#{name} [#{tag}]", "#{faction_name} - #{outfit["member_count"]} members\nAvg. KDR: #{outfit_kdr}" ) |> Embed.put_field( "Online Members:\nName / Rank (Rank Ordinal)", (online_member_cards == "" && "No online members.") || online_member_cards ) |> Embed.put_color(faction_color) |> Embed.put_thumbnail(faction_logo) |> Embed.put_footer( "Created #{ outfit["time_created"] |> String.to_integer() |> DateTime.from_unix!() |> DateTime.to_date() }" ) Api.create_message!(message.channel_id, embed: embed) else {:ok, %QueryResult{returned: 0}} -> Api.create_message(message.channel_id, "No outfit found.") {:error, error} -> Api.create_message( message.channel_id, "An error occurred while fetching the outfit. Please try again in a bit (and make sure the name/tag is spelled correctly.)" ) Logger.error("Query Error for command !outfit: #{inspect(error)}") end end defp outfit_members_stats(members) do Enum.reduce(members, %{}, fn %{"character" => %{"stats" => stats}}, acc -> Enum.reduce(stats, acc, fn %{"stat_name" => stat_name, "all_time" => val}, cur_acc -> value = String.to_integer(val) Map.update(cur_acc, stat_name, value, &(&1 + value)) _, cur_acc -> cur_acc end) _, acc -> acc end) end defp query_outfit_with_identifier(identifier_type, value) do Query.new(collection: "outfit") |> term(identifier_type, value, :contains) |> exact_match_first(true) |> join( Join.new(collection: "outfit_member") |> list(true) |> inject_at("members") |> show(["character_id", "rank_ordinal", "rank"]) |> join( Join.new(collection: "character") |> show(["name", "faction_id"]) |> inject_at("character") |> join( Join.new(collection: "characters_stat_history") |> list(true) |> inject_at("stats") |> term("stat_name", ["kills", "deaths"]) |> show(["stat_name", "all_time"]) ) |> join( Join.new(collection: "characters_online_status") |> inject_at("status") |> hide("character_id") ) ) ) end end
30.453333
133
0.586252
ff817ccff00425727631af07d37b5610a7564d0d
1,721
ex
Elixir
apps/banking_account_manager_web/lib/banking_account_manager_web.ex
danielscosta/banking_account_manager
8acec8f4fa774c85401e67b4aa39c97a0ca9d149
[ "MIT" ]
null
null
null
apps/banking_account_manager_web/lib/banking_account_manager_web.ex
danielscosta/banking_account_manager
8acec8f4fa774c85401e67b4aa39c97a0ca9d149
[ "MIT" ]
null
null
null
apps/banking_account_manager_web/lib/banking_account_manager_web.ex
danielscosta/banking_account_manager
8acec8f4fa774c85401e67b4aa39c97a0ca9d149
[ "MIT" ]
null
null
null
defmodule BankingAccountManagerWeb 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 BankingAccountManagerWeb, :controller use BankingAccountManagerWeb, :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: BankingAccountManagerWeb import Plug.Conn import BankingAccountManagerWeb.Gettext alias BankingAccountManagerWeb.Router.Helpers, as: Routes end end def view do quote do use Phoenix.View, root: "lib/banking_account_manager_web/templates", namespace: BankingAccountManagerWeb # Import convenience functions from controllers import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1] import BankingAccountManagerWeb.ErrorHelpers import BankingAccountManagerWeb.Gettext alias BankingAccountManagerWeb.Router.Helpers, as: Routes end end def router do quote do use Phoenix.Router import Plug.Conn import Phoenix.Controller end end def channel do quote do use Phoenix.Channel import BankingAccountManagerWeb.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
26.075758
83
0.722836
ff818c43d49f75dbdd65f85f464eb6a57ce3139d
7,332
exs
Elixir
.credo.exs
bitpal/bitpal_demo
989df08f60dadc5d4e340fef91890cf8bb3106ad
[ "BSD-3-Clause-Clear" ]
null
null
null
.credo.exs
bitpal/bitpal_demo
989df08f60dadc5d4e340fef91890cf8bb3106ad
[ "BSD-3-Clause-Clear" ]
1
2021-06-04T13:53:01.000Z
2021-06-04T13:53:01.000Z
.credo.exs
bitpal/bitpal_demo
989df08f60dadc5d4e340fef91890cf8bb3106ad
[ "BSD-3-Clause-Clear" ]
null
null
null
# This file contains the configuration for Credo and you are probably reading # this after creating it with `mix credo.gen.config`. # # If you find anything wrong or unclear in this file, please report an # issue on GitHub: https://github.com/rrrene/credo/issues # %{ # # You can have as many configs as you like in the `configs:` field. configs: [ %{ # # Run any config using `mix credo -C <name>`. If no config name is given # "default" is used. # name: "default", # # These are the files included in the analysis: files: %{ # # You can give explicit globs or simply directories. # In the latter case `**/*.{ex,exs}` will be used. # included: [ "lib/", "src/", "test/", "web/", "apps/*/lib/", "apps/*/src/", "apps/*/test/", "apps/*/web/" ], excluded: [~r"/_build/", ~r"/deps/", ~r"/node_modules/"] }, # # Load and configure plugins here: # plugins: [], # # If you create your own checks, you must specify the source files for # them here, so they can be loaded by Credo before running the analysis. # requires: [], # # If you want to enforce a style guide and need a more traditional linting # experience, you can change `strict` to `true` below: # strict: false, # # To modify the timeout for parsing files, change this value: # parse_timeout: 5000, # # If you want to use uncolored output by default, you can change `color` # to `false` below: # color: true, # # You can customize the parameters of any check by adding a second element # to the tuple. # # To disable a check put `false` as second element: # # {Credo.Check.Design.DuplicatedCode, false} # checks: [ # ## Consistency Checks # {Credo.Check.Consistency.ExceptionNames, []}, {Credo.Check.Consistency.LineEndings, []}, {Credo.Check.Consistency.ParameterPatternMatching, []}, {Credo.Check.Consistency.SpaceAroundOperators, []}, {Credo.Check.Consistency.SpaceInParentheses, []}, {Credo.Check.Consistency.TabsOrSpaces, []}, # ## Design Checks # # You can customize the priority of any check # Priority values are: `low, normal, high, higher` # {Credo.Check.Design.AliasUsage, [priority: :low, if_nested_deeper_than: 2, if_called_more_often_than: 0]}, # You can also customize the exit_status of each check. # If you don't want TODO comments to cause `mix credo` to fail, just # set this value to 0 (zero). # {Credo.Check.Design.TagTODO, [exit_status: 2]}, {Credo.Check.Design.TagFIXME, []}, # ## Readability Checks # {Credo.Check.Readability.AliasOrder, []}, {Credo.Check.Readability.FunctionNames, []}, {Credo.Check.Readability.LargeNumbers, []}, {Credo.Check.Readability.MaxLineLength, [priority: :low, max_length: 120]}, {Credo.Check.Readability.ModuleAttributeNames, []}, {Credo.Check.Readability.ModuleDoc, false}, {Credo.Check.Readability.ModuleNames, []}, {Credo.Check.Readability.ParenthesesInCondition, []}, {Credo.Check.Readability.ParenthesesOnZeroArityDefs, []}, {Credo.Check.Readability.PredicateFunctionNames, []}, {Credo.Check.Readability.PreferImplicitTry, []}, {Credo.Check.Readability.RedundantBlankLines, []}, {Credo.Check.Readability.Semicolons, []}, {Credo.Check.Readability.SpaceAfterCommas, []}, {Credo.Check.Readability.StringSigils, []}, {Credo.Check.Readability.TrailingBlankLine, []}, {Credo.Check.Readability.TrailingWhiteSpace, []}, {Credo.Check.Readability.UnnecessaryAliasExpansion, []}, {Credo.Check.Readability.VariableNames, []}, # ## Refactoring Opportunities # {Credo.Check.Refactor.CondStatements, []}, {Credo.Check.Refactor.CyclomaticComplexity, false}, {Credo.Check.Refactor.FunctionArity, []}, {Credo.Check.Refactor.LongQuoteBlocks, []}, # {Credo.Check.Refactor.MapInto, []}, {Credo.Check.Refactor.MatchInCondition, []}, {Credo.Check.Refactor.NegatedConditionsInUnless, []}, {Credo.Check.Refactor.NegatedConditionsWithElse, []}, {Credo.Check.Refactor.Nesting, [max_nesting: 3]}, {Credo.Check.Refactor.UnlessWithElse, []}, {Credo.Check.Refactor.WithClauses, []}, # ## Warnings # {Credo.Check.Warning.ApplicationConfigInModuleAttribute, []}, {Credo.Check.Warning.BoolOperationOnSameValues, []}, {Credo.Check.Warning.ExpensiveEmptyEnumCheck, []}, {Credo.Check.Warning.IExPry, []}, {Credo.Check.Warning.IoInspect, []}, # {Credo.Check.Warning.LazyLogging, []}, {Credo.Check.Warning.MixEnv, []}, {Credo.Check.Warning.OperationOnSameValues, []}, {Credo.Check.Warning.OperationWithConstantResult, []}, {Credo.Check.Warning.RaiseInsideRescue, []}, {Credo.Check.Warning.UnusedEnumOperation, []}, {Credo.Check.Warning.UnusedFileOperation, []}, {Credo.Check.Warning.UnusedKeywordOperation, []}, {Credo.Check.Warning.UnusedListOperation, []}, {Credo.Check.Warning.UnusedPathOperation, []}, {Credo.Check.Warning.UnusedRegexOperation, []}, {Credo.Check.Warning.UnusedStringOperation, []}, {Credo.Check.Warning.UnusedTupleOperation, []}, {Credo.Check.Warning.UnsafeExec, []}, # # Checks scheduled for next check update (opt-in for now, just replace `false` with `[]`) # # Controversial and experimental checks (opt-in, just replace `false` with `[]`) # {Credo.Check.Consistency.MultiAliasImportRequireUse, false}, {Credo.Check.Consistency.UnusedVariableNames, false}, {Credo.Check.Design.DuplicatedCode, false}, {Credo.Check.Readability.AliasAs, false}, {Credo.Check.Readability.BlockPipe, []}, {Credo.Check.Readability.ImplTrue, false}, {Credo.Check.Readability.MultiAlias, []}, {Credo.Check.Readability.SeparateAliasRequire, []}, {Credo.Check.Readability.SinglePipe, false}, {Credo.Check.Readability.Specs, false}, {Credo.Check.Readability.StrictModuleLayout, []}, {Credo.Check.Readability.WithCustomTaggedTuple, false}, {Credo.Check.Refactor.ABCSize, false}, {Credo.Check.Refactor.AppendSingleItem, []}, {Credo.Check.Refactor.DoubleBooleanNegation, []}, {Credo.Check.Refactor.ModuleDependencies, false}, {Credo.Check.Refactor.NegatedIsNil, []}, {Credo.Check.Refactor.PipeChainStart, false}, {Credo.Check.Refactor.VariableRebinding, false}, {Credo.Check.Warning.LeakyEnvironment, []}, {Credo.Check.Warning.MapGetUnsafePass, []}, {Credo.Check.Warning.UnsafeToAtom, []} # # Custom checks can be created using `mix credo.gen.check`. # ] } ] }
38.589474
97
0.60952
ff81afffa398fe07b1ed868fadc6ef528555b744
1,373
ex
Elixir
lib/influxql/quote.ex
jeffweiss/influxql
3ada4c123c6751a6cdebf27729c0eb6d6e7f06bf
[ "Apache-2.0" ]
null
null
null
lib/influxql/quote.ex
jeffweiss/influxql
3ada4c123c6751a6cdebf27729c0eb6d6e7f06bf
[ "Apache-2.0" ]
null
null
null
lib/influxql/quote.ex
jeffweiss/influxql
3ada4c123c6751a6cdebf27729c0eb6d6e7f06bf
[ "Apache-2.0" ]
null
null
null
defmodule InfluxQL.Quote do @moduledoc """ InfluxQL element quoting module. """ @doc """ Quotes an identifier for use in a query. ## Examples iex> identifier(:from_atom) "from_atom" iex> identifier("unquoted") "unquoted" iex> identifier("unquoted_100") "unquoted_100" iex> identifier("_unquoted") "_unquoted" iex> identifier("100quotes") "\\"100quotes\\"" iex> identifier("quotes for whitespace") "\\"quotes for whitespace\\"" iex> identifier("dáshes-and.stüff") "\\"dáshes-and.stüff\\"" """ @spec identifier(String.t()) :: String.t() for char <- ?0..?9 do def identifier(<<unquote(char), _::binary>> = identifier), do: "\"#{identifier}\"" end def identifier(identifier) when is_binary(identifier) do case Regex.match?(~r/([^a-zA-Z0-9_])/, identifier) do false -> identifier true -> "\"#{identifier}\"" end end def identifier(identifier), do: identifier |> Kernel.to_string() |> identifier() @doc """ Quotes a value for use in a query. ## Examples iex> value(100) "100" iex> value(:foo) "foo" iex> value("stringy") "'stringy'" """ @spec value(any) :: String.t() def value(value) when is_binary(value), do: "'#{value}'" def value(value), do: Kernel.to_string(value) end
21.453125
86
0.590677
ff81bff114e0dbfa3371b2a0e4d56acf0cee86fc
579
ex
Elixir
lib/accent/schemas/version.ex
leonardocouy/accent
29fb324395ff998cc5cdc6947c60070ffabe647c
[ "BSD-3-Clause" ]
null
null
null
lib/accent/schemas/version.ex
leonardocouy/accent
29fb324395ff998cc5cdc6947c60070ffabe647c
[ "BSD-3-Clause" ]
null
null
null
lib/accent/schemas/version.ex
leonardocouy/accent
29fb324395ff998cc5cdc6947c60070ffabe647c
[ "BSD-3-Clause" ]
null
null
null
defmodule Accent.Version do use Accent.Schema schema "versions" do field(:name, :string) field(:tag, :string) belongs_to(:user, Accent.User) belongs_to(:project, Accent.Project) has_many(:translations, Accent.Translation) has_many(:operations, Accent.Operation) timestamps() end @required_fields [:project_id, :user_id, :name, :tag] def changeset(model, params) do model |> cast(params, @required_fields) |> validate_required(@required_fields) |> unique_constraint(:tag, name: :versions_tag_project_id_index) end end
22.269231
68
0.701209
ff81dad0b793e2f3e659010af20e2e0e52219d74
834
ex
Elixir
test/support/integration_case.ex
onekilo79/tilex
c1b2dbea911a22d21420f52533e96bd63ce8f4ff
[ "MIT" ]
null
null
null
test/support/integration_case.ex
onekilo79/tilex
c1b2dbea911a22d21420f52533e96bd63ce8f4ff
[ "MIT" ]
null
null
null
test/support/integration_case.ex
onekilo79/tilex
c1b2dbea911a22d21420f52533e96bd63ce8f4ff
[ "MIT" ]
null
null
null
defmodule Tilex.IntegrationCase do use ExUnit.CaseTemplate using do quote do use Wallaby.DSL alias Wallaby.Query alias Wallaby.Element alias Tilex.{Endpoint, Channel, Factory, Post, Repo} import Ecto import Ecto.Changeset import Ecto.Query import TilexWeb.Router.Helpers import Tilex.TestHelpers def sign_in(session, developer) do visit(session, "/admin?id=#{developer.id}") end end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Tilex.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Tilex.Repo, {:shared, self()}) end metadata = Phoenix.Ecto.SQL.Sandbox.metadata_for(Tilex.Repo, self()) {:ok, session} = Wallaby.start_session(metadata: metadata) {:ok, session: session} end end
21.947368
72
0.66307
ff81f67f428362faaede6c53a71d30ff7ed22c80
3,139
exs
Elixir
test/process_managers/process_manager_instance_test.exs
SimpleBet/commanded
dc89737bd22daf4f6c5b3333b5d8d8de47fea5b8
[ "MIT" ]
1
2020-03-09T11:50:38.000Z
2020-03-09T11:50:38.000Z
test/process_managers/process_manager_instance_test.exs
perzanko/commanded
fd18ee3981cd237cbb874d1ccd8155e98d35d178
[ "MIT" ]
null
null
null
test/process_managers/process_manager_instance_test.exs
perzanko/commanded
fd18ee3981cd237cbb874d1ccd8155e98d35d178
[ "MIT" ]
null
null
null
defmodule Commanded.ProcessManagers.ProcessManagerInstanceTest do use Commanded.StorageCase alias Commanded.ExampleDomain.BankAccount.Commands.OpenAccount alias Commanded.ExampleDomain.BankApp alias Commanded.ExampleDomain.BankRouter alias Commanded.ExampleDomain.MoneyTransfer.Events.MoneyTransferRequested alias Commanded.ExampleDomain.TransferMoneyProcessManager alias Commanded.EventStore.RecordedEvent alias Commanded.ProcessManagers.ProcessManagerInstance alias Commanded.Helpers.CommandAuditMiddleware alias Commanded.Helpers.ProcessHelper setup do start_supervised!(CommandAuditMiddleware) start_supervised!(BankApp) :ok end test "process manager handles an event" do transfer_uuid = UUID.uuid4() account1_uuid = UUID.uuid4() account2_uuid = UUID.uuid4() :ok = open_account(account1_uuid, 1_000) :ok = open_account(account2_uuid, 500) {:ok, process_manager} = ProcessManagerInstance.start_link( application: BankApp, idle_timeout: :infinity, process_manager_name: "TransferMoneyProcessManager", process_manager_module: TransferMoneyProcessManager, process_router: self(), process_uuid: transfer_uuid ) event = %RecordedEvent{ event_number: 1, stream_id: "stream-id", stream_version: 1, data: %MoneyTransferRequested{ transfer_uuid: transfer_uuid, debit_account: account1_uuid, credit_account: account2_uuid, amount: 100 } } :ok = ProcessManagerInstance.process_event(process_manager, event) # Should send ack to process router after processing event assert_receive({:"$gen_cast", {:ack_event, ^event, _instance}}, 1_000) ProcessHelper.shutdown(process_manager) end test "should provide `__name__/0` function" do assert TransferMoneyProcessManager.__name__() == "Commanded.ExampleDomain.TransferMoneyProcessManager" end test "should ensure a process manager application is provided" do assert_raise ArgumentError, "NoAppProcessManager expects :application option", fn -> Code.eval_string(""" defmodule NoAppProcessManager do use Commanded.ProcessManagers.ProcessManager, name: __MODULE__ end """) end end test "should ensure a process manager name is provided" do assert_raise ArgumentError, "UnnamedProcessManager expects :name option", fn -> Code.eval_string(""" defmodule UnnamedProcessManager do use Commanded.ProcessManagers.ProcessManager, application: Commanded.DefaultApp end """) end end test "should allow using process manager module as name" do Code.eval_string(""" defmodule MyProcessManager do use Commanded.ProcessManagers.ProcessManager, application: Commanded.DefaultApp, name: __MODULE__ end """) end defp open_account(account_number, initial_balance) do command = %OpenAccount{account_number: account_number, initial_balance: initial_balance} BankRouter.dispatch(command, application: BankApp) end end
31.39
92
0.727939
ff820dcfc188ea1a0c7b2962094a67748e7c785c
515
ex
Elixir
lib/admint_web/live/navigation_live.ex
tiberiuc/admint
6d1bd5462f49053c7c3999c35cc301c7b8f08a70
[ "MIT" ]
null
null
null
lib/admint_web/live/navigation_live.ex
tiberiuc/admint
6d1bd5462f49053c7c3999c35cc301c7b8f08a70
[ "MIT" ]
null
null
null
lib/admint_web/live/navigation_live.ex
tiberiuc/admint
6d1bd5462f49053c7c3999c35cc301c7b8f08a70
[ "MIT" ]
null
null
null
defmodule Admint.Web.NavigationLive do use Admint.Web, :live_component import Admint.Definition.Helpers @impl true def update(assigns, socket) do admint = assigns.admint module = get_module(admint) navigation = get_navigation(module) pages = get_pages(module) categories = get_categories(module) socket = socket |> assign( admint: admint, navigation: navigation, categories: categories, pages: pages ) {:ok, socket} end end
20.6
39
0.652427
ff823e0029a7a359b78418900cb243f022fa877f
539
ex
Elixir
apps/core/lib/core/schema/impersonation_policy.ex
michaeljguarino/forge
50ee583ecb4aad5dee4ef08fce29a8eaed1a0824
[ "Apache-2.0" ]
59
2021-09-16T19:29:39.000Z
2022-03-31T20:44:24.000Z
apps/core/lib/core/schema/impersonation_policy.ex
svilenkov/plural
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
[ "Apache-2.0" ]
111
2021-08-15T09:56:37.000Z
2022-03-31T23:59:32.000Z
apps/core/lib/core/schema/impersonation_policy.ex
svilenkov/plural
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
[ "Apache-2.0" ]
4
2021-12-13T09:43:01.000Z
2022-03-29T18:08:44.000Z
defmodule Core.Schema.ImpersonationPolicy do use Piazza.Ecto.Schema alias Core.Schema.{User, ImpersonationPolicyBinding} schema "impersonation_policies" do belongs_to :user, User has_many :bindings, ImpersonationPolicyBinding, on_replace: :delete, foreign_key: :policy_id timestamps() end @valid ~w(user_id)a def changeset(model, attrs \\ %{}) do model |> cast(attrs, @valid) |> cast_assoc(:bindings) |> unique_constraint(:user_id) |> foreign_key_constraint(:user_id) end end
21.56
54
0.699443
ff82441868264d4c3aee6366fea0d23fa37ff892
1,649
exs
Elixir
apps/ewallet_db/priv/repo/migrations/20180405195847_rename_relation_id_to_relation_uuid.exs
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
1
2018-12-07T06:21:21.000Z
2018-12-07T06:21:21.000Z
apps/ewallet_db/priv/repo/migrations/20180405195847_rename_relation_id_to_relation_uuid.exs
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
apps/ewallet_db/priv/repo/migrations/20180405195847_rename_relation_id_to_relation_uuid.exs
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
defmodule EWalletDB.Repo.Migrations.RenameRelationIdToRelationUuid do use Ecto.Migration @tables [ account: [ parent_id: :parent_uuid ], api_key: [ account_id: :account_uuid ], auth_token: [ user_id: :user_uuid ], balance: [ user_id: :user_uuid, minted_token_id: :minted_token_uuid, account_id: :account_uuid ], forget_password_request: [ user_id: :user_uuid ], invite: [], key: [ account_id: :account_uuid ], membership: [ user_id: :user_uuid, account_id: :account_uuid, role_id: :role_uuid ], mint: [ minted_token_id: :minted_token_uuid, account_id: :account_uuid, transfer_id: :transfer_uuid ], minted_token: [ account_id: :account_uuid ], role: [], transaction_consumption: [ transfer_id: :transfer_uuid, user_id: :user_uuid, account_id: :account_uuid, transaction_request_id: :transaction_request_uuid, minted_token_id: :minted_token_uuid ], transaction_request: [ user_id: :user_uuid, account_id: :account_uuid, minted_token_id: :minted_token_uuid ], transfer: [ minted_token_id: :minted_token_uuid ], user: [ invite_id: :invite_uuid ] ] def up do Enum.each(@tables, fn({table, maps}) -> Enum.each(maps, fn({old, new}) -> rename table(table), old, to: new end) end) end def down do Enum.each(@tables, fn({table, maps}) -> Enum.each(maps, fn({old, new}) -> rename table(table), new, to: old end) end) end end
21.697368
69
0.600364
ff825ae1da39b538fc642e51e813cd3e392785a6
185
exs
Elixir
priv/repo/migrations/20200627062001_add_description_to_product.exs
abmBispo/elixir-ecommerce
0507f7621d68ba8f0f65409a1a503683b7c0d37b
[ "MIT" ]
4
2020-05-29T03:33:02.000Z
2021-08-21T23:01:48.000Z
priv/repo/migrations/20200627062001_add_description_to_product.exs
abmBispo/elixir-ecommerce
0507f7621d68ba8f0f65409a1a503683b7c0d37b
[ "MIT" ]
2
2020-07-29T01:50:46.000Z
2021-08-31T20:10:47.000Z
priv/repo/migrations/20200627062001_add_description_to_product.exs
abmBispo/elixir-ecommerce
0507f7621d68ba8f0f65409a1a503683b7c0d37b
[ "MIT" ]
1
2022-03-21T18:13:21.000Z
2022-03-21T18:13:21.000Z
defmodule ElixirEcommerce.Repo.Migrations.AddDescriptionToProduct do use Ecto.Migration def change do alter table(:products) do add :description, :text end end end
18.5
68
0.740541
ff827bc22e4406092284c6ffd4474296e49c98fb
5,759
ex
Elixir
lib/petal_components/pagination.ex
cohawk/petal_components
2741c4de66fa8dfa2896fe1e6e02f1d1653422cd
[ "MIT" ]
null
null
null
lib/petal_components/pagination.ex
cohawk/petal_components
2741c4de66fa8dfa2896fe1e6e02f1d1653422cd
[ "MIT" ]
null
null
null
lib/petal_components/pagination.ex
cohawk/petal_components
2741c4de66fa8dfa2896fe1e6e02f1d1653422cd
[ "MIT" ]
null
null
null
defmodule PetalComponents.Pagination do use Phoenix.Component alias PetalComponents.Heroicons import PetalComponents.Link # prop path, :string # prop class, :string # prop sibling_count, :integer # prop boundary_count, :integer # prop link_type, :string, options: ["a", "live_patch", "live_redirect"] @doc """ In the `path` param you can specify :page as the place your page number will appear. e.g "/posts/:page" => "/posts/1" """ def pagination(assigns) do assigns = assigns |> assign_new(:class, fn -> "" end) |> assign_new(:link_type, fn -> "a" end) |> assign_new(:sibling_count, fn -> 1 end) |> assign_new(:boundary_count, fn -> 1 end) |> assign_new(:path, fn -> "/:page" end) ~H""" <div class={"#{@class} flex"}> <ul class="inline-flex -space-x-px text-sm font-medium"> <%= for item <- get_items(@total_pages, @current_page, @sibling_count, @boundary_count) do %> <%= if item.type == "previous" do %> <div> <.link type={@link_type} to={get_path(@path, item.number, @current_page)} class="mr-2 inline-flex items-center justify-center rounded leading-5 px-2.5 py-2 bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800 border dark:border-gray-400 border-gray-200 text-gray-600 hover:text-gray-800"> <Heroicons.Solid.chevron_left class="w-5 h-5 text-gray-600 dark:text-gray-400" /> </.link> </div> <% end %> <%= if item.type == "page" do %> <li> <%= if item.number == @current_page do %> <span class={get_box_class(item, true)}><%= item.number %></span> <% else %> <.link type={@link_type} to={get_path(@path, item.number, @current_page)} class={get_box_class(item)}> <%= item.number %> </.link> <% end %> </li> <% end %> <%= if item.type == "ellipsis" do %> <li> <span class="inline-flex items-center justify-center leading-5 px-3.5 py-2 bg-white border dark:bg-gray-900 dark:border-gray-400 border-gray-200 text-gray-400">...</span> </li> <% end %> <%= if item.type == "next" do %> <div> <.link type={@link_type} to={get_path(@path, item.number, @current_page)} class="ml-2 inline-flex items-center justify-center rounded leading-5 px-2.5 py-2 bg-white hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800 dark:border-gray-400 border border-gray-200 text-gray-600 hover:text-gray-800"> <Heroicons.Solid.chevron_right class="w-5 h-5 text-gray-600 dark:text-gray-400" /> </.link> </div> <% end %> <% end %> </ul> </div> """ end defp get_items(total_pages, current_page, sibling_count, boundary_count) do start_pages = 1..min(boundary_count, total_pages) |> Enum.to_list() end_pages = max(total_pages - boundary_count + 1, boundary_count + 1)..total_pages |> Enum.to_list() siblings_start = max( min( current_page - sibling_count, total_pages - boundary_count - sibling_count * 2 - 1), boundary_count + 2 ) siblings_end = min( max(current_page + sibling_count, boundary_count + sibling_count * 2 + 2), (if length(end_pages) > 0, do: List.first(end_pages) - 2, else: total_pages - 1) ) items = [] # Previous button items = if current_page > 1, do: items ++ [%{type: "previous", number: current_page - 1}], else: items # Start pages items = Enum.reduce(start_pages, items, fn i, acc -> acc ++ [%{type: "page", number: i, first: i == 1}] end) # First ellipsis items = if siblings_start > boundary_count + 2, do: items ++ [%{type: "ellipsis"}], else: (if boundary_count + 1 < total_pages - boundary_count, do: items ++ [%{type: "page", number: boundary_count + 1}], else: items) # Siblings items = Enum.reduce(siblings_start..siblings_end, items, fn i, acc -> acc ++ [%{type: "page", number: i}] end) # Second ellipsis items = if siblings_end < total_pages - boundary_count - 1, do: items ++ [%{type: "ellipsis"}], else: (if total_pages - boundary_count > boundary_count, do: items ++ [%{type: "page", number: total_pages - boundary_count}], else: items) # End pages items = Enum.reduce(end_pages, items, fn i, acc -> acc ++ [%{type: "page", number: i, last: i == total_pages}] end) # Next button if current_page < total_pages, do: items ++ [%{type: "next", number: current_page + 1}], else: items end defp get_box_class(item, is_active \\ false) do base_classes = "inline-flex items-center justify-center leading-5 px-3.5 py-2 border border-gray-200 hover:bg-gray-50 dark:hover:bg-gray-800 dark:border-gray-400 border border-gray-200 text-gray-600 hover:text-gray-800" active_classes = if is_active, do: "bg-gray-100 dark:bg-gray-800 dark:text-gray-300 hover:bg-gray-100 text-gray-800", else: "dark:text-gray-400 text-gray-600 hover:text-gray-800 dark:hover:text-gray-400" rounded_classes = cond do item[:first] -> "rounded-l " item[:last] -> "rounded-r" true -> "" end Enum.join([base_classes, active_classes, rounded_classes], " ") end defp get_path(path, "previous", current_page) do String.replace(path, ":page", Integer.to_string(current_page - 1)) end defp get_path(path, "next", current_page) do String.replace(path, ":page", Integer.to_string(current_page + 1)) end defp get_path(path, page_number, _current_page) do String.replace(path, ":page", Integer.to_string(page_number)) end end
40.843972
315
0.612259
ff8289e11d74f17c964644888c72da544f40fed9
136
ex
Elixir
lib/pgsub_web/controllers/page_controller.ex
bredikhin/phoenix-postgresql-notify-listen-example
1b6be1963a9da90e166f7b345850fbfd95d17498
[ "MIT" ]
18
2017-07-27T10:13:46.000Z
2021-09-03T22:28:28.000Z
lib/pgsub_web/controllers/page_controller.ex
bredikhin/phoenix-postgresql-notify-listen-example
1b6be1963a9da90e166f7b345850fbfd95d17498
[ "MIT" ]
1
2021-04-27T10:15:22.000Z
2021-04-27T10:15:22.000Z
lib/pgsub_web/controllers/page_controller.ex
bredikhin/phoenix-postgresql-notify-listen-example
1b6be1963a9da90e166f7b345850fbfd95d17498
[ "MIT" ]
3
2020-08-30T09:05:35.000Z
2022-01-24T09:06:15.000Z
defmodule PgsubWeb.PageController do use PgsubWeb, :controller def index(conn, _params) do render conn, "index.html" end end
17
36
0.735294