hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequence
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequence
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequence
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
73322ba4acecd9a81c2962202b0e9fa04d3774cd
3,408
ex
Elixir
lib/mavlink/udp_in_connection.ex
beamuav/elixir-mavlink
1db95ccb7e631f89159ff1d0927fe7d5722107be
[ "MIT" ]
5
2019-08-10T08:21:38.000Z
2021-05-27T23:51:05.000Z
lib/mavlink/udp_in_connection.ex
beamuav/elixir-mavlink
1db95ccb7e631f89159ff1d0927fe7d5722107be
[ "MIT" ]
15
2019-08-18T08:47:05.000Z
2021-05-24T07:05:18.000Z
lib/mavlink/udp_in_connection.ex
beamuav/elixir-mavlink
1db95ccb7e631f89159ff1d0927fe7d5722107be
[ "MIT" ]
null
null
null
defmodule MAVLink.UDPInConnection do @moduledoc """ MAVLink.Router delegate for UDP connections """ require Logger import MAVLink.Frame, only: [binary_to_frame_and_tail: 1, validate_and_unpack: 2] alias MAVLink.Frame defstruct [ address: nil, port: nil, socket: nil] @type t :: %MAVLink.UDPInConnection{ address: MAVLink.Types.net_address, port: MAVLink.Types.net_port, socket: pid} # Create connection if this is the first time we've received on it def handle_info({:udp, socket, source_addr, source_port, raw}, nil, dialect) do handle_info( {:udp, socket, source_addr, source_port, raw}, %MAVLink.UDPInConnection{address: source_addr, port: source_port, socket: socket}, dialect) end def handle_info({:udp, socket, source_addr, source_port, raw}, receiving_connection, dialect) do case binary_to_frame_and_tail(raw) do :not_a_frame -> # Noise or malformed frame :ok = Logger.debug("UDPInConnection.handle_info: Not a frame #{inspect(raw)}") {:error, :not_a_frame, {socket, source_addr, source_port}, receiving_connection} {received_frame, _rest} -> # UDP sends frame per packet, so ignore rest case validate_and_unpack(received_frame, dialect) do {:ok, valid_frame} -> # Include address and port in connection key because multiple # clients can connect to a UDP "in" port. {:ok, {socket, source_addr, source_port}, receiving_connection, valid_frame} :unknown_message -> # We re-broadcast valid frames with unknown messages :ok = Logger.debug "rebroadcasting unknown message with id #{received_frame.message_id}}" {:ok, {socket, source_addr, source_port}, receiving_connection, struct(received_frame, [target: :broadcast])} reason -> :ok = Logger.debug( "UDPInConnection.handle_info: frame received from " <> "#{Enum.join(Tuple.to_list(source_addr), ".")}:#{source_port} failed: #{Atom.to_string(reason)}") {:error, reason, {socket, source_addr, source_port}, receiving_connection} end end end def connect(["udpin", address, port], controlling_process) do # Do not add to connections, we don't want to forward to ourselves # Router.update_route_info() will add connections for other parties that # connect to this socket case :gen_udp.open(port, [:binary, ip: address, active: :true]) do {:ok, socket} -> :ok = Logger.info("Opened udpin:#{Enum.join(Tuple.to_list(address), ".")}:#{port}") :gen_udp.controlling_process(socket, controlling_process) other -> :ok = Logger.warn("Could not open udpin:#{Enum.join(Tuple.to_list(address), ".")}:#{port}: #{inspect(other)}. Retrying in 1 second") :timer.sleep(1000) connect(["udpin", address, port], controlling_process) end end def forward(%MAVLink.UDPInConnection{ socket: socket, address: address, port: port}, %Frame{version: 1, mavlink_1_raw: packet}) do :gen_udp.send(socket, address, port, packet) end def forward(%MAVLink.UDPInConnection{ socket: socket, address: address, port: port}, %Frame{version: 2, mavlink_2_raw: packet}) do :gen_udp.send(socket, address, port, packet) end end
41.060241
140
0.655223
73323ce347062745b6e77b2295c51040e7545fb1
1,119
exs
Elixir
clients/sheets/mix.exs
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/sheets/mix.exs
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/sheets/mix.exs
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
defmodule GoogleApi.Sheets.V4.Mixfile do use Mix.Project @version "0.4.0" def project do [app: :google_api_sheets, version: @version, elixir: "~> 1.4", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/sheets" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.1.0"}, {:ex_doc, "~> 0.16", only: :dev}, {:dialyxir, "~> 0.5", only: [:dev], runtime: false} ] end defp description() do """ Reads and writes Google Sheets. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/sheets", "Homepage" => "https://developers.google.com/sheets/" } ] end end
22.836735
106
0.581769
7332661392aa0a5c53396b6cbbb812ed7dcc3c7a
4,944
ex
Elixir
bricks/test/lib/genservers.ex
jjl/bricks.ex
318db55c0b316fe88c701a962d8a3fd24019130e
[ "Apache-2.0" ]
null
null
null
bricks/test/lib/genservers.ex
jjl/bricks.ex
318db55c0b316fe88c701a962d8a3fd24019130e
[ "Apache-2.0" ]
null
null
null
bricks/test/lib/genservers.ex
jjl/bricks.ex
318db55c0b316fe88c701a962d8a3fd24019130e
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2018 James Laver # # 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 Bricks.Test.Genserver.Echo1 do use GenServer alias Bricks.{Connector, Socket} import Bricks.Sugar def start_link(args) do GenServer.start_link(__MODULE__, args, []) end def send_data(pid, data) do GenServer.call(pid, {:send, data}) end def stop(pid) do GenServer.stop(pid) end # Callbacks def init([conn, parent]) do {:ok, sock} = Connector.connect(conn) {:ok, sock} = Socket.extend_active(sock) {:ok, {sock, parent}} end def handle_call({:send, data}, _from, {sock, _} = state) do :ok = Socket.send_data(sock, data) {:reply, :ok, state} end defhandle_info data({SOCKET, parent} = state, data) do send(parent, {:data, data}) {:noreply, state} end defhandle_info error({SOCKET, _expected, _buffer, _parent} = state, reason) do {:stop, reason, state} end defhandle_info closed({SOCKET, parent} = state) do send(parent, :closed) {:stop, :closed, state} end defhandle_info passive({SOCKET = socket, parent}) do {:ok, sock} = Socket.extend_active(socket) {:noreply, {sock, parent}} end end defmodule Bricks.Test.Genserver.EchoOnce do use GenServer alias Bricks.{Connector, Socket} import Bricks.Sugar def start_link(args) do GenServer.start_link(__MODULE__, args, []) end def send_data(pid, data) do GenServer.call(pid, {:send, data}) end def stop(pid) do GenServer.stop(pid) end # Callbacks def init([conn, parent]) do {:ok, sock} = Connector.connect(conn) {:ok, sock} = Socket.extend_active(sock) {:ok, {sock, parent}} end def handle_call({:send, data}, _from, {sock, _} = state) do :ok = Socket.send_data(sock, data) {:reply, :ok, state} end defhandle_info data({SOCKET = socket, parent}, data) do send(parent, {:data, data}) {:ok, sock} = Socket.extend_active(socket) {:noreply, {sock, parent}} end defhandle_info error({SOCKET, _expected, _buffer, _parent} = state, reason) do {:stop, reason, state} end defhandle_info closed({SOCKET, parent} = state) do send(parent, :closed) {:stop, :closed, state} end end defmodule Bricks.Test.Genserver.Fixed1 do use GenServer alias Bricks.{Connector, Socket} import Bricks.Sugar def start_link(args) do GenServer.start_link(__MODULE__, args, []) end def stop(pid) do GenServer.stop(pid) end # Callbacks def init([conn, target, parent]) do {:ok, sock} = Connector.connect(conn) {:ok, sock} = Socket.extend_active(sock) {:ok, {sock, parent, target, ""}} end defhandle_info data({SOCKET = socket, parent, target, acc} = state, data) do data = acc <> data if byte_size(data) >= target do send(parent, {:data, data}) {:noreply, state} else {:noreply, {socket, parent, target, data}} end end defhandle_info error({SOCKET, _, _, _} = state, reason) do {:stop, reason, state} end defhandle_info closed({SOCKET, parent, _, _} = state) do send(parent, :closed) {:stop, :closed, state} end defhandle_info passive({SOCKET = socket, parent, target, acc}) do {:ok, sock} = Socket.extend_active(socket) {:noreply, {sock, parent, target, acc}} end end defmodule Bricks.Test.Genserver.FixedOnce do use GenServer alias Bricks.{Connector, Socket} import Bricks.Sugar def start_link(args) do GenServer.start_link(__MODULE__, args, []) end def stop(pid) do GenServer.stop(pid) end # Callbacks def init([conn, target, parent]) do {:ok, sock} = Connector.connect(conn) {:ok, sock} = Socket.extend_active(sock) {:ok, {sock, parent, target, ""}} end defhandle_info data({SOCKET = socket, parent, target, acc} = state, data) do data = acc <> data if byte_size(data) >= target do send(parent, {:data, data}) {:noreply, state} else {:ok, sock} = Socket.extend_active(socket) {:noreply, {sock, parent, target, data}} end end defhandle_info error({SOCKET, _, _, _} = state, reason) do {:stop, reason, state} end defhandle_info closed({SOCKET, parent, _, _} = state) do send(parent, :closed) {:stop, :closed, state} end defhandle_info passive({SOCKET = socket, parent, target, acc}) do {:ok, sock} = Socket.extend_active(socket) {:noreply, {sock, parent, target, acc}} end end
24.117073
80
0.657362
73328f90c07cc2d4bfc372bc840a79e223836be7
1,517
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/networks_update_peering_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/compute/lib/google_api/compute/v1/model/networks_update_peering_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/compute/lib/google_api/compute/v1/model/networks_update_peering_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Compute.V1.Model.NetworksUpdatePeeringRequest do @moduledoc """ ## Attributes * `networkPeering` (*type:* `GoogleApi.Compute.V1.Model.NetworkPeering.t`, *default:* `nil`) - """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :networkPeering => GoogleApi.Compute.V1.Model.NetworkPeering.t() | nil } field(:networkPeering, as: GoogleApi.Compute.V1.Model.NetworkPeering) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.NetworksUpdatePeeringRequest do def decode(value, options) do GoogleApi.Compute.V1.Model.NetworksUpdatePeeringRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.NetworksUpdatePeeringRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.276596
99
0.752142
733290f712796769dcce0ecc8a9f130f8cf44c11
784
exs
Elixir
2016/day05/test/day05/password_test.exs
matt-thomson/advent-of-code
feff903151284240a9d3f0c84cdfe52d8d11ef06
[ "MIT" ]
null
null
null
2016/day05/test/day05/password_test.exs
matt-thomson/advent-of-code
feff903151284240a9d3f0c84cdfe52d8d11ef06
[ "MIT" ]
null
null
null
2016/day05/test/day05/password_test.exs
matt-thomson/advent-of-code
feff903151284240a9d3f0c84cdfe52d8d11ef06
[ "MIT" ]
null
null
null
defmodule Day05.PasswordTest do use ExUnit.Case alias Day05.Password test "selects the password character from a hash for part one" do assert Password.char_one(<<0, 0, 8, 100>>) == "8" assert Password.char_one(<<0, 0, 12, 100>>) == "c" end test "selects the password character from a hash for part two" do assert Password.char_two(<<0, 0, 8, 100>>) == "6" assert Password.char_two(<<0, 0, 12, 200>>) == "c" end test "selects the password position from a hash" do assert Password.position(<<0, 0, 6, 4>>) == 6 end test "sets characters from a hash" do hash = <<0, 0, 1, 200>> assert [nil, nil, "a"] |> Password.set_char(hash) == [nil, "c", "a"] assert [nil, "b", "a"] |> Password.set_char(hash) == [nil, "b", "a"] end end
29.037037
72
0.608418
7332bcefef35f5019aec6b0373b011a448ffc200
405
ex
Elixir
lib/ambry_web/live/components/search_box.ex
doughsay/ambry
c04e855bf06a6b00b8053c6eacb2eac14a56a37c
[ "MIT" ]
12
2021-09-30T20:51:49.000Z
2022-01-27T04:09:32.000Z
lib/ambry_web/live/components/search_box.ex
doughsay/ambry
c04e855bf06a6b00b8053c6eacb2eac14a56a37c
[ "MIT" ]
76
2021-10-01T05:45:11.000Z
2022-03-28T04:12:39.000Z
lib/ambry_web/live/components/search_box.ex
doughsay/ambry
c04e855bf06a6b00b8053c6eacb2eac14a56a37c
[ "MIT" ]
2
2021-10-04T19:27:28.000Z
2022-01-13T22:36:38.000Z
defmodule AmbryWeb.Components.SearchBox do @moduledoc false use AmbryWeb, :live_component @impl Phoenix.LiveComponent def handle_event("search", %{"search" => %{"query" => query}}, socket) do case String.trim(query) do "" -> {:noreply, socket} query -> {:noreply, push_redirect(socket, to: Routes.search_results_path(socket, :results, query))} end end end
23.823529
98
0.654321
7332f733ba74e80cca2272b51c733e67ed07a6cf
714
ex
Elixir
lib/openapi_compiler/component/schema.ex
jshmrtn/openapi-compiler
72ce58321bcaf7310b1286fa90dd2feaa2a7b565
[ "MIT" ]
3
2021-09-07T13:13:44.000Z
2022-01-16T22:25:11.000Z
lib/openapi_compiler/component/schema.ex
jshmrtn/openapi-compiler
72ce58321bcaf7310b1286fa90dd2feaa2a7b565
[ "MIT" ]
26
2020-03-31T17:26:58.000Z
2020-04-01T17:32:21.000Z
lib/openapi_compiler/component/schema.ex
jshmrtn/openapi-compiler
72ce58321bcaf7310b1286fa90dd2feaa2a7b565
[ "MIT" ]
1
2020-10-27T13:32:07.000Z
2020-10-27T13:32:07.000Z
defmodule OpenAPICompiler.Component.Schema do @moduledoc false defmacro define_module(context, mode) do quote location: :keep, bind_quoted: [context: context, mode: mode] do module_key = :"components_schema_#{mode}_module" %OpenAPICompiler.Context{schema: schema} = %{^module_key => module} = context defmodule module do require OpenAPICompiler.Typespec.Schema for root <- schema, {name, value} <- root["components"]["schemas"] || [] do OpenAPICompiler.Typespec.Schema.typespec(name, value, mode, context) end case @type do [] -> @moduledoc false _ -> @moduledoc "TODO" end end end end end
28.56
83
0.627451
7333068e1bcc39831ee45eafebb85c2c45a4eecf
2,521
ex
Elixir
clients/analytics_admin/lib/google_api/analytics_admin/v1alpha/model/google_analytics_admin_v1alpha_list_display_video360_advertiser_link_proposals_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/analytics_admin/lib/google_api/analytics_admin/v1alpha/model/google_analytics_admin_v1alpha_list_display_video360_advertiser_link_proposals_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/analytics_admin/lib/google_api/analytics_admin/v1alpha/model/google_analytics_admin_v1alpha_list_display_video360_advertiser_link_proposals_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaListDisplayVideo360AdvertiserLinkProposalsResponse do @moduledoc """ Response message for ListDisplayVideo360AdvertiserLinkProposals RPC. ## Attributes * `displayVideo360AdvertiserLinkProposals` (*type:* `list(GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaDisplayVideo360AdvertiserLinkProposal.t)`, *default:* `nil`) - List of DisplayVideo360AdvertiserLinkProposals. * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :displayVideo360AdvertiserLinkProposals => list( GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaDisplayVideo360AdvertiserLinkProposal.t() ) | nil, :nextPageToken => String.t() | nil } field(:displayVideo360AdvertiserLinkProposals, as: GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaDisplayVideo360AdvertiserLinkProposal, type: :list ) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaListDisplayVideo360AdvertiserLinkProposalsResponse do def decode(value, options) do GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaListDisplayVideo360AdvertiserLinkProposalsResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaListDisplayVideo360AdvertiserLinkProposalsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.19697
238
0.769139
7333954a5b40e6e6a6c8d102a178222d036346b3
143
ex
Elixir
web/controllers/dashboard_controller.ex
ikeikeikeike/panglao
6d3f6515d9f1ceb9a2e771ae2d54c222cedbf538
[ "MIT" ]
1
2017-02-18T21:20:17.000Z
2017-02-18T21:20:17.000Z
web/controllers/dashboard_controller.ex
ikeikeikeike/panglao
6d3f6515d9f1ceb9a2e771ae2d54c222cedbf538
[ "MIT" ]
null
null
null
web/controllers/dashboard_controller.ex
ikeikeikeike/panglao
6d3f6515d9f1ceb9a2e771ae2d54c222cedbf538
[ "MIT" ]
null
null
null
defmodule Panglao.DashboardController do use Panglao.Web, :controller def index(conn, _params) do render conn, "index.html" end end
17.875
40
0.741259
7333b6ddd38e09b3cc9e6e60a2324c333ac1fff1
411
exs
Elixir
apps/realtime/config/dev.exs
bus-detective/bus_detective_ng
ef54684d4f640384bd20a4d5550ff51ab440190b
[ "MIT" ]
8
2018-07-06T14:44:10.000Z
2021-08-19T17:24:25.000Z
apps/realtime/config/dev.exs
bus-detective/bus_detective_ng
ef54684d4f640384bd20a4d5550ff51ab440190b
[ "MIT" ]
12
2018-07-15T18:43:04.000Z
2022-02-10T16:07:47.000Z
apps/realtime/config/dev.exs
bus-detective/bus_detective_ng
ef54684d4f640384bd20a4d5550ff51ab440190b
[ "MIT" ]
1
2018-07-13T17:30:20.000Z
2018-07-13T17:30:20.000Z
use Mix.Config config :realtime, feeds: %{ "SORTA" => %{ trip_updates_url: "http://developer.go-metro.com/TMGTFSRealTimeWebService/TripUpdate/TripUpdates.pb", vehicle_positions_url: "http://developer.go-metro.com/TMGTFSRealTimeWebService/vehicle/VehiclePositions.pb" } } file = Path.join(Path.dirname(__ENV__.file), "dev.secret.exs") if File.exists?(file) do import_config file end
25.6875
113
0.727494
7333ca8ed1ae27593e2712f4d2ac23305541b4f9
7,249
exs
Elixir
.credo.exs
junan/elixir_google_scraper
d032f3a9d5a30e354f1e6d607434670334936630
[ "MIT" ]
null
null
null
.credo.exs
junan/elixir_google_scraper
d032f3a9d5a30e354f1e6d607434670334936630
[ "MIT" ]
25
2021-05-21T02:23:37.000Z
2021-07-09T09:22:32.000Z
.credo.exs
junan/elixir_google_scraper
d032f3a9d5a30e354f1e6d607434670334936630
[ "MIT" ]
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: 100]}, {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, []}, {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, []}, {Credo.Check.Refactor.UnlessWithElse, []}, {Credo.Check.Refactor.WithClauses, []}, # ## Warnings # {Credo.Check.Warning.BoolOperationOnSameValues, []}, {Credo.Check.Warning.ExpensiveEmptyEnumCheck, []}, {Credo.Check.Warning.IExPry, []}, {Credo.Check.Warning.IoInspect, []}, {Credo.Check.Warning.LazyLogging, []}, {Credo.Check.Warning.MixEnv, false}, {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.Readability.StrictModuleLayout, [ order: ~w/shortdoc moduledoc behaviour use import alias require module_attribute defstruct callback/a ]}, {Credo.Check.Consistency.MultiAliasImportRequireUse, false}, {Credo.Check.Consistency.UnusedVariableNames, false}, {Credo.Check.Design.DuplicatedCode, []}, {Credo.Check.Readability.AliasAs, false}, {Credo.Check.Readability.MultiAlias, false}, {Credo.Check.Readability.Specs, false}, {Credo.Check.Readability.SinglePipe, []}, {Credo.Check.Readability.WithCustomTaggedTuple, []}, {Credo.Check.Refactor.ABCSize, []}, {Credo.Check.Refactor.AppendSingleItem, []}, {Credo.Check.Refactor.DoubleBooleanNegation, []}, {Credo.Check.Refactor.ModuleDependencies, false}, {Credo.Check.Refactor.NegatedIsNil, []}, {Credo.Check.Refactor.PipeChainStart, []}, {Credo.Check.Refactor.VariableRebinding, files: %{excluded: ["**/*_test.exs"]}}, {Credo.Check.Warning.LeakyEnvironment, []}, {Credo.Check.Warning.MapGetUnsafePass, []}, {Credo.Check.Warning.UnsafeToAtom, []} # # Custom checks can be created using `mix credo.gen.check`. # ] } ] }
38.152632
107
0.604773
7333d8c78ff04322a28c450292115272a03d2b6f
3,195
exs
Elixir
apps/service_broadcast/test/broadcast/event/handler_test.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
12
2020-01-27T19:43:02.000Z
2021-07-28T19:46:29.000Z
apps/service_broadcast/test/broadcast/event/handler_test.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
81
2020-01-28T18:07:23.000Z
2021-11-22T02:12:13.000Z
apps/service_broadcast/test/broadcast/event/handler_test.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
10
2020-02-13T21:24:09.000Z
2020-05-21T18:39:35.000Z
defmodule Broadcast.Event.HandlerTest do use ExUnit.Case use Placebo import AssertAsync import Events, only: [transform_define: 0, dataset_delete: 0] import Definition, only: [identifier: 1] alias Broadcast.ViewState @instance Broadcast.Application.instance() setup do on_exit(fn -> [ViewState.Streams, ViewState.Transformations, ViewState.Sources, ViewState.Destinations] |> Enum.each(fn state -> Brook.Test.clear_view_state(@instance, state.collection()) end) end) :ok end describe "#{transform_define()}" do test "will store the transform definition in view state" do transform = Transform.new!( id: "transform-1", dataset_id: "dataset-1", subset_id: "sb1", dictionary: [ Dictionary.Type.String.new!(name: "name"), Dictionary.Type.Integer.new!(name: "age") ], steps: [ Transform.MoveField.new!(from: "name", to: "fullname") ] ) Brook.Test.send(@instance, transform_define(), "testing", transform) assert {:ok, ^transform} = identifier(transform) |> Broadcast.ViewState.Transformations.get() end end describe "dataset_delete" do setup do allow(Broadcast.Stream.Supervisor.terminate_child(any()), return: :ok) transform = Transform.new!( id: "transform-1", dataset_id: "ds1", subset_id: "sb1", dictionary: [], steps: [] ) load = Load.new!( id: "load-1", dataset_id: "ds1", subset_id: "sb1", source: Source.Fake.new!(), destination: Destination.Fake.new!() ) key = identifier(load) Brook.Test.with_event(@instance, fn -> ViewState.Transformations.persist(key, transform) ViewState.Streams.persist(key, load) ViewState.Sources.persist(key, load.source) ViewState.Destinations.persist(key, load.destination) end) delete = Delete.new!( id: "delete-1", dataset_id: "ds1", subset_id: "sb1" ) Brook.Test.send(@instance, dataset_delete(), "testing", delete) [transform: transform, load: load, delete: delete, key: key] end test "deletes the transformation", %{key: key} do assert_async do assert {:ok, nil} = ViewState.Transformations.get(key) end end test "deletes the stream", %{key: key} do assert_async do assert {:ok, nil} = ViewState.Streams.get(key) end end test "stops the stream", %{load: load} do assert_async do assert_called(Broadcast.Stream.Supervisor.terminate_child(load)) end end test "deletes the source", %{load: %{source: source}, key: key} do assert_receive {:source_delete, ^source}, 1_000 assert {:ok, nil} = ViewState.Sources.get(key) end test "deletes the destination", %{load: %{destination: destination}, key: key} do assert_receive {:destination_delete, ^destination} assert {:ok, nil} = ViewState.Destinations.get(key) end end end
27.543103
95
0.599061
7333e1a64f8cd70080d68dc9defa1de16c68b77e
357
exs
Elixir
test/phoenix_starter/users/user_role_test.exs
newaperio/phoenix_starter
02f2f5550a94b940bb4e9c61042b032f54af8b72
[ "MIT" ]
3
2021-03-19T10:39:02.000Z
2021-07-25T19:54:09.000Z
test/phoenix_starter/users/user_role_test.exs
newaperio/phoenix_starter
02f2f5550a94b940bb4e9c61042b032f54af8b72
[ "MIT" ]
204
2020-11-27T06:00:31.000Z
2022-03-25T08:08:16.000Z
test/phoenix_starter/users/user_role_test.exs
newaperio/phoenix_starter
02f2f5550a94b940bb4e9c61042b032f54af8b72
[ "MIT" ]
null
null
null
defmodule PhoenixStarter.Users.UserRoleTest do use PhoenixStarter.DataCase alias PhoenixStarter.Users.UserRole test "roles/0" do assert UserRole.roles() == [:admin, :ops_admin, :user] end test "role/1" do assert %UserRole{} = UserRole.role(:admin) assert_raise ArgumentError, fn -> UserRole.role(:notarole) end end end
19.833333
58
0.697479
7333eda9ae0a3a85a44fe682bcd0b6f9df1dbe16
3,940
ex
Elixir
lib/banchan_web/router.ex
riamaria/banchan
c4f8bd9374acaf0a8bb2c501e2ae1eb78f96579f
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
lib/banchan_web/router.ex
riamaria/banchan
c4f8bd9374acaf0a8bb2c501e2ae1eb78f96579f
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
lib/banchan_web/router.ex
riamaria/banchan
c4f8bd9374acaf0a8bb2c501e2ae1eb78f96579f
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
defmodule BanchanWeb.Router do use BanchanWeb, :router import BanchanWeb.UserAuth import Phoenix.LiveDashboard.Router alias BanchanWeb.EnsureRolePlug pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_live_flash plug :put_root_layout, {BanchanWeb.LayoutView, :root} plug :protect_from_forgery # NB(zkat): unsafe-eval has to be enabled because webpack does it for its internals. plug :put_secure_browser_headers, %{ "content-security-policy" => "default-src 'self' 'unsafe-eval'; style-src data: 'self' 'unsafe-inline'; script-src data: 'self' 'unsafe-inline' 'unsafe-eval'; object-src data: 'unsafe-eval'; font-src data: 'unsafe-eval'; img-src data: 'self'" } plug :fetch_current_user end pipeline :api do plug :accepts, ["json"] end pipeline :admin do plug EnsureRolePlug, :admin end pipeline :mod do plug EnsureRolePlug, [:admin, :mod] end pipeline :creator do plug EnsureRolePlug, [:admin, :mod, :creator] end scope "/", BanchanWeb do pipe_through [:browser, :require_authenticated_user] live "/denizens/:handle/edit", DenizenLive.Edit, :edit live "/studios/new", StudioLive.New, :new live "/studios/:handle/settings", StudioLive.Settings, :show live "/studios/:handle/offerings", StudioLive.Offerings.Index, :index live "/studios/:handle/offerings/new", StudioLive.Offerings.New, :new live "/studios/:handle/offerings/edit/:offering_type", StudioLive.Offerings.Edit, :edit live "/studios/:handle/commissions/new/:offering_type", StudioLive.Commissions.New, :new live "/studios/:handle/commissions/:commission_id", StudioLive.Commissions.Show, :show get "/studios/:handle/commissions/:commission_id/attachment/:key", CommissionAttachmentController, :show get "/studios/:handle/commissions/:commission_id/attachment/:key/thumbnail", CommissionAttachmentController, :thumbnail live "/dashboard", DashboardLive, :index live "/settings", SettingsLive, :edit live "/mfa_setup", SetupMfaLive, :edit get "/settings/confirm_email/:token", UserSettingsController, :confirm_email get "/settings/refresh_session/:return_to", UserSessionController, :refresh_session end scope "/", BanchanWeb do pipe_through :browser live "/", HomeLive, :index live "/denizens/:handle", DenizenLive.Show, :show get "/denizens/:handle/pfp.jpeg", ProfileImageController, :pfp get "/denizens/:handle/pfp_thumb.jpeg", ProfileImageController, :thumb get "/denizens/:handle/header.jpeg", ProfileImageController, :header live "/studios", StudioLive.Index, :index live "/studios/:handle", StudioLive.Shop, :show live "/studios/:handle/about", StudioLive.About, :show live "/studios/:handle/portfolio", StudioLive.Portfolio, :show live "/studios/:handle/qa", StudioLive.Qa, :show live "/confirm", ConfirmationLive, :show get "/confirm/:token", UserConfirmationController, :confirm delete "/logout", UserSessionController, :delete get "/force_logout", UserSessionController, :force_logout get "/go/:handle", DispatchController, :dispatch end scope "/", BanchanWeb do pipe_through [:browser, :redirect_if_user_is_authenticated] live "/login", LoginLive, :new post "/login", UserSessionController, :create live "/register", RegisterLive, :new post "/register", UserRegistrationController, :create live "/reset_password", ForgotPasswordLive, :edit live "/reset_password/:token", ResetPasswordLive, :edit end scope "/admin" do # Enable admin stuff dev/test side but restrict it in prod pipe_through [:browser | if(Mix.env() in [:dev, :test], do: [], else: [:admin])] live_dashboard "/dashboard", metrics: BanchanWeb.Telemetry, ecto_repos: Banchan.Repo forward "/sent_emails", Bamboo.SentEmailViewerPlug end end
33.965517
221
0.709137
7333f65acae4d651881676e35ccc13b7aacb64d8
1,531
ex
Elixir
clients/firebase_rules/lib/google_api/firebase_rules/v1/model/empty.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/firebase_rules/lib/google_api/firebase_rules/v1/model/empty.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/firebase_rules/lib/google_api/firebase_rules/v1/model/empty.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "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.FirebaseRules.V1.Model.Empty do @moduledoc """ A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. ## Attributes """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{} end defimpl Poison.Decoder, for: GoogleApi.FirebaseRules.V1.Model.Empty do def decode(value, options) do GoogleApi.FirebaseRules.V1.Model.Empty.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.FirebaseRules.V1.Model.Empty do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.452381
345
0.758328
73341b9016876571359c0bd7b9c9d94563f91b68
2,040
exs
Elixir
test/central_web/controllers/logging/error_log_controller_test.exs
icexuick/teiserver
22f2e255e7e21f977e6b262acf439803626a506c
[ "MIT" ]
6
2021-02-08T10:42:53.000Z
2021-04-25T12:12:03.000Z
test/central_web/controllers/logging/error_log_controller_test.exs
icexuick/teiserver
22f2e255e7e21f977e6b262acf439803626a506c
[ "MIT" ]
null
null
null
test/central_web/controllers/logging/error_log_controller_test.exs
icexuick/teiserver
22f2e255e7e21f977e6b262acf439803626a506c
[ "MIT" ]
2
2021-02-23T22:34:00.000Z
2021-04-08T13:31:36.000Z
defmodule CentralWeb.Logging.ErrorLogControllerTest do use CentralWeb.ConnCase, async: true alias Central.Logging alias Central.Helpers.GeneralTestLib setup do GeneralTestLib.conn_setup(~w(logging.error.show admin.dev)) end defp create_test_error(conn) do assert_raise ArithmeticError, fn -> get(conn, Routes.admin_tool_path(conn, :test_error)) end end test "lists all entries on index", %{conn: conn} do create_test_error(conn) create_test_error(conn) create_test_error(conn) conn = get(conn, Routes.logging_error_log_path(conn, :index)) assert html_response(conn, 200) =~ "Error logs" assert html_response(conn, 200) =~ "Delete all" end test "shows chosen resource", %{conn: conn} do create_test_error(conn) error_log = Logging.get_error_log!(nil) conn = get(conn, Routes.logging_error_log_path(conn, :show, error_log)) assert html_response(conn, 200) =~ "<h4>Error log #" end test "deletes chosen resource", %{conn: conn} do create_test_error(conn) error_log = Logging.get_error_log!(nil) conn = delete(conn, Routes.logging_error_log_path(conn, :delete, error_log)) assert redirected_to(conn) == Routes.logging_error_log_path(conn, :index) assert_raise Ecto.NoResultsError, fn -> Logging.get_error_log!(error_log.id) end end test "delete all", %{conn: conn} do create_test_error(conn) create_test_error(conn) create_test_error(conn) create_test_error(conn) assert Enum.count(Logging.list_error_logs()) == 4 conn = get(conn, Routes.logging_error_log_path(conn, :delete_all_form)) assert html_response(conn, 200) =~ "Back to error logs" assert html_response(conn, 200) =~ "Confirm deletion" assert Enum.count(Logging.list_error_logs()) == 4 conn = post(conn, Routes.logging_error_log_path(conn, :delete_all_post)) assert redirected_to(conn) == Routes.logging_error_log_path(conn, :index) assert Enum.count(Logging.list_error_logs()) == 0 end end
32.903226
80
0.715686
73342f0b594ce6975642d76d9e4f63fe08a93591
1,529
exs
Elixir
test/url_gen_test.exs
X-Plane/weather-mirror
7db39c342ef33fa9688751ce661ab5ff8e6ebb6c
[ "MIT" ]
6
2019-09-08T15:45:52.000Z
2022-03-18T07:08:03.000Z
test/url_gen_test.exs
X-Plane/weather-mirror
7db39c342ef33fa9688751ce661ab5ff8e6ebb6c
[ "MIT" ]
null
null
null
test/url_gen_test.exs
X-Plane/weather-mirror
7db39c342ef33fa9688751ce661ab5ff8e6ebb6c
[ "MIT" ]
1
2019-12-12T13:29:52.000Z
2019-12-12T13:29:52.000Z
defmodule WeatherMirror.UrlGenTest do use ExUnit.Case, async: true import WeatherMirror.UrlGen, only: [gfs: 1, wafs: 1, metar: 1] # 2019-02-13 02:37Z --- 6 hours ago will cross the date boundary @early DateTime.from_unix!(1_550_025_476) # 2019-02-12 17:32Z @mid DateTime.from_unix!(1_549_992_766) # 2019-02-11 22:14Z @late DateTime.from_unix!(1_549_923_284) test "generates GFS URLs" do gfs_base = "https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_1p00.pl" assert gfs(@early) == "#{gfs_base}?dir=%2Fgfs.20190212/18&file=gfs.t18z.pgrb2.1p00.f006&lev_700_mb=1&lev_250_mb=1&var_UGRD=1&var_VGRD=1" assert gfs(@mid) == "#{gfs_base}?dir=%2Fgfs.20190212/12&file=gfs.t12z.pgrb2.1p00.f003&lev_700_mb=1&lev_250_mb=1&var_UGRD=1&var_VGRD=1" assert gfs(@late) == "#{gfs_base}?dir=%2Fgfs.20190211/18&file=gfs.t18z.pgrb2.1p00.f003&lev_700_mb=1&lev_250_mb=1&var_UGRD=1&var_VGRD=1" end test "generates WAFS URLs" do assert wafs(@early) == "https://www.ftp.ncep.noaa.gov/data/nccf/com/gfs/prod/gfs.20190212/18/WAFS_blended_2019021218f06.grib2" assert wafs(@mid) == "https://www.ftp.ncep.noaa.gov/data/nccf/com/gfs/prod/gfs.20190212/12/WAFS_blended_2019021212f06.grib2" assert wafs(@late) == "https://www.ftp.ncep.noaa.gov/data/nccf/com/gfs/prod/gfs.20190211/18/WAFS_blended_2019021118f06.grib2" end test "generates METAR URLs" do test_date = DateTime.from_unix!(1_550_019_493) assert metar(test_date) == "https://tgftp.nws.noaa.gov/data/observations/metar/cycles/23Z.TXT" end end
50.966667
140
0.734467
73343922ba38d5802392eb5b2b4e786c060bddae
84
exs
Elixir
test/asteroid_web/views/layout_view_test.exs
tanguilp/asteroid
8e03221d365da7f03f82df192c535d3ba2101f4d
[ "Apache-2.0" ]
36
2019-07-23T20:01:05.000Z
2021-08-05T00:52:34.000Z
test/asteroid_web/views/layout_view_test.exs
tanguilp/asteroid
8e03221d365da7f03f82df192c535d3ba2101f4d
[ "Apache-2.0" ]
19
2019-08-23T19:04:50.000Z
2021-05-07T22:12:25.000Z
test/asteroid_web/views/layout_view_test.exs
tanguilp/asteroid
8e03221d365da7f03f82df192c535d3ba2101f4d
[ "Apache-2.0" ]
3
2019-09-06T10:47:20.000Z
2020-09-09T03:43:31.000Z
defmodule AsteroidWeb.LayoutViewTest do use AsteroidWeb.ConnCase, async: true end
21
39
0.833333
73343c54a996ef2e250e7fc583d0294947d2b2d6
1,280
exs
Elixir
test/models/tp_threshold_test.exs
zombalo/cgrates_web_jsonapi
47845be4311839fe180cc9f2c7c6795649da4430
[ "MIT" ]
null
null
null
test/models/tp_threshold_test.exs
zombalo/cgrates_web_jsonapi
47845be4311839fe180cc9f2c7c6795649da4430
[ "MIT" ]
null
null
null
test/models/tp_threshold_test.exs
zombalo/cgrates_web_jsonapi
47845be4311839fe180cc9f2c7c6795649da4430
[ "MIT" ]
null
null
null
defmodule CgratesWebJsonapi.TpThresholdTest do use CgratesWebJsonapi.ModelCase alias CgratesWebJsonapi.TpThreshold alias CgratesWebJsonapi.Repo import CgratesWebJsonapi.Factory @valid_attrs %{tenant: "some content", custom_id: "true", max_hits: "10", filter_ids: "some content", activation_interval: "some content", min_hits: "1", action_ids: "some content", min_sleep: "some content", async: false, blocker: false, tpid: "some content", weight: "100.5"} @invalid_attrs %{} test "changeset with valid attributes" do changeset = TpThreshold.changeset(%TpThreshold{}, @valid_attrs) assert changeset.valid? end test "changeset with invalid attributes" do changeset = TpThreshold.changeset(%TpThreshold{}, @invalid_attrs) refute changeset.valid? end describe "#from_csv" do test "it parses csv and inerts records to DB" do path = Path.expand("../fixtures/csv/tp-thresholds.csv", __DIR__) tariff_plan = insert :tariff_plan path |> TpThreshold.from_csv(tariff_plan.alias) |> Enum.into([]) assert Repo.get_by(TpThreshold, %{ tenant: "tenant1", custom_id: "cust1", blocker: false, tpid: tariff_plan.alias }) end end end
32
101
0.675781
73344d7b665e7890699767458a47f05c8f1d9e52
268
exs
Elixir
day02/el_a.exs
mason-bially/aoc-2019
f1cefa455b967d9d23dcd092be6242f8ff539c7a
[ "MIT" ]
1
2019-12-13T22:44:09.000Z
2019-12-13T22:44:09.000Z
day02/el_a.exs
mason-bially/aoc-2019
f1cefa455b967d9d23dcd092be6242f8ff539c7a
[ "MIT" ]
null
null
null
day02/el_a.exs
mason-bially/aoc-2019
f1cefa455b967d9d23dcd092be6242f8ff539c7a
[ "MIT" ]
1
2019-12-05T21:06:06.000Z
2019-12-05T21:06:06.000Z
Code.require_file("el.ex", __DIR__) memory = Day02.read_intcode("day02/input.txt") memory = :array.set(1, 12, memory) memory = :array.set(2, 2, memory) memory = Day02.run_program(%{memory: memory, pc: 0}) result = :array.get(0, memory) IO.inspect(result) # 6568671
24.363636
52
0.701493
7334c3036235f8217e378de15d466a617ec479bb
2,302
exs
Elixir
test/controllers/user_controller_test.exs
bschmeck/ex_gnarl
25d6961795f10a2d49efd1a29167a771ef9772f1
[ "MIT" ]
null
null
null
test/controllers/user_controller_test.exs
bschmeck/ex_gnarl
25d6961795f10a2d49efd1a29167a771ef9772f1
[ "MIT" ]
1
2017-04-21T17:02:56.000Z
2017-04-21T17:02:56.000Z
test/controllers/user_controller_test.exs
bschmeck/ex_gnarl
25d6961795f10a2d49efd1a29167a771ef9772f1
[ "MIT" ]
null
null
null
defmodule ExGnarl.UserControllerTest do use ExGnarl.ConnCase alias ExGnarl.User @valid_attrs %{email: "some content"} @invalid_attrs %{} test "lists all entries on index", %{conn: conn} do conn = get conn, user_path(conn, :index) assert html_response(conn, 200) =~ "Listing users" end test "renders form for new resources", %{conn: conn} do conn = get conn, user_path(conn, :new) assert html_response(conn, 200) =~ "New user" end test "creates resource and redirects when data is valid", %{conn: conn} do conn = post conn, user_path(conn, :create), user: @valid_attrs assert redirected_to(conn) == user_path(conn, :index) assert Repo.get_by(User, @valid_attrs) end test "does not create resource and renders errors when data is invalid", %{conn: conn} do conn = post conn, user_path(conn, :create), user: @invalid_attrs assert html_response(conn, 200) =~ "New user" end test "shows chosen resource", %{conn: conn} do user = Repo.insert! %User{} conn = get conn, user_path(conn, :show, user) assert html_response(conn, 200) =~ "Show user" end test "renders page not found when id is nonexistent", %{conn: conn} do assert_error_sent 404, fn -> get conn, user_path(conn, :show, -1) end end test "renders form for editing chosen resource", %{conn: conn} do user = Repo.insert! %User{} conn = get conn, user_path(conn, :edit, user) assert html_response(conn, 200) =~ "Edit user" end test "updates chosen resource and redirects when data is valid", %{conn: conn} do user = Repo.insert! %User{} conn = put conn, user_path(conn, :update, user), user: @valid_attrs assert redirected_to(conn) == user_path(conn, :show, user) assert Repo.get_by(User, @valid_attrs) end test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do user = Repo.insert! %User{} conn = put conn, user_path(conn, :update, user), user: @invalid_attrs assert html_response(conn, 200) =~ "Edit user" end test "deletes chosen resource", %{conn: conn} do user = Repo.insert! %User{} conn = delete conn, user_path(conn, :delete, user) assert redirected_to(conn) == user_path(conn, :index) refute Repo.get(User, user.id) end end
34.358209
98
0.675934
7334e91d3228055a679b2892e125e7354752430a
1,193
ex
Elixir
Seminarie 3/brot.ex
evansaboo/elixir-programming
57408424914003091003430500473546c94354d9
[ "MIT" ]
null
null
null
Seminarie 3/brot.ex
evansaboo/elixir-programming
57408424914003091003430500473546c94354d9
[ "MIT" ]
null
null
null
Seminarie 3/brot.ex
evansaboo/elixir-programming
57408424914003091003430500473546c94354d9
[ "MIT" ]
null
null
null
defmodule Brot do # This is the client version. def start(mandel) do {:ok, spawn(fn -> init(mandel) end)} end defp init(mandel) do self = self() brot(mandel, self) end defp brot(mandel, self) do send(mandel, {:req, self}) receive do {:pos, pr, pos, c, m} -> i = mandelbrot(c, m) send(pr, {:res, pos, i}) brot(mandel, self) :done -> :ok end end # mandelbrot(c, m): calculate the mandelbrot value of # complex value c with a maximum iteration of m. Returns # 0..(m - 1). def mandelbrot(c, m) do mandelbrot_vanilla(c, m) end # This is the vanilla version def mandelbrot_vanilla(c, m) do z0 = Cmplx.new(0, 0) test(0, z0, c, m) end def test(m, _z, _c, m), do: 0 def test(i, z, c, m) do a = Cmplx.abs(z) if a <= 2.0 do z1 = Cmplx.add(Cmplx.sqr(z), c) test(i + 1, z1, c, m) else i end end # This is using the Cmplx version of the calculation. def mandelbrot_cmplx(c, m) do Cmplx.mandelbrot(c, m) end # This is if we want to use the native code version. def mandelbrot_nif(c, m) do Cmplx.mandelbrot_nif(c, m) end end
18.936508
58
0.575021
7334ebbcb9a6bddb5ab48cf773398ea4da7aee70
570
ex
Elixir
plugins/ucc_chat/lib/ucc_chat_web/flex_bar/tab/mention.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
plugins/ucc_chat/lib/ucc_chat_web/flex_bar/tab/mention.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
plugins/ucc_chat/lib/ucc_chat_web/flex_bar/tab/mention.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
defmodule UccChatWeb.FlexBar.Tab.Mention do use UccChatWeb.FlexBar.Helpers alias UccChat.Mention alias UcxUcc.TabBar.Tab def add_buttons do TabBar.add_button Tab.new( __MODULE__, ~w[channel direct im], "mentions", ~g"Mentions", "icon-at", View, "mentions.html", 70) end def args(socket, {user_id, channel_id, _, _}, _) do mentions = user_id |> Mention.get_by_user_id_and_channel_id(channel_id) |> do_messages_args(user_id, channel_id) {[mentions: mentions], socket} end end
20.357143
58
0.647368
7334f99d0d139c59fc3ef8970bd801f6b1b6e9d2
2,822
ex
Elixir
clients/games/lib/google_api/games/v1/model/room_p2_p_status.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/model/room_p2_p_status.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/model/room_p2_p_status.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Games.V1.Model.RoomP2PStatus do @moduledoc """ This is a JSON template for an update on the status of a peer in a room. ## Attributes - connectionSetupLatencyMillis (Integer): The amount of time in milliseconds it took to establish connections with this peer. Defaults to: `null`. - error (String): The error code in event of a failure. Possible values are: - \&quot;P2P_FAILED\&quot; - The client failed to establish a P2P connection with the peer. - \&quot;PRESENCE_FAILED\&quot; - The client failed to register to receive P2P connections. - \&quot;RELAY_SERVER_FAILED\&quot; - The client received an error when trying to use the relay server to establish a P2P connection with the peer. Defaults to: `null`. - error_reason (String): More detailed diagnostic message returned in event of a failure. Defaults to: `null`. - kind (String): Uniquely identifies the type of this resource. Value is always the fixed string games#roomP2PStatus. Defaults to: `null`. - participantId (String): The ID of the participant. Defaults to: `null`. - status (String): The status of the peer in the room. Possible values are: - \&quot;CONNECTION_ESTABLISHED\&quot; - The client established a P2P connection with the peer. - \&quot;CONNECTION_FAILED\&quot; - The client failed to establish directed presence with the peer. Defaults to: `null`. - unreliableRoundtripLatencyMillis (Integer): The amount of time in milliseconds it took to send packets back and forth on the unreliable channel with this peer. Defaults to: `null`. """ defstruct [ :"connectionSetupLatencyMillis", :"error", :"error_reason", :"kind", :"participantId", :"status", :"unreliableRoundtripLatencyMillis" ] end defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.RoomP2PStatus do def decode(value, _options) do value end end defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.RoomP2PStatus do def encode(value, options) do GoogleApi.Games.V1.Deserializer.serialize_non_nil(value, options) end end
48.655172
435
0.74876
7334fae6d90857cf7fe6d2b99b112fd926d357dc
203
exs
Elixir
test/queerlink_web/controllers/page_controller_test.exs
Queertoo/Queerlink
0a7726460cda63fc4ab342a2fe1d1155caa3d6d4
[ "MIT" ]
38
2015-11-07T23:54:26.000Z
2021-04-09T04:14:25.000Z
test/queerlink_web/controllers/page_controller_test.exs
Queertoo/Queerlink
0a7726460cda63fc4ab342a2fe1d1155caa3d6d4
[ "MIT" ]
2
2015-11-23T15:00:34.000Z
2015-11-26T09:59:26.000Z
test/queerlink_web/controllers/page_controller_test.exs
Queertoo/Queerlink
0a7726460cda63fc4ab342a2fe1d1155caa3d6d4
[ "MIT" ]
6
2015-11-26T00:25:22.000Z
2020-03-04T22:13:59.000Z
defmodule QueerlinkWeb.PageControllerTest do use QueerlinkWeb.ConnCase test "GET /", %{conn: conn} do conn = get conn, "/" assert html_response(conn, 200) =~ "Welcome to Phoenix!" end end
22.555556
60
0.689655
733523f7131ada03090a1f8612c6f902ab18cf8e
524
ex
Elixir
lib/glimesh/release.ex
FROSADO/glimesh.tv
d395e89bcf8ab33ccb723ad603c0a6fb6d4ca139
[ "MIT" ]
null
null
null
lib/glimesh/release.ex
FROSADO/glimesh.tv
d395e89bcf8ab33ccb723ad603c0a6fb6d4ca139
[ "MIT" ]
null
null
null
lib/glimesh/release.ex
FROSADO/glimesh.tv
d395e89bcf8ab33ccb723ad603c0a6fb6d4ca139
[ "MIT" ]
null
null
null
defmodule Glimesh.Release do @app :glimesh def migrate do load_app() for repo <- repos() do {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true)) end end def rollback(repo, version) do load_app() {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version)) end defp repos do Application.fetch_env!(@app, :ecto_repos) end defp load_app do Application.load(@app) Application.ensure_all_started(:ssl) end end
20.153846
91
0.646947
73353a02790994d1c5a3198f075120df0f1b4c2e
609
exs
Elixir
test/spec_compliance/fetching_data_test.exs
peillis/ash_json_api
f63ccacebc049eba8d37b8b58181fb46a4a0ea8c
[ "MIT" ]
11
2020-09-21T22:03:42.000Z
2022-02-02T23:48:11.000Z
test/spec_compliance/fetching_data_test.exs
peillis/ash_json_api
f63ccacebc049eba8d37b8b58181fb46a4a0ea8c
[ "MIT" ]
44
2020-05-02T04:37:42.000Z
2021-06-25T14:38:44.000Z
test/spec_compliance/fetching_data_test.exs
peillis/ash_json_api
f63ccacebc049eba8d37b8b58181fb46a4a0ea8c
[ "MIT" ]
9
2020-08-25T20:23:34.000Z
2022-02-14T04:40:10.000Z
defmodule AshJsonApiTest.FetchingData do use ExUnit.Case use Plug.Test @moduletag :json_api_spec_1_0 @tag :spec_must # JSON:API 1.0 Specification # -------------------------- # A server MUST support fetching resource data for every URL provided as: # a self link as part of the top-level links object # a self link as part of a resource-level links object # a related link as part of a relationship-level links object # -------------------------- describe "fetching resource data" do # What does this mean - that all the URLS contained in a response are valid API urls? end end
33.833333
89
0.674877
73353fdc84c0cff703060cead7af1875d16775d3
333
ex
Elixir
lib/consul.ex
grufino/consul-elixir
1486291da0d873a46faf6bec25aaccaa37872ce3
[ "MIT" ]
11
2018-10-30T03:55:42.000Z
2021-02-06T18:23:47.000Z
lib/consul.ex
grufino/consul-elixir
1486291da0d873a46faf6bec25aaccaa37872ce3
[ "MIT" ]
null
null
null
lib/consul.ex
grufino/consul-elixir
1486291da0d873a46faf6bec25aaccaa37872ce3
[ "MIT" ]
3
2019-11-27T06:43:52.000Z
2020-05-24T08:18:34.000Z
defmodule Consul do @moduledoc false use Application def start(_type, _args) do import Supervisor.Spec, warn: false children = [ supervisor(Task.Supervisor, [[name: Consul.WatchSupervisor]]) ] opts = [strategy: :one_for_one, name: Consul.Supervisor] Supervisor.start_link(children, opts) end end
20.8125
67
0.696697
733555fa415ff350a6150c9df043c2d82bf048b7
1,243
ex
Elixir
clients/datastream/lib/google_api/datastream/v1/model/avro_file_format.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/datastream/lib/google_api/datastream/v1/model/avro_file_format.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/datastream/lib/google_api/datastream/v1/model/avro_file_format.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.Datastream.V1.Model.AvroFileFormat do @moduledoc """ AVRO file format configuration. ## Attributes """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{} end defimpl Poison.Decoder, for: GoogleApi.Datastream.V1.Model.AvroFileFormat do def decode(value, options) do GoogleApi.Datastream.V1.Model.AvroFileFormat.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Datastream.V1.Model.AvroFileFormat do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
29.595238
76
0.760257
73355affc5b0500e6e44f8dacaceef2720411198
445
exs
Elixir
apps/man_api/priv/repo/migrations/20190417121851_update_contracts_form3.exs
edenlabllc/man.api.public
010016c5ecc209413a56ee1f8e9e6fa31da8de18
[ "MIT" ]
null
null
null
apps/man_api/priv/repo/migrations/20190417121851_update_contracts_form3.exs
edenlabllc/man.api.public
010016c5ecc209413a56ee1f8e9e6fa31da8de18
[ "MIT" ]
null
null
null
apps/man_api/priv/repo/migrations/20190417121851_update_contracts_form3.exs
edenlabllc/man.api.public
010016c5ecc209413a56ee1f8e9e6fa31da8de18
[ "MIT" ]
null
null
null
defmodule Man.Repo.Migrations.UpdateContractsForm3 do use Ecto.Migration alias Man.Templates.API def change do API.update_template_body!("CRPF", Application.app_dir(:man_api, "priv/static/CRPF.html.eex")) API.update_template_body!("CRPF appendix", Application.app_dir(:man_api, "priv/static/CRPF_appendix.html.eex")) API.update_template_body!("RCRPF", Application.app_dir(:man_api, "priv/static/RCRPF.html.eex")) end end
37.083333
115
0.761798
73356af0d13fc3a437955d65987bfc958004e52a
898
ex
Elixir
lib/rocketpay_web/router.ex
lucassm02/rocket-pay
af9ccbb68bc5d79793703e32bdb1d41f57e29682
[ "MIT" ]
null
null
null
lib/rocketpay_web/router.ex
lucassm02/rocket-pay
af9ccbb68bc5d79793703e32bdb1d41f57e29682
[ "MIT" ]
null
null
null
lib/rocketpay_web/router.ex
lucassm02/rocket-pay
af9ccbb68bc5d79793703e32bdb1d41f57e29682
[ "MIT" ]
null
null
null
defmodule RocketpayWeb.Router do use RocketpayWeb, :router pipeline :api do plug(:accepts, ["json"]) end scope "/api", RocketpayWeb do pipe_through(:api) get("/:filename", WelcomeController, :index) post("/:users", UserController, :create) end # Enables LiveDashboard only for development # # If you want to use the LiveDashboard in production, you should put # it behind authentication and allow only admins to access it. # If your application does not have an admins-only section yet, # you can use Plug.BasicAuth to set up some basic authentication # as long as you are also using SSL (which you should anyway). if Mix.env() in [:dev, :test] do import Phoenix.LiveDashboard.Router scope "/" do pipe_through([:fetch_session, :protect_from_forgery]) live_dashboard("/dashboard", metrics: RocketpayWeb.Telemetry) end end end
28.967742
70
0.708241
73357892c63ce3d3f0a8babebf490281d7d8490d
2,150
exs
Elixir
test/controllers/todo_controller_test.exs
Baransu/todos
a1ce771b35dc0f30efd043c283b513b52eba4657
[ "BSD-3-Clause" ]
null
null
null
test/controllers/todo_controller_test.exs
Baransu/todos
a1ce771b35dc0f30efd043c283b513b52eba4657
[ "BSD-3-Clause" ]
null
null
null
test/controllers/todo_controller_test.exs
Baransu/todos
a1ce771b35dc0f30efd043c283b513b52eba4657
[ "BSD-3-Clause" ]
null
null
null
defmodule Todos.TodoControllerTest do use Todos.ConnCase alias Todos.Todo @valid_attrs %{ description: "some content", title: "some content"} @invalid_attrs %{} setup %{conn: conn} do {:ok, conn: put_req_header(conn, "accept", "application/json")} end test "lists all entries on index", %{conn: conn} do conn = get conn, todo_path(conn, :index) assert json_response(conn, 200)["data"] == [] end test "shows chosen resource", %{conn: conn} do todo = Repo.insert! %Todo{} conn = get conn, todo_path(conn, :show, todo) assert json_response(conn, 200)["data"] == %{ "id" => todo.id, "title" => todo.title, "description" => todo.description, "completed" => todo.completed } end test "renders page not found when id is nonexistent", %{conn: conn} do assert_error_sent 404, fn -> get conn, todo_path(conn, :show, -1) end end test "creates and renders resource when data is valid", %{conn: conn} do conn = post conn, todo_path(conn, :create), todo: @valid_attrs assert json_response(conn, 201)["data"]["id"] assert Repo.get_by(Todo, @valid_attrs) end test "does not create resource and renders errors when data is invalid", %{conn: conn} do conn = post conn, todo_path(conn, :create), todo: @invalid_attrs assert json_response(conn, 422)["errors"] != %{} end test "updates and renders chosen resource when data is valid", %{conn: conn} do todo = Repo.insert! %Todo{} conn = put conn, todo_path(conn, :update, todo), todo: @valid_attrs assert json_response(conn, 200)["data"]["id"] assert Repo.get_by(Todo, @valid_attrs) end test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do todo = Repo.insert! %Todo{} conn = put conn, todo_path(conn, :update, todo), todo: @invalid_attrs assert json_response(conn, 422)["errors"] != %{} end test "deletes chosen resource", %{conn: conn} do todo = Repo.insert! %Todo{} conn = delete conn, todo_path(conn, :delete, todo) assert response(conn, 204) refute Repo.get(Todo, todo.id) end end
32.089552
98
0.653953
73358562a8531d123bce2afa5e41cb334c200e46
1,821
ex
Elixir
clients/dlp/lib/google_api/dlp/v2beta1/model/google_privacy_dlp_v2beta1_record_key.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/dlp/lib/google_api/dlp/v2beta1/model/google_privacy_dlp_v2beta1_record_key.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/dlp/lib/google_api/dlp/v2beta1/model/google_privacy_dlp_v2beta1_record_key.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.DLP.V2beta1.Model.GooglePrivacyDlpV2beta1RecordKey do @moduledoc """ Message for a unique key indicating a record that contains a finding. ## Attributes - cloudStorageKey (GooglePrivacyDlpV2beta1CloudStorageKey): Defaults to: `null`. - datastoreKey (GooglePrivacyDlpV2beta1DatastoreKey): Defaults to: `null`. """ defstruct [ :"cloudStorageKey", :"datastoreKey" ] end defimpl Poison.Decoder, for: GoogleApi.DLP.V2beta1.Model.GooglePrivacyDlpV2beta1RecordKey do import GoogleApi.DLP.V2beta1.Deserializer def decode(value, options) do value |> deserialize(:"cloudStorageKey", :struct, GoogleApi.DLP.V2beta1.Model.GooglePrivacyDlpV2beta1CloudStorageKey, options) |> deserialize(:"datastoreKey", :struct, GoogleApi.DLP.V2beta1.Model.GooglePrivacyDlpV2beta1DatastoreKey, options) end end defimpl Poison.Encoder, for: GoogleApi.DLP.V2beta1.Model.GooglePrivacyDlpV2beta1RecordKey do def encode(value, options) do GoogleApi.DLP.V2beta1.Deserializer.serialize_non_nil(value, options) end end
35.705882
124
0.773202
73359d1a2d48ebc3efebdf0d4453b4586eec116d
1,131
exs
Elixir
parser_sdk/config/config.exs
flixbi/element-parsers
b92ef1cff139130acbac4f40d0d48568a3de6590
[ "MIT" ]
1
2021-11-10T18:06:59.000Z
2021-11-10T18:06:59.000Z
parser_sdk/config/config.exs
SeppPenner/element-parsers
8a2594e0f15ca7177f6782d0441f25e3e55b8416
[ "MIT" ]
null
null
null
parser_sdk/config/config.exs
SeppPenner/element-parsers
8a2594e0f15ca7177f6782d0441f25e3e55b8416
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :parser_sdk, key: :value # # and access this configuration in your application as: # # Application.get_env(:parser_sdk, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env()}.exs"
36.483871
73
0.751547
7335aedab1046c7844f7fa0b53ebbead0df01d71
9,410
ex
Elixir
lib/elixir/lib/supervisor/spec.ex
anshul77/elixir
c190f09d5cbb1e79b510ea4332c65a7717aa9eb8
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/supervisor/spec.ex
anshul77/elixir
c190f09d5cbb1e79b510ea4332c65a7717aa9eb8
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/supervisor/spec.ex
anshul77/elixir
c190f09d5cbb1e79b510ea4332c65a7717aa9eb8
[ "Apache-2.0" ]
null
null
null
defmodule Supervisor.Spec do @moduledoc """ Outdated functions for building child specifications. The functions in this module are deprecated and they do not work with the module-based child specs introduced in Elixir v1.5. Please see the `Supervisor` documentation instead. Convenience functions for defining supervisor specifications. ## Example By using the functions in this module one can specify the children to be used under a supervisor, started with `Supervisor.start_link/2`: import Supervisor.Spec children = [ worker(MyWorker, [arg1, arg2, arg3]), supervisor(MySupervisor, [arg1]) ] Supervisor.start_link(children, strategy: :one_for_one) Sometimes, it may be handy to define supervisors backed by a module: defmodule MySupervisor do use Supervisor def start_link(arg) do Supervisor.start_link(__MODULE__, arg) end def init(arg) do children = [ worker(MyWorker, [arg], restart: :temporary) ] supervise(children, strategy: :simple_one_for_one) end end Notice in this case we don't have to explicitly import `Supervisor.Spec` as `use Supervisor` automatically does so. Defining a module-based supervisor can be useful, for example, to perform initialization tasks in the `c:init/1` callback. ## Supervisor and worker options In the example above, we defined specs for workers and supervisors. These specs (both for workers as well as supervisors) accept the following options: * `:id` - a name used to identify the child specification internally by the supervisor; defaults to the given module name for the child worker/supervisor * `:function` - the function to invoke on the child to start it * `:restart` - an atom that defines when a terminated child process should be restarted (see the "Restart values" section below) * `:shutdown` - an atom that defines how a child process should be terminated (see the "Shutdown values" section below) * `:modules` - it should be a list with one element `[module]`, where module is the name of the callback module only if the child process is a `Supervisor` or `GenServer`; if the child process is a `GenEvent`, `:modules` should be `:dynamic` ### Restart values (:restart) The following restart values are supported in the `:restart` option: * `:permanent` - the child process is always restarted * `:temporary` - the child process is never restarted (not even when the supervisor's strategy is `:rest_for_one` or `:one_for_all`) * `:transient` - the child process is restarted only if it terminates abnormally, i.e., with an exit reason other than `:normal`, `:shutdown` or `{:shutdown, term}` Notice that supervisor that reached maximum restart intensity will exit with `:shutdown` reason. In this case the supervisor will only be restarted if its child specification was defined with the `:restart` option is set to `:permanent` (the default). ### Shutdown values (`:shutdown`) The following shutdown values are supported in the `:shutdown` option: * `:brutal_kill` - the child process is unconditionally terminated using `Process.exit(child, :kill)` * `:infinity` - if the child process is a supervisor, this is a mechanism to give the subtree enough time to shut down; it can also be used with workers with care * a non-negative integer - the amount of time in milliseconds that the supervisor tells the child process to terminate by calling `Process.exit(child, :shutdown)` and then waits for an exit signal back. If no exit signal is received within the specified time, the child process is unconditionally terminated using `Process.exit(child, :kill)` """ @moduledoc deprecated: "Use the new child specifications outlined in the Supervisor module instead" # TODO: Deprecate all functions in this module on Elixir v1.9. # Also deprecate entry in Supervisor.Default. @typedoc "Supported strategies" @type strategy :: :simple_one_for_one | :one_for_one | :one_for_all | :rest_for_one @typedoc "Supported restart values" @type restart :: :permanent | :transient | :temporary @typedoc "Supported shutdown values" @type shutdown :: timeout | :brutal_kill @typedoc "Supported worker values" @type worker :: :worker | :supervisor @typedoc "Supported module values" @type modules :: :dynamic | [module] @typedoc "Supported id values" @type child_id :: term @typedoc "The supervisor specification" @type spec :: {child_id, start_fun :: {module, atom, [term]}, restart, shutdown, worker, modules} @doc """ Receives a list of children (workers or supervisors) to supervise and a set of options. Returns a tuple containing the supervisor specification. This tuple can be used as the return value of the `c:init/1` callback when implementing a module-based supervisor. ## Examples supervise(children, strategy: :one_for_one) ## Options * `:strategy` - the restart strategy option. It can be either `:one_for_one`, `:rest_for_one`, `:one_for_all`, or `:simple_one_for_one`. You can learn more about strategies in the `Supervisor` module docs. * `:max_restarts` - the maximum number of restarts allowed in a time frame. Defaults to `3`. * `:max_seconds` - the time frame in which `:max_restarts` applies. Defaults to `5`. The `:strategy` option is required and by default a maximum of 3 restarts is allowed within 5 seconds. Check the `Supervisor` module for a detailed description of the available strategies. """ @spec supervise( [spec], strategy: strategy, max_restarts: non_neg_integer, max_seconds: pos_integer ) :: {:ok, tuple} def supervise(children, options) do unless strategy = options[:strategy] do raise ArgumentError, "expected :strategy option to be given" end maxR = Keyword.get(options, :max_restarts, 3) maxS = Keyword.get(options, :max_seconds, 5) assert_unique_ids(Enum.map(children, &get_id/1)) {:ok, {{strategy, maxR, maxS}, children}} end defp get_id({id, _, _, _, _, _}) do id end defp get_id(other) do raise ArgumentError, "invalid tuple specification given to supervise/2. If you are trying to use " <> "the map child specification that is part of the Elixir v1.5, use Supervisor.init/2 " <> "instead of Supervisor.Spec.supervise/2. See the Supervisor module for more information. " <> "Got: #{inspect(other)}" end defp assert_unique_ids([id | rest]) do if id in rest do raise ArgumentError, "duplicated id #{inspect(id)} found in the supervisor specification, " <> "please explicitly pass the :id option when defining this worker/supervisor" else assert_unique_ids(rest) end end defp assert_unique_ids([]) do :ok end @doc """ Defines the given `module` as a worker which will be started with the given arguments. worker(ExUnit.Runner, [], restart: :permanent) By default, the function `start_link` is invoked on the given module. Overall, the default values for the options are: [ id: module, function: :start_link, restart: :permanent, shutdown: 5000, modules: [module] ] See the "Supervisor and worker options" section in the `Supervisor.Spec` module for more information on the available options. """ @spec worker( module, [term], restart: restart, shutdown: shutdown, id: term, function: atom, modules: modules ) :: spec def worker(module, args, options \\ []) do child(:worker, module, args, options) end @doc """ Defines the given `module` as a supervisor which will be started with the given arguments. supervisor(module, [], restart: :permanent) By default, the function `start_link` is invoked on the given module. Overall, the default values for the options are: [ id: module, function: :start_link, restart: :permanent, shutdown: :infinity, modules: [module] ] See the "Supervisor and worker options" section in the `Supervisor.Spec` module for more information on the available options. """ @spec supervisor( module, [term], restart: restart, shutdown: shutdown, id: term, function: atom, modules: modules ) :: spec def supervisor(module, args, options \\ []) do options = Keyword.put_new(options, :shutdown, :infinity) child(:supervisor, module, args, options) end defp child(type, module, args, options) do id = Keyword.get(options, :id, module) modules = Keyword.get(options, :modules, modules(module)) function = Keyword.get(options, :function, :start_link) restart = Keyword.get(options, :restart, :permanent) shutdown = Keyword.get(options, :shutdown, 5000) {id, {module, function, args}, restart, shutdown, type, modules} end defp modules(GenEvent), do: :dynamic defp modules(module), do: [module] end
32.448276
105
0.672795
7335f7ce7b0d4f1659cbf817418ca177d0c02e35
3,092
ex
Elixir
lib/oli/delivery/attempts/scoring.ex
chrislawson/oli-torus
94165b211ab74fac3e7c8a14110a394fa9a6f320
[ "MIT" ]
45
2020-04-17T15:40:27.000Z
2022-03-25T00:13:30.000Z
lib/oli/delivery/attempts/scoring.ex
chrislawson/oli-torus
94165b211ab74fac3e7c8a14110a394fa9a6f320
[ "MIT" ]
944
2020-02-13T02:37:01.000Z
2022-03-31T17:50:07.000Z
lib/oli/delivery/attempts/scoring.ex
chrislawson/oli-torus
94165b211ab74fac3e7c8a14110a394fa9a6f320
[ "MIT" ]
23
2020-07-28T03:36:13.000Z
2022-03-17T14:29:02.000Z
defmodule Oli.Delivery.Attempts.Scoring do alias Oli.Delivery.Evaluation.Result alias Oli.Resources.ScoringStrategy @doc """ Calculates a result from a list of maps that contain a score and out_of. This can be used either by passing in the strategy id or directly passing in the scoring strategy string id. A key aspect of the implmementations here is that they are correct in the face of attempts that might have different `out_of` values. This situation can occur when attempts are simply pinned to different revisions of a resource that have a different number of activities. Returns a `%Result{}` struct with the calculated score. """ def calculate_score(strategy_id, items) when is_number(strategy_id) do calculate_score(ScoringStrategy.get_type_by_id(strategy_id), items) end # The average calculated here is normalized out of 100%, but then # reported back as a score out of the maximum possible of # any attempt. So an average of two attempts with 5/10 on one and 10/20 on # another would result in a 10/20 result. This approach allows the # correct handling of cases where attempts are pinned to different revisions # of a resource with a possibly different number of activities def calculate_score("average", items) do {total, max_out_of} = Enum.reduce(items, {0, 0}, fn p, {total, max_out_of} -> {total + safe_percentage(p.score, p.out_of), if max_out_of < p.out_of do p.out_of else max_out_of end} end) %Result{ score: total / length(items) * max_out_of, out_of: max_out_of } end # The 'best' score is the attempt with the highest percentage correct, # not the highest raw score. def calculate_score("best", items) do {score, out_of, _} = Enum.reduce(items, {0, 0, 0.0}, fn p, {score, out_of, best} -> if safe_percentage(p.score, p.out_of) >= best do {p.score, p.out_of, safe_percentage(p.score, p.out_of)} else {score, out_of, best} end end) %Result{ score: score, out_of: out_of } end # The most recent is assumed to be the last item in the list def calculate_score("most_recent", items) do most_recent = Enum.reverse(items) |> hd %Result{ score: Map.get(most_recent, :score), out_of: Map.get(most_recent, :out_of) } end # The total strategy simply adds up the scores and adds up the out_of def calculate_score("total", items) do {score, out_of} = Enum.reduce(items, {0, 0}, fn p, {score, out_of} -> {score + p.score, out_of + p.out_of} end) %Result{ score: score, out_of: out_of } end # Instead of failing at runtime if there is ever a strategy passed in that # we do not handle, we default to the "average" strategy. def calculate_score(_, items) do calculate_score("average", items) end defp safe_percentage(score, out_of) do case out_of do nil -> 0.0 0.0 -> 0.0 0 -> 0.0 _ -> score / out_of end end end
30.613861
80
0.665265
73360d3ff52b217819d6107defe75f0ac5b8d6a9
2,756
ex
Elixir
lib/plaid/transactions/transaction.ex
ethangunderson/elixir-plaid
53aa0a87a4a837df6a2d15684870e7a58a003db6
[ "MIT" ]
16
2021-03-09T02:29:32.000Z
2022-03-13T07:18:03.000Z
lib/plaid/transactions/transaction.ex
ethangunderson/elixir-plaid
53aa0a87a4a837df6a2d15684870e7a58a003db6
[ "MIT" ]
5
2021-04-24T20:38:14.000Z
2022-03-19T22:03:09.000Z
lib/plaid/transactions/transaction.ex
ethangunderson/elixir-plaid
53aa0a87a4a837df6a2d15684870e7a58a003db6
[ "MIT" ]
2
2021-06-11T02:15:01.000Z
2022-03-15T18:39:59.000Z
defmodule Plaid.Transactions.Transaction do @moduledoc """ [Plaid Transaction schema.](https://plaid.com/docs/api/transactions) """ @behaviour Plaid.Castable alias Plaid.Castable alias Plaid.Transactions.Transaction.{Location, PaymentMeta} @type t :: %__MODULE__{ account_id: String.t(), amount: number(), iso_currency_code: String.t() | nil, unofficial_currency_code: String.t() | nil, category: [String.t()] | nil, category_id: String.t(), date: String.t(), authorized_date: String.t() | nil, location: Location.t(), name: String.t(), merchant_name: String.t() | nil, payment_meta: PaymentMeta.t(), payment_channel: String.t(), pending: boolean(), pending_transaction_id: String.t() | nil, account_owner: String.t() | nil, transaction_id: String.t(), transaction_code: String.t() | nil, transaction_type: String.t(), date_transacted: String.t() | nil, original_description: String.t() | nil } defstruct [ :account_id, :amount, :iso_currency_code, :unofficial_currency_code, :category, :category_id, :date, :authorized_date, :location, :name, :merchant_name, :payment_meta, :payment_channel, :pending, :pending_transaction_id, :account_owner, :transaction_id, :transaction_code, :transaction_type, :date_transacted, :original_description ] @impl true def cast(generic_map) do %__MODULE__{ account_id: generic_map["account_id"], amount: generic_map["amount"], iso_currency_code: generic_map["iso_currency_code"], unofficial_currency_code: generic_map["unofficial_currency_code"], category: generic_map["category"], category_id: generic_map["category_id"], date: generic_map["date"], authorized_date: generic_map["authorized_date"], location: Castable.cast(Location, generic_map["location"]), name: generic_map["name"], merchant_name: generic_map["merchant_name"], payment_meta: Castable.cast(PaymentMeta, generic_map["payment_meta"]), payment_channel: generic_map["payment_channel"], pending: generic_map["pending"], pending_transaction_id: generic_map["pending_transaction_id"], account_owner: generic_map["account_owner"], transaction_id: generic_map["transaction_id"], transaction_code: generic_map["transaction_code"], transaction_type: generic_map["transaction_type"], date_transacted: generic_map["date_transacted"], original_description: generic_map["original_description"] } end end
32.046512
76
0.652758
7336264f3c2f836b5ca6e852ae6f1cff156c056f
947
ex
Elixir
lib/ecto_role/timer.ex
mithereal/ecto-role
2cecb9ceee5e16e834fa9ee12e72df9b438bec5c
[ "MIT" ]
2
2019-05-23T10:14:46.000Z
2020-01-26T23:30:54.000Z
lib/ecto_role/timer.ex
mithereal/ecto-role
2cecb9ceee5e16e834fa9ee12e72df9b438bec5c
[ "MIT" ]
2
2018-01-28T22:00:20.000Z
2018-04-16T17:35:35.000Z
lib/ecto_role/timer.ex
mithereal/ecto-role
2cecb9ceee5e16e834fa9ee12e72df9b438bec5c
[ "MIT" ]
2
2018-02-14T18:55:12.000Z
2018-04-16T17:34:52.000Z
defmodule EctoRole.Timer do use GenServer require Logger @name __MODULE__ defstruct tick_interval: 500, ticker_ref: :none def init(args) do {:ok, args} end def start_link(id) do GenServer.start_link(__MODULE__, [id], name: @name) end def handle_cast(:start_timer, %{tick_interval: tick_interval, ticker_ref: ticker_ref} = state) when ticker_ref == :none do Logger.debug("#{@name} started") {:ok, new_ticker_ref} = :timer.send_after(tick_interval, :tick) {:noreply, %{state | ticker_ref: new_ticker_ref}} end def handle_cast(:start_timer, state), do: {:noreply, state} def handle_cast(:stop_timer, %{ticker_ref: ticker_ref} = state) when ticker_ref == :none do {:noreply, state} end def handle_cast(:stop_timer, %{ticker_ref: ticker_ref} = state) do Logger.debug("#{@name} cancelled") :timer.cancel(ticker_ref) {:noreply, %{state | ticker_ref: :none}} end end
24.282051
96
0.680042
73368d41e6b757a86dbb08ca98e8d444100260b6
1,060
ex
Elixir
lib/absinthe/phase/document/validation/only_one_subscription.ex
se-apc/absinthe
a95f8d7658091f99e2ebf5af659bfcfaecc97423
[ "MIT" ]
null
null
null
lib/absinthe/phase/document/validation/only_one_subscription.ex
se-apc/absinthe
a95f8d7658091f99e2ebf5af659bfcfaecc97423
[ "MIT" ]
2
2018-08-02T13:35:38.000Z
2018-08-02T13:36:42.000Z
lib/absinthe/phase/document/validation/only_one_subscription.ex
se-apc/absinthe
a95f8d7658091f99e2ebf5af659bfcfaecc97423
[ "MIT" ]
null
null
null
defmodule Absinthe.Phase.Document.Validation.OnlyOneSubscription do @moduledoc false # Validates document to ensure that the only variables that are used in a # document are defined on the operation. alias Absinthe.{Blueprint, Phase} use Absinthe.Phase use Absinthe.Phase.Validation @doc """ Run the validation. """ @spec run(Blueprint.t(), Keyword.t()) :: Phase.result_t() def run(input, _options \\ []) do bp = Blueprint.update_current(input, fn %{type: :subscription} = op -> check_op(op) op -> op end) {:ok, bp} end # Multiple Root Objects are Supported # TODO: Figure out why this arbitrary limit was added # defp check_op(%{selections: [_, _ | _]} = op) do # error = %Phase.Error{ # phase: __MODULE__, # message: "Only one field is permitted on the root object when subscribing", # locations: [op.source_location], # } # op # |> flag_invalid(:too_many_fields) # |> put_error(error) # end defp check_op(op), do: op end
24.090909
83
0.633962
7336abd8c7da9c030b93acd1bf5dc83b12a87d3e
58
ex
Elixir
lib/sippet/transports/udp.ex
enzoqtvf/elixir-sippet
8f35eac41d6242b682446ec445229a694b4061d9
[ "BSD-3-Clause" ]
5
2018-08-02T15:41:23.000Z
2020-12-07T15:50:45.000Z
lib/sippet/transports/udp.ex
team-telnyx/elixir-sippet
32de78b585132004edcb285b16c7bcd5d8f2afb6
[ "BSD-3-Clause" ]
null
null
null
lib/sippet/transports/udp.ex
team-telnyx/elixir-sippet
32de78b585132004edcb285b16c7bcd5d8f2afb6
[ "BSD-3-Clause" ]
null
null
null
defmodule Sippet.Transports.UDP do @moduledoc false end
14.5
34
0.810345
7336d30b07208aa29a0ae256c7f7a0a43419639b
1,089
ex
Elixir
lib/todo_api_web/controllers/todo_controller.ex
westrik/todo-ex
6ab0c61b91d3e76239e77e988e51aa0b06f30408
[ "MIT" ]
1
2020-11-12T08:26:51.000Z
2020-11-12T08:26:51.000Z
lib/todo_api_web/controllers/todo_controller.ex
westrik/todo-ex
6ab0c61b91d3e76239e77e988e51aa0b06f30408
[ "MIT" ]
null
null
null
lib/todo_api_web/controllers/todo_controller.ex
westrik/todo-ex
6ab0c61b91d3e76239e77e988e51aa0b06f30408
[ "MIT" ]
null
null
null
defmodule TodoApiWeb.TodoController do use TodoApiWeb, :controller alias TodoApi.Todos alias TodoApi.Todos.Todo action_fallback TodoApiWeb.FallbackController def index(conn, _params) do todos = Todos.list_todos() render(conn, "index.json", todos: todos) end def create(conn, %{"todo" => todo_params}) do with {:ok, %Todo{} = todo} <- Todos.create_todo(todo_params) do conn |> put_status(:created) |> put_resp_header("location", Routes.todo_path(conn, :show, todo)) |> render("show.json", todo: todo) end end def show(conn, %{"id" => id}) do todo = Todos.get_todo!(id) render(conn, "show.json", todo: todo) end def update(conn, %{"id" => id, "todo" => todo_params}) do todo = Todos.get_todo!(id) with {:ok, %Todo{} = todo} <- Todos.update_todo(todo, todo_params) do render(conn, "show.json", todo: todo) end end def delete(conn, %{"id" => id}) do todo = Todos.get_todo!(id) with {:ok, %Todo{}} <- Todos.delete_todo(todo) do send_resp(conn, :no_content, "") end end end
24.75
73
0.627181
7336d9e5a042fd40974de462023151e8b81e2939
689
ex
Elixir
lib/elixoids/application.ex
devstopfix/elixoids
df4f2ba9ddb3d13c3c86e57f100c3d57fa64ed8d
[ "MIT" ]
5
2016-07-05T13:42:33.000Z
2020-12-07T14:12:16.000Z
lib/elixoids/application.ex
devstopfix/elixoids
df4f2ba9ddb3d13c3c86e57f100c3d57fa64ed8d
[ "MIT" ]
70
2016-06-04T11:31:27.000Z
2020-11-21T20:00:09.000Z
lib/elixoids/application.ex
devstopfix/elixoids
df4f2ba9ddb3d13c3c86e57f100c3d57fa64ed8d
[ "MIT" ]
1
2016-07-05T17:10:05.000Z
2016-07-05T17:10:05.000Z
defmodule Elixoids.Application do @moduledoc false use Application @port Application.get_env(:elixoids, :cowboy_port) def start(_start_type, _start_args) do children = [ {Registry, name: Registry.Elixoids.Collisions, keys: :unique}, {Registry, name: Registry.Elixoids.Games, keys: :unique}, {Registry, name: Registry.Elixoids.News, keys: :duplicate}, {Registry, name: Registry.Elixoids.Ships, keys: :unique}, {Elixoids.Api, [port: @port]}, Elixoids.Collision.Supervisor, Elixoids.Game.Supervisor, Elixoids.Game.Zero, Elixoids.Saucer.Supervisor ] Supervisor.start_link(children, strategy: :one_for_one) end end
29.956522
68
0.69521
73370c2654c86657b782d7ef244da856b3265f7e
7,257
ex
Elixir
lib/makeup/lexer/combinators.ex
kw7oe/makeup
c281c8e08b0c38c258f681eb6831d7b6d86af698
[ "BSD-2-Clause" ]
null
null
null
lib/makeup/lexer/combinators.ex
kw7oe/makeup
c281c8e08b0c38c258f681eb6831d7b6d86af698
[ "BSD-2-Clause" ]
null
null
null
lib/makeup/lexer/combinators.ex
kw7oe/makeup
c281c8e08b0c38c258f681eb6831d7b6d86af698
[ "BSD-2-Clause" ]
null
null
null
defmodule Makeup.Lexer.Combinators do @moduledoc """ Common components useful in many lexers. """ import NimbleParsec @doc """ Wraps the given combinator into a token of the given `ttype`. Instead of a combinator, the first argument can also be a string literal. """ def token(literal, token_type) when is_binary(literal) do replace(string(literal), {token_type, %{}, literal}) end def token(combinator, token_type) do combinator |> post_traverse({__MODULE__, :__token__, [token_type]}) end def token(literal, token_type, attrs) when is_binary(literal) and is_map(attrs) do replace(string(literal), {token_type, attrs, literal}) end def token(combinator, token_type, attrs) when is_map(attrs) do combinator |> post_traverse({__MODULE__, :__token__, [token_type, attrs]}) end @doc """ Joins the result of the given combinator into a single string. This is not usually necessary, but it can be useful if you want to match on the tokens. It's easier to match on the token `{:keyword, %{}, "unquote"}` than on something like `{:keyword, %{}, ["u", "nquote"]}`, even though both tokens will be treated the same way by the formatter. """ def lexeme(combinator) do combinator |> post_traverse({__MODULE__, :__lexeme__, []}) end @doc false def __token__(_rest, [arg], context, _line, _offset, token_type) do {[{token_type, %{}, arg}], context} end def __token__(_rest, arg, context, _line, _offset, token_type) when is_binary(arg) do {[{token_type, %{}, arg}], context} end def __token__(_rest, args, context, _line, _offset, token_type) do {[{token_type, %{}, args |> :lists.reverse()}], context} end @doc false def __token__(_rest, [arg], context, _line, _offset, token_type, attrs) do {[{token_type, attrs, arg}], context} end def __token__(_rest, arg, context, _line, _offset, token_type, attrs) when is_binary(arg) do {[{token_type, attrs, arg}], context} end def __token__(_rest, args, context, _line, _offset, token_type, attrs) do {[{token_type, attrs, args |> :lists.reverse()}], context} end @doc false def __lexeme__(_rest, args, context, _line, _offset) do result = args |> List.wrap() |> :lists.reverse() |> IO.iodata_to_binary() {[result], context} end defp reverse_sort(items) do Enum.sort(items, fn a, b -> {byte_size(a), a} > {byte_size(b), b} end) end @doc """ Matches one of the literal strings in the list. The strings aren't matched in order: they are automatically sorted in a way that guarantees that the longest strings will be tried first. ## Examples keywords = word_from_list(~w[do end catch after rescue]) """ def word_from_list(words) do choice(for word <- reverse_sort(words), do: string(word)) end @doc """ Matches one of the literal strings in the list and wraps it in a token of the given type. This is is just a shorthand. The strings aren't matched in order: they are automatically sorted in a way that guarantees that the longest strings will be tried first. ## Examples keywords = word_from_list(~w[do end catch after rescue], :keyword) """ def word_from_list(words, ttype) do choice(for word <- reverse_sort(words), do: string(word)) |> token(ttype) end @doc """ Matches one of the literal strings in the list and wraps it in a token of the given `type`, with the given `attrs`. This is is just a shorthand. The strings aren't matched in order: they are automatically sorted in a way that guarantees that the longest strings will be tried first. """ def word_from_list(words, ttype, attrs) do choice(for word <- reverse_sort(words), do: string(word)) |> token(ttype, attrs) end @doc """ Matches a given combinator, repeated 0 or more times, surrounded by left and right delimiters. Delimiters can be combinators or literal strings (either both combinators or both literal strings). """ def many_surrounded_by(combinator, left, right) when is_binary(left) and is_binary(right) do token(left, :punctuation) |> concat( repeat( lookahead_not(string(right)) |> concat(combinator) ) ) |> concat(token(right, :punctuation)) end def many_surrounded_by(combinator, left, right) do left |> concat( repeat( lookahead_not(right) |> concat(combinator) ) ) |> concat(right) end @doc """ Matches a given combinator, repeated 0 or more times, surrounded by left and right delimiters, and wraps the `right` and `left` delimiters into a token of the given `ttype`. """ def many_surrounded_by(combinator, left, right, ttype) do token(left, ttype) |> concat( repeat( lookahead_not(string(right)) |> concat(combinator) ) ) |> concat(token(right, ttype)) end @doc false def collect_raw_chars_and_binaries(_rest, args, context, _line, _offset, ttype, attrs) do result = merge_chars_helper(ttype, attrs, [], args) {result, context} end defp merge_chars_helper(_ttype, _attrs, [], []), do: [] defp merge_chars_helper(ttype, attrs, acc, [next | rest]) when is_integer(next) or is_binary(next) do merge_chars_helper(ttype, attrs, [next | acc], rest) end defp merge_chars_helper(ttype, attrs, [], [element | rest]) do [element | merge_chars_helper(ttype, attrs, [], rest)] end defp merge_chars_helper(ttype, attrs, acc, list) do tok = {ttype, attrs, acc} [tok | merge_chars_helper(ttype, attrs, [], list)] end @doc """ A generic combinator for string-like syntactic structures. It takes the following parameters: * `left` - left delimiter for the string. Can be a binary or a general combinator. * `right` - right delimiter for the string. Can be a binary or a general combinator * `middle` - a list of parsers to run inside the strig which parse entities that aren't characters. The most common example are special characters and string interpolation for languages that support it like Elixir. * `ttype` - the token type to use for the string delimiters and ordinary characters (tokens parsd by the ) * `attrs` - metadata attributes for the string delimiters and ordinary characters ## Examples single_quoted_heredocs = string_like( "'''", "'''", combinators_inside_string, :string_char ) The above is equivalent to the following more explicit version: single_quoted_heredocs = string_like( string("'''"), string("'''"), combinators_inside_string, :string_char ) """ def string_like(left, right, middle, ttype, attrs \\ %{}) when is_list(middle) do left_combinator = case is_binary(left) do true -> string(left) false -> left end right_combinator = case is_binary(right) do true -> string(right) false -> right end choices = middle ++ [utf8_char([])] left_combinator |> repeat(lookahead_not(right_combinator) |> choice(choices)) |> concat(right_combinator) |> post_traverse({__MODULE__, :collect_raw_chars_and_binaries, [ttype, attrs]}) end end
30.620253
101
0.672592
73370cef47a59d2205d268f581b6a444e6111b42
1,437
ex
Elixir
web/controllers/cdn_controller.ex
rob05c/tox
f54847ca058ad24b909341ad65d595a4069d2471
[ "Apache-2.0" ]
2
2016-11-16T17:24:21.000Z
2019-02-15T05:38:27.000Z
web/controllers/cdn_controller.ex
rob05c/tox
f54847ca058ad24b909341ad65d595a4069d2471
[ "Apache-2.0" ]
null
null
null
web/controllers/cdn_controller.ex
rob05c/tox
f54847ca058ad24b909341ad65d595a4069d2471
[ "Apache-2.0" ]
null
null
null
defmodule Tox.CdnController do use Tox.Web, :controller alias Tox.Cdn def index(conn, _params) do cdns = Repo.all(Cdn) render(conn, "index.json", cdns: cdns) end def create(conn, %{"cdn" => cdn_params}) do changeset = Cdn.changeset(%Cdn{}, cdn_params) case Repo.insert(changeset) do {:ok, cdn} -> conn |> put_status(:created) |> put_resp_header("location", cdn_path(conn, :show, cdn)) |> render("show.json", cdn: cdn) {:error, changeset} -> conn |> put_status(:unprocessable_entity) |> render(Tox.ChangesetView, "error.json", changeset: changeset) end end def show(conn, %{"id" => id}) do cdn = Repo.get!(Cdn, id) render(conn, "show.json", cdn: cdn) end def update(conn, %{"id" => id, "cdn" => cdn_params}) do cdn = Repo.get!(Cdn, id) changeset = Cdn.changeset(cdn, cdn_params) case Repo.update(changeset) do {:ok, cdn} -> render(conn, "show.json", cdn: cdn) {:error, changeset} -> conn |> put_status(:unprocessable_entity) |> render(Tox.ChangesetView, "error.json", changeset: changeset) end end def delete(conn, %{"id" => id}) do cdn = Repo.get!(Cdn, id) # Here we use delete! (with a bang) because we expect # it to always work (and if it does not, it will raise). Repo.delete!(cdn) send_resp(conn, :no_content, "") end end
25.660714
72
0.592206
733742cc6e05e7c4b3fd977a9906070e3f81a38a
1,081
exs
Elixir
test/user_friendly_formatter_test.exs
secomind/pretty_log
2fe58d2850344ca9118112bed232fbd266f25f06
[ "Apache-2.0" ]
5
2019-10-18T15:07:15.000Z
2021-04-20T22:46:22.000Z
test/user_friendly_formatter_test.exs
secomind/pretty_log
2fe58d2850344ca9118112bed232fbd266f25f06
[ "Apache-2.0" ]
2
2021-04-07T14:28:55.000Z
2021-12-23T13:31:49.000Z
test/user_friendly_formatter_test.exs
secomind/pretty_log
2fe58d2850344ca9118112bed232fbd266f25f06
[ "Apache-2.0" ]
3
2019-10-08T10:17:37.000Z
2021-09-11T01:31:44.000Z
defmodule PrettyLog.UserFriendlyFormatterTest do use ExUnit.Case alias PrettyLog.UserFriendlyFormatter doctest PrettyLog.UserFriendlyFormatter test "formats a warning log entry" do assert :erlang.iolist_to_binary( UserFriendlyFormatter.format( :warn, "This is a test message", {{2019, 10, 8}, {11, 58, 39, 5}}, [] ) ) == "11:58:39.5\t|WARN | This is a test message\n" end test "formats an error log entry with an integer metadata" do assert :erlang.iolist_to_binary( UserFriendlyFormatter.format( :error, "This is a test message", {{2019, 10, 8}, {11, 58, 39, 5}}, line: 100 ) ) == "11:58:39.5\t|ERROR| This is a test message line=100\n" end test "format does not crash" do assert :erlang.iolist_to_binary(UserFriendlyFormatter.format(:fail, "hello", :err, [])) == "LOG_FORMATTER_ERROR: {:fail, \"hello\", :err, []}\n" end end
31.794118
94
0.557817
7337887f701157d1b9c512eed25fa569115ed852
1,429
ex
Elixir
test/support/data_case.ex
jinjagit/api
c1a176d8c318e05810bc1635706c56395819191e
[ "MIT" ]
null
null
null
test/support/data_case.ex
jinjagit/api
c1a176d8c318e05810bc1635706c56395819191e
[ "MIT" ]
10
2020-09-28T06:37:48.000Z
2021-12-22T15:04:38.000Z
test/support/data_case.ex
jinjagit/api
c1a176d8c318e05810bc1635706c56395819191e
[ "MIT" ]
null
null
null
defmodule LiquidVoting.DataCase do @moduledoc """ This module defines the setup for tests requiring access to the application's data layer. You may define functions here to be used as helpers in your tests. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do alias LiquidVoting.Repo import Ecto import Ecto.Changeset import Ecto.Query import LiquidVoting.DataCase end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(LiquidVoting.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(LiquidVoting.Repo, {:shared, self()}) end :ok end @doc """ A helper that transforms changeset errors into a map of messages. assert {:error, changeset} = Accounts.create_user(%{password: "short"}) assert "password is too short" in errors_on(changeset).password assert %{password: ["password is too short"]} = errors_on(changeset) """ def errors_on(changeset) do Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> Regex.replace(~r"%{(\w+)}", message, fn _, key -> opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() end) end) end end
26.462963
77
0.685094
7337bf30afef6d8abf5ff88277095d8c104ad2bf
1,966
exs
Elixir
clients/binary_authorization/mix.exs
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "Apache-2.0" ]
null
null
null
clients/binary_authorization/mix.exs
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/binary_authorization/mix.exs
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "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.BinaryAuthorization.Mixfile do use Mix.Project @version "0.10.0" def project() do [ app: :google_api_binary_authorization, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/binary_authorization" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Binary Authorization API client library. The management interface for Binary Authorization, a system providing policy control for images deployed to Kubernetes Engine clusters. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/binary_authorization", "Homepage" => "https://cloud.google.com/binary-authorization/" } ] end end
29.343284
181
0.672431
7337d2fb50fa87beb107dffc38777e1c7f2d887d
85
exs
Elixir
apps/exth_crypto/test/exth_crypto/cipher_test.exs
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
152
2018-10-27T04:52:03.000Z
2022-03-26T10:34:00.000Z
apps/exth_crypto/test/exth_crypto/cipher_test.exs
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
270
2018-04-14T07:34:57.000Z
2018-10-25T18:10:45.000Z
apps/exth_crypto/test/exth_crypto/cipher_test.exs
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
25
2018-10-27T12:15:13.000Z
2022-01-25T20:31:14.000Z
defmodule ExthCrypto.CipherTest do use ExUnit.Case doctest ExthCrypto.Cipher end
17
34
0.823529
7337dcf3956b686ac390d7ec4557e7c990d6a34a
2,786
exs
Elixir
home_page_local/test/home_page_web/controllers/category_controller_test.exs
tlk-emb/CMS_koji
40a93073128bfad7fdfa987c69d4a8759752064f
[ "Apache-2.0" ]
8
2019-06-02T05:02:36.000Z
2021-08-11T04:23:10.000Z
home_page_local/test/home_page_web/controllers/category_controller_test.exs
tlk-emb/CMS_koji
40a93073128bfad7fdfa987c69d4a8759752064f
[ "Apache-2.0" ]
7
2019-05-15T08:32:51.000Z
2020-06-10T07:46:43.000Z
home_page_local/test/home_page_web/controllers/category_controller_test.exs
tlk-emb/CMS_koji
40a93073128bfad7fdfa987c69d4a8759752064f
[ "Apache-2.0" ]
1
2019-06-02T05:02:47.000Z
2019-06-02T05:02:47.000Z
defmodule HomePageWeb.CategoryControllerTest do use HomePageWeb.ConnCase alias HomePage.Pages @create_attrs %{title: "some title"} @update_attrs %{title: "some updated title"} @invalid_attrs %{title: nil} def fixture(:category) do {:ok, category} = Pages.create_category(@create_attrs) category end describe "index" do test "lists all categories", %{conn: conn} do conn = get conn, category_path(conn, :index) assert html_response(conn, 200) =~ "Listing Categories" end end describe "new category" do test "renders form", %{conn: conn} do conn = get conn, category_path(conn, :new) assert html_response(conn, 200) =~ "New Category" end end describe "create category" do test "redirects to show when data is valid", %{conn: conn} do conn = post conn, category_path(conn, :create), category: @create_attrs assert %{id: id} = redirected_params(conn) assert redirected_to(conn) == category_path(conn, :show, id) conn = get conn, category_path(conn, :show, id) assert html_response(conn, 200) =~ "Show Category" end test "renders errors when data is invalid", %{conn: conn} do conn = post conn, category_path(conn, :create), category: @invalid_attrs assert html_response(conn, 200) =~ "New Category" end end describe "edit category" do setup [:create_category] test "renders form for editing chosen category", %{conn: conn, category: category} do conn = get conn, category_path(conn, :edit, category) assert html_response(conn, 200) =~ "Edit Category" end end describe "update category" do setup [:create_category] test "redirects when data is valid", %{conn: conn, category: category} do conn = put conn, category_path(conn, :update, category), category: @update_attrs assert redirected_to(conn) == category_path(conn, :show, category) conn = get conn, category_path(conn, :show, category) assert html_response(conn, 200) =~ "some updated title" end test "renders errors when data is invalid", %{conn: conn, category: category} do conn = put conn, category_path(conn, :update, category), category: @invalid_attrs assert html_response(conn, 200) =~ "Edit Category" end end describe "delete category" do setup [:create_category] test "deletes chosen category", %{conn: conn, category: category} do conn = delete conn, category_path(conn, :delete, category) assert redirected_to(conn) == category_path(conn, :index) assert_error_sent 404, fn -> get conn, category_path(conn, :show, category) end end end defp create_category(_) do category = fixture(:category) {:ok, category: category} end end
31.303371
89
0.674803
7337de6ade966a19992933a4f2d5d3638a4f25f4
283
exs
Elixir
test/grizzly/zwave/commands/powerlevel_test_node_get_test.exs
smartrent/grizzly
65a397ea7bfedb5518fe63a3f058a0b6af473e39
[ "Apache-2.0" ]
76
2019-09-04T16:56:58.000Z
2022-03-29T06:54:36.000Z
test/grizzly/zwave/commands/powerlevel_test_node_get_test.exs
smartrent/grizzly
65a397ea7bfedb5518fe63a3f058a0b6af473e39
[ "Apache-2.0" ]
124
2019-09-05T14:01:24.000Z
2022-02-28T22:58:14.000Z
test/grizzly/zwave/commands/powerlevel_test_node_get_test.exs
smartrent/grizzly
65a397ea7bfedb5518fe63a3f058a0b6af473e39
[ "Apache-2.0" ]
10
2019-10-23T19:25:45.000Z
2021-11-17T13:21:20.000Z
defmodule Grizzly.ZWave.Commands.PowerlevelTestNodeGetTest do use ExUnit.Case, async: true alias Grizzly.ZWave.Commands.PowerlevelTestNodeGet test "creates the command and validates params" do params = [] {:ok, _command} = PowerlevelTestNodeGet.new(params) end end
25.727273
61
0.766784
7337df58193cb2c8a27c4fa7e6f22dd3ceb08969
1,885
exs
Elixir
test/scheduler/schedule/schedule_test.exs
utrustdev/commanded-scheduler
7532f192d39df2d0b7d1d500973ceaa8ec987ed3
[ "MIT" ]
31
2017-11-25T00:18:12.000Z
2022-03-03T20:11:17.000Z
test/scheduler/schedule/schedule_test.exs
utrustdev/commanded-scheduler
7532f192d39df2d0b7d1d500973ceaa8ec987ed3
[ "MIT" ]
12
2018-01-09T21:18:30.000Z
2021-09-06T10:35:43.000Z
test/scheduler/schedule/schedule_test.exs
utrustdev/commanded-scheduler
7532f192d39df2d0b7d1d500973ceaa8ec987ed3
[ "MIT" ]
13
2018-02-08T15:15:11.000Z
2020-08-13T12:25:18.000Z
defmodule Commanded.ScheduleTest do use Commanded.Scheduler.RuntimeCase import Commanded.Assertions.EventAssertions import Commanded.Scheduler.Factory alias Commanded.Scheduler.{ Router, ScheduleOnce, ScheduledOnce, ScheduleRecurring, ScheduledRecurring, } describe "schedule once" do setup [:schedule_once] test "should create scheduled once domain event", context do assert_receive_event ScheduledOnce, fn scheduled -> assert scheduled.schedule_uuid == context.schedule_uuid assert scheduled.command == context.command assert scheduled.command_type == "Elixir.ExampleDomain.TicketBooking.Commands.TimeoutReservation" assert scheduled.due_at == context.due_at end end test "should error attempting to schedule duplicate", context do schedule_once = %ScheduleOnce{ schedule_uuid: context.schedule_uuid, command: context.command, due_at: context.due_at, } assert {:error, :already_scheduled} = Router.dispatch(schedule_once) end end describe "schedule recurring" do setup [:schedule_recurring] test "should create scheduled recurring domain event", context do assert_receive_event ScheduledRecurring, fn scheduled -> assert scheduled.schedule_uuid == context.schedule_uuid assert scheduled.command == context.command assert scheduled.command_type == "Elixir.Commanded.Scheduler.ExampleCommand" assert scheduled.schedule == "@daily" end end test "should error attempting to schedule duplicate", context do schedule_recurring = %ScheduleRecurring{ schedule_uuid: context.schedule_uuid, command: context.command, schedule: context.schedule, } assert {:error, :already_scheduled} = Router.dispatch(schedule_recurring) end end end
30.901639
105
0.715119
7337f57a0d859ad40d7370a57ff8730de747143d
466
exs
Elixir
test/push_ex_web/config_test.exs
pushex-project/push.ex
a6d4b18face39dd84d01a887dce60db2d0001d37
[ "MIT" ]
78
2018-12-02T23:58:37.000Z
2021-09-30T18:52:45.000Z
test/push_ex_web/config_test.exs
pushex-project/push.ex
a6d4b18face39dd84d01a887dce60db2d0001d37
[ "MIT" ]
23
2018-11-27T14:57:20.000Z
2021-09-24T16:14:43.000Z
test/push_ex_web/config_test.exs
pushex-project/push.ex
a6d4b18face39dd84d01a887dce60db2d0001d37
[ "MIT" ]
3
2019-01-30T02:08:37.000Z
2021-09-03T20:53:35.000Z
defmodule PushExWeb.ConfigTest do use ExUnit.Case, async: false alias PushExWeb.Config describe "close_connections?/0" do test "it is false by default" do assert Config.close_connections?() == false end test "it can be set to true or false" do Config.close_connections!(true) assert Config.close_connections?() == true Config.close_connections!(false) assert Config.close_connections?() == false end end end
23.3
49
0.690987
7338048d0e724845b156b23b16338dca8e028173
9,773
ex
Elixir
lib/kazan/watcher.ex
ahovgaard/kazan
a93ea241ae9d94f327f741875ff43f509f72b2c6
[ "MIT" ]
null
null
null
lib/kazan/watcher.ex
ahovgaard/kazan
a93ea241ae9d94f327f741875ff43f509f72b2c6
[ "MIT" ]
null
null
null
lib/kazan/watcher.ex
ahovgaard/kazan
a93ea241ae9d94f327f741875ff43f509f72b2c6
[ "MIT" ]
null
null
null
defmodule Kazan.Watcher do @moduledoc """ Watches for changes on a resource. This works by creating a HTTPoison ASync request. The request will eventually timeout, however the Watcher handles recreating the request when this occurs and requesting new events that have occurred since the last *resource_version* received. To use: 1. Create a request in the normal way that supports the `watch` parameter. Alternatively create a watch request. ``` request = Kazan.Apis.Core.V1.list_namespace!() # No need to add watch: true ``` or ``` request = Kazan.Apis.Core.V1.watch_namespace_list!() ``` 2. Start a watcher using the request, and passing the initial resource version and a pid to which to send received messages. ``` Kazan.Watcher.start_link(request, resource_version: rv, send_to: self()) ``` If no `resource_version` is passed then the watcher initially makes a normal request to get the starting value. This will only work if a non `watch` request is used. i.e. `Kazan.Apis.Core.V1.list_namespace!()` rather than `Kazan.Apis.Core.V1.watch_namespace_list!()` 3. In your client code you receive messages for each `%Watcher.Event{}`. You can pattern match on the object type if you have multiple watchers configured. For example, if the client is a `GenServer` ``` # type is `:added`, `:deleted`, `:modified` or `:gone` def handle_info(%Watcher.Event{object: object, from: watcher_pid, type: type}, state) do case object do %Kazan.Apis.Core.V1.Namespace{} = namespace -> process_namespace_event(type, namespace) %Kazan.Apis.Batch.V1.Job{} = job -> process_job_event(type, job) end {:noreply, state} end ``` 4. In the case that a `:gone` is received, then this indicates that Kubernetes has sent a 410 error. In this case the Watcher will automatically terminate and the consumer must clear its cache, reload any cached resources and restart the watcher. A Watcher can be terminated by calling `stop_watch/1`. """ use GenServer alias Kazan.LineBuffer require Logger defmodule State do @moduledoc false # Stores the internal state of the watcher. # # Includes: # # resource_version: # # The K8S *resource_version* (RV) is used to version each change in the cluster. # When we listen for events we need to specify the RV to start listening from. # For each event received we also receive a new RV, which we store in state. # When the watch eventually times-out (it is an HTTP request with a chunked response), # we can then create a new request passing the latest RV that was received. # # buffer: # # Chunked HTTP responses are not always a complete line, so we must buffer them # until we have a complete line before parsing. defstruct id: nil, request: nil, send_to: nil, name: nil, buffer: nil, rv: nil, client_opts: [], log_level: false end defmodule Event do defstruct [:type, :object, :from] end @doc """ Starts a watch request to the kube server The server should be set in the kazan config or provided in the options. ### Options * `send_to` - A `pid` to which events are sent. Defaults to `self()`. * `resource_version` - The version from which to start watching. * `name` - An optional name for the watcher. Displayed in logs. * `log` - the level to log. When false, disables watcher logging. * Other options are passed directly to `Kazan.Client.run/2` """ def start_link(%Kazan.Request{} = request, opts) do {send_to, opts} = Keyword.pop(opts, :send_to, self()) GenServer.start_link(__MODULE__, [request, send_to, opts]) end @doc "Stops the watch and terminates the process" def stop_watch(pid) do # Need to catch the case where the watch might have already terminated due # to a GONE already having being received. This can happen if the send_to process # has multiple watches and it manually tries to stop other watches once a GONE is received # on two at the same time. try do GenServer.call(pid, :stop_watch) catch :exit, {:noproc, _} -> :already_stopped end end @impl GenServer def init([request, send_to, opts]) do {rv, opts} = Keyword.pop(opts, :resource_version) {name, opts} = Keyword.pop(opts, :name, inspect(self())) {log_level, opts} = Keyword.pop(opts, :log, false) rv = case rv do nil -> log(log_level, "Obtaining initial rv") {:ok, object} = Kazan.run(request, Keyword.put(opts, :timeout, 500)) extract_rv(object) rv -> rv end client_opts = opts |> Keyword.put_new(:recv_timeout, 5 * 60 * 1000) log( log_level, "Watcher init: #{name} rv: #{rv} request: #{inspect(request)}" ) state = %State{ request: request, rv: rv, send_to: send_to, name: name, client_opts: client_opts, log_level: log_level } |> start_request() # Monitor send_to process so we can terminate when it goes down Process.monitor(send_to) {:ok, state} end @impl GenServer def handle_call(:stop_watch, _from, %State{} = state) do log(state, "Stopping watch #{inspect(self())}") {:stop, :normal, :ok, state} end @impl GenServer # should not be used normally - just used for testing and debugging to force # a 410 error to be generated by setting the rv to a low value def handle_info({:set_rv, rv}, state) do log(state, "Setting rv to #{rv}") {:noreply, %State{state | rv: rv}} end @impl GenServer def handle_info(%HTTPoison.AsyncStatus{code: 200}, state) do {:noreply, state} end @impl GenServer def handle_info(%HTTPoison.AsyncHeaders{}, state) do {:noreply, state} end @impl GenServer def handle_info( %HTTPoison.AsyncChunk{chunk: chunk, id: request_id}, %State{id: request_id, buffer: buffer} = state ) do {lines, buffer} = buffer |> LineBuffer.add_chunk(chunk) |> LineBuffer.get_lines() case process_lines(state, lines) do {:ok, new_rv} -> {:noreply, %State{state | buffer: buffer, rv: new_rv}} {:error, :gone} -> {:stop, :normal, state} end end @impl GenServer def handle_info( %HTTPoison.Error{reason: {:closed, :timeout}}, %State{name: name, rv: rv} = state ) do log(state, "Received Timeout: #{name} rv: #{rv}") {:noreply, start_request(state)} end @impl GenServer def handle_info( %HTTPoison.AsyncEnd{id: request_id}, %State{id: request_id, name: name, rv: rv} = state ) do log(state, "Received AsyncEnd: #{name} rv: #{rv}") {:noreply, start_request(state)} end @impl GenServer def handle_info({:DOWN, _ref, :process, pid, reason}, %State{} = state) do %State{name: name} = state log( state, "#{inspect(self())} - #{name} send_to process #{inspect(pid)} :DOWN reason: #{ inspect(reason) }" ) {:stop, :normal, state} end # INTERNAL defp start_request( %State{request: request, name: name, rv: rv, client_opts: client_opts} = state ) do query_params = request.query_params |> Map.put("watch", true) |> Map.put("resourceVersion", rv) request = %Kazan.Request{request | query_params: query_params} {:ok, id} = Kazan.run(request, [{:stream_to, self()} | client_opts]) log(state, "Started request: #{name} rv: #{rv}") %State{state | id: id, buffer: LineBuffer.new()} end defp process_lines(%State{name: name, rv: rv} = state, lines) do log(state, "Process lines: #{name}") Enum.reduce(lines, {:ok, rv}, fn line, status -> case status do {:ok, current_rv} -> process_line(line, current_rv, state) # stop on error {:error, :gone} -> {:error, :gone} end end) end # Processes each line returning either {:ok, new_rv} or {:error, :gone} # corresponding messages are sent to the send_to process defp process_line(line, current_rv, %State{} = state) do %State{ name: name, send_to: send_to } = state {:ok, %{"type" => type, "object" => raw_object}} = Poison.decode(line) {:ok, model} = Kazan.Models.decode(raw_object, nil) case extract_rv(raw_object) do {:gone, message} -> log(state, "Received 410: #{name} message: #{message}.") send(send_to, %Event{type: :gone, from: self()}) {:error, :gone} ^current_rv -> log(state, "Duplicate message: #{name} type: #{type} rv: #{current_rv}") {:ok, current_rv} new_rv -> log(state, "Received message: #{name} type: #{type} rv: #{new_rv}") send(send_to, %Event{ type: type_to_atom(type), object: model, from: self() }) {:ok, new_rv} end end defp type_to_atom("ADDED"), do: :added defp type_to_atom("MODIFIED"), do: :modified defp type_to_atom("DELETED"), do: :deleted defp extract_rv(%{ "code" => 410, "kind" => "Status", "reason" => "Gone", "status" => "Failure", "message" => message }), do: {:gone, message} defp extract_rv(%{"metadata" => %{"resourceVersion" => rv}}), do: rv defp extract_rv(%{metadata: %{resource_version: rv}}), do: rv defp log(%State{log_level: log_level}, msg), do: log(log_level, msg) defp log(false, _), do: :ok defp log(log_level, msg) do Logger.log(log_level, fn -> msg end) end end
29.436747
97
0.624373
733822840991ca081a1a9cc6be191353b9256dff
974
exs
Elixir
demo/config/config.exs
git-toni/lv-states
588652ae698efc7193dc25a8e4a68b5201aa09bd
[ "MIT" ]
3
2021-07-07T09:10:11.000Z
2022-03-18T10:28:14.000Z
demo/config/config.exs
git-toni/lv-states
588652ae698efc7193dc25a8e4a68b5201aa09bd
[ "MIT" ]
12
2021-07-06T21:08:21.000Z
2021-09-27T11:11:19.000Z
demo/config/config.exs
git-toni/lv-states
588652ae698efc7193dc25a8e4a68b5201aa09bd
[ "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 # Configures the endpoint config :demo, DemoWeb.Endpoint, url: [host: "localhost"], secret_key_base: "4SBEpKF/Cuq908tRsicQGStPukO65SMOEXfuwAFwq/cUERViWNiFITLfOHB4Xbpm", render_errors: [view: DemoWeb.ErrorView, accepts: ~w(html json), layout: false], pubsub_server: Demo.PubSub, live_view: [signing_salt: "ke+73GaH"] # 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 # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{Mix.env()}.exs"
33.586207
86
0.767967
7338433ad45a7ed0ae51702b462fb7d946c8e49f
1,518
ex
Elixir
lib/coderjobs_web/helpers/twbs4_form_helper.ex
johndavedecano/CoderJobs
a185c3129f92430d8e72184f359c16f93f24c43b
[ "MIT" ]
28
2017-11-20T02:01:17.000Z
2021-05-08T16:52:58.000Z
lib/coderjobs_web/helpers/twbs4_form_helper.ex
johndavedecano/CoderJobs
a185c3129f92430d8e72184f359c16f93f24c43b
[ "MIT" ]
1
2018-12-05T06:07:36.000Z
2018-12-09T17:33:28.000Z
lib/coderjobs_web/helpers/twbs4_form_helper.ex
johndavedecano/CoderJobs
a185c3129f92430d8e72184f359c16f93f24c43b
[ "MIT" ]
3
2017-12-21T03:29:39.000Z
2019-08-11T02:56:08.000Z
defmodule CoderjobsWeb.Helpers.Twbs4FormHelper do import Phoenix.HTML.Tag import Phoenix.HTML.Form def twbs4_error_tag(form, field) do if error = form.errors[field] do {message, _} = error IO.inspect message content_tag :div, humanize(field) <> " " <> message, class: "invalid-feedback" end end def twbs4_text_input_tag(form, field, opts \\ []) do class_name = "form-control " <> Keyword.get(opts, :class, "") if form.errors[field] do custom_opts = Keyword.put(opts, :class, class_name <> " is-invalid") text_input form, field, custom_opts else custom_opts = Keyword.put(opts, :class, class_name) text_input form, field, custom_opts end end def twbs4_textarea_tag(form, field, opts \\ []) do class_name = "form-control " <> Keyword.get(opts, :class, "") if form.errors[field] do custom_opts = Keyword.put(opts, :class, class_name <> " is-invalid") textarea form, field, custom_opts else custom_opts = Keyword.put(opts, :class, class_name) textarea form, field, custom_opts end end def twbs4_select_tag(form, field, options, opts \\ []) do class_name = "form-control " <> Keyword.get(opts, :class, "") if form.errors[field] do custom_opts = Keyword.put(opts, :class, class_name <> " is-invalid") select form, field, options, custom_opts else custom_opts = Keyword.put(opts, :class, class_name) select form, field, options, custom_opts end end end
33
84
0.660079
73384a72b3bfeaddd8f5d0a0eea955e713b705cb
1,183
ex
Elixir
apps/painting/lib/painting/storage/disk.ex
danmarcab/deep_painting
860c7d02bd6b112fffa199f715e61d895cba6623
[ "Apache-2.0" ]
null
null
null
apps/painting/lib/painting/storage/disk.ex
danmarcab/deep_painting
860c7d02bd6b112fffa199f715e61d895cba6623
[ "Apache-2.0" ]
11
2020-01-28T22:19:10.000Z
2022-03-11T23:18:18.000Z
apps/painting/lib/painting/storage/disk.ex
danmarcab/deep_painting
860c7d02bd6b112fffa199f715e61d895cba6623
[ "Apache-2.0" ]
null
null
null
defmodule Painting.Storage.Disk do @moduledoc """ Painting.Storage.Disk implements Painting.Storage storing data in disk. Data stays after application restarts. """ use GenServer @behaviour Painting.Storage def start(storage, opts \\ []) do file_name = Keyword.get(opts, :file_name, Application.app_dir(:painting, "priv") <> "/storage/" <> Atom.to_string(storage)) {:ok, ^storage} = :dets.open_file(storage, [type: :set, file: String.to_char_list(file_name)]) :ok end def save(storage, painting) do :dets.insert(storage, {painting.name, painting}) :ok end def find(storage, painting_name) do resp = :dets.lookup(storage, painting_name) case resp do [{^painting_name, painting}] -> {:ok, painting} _ -> :error end end def all(storage) do paintings = :dets.match(storage, :"$1") paintings |> List.flatten |> Enum.into(%{}) end def exists?(storage, painting_name) do resp = :dets.lookup(storage, painting_name) case resp do [{^painting_name, _painting}] -> true _ -> false end end def clear(storage) do :dets.delete_all_objects(storage) :ok end end
23.196078
128
0.652578
73386c99e648a28a4b27323b57677935685defcd
14,437
ex
Elixir
lib/phoenix/socket/transport.ex
misfo/phoenix
04464429d9b958e331b2ffe0f0f5926690ab3b56
[ "MIT" ]
1
2021-03-14T17:50:24.000Z
2021-03-14T17:50:24.000Z
lib/phoenix/socket/transport.ex
misfo/phoenix
04464429d9b958e331b2ffe0f0f5926690ab3b56
[ "MIT" ]
null
null
null
lib/phoenix/socket/transport.ex
misfo/phoenix
04464429d9b958e331b2ffe0f0f5926690ab3b56
[ "MIT" ]
2
2020-08-02T04:00:17.000Z
2020-10-07T16:07:37.000Z
defmodule Phoenix.Socket.Transport do @moduledoc """ API for building transports. This module describes what is required to build a Phoenix transport. The transport sits between the socket and channels, forwarding client messages to channels and vice-versa. A transport is responsible for: * Implementing the transport behaviour * Establishing the socket connection * Handling of incoming messages * Handling of outgoing messages * Managing channels * Providing secure defaults ## The transport behaviour The transport requires two functions: * `default_config/0` - returns the default transport configuration to be merged when the transport is declared in the socket module * `handlers/0` - returns a map of handlers. For example, if the transport can be run cowboy, it just need to specify the appropriate cowboy handler ## Socket connections Once a connection is established, the transport is responsible for invoking the `Phoenix.Socket.connect/2` callback and acting accordingly. Once connected, the transport should request the `Phoenix.Socket.id/1` and subscribe to the topic if one exists. On subscribed, the transport must be able to handle "disconnect" broadcasts on the given id topic. The `connect/6` function in this module can be used as a convenience or a documentation on such steps. ## Incoming messages Incoming messages are encoded in whatever way the transport chooses. Those messages must be decoded in the transport into a `Phoenix.Socket.Message` before being forwarded to a channel. Most of those messages are user messages except by: * "heartbeat" events in the "phoenix" topic - should just emit an OK reply * "phx_join" on any topic - should join the topic * "phx_leave" on any topic - should leave the topic The function `dispatch/3` can help with handling of such messages. ## Outgoing messages Channels can send two types of messages back to a transport: `Phoenix.Socket.Message` and `Phoenix.Socket.Reply`. Those messages are encoded in the channel into a format defined by the transport. That's why transports are required to pass a serializer that abides to the behaviour described in `Phoenix.Transports.Serializer`. ## Managing channels Because channels are spawned from the transport process, transports must trap exists and correctly handle the `{:EXIT, _, _}` messages arriving from channels, relaying the proper response to the client. The function `on_exit_message/2` should aid with that. ## Security This module also provides functions to enable a secure environment on transports that, at some point, have access to a `Plug.Conn`. The functionality provided by this module help with doing "origin" header checks and ensuring only SSL connections are allowed. ## Remote Client Channels can reply, synchronously, to any `handle_in/3` event. To match pushes with replies, clients must include a unique `ref` with every message and the channel server will reply with a matching ref where the client and pick up the callback for the matching reply. Phoenix includes a JavaScript client for WebSocket and Longpolling support using JSON encodings. However, a client can be implemented for other protocols and encodings by abiding by the `Phoenix.Socket.Message` format. ## Protocol Versioning Clients are expected to send the Channel Transport protocol version that they expect to be talking to. The version can be retrieved on the server from `Phoenix.Channel.Transport.protocol_version/0`. If no version is provided, the Transport adapters should default to assume a `"1.0.0"` version number. See `web/static/js/phoenix.js` for an example transport client implementation. """ require Logger alias Phoenix.Endpoint.Instrument alias Phoenix.Socket alias Phoenix.Socket.Message alias Phoenix.Socket.Reply @protocol_version "1.0.0" @client_vsn_requirements "~> 1.0" @doc """ Provides a keyword list of default configuration for socket transports. """ @callback default_config() :: Keyword.t @doc """ Returns the Channel Transport protocol version. """ def protocol_version, do: @protocol_version @doc """ Handles the socket connection. It builds a new `Phoenix.Socket` and invokes the handler `connect/2` callback and returns the result. If the connection was successful, generates `Phoenix.PubSub` topic from the `id/1` callback. """ def connect(endpoint, handler, transport_name, transport, serializer, params) do vsn = params["vsn"] || "1.0.0" if Version.match?(vsn, @client_vsn_requirements) do connect_vsn(endpoint, handler, transport_name, transport, serializer, params) else Logger.error "The client's requested channel transport version \"#{vsn}\" " <> "does not match server's version requirements of \"#{@client_vsn_requirements}\"" :error end end defp connect_vsn(endpoint, handler, transport_name, transport, serializer, params) do socket = %Socket{endpoint: endpoint, transport: transport, transport_pid: self(), transport_name: transport_name, handler: handler, pubsub_server: endpoint.__pubsub_server__, serializer: serializer} case handler.connect(params, socket) do {:ok, socket} -> case handler.id(socket) do nil -> {:ok, socket} id when is_binary(id) -> {:ok, %Socket{socket | id: id}} invalid -> Logger.error "#{inspect handler}.id/1 returned invalid identifier #{inspect invalid}. " <> "Expected nil or a string." :error end :error -> :error invalid -> Logger.error "#{inspect handler}.connect/2 returned invalid value #{inspect invalid}. " <> "Expected {:ok, socket} or :error" :error end end @doc """ Dispatches `Phoenix.Socket.Message` to a channel. All serialized, remote client messages should be deserialized and forwarded through this function by adapters. The following returns must be handled by transports: * `:noreply` - Nothing to be done by the transport * `{:reply, reply}` - The reply to be sent to the client * `{:joined, channel_pid, reply}` - The channel was joined and the reply must be sent as result * `{:error, reason, reply}` - An error happened and the reply must be sent as result ## Parameters filtering on join When logging parameters, Phoenix can filter out sensitive parameters in the logs, such as passwords, tokens and what not. Parameters to be filtered can be added via the `:filter_parameters` option: config :phoenix, :filter_parameters, ["password", "secret"] With the configuration above, Phoenix will filter any parameter that contains the terms `password` or `secret`. The match is case sensitive. Phoenix's default is `["password"]`. """ def dispatch(msg, channels, socket) def dispatch(%{ref: ref, topic: "phoenix", event: "heartbeat"}, _channels, _socket) do {:reply, %Reply{ref: ref, topic: "phoenix", status: :ok, payload: %{}}} end def dispatch(%Message{} = msg, channels, socket) do channels |> Map.get(msg.topic) |> do_dispatch(msg, socket) end defp do_dispatch(nil, %{event: "phx_join", topic: topic} = msg, socket) do if channel = socket.handler.__channel__(topic, socket.transport_name) do socket = %Socket{socket | topic: topic, channel: channel} filtered_payload = Instrument.filter_values(msg.payload, Application.get_env(:phoenix, :filter_parameters)) log_info topic, fn -> "JOIN #{topic} to #{inspect(channel)}\n" <> " Transport: #{inspect socket.transport}\n" <> " Parameters: #{inspect filtered_payload}" end case Phoenix.Channel.Server.join(socket, msg.payload) do {:ok, response, pid} -> log_info topic, fn -> "Replied #{topic} :ok" end {:joined, pid, %Reply{ref: msg.ref, topic: topic, status: :ok, payload: response}} {:error, reason} -> log_info topic, fn -> "Replied #{topic} :error" end {:error, reason, %Reply{ref: msg.ref, topic: topic, status: :error, payload: reason}} end else reply_ignore(msg, socket) end end defp do_dispatch(nil, msg, socket) do reply_ignore(msg, socket) end defp do_dispatch(channel_pid, msg, _socket) do send(channel_pid, msg) :noreply end defp log_info("phoenix" <> _, _func), do: :noop defp log_info(_topic, func), do: Logger.info(func) defp reply_ignore(msg, socket) do Logger.debug fn -> "Ignoring unmatched topic \"#{msg.topic}\" in #{inspect(socket.handler)}" end {:error, :unmatched_topic, %Reply{ref: msg.ref, topic: msg.topic, status: :error, payload: %{reason: "unmatched topic"}}} end @doc """ Returns the message to be relayed when a channel exists. """ def on_exit_message(topic, reason) do case reason do :normal -> %Message{topic: topic, event: "phx_close", payload: %{}} :shutdown -> %Message{topic: topic, event: "phx_close", payload: %{}} {:shutdown, _} -> %Message{topic: topic, event: "phx_close", payload: %{}} _ -> %Message{topic: topic, event: "phx_error", payload: %{}} end end @doc """ Forces SSL in the socket connection. Uses the endpoint configuration to decide so. It is a noop if the connection has been halted. """ def force_ssl(%Plug.Conn{halted: true} = conn, _socket, _endpoint, _opts) do conn end def force_ssl(conn, socket, endpoint, opts) do if force_ssl = force_ssl_config(socket, endpoint, opts) do Plug.SSL.call(conn, force_ssl) else conn end end defp force_ssl_config(socket, endpoint, opts) do Phoenix.Config.cache(endpoint, {:force_ssl, socket}, fn _ -> opts = if force_ssl = Keyword.get(opts, :force_ssl, endpoint.config(:force_ssl)) do force_ssl |> Keyword.put_new(:host, endpoint.config(:url)[:host] || "localhost") |> Plug.SSL.init() end {:cache, opts} end) end @doc """ Logs the transport request. Available for transports that generate a connection. """ def transport_log(conn, level) do if level do Plug.Logger.call(conn, Plug.Logger.init(log: level)) else conn end end @doc """ Checks the origin request header against the list of allowed origins. Should be called by transports before connecting when appropriate. If the origin header matches the allowed origins, no origin header was sent or no origin was configured, it will return the given connection. Otherwise a otherwise a 403 Forbidden response will be sent and the connection halted. It is a noop if the connection has been halted. """ def check_origin(conn, handler, endpoint, opts, sender \\ &Plug.Conn.send_resp/1) def check_origin(%Plug.Conn{halted: true} = conn, _handler, _endpoint, _opts, _sender), do: conn def check_origin(conn, handler, endpoint, opts, sender) do import Plug.Conn origin = get_req_header(conn, "origin") |> List.first check_origin = check_origin_config(handler, endpoint, opts) cond do is_nil(origin) or check_origin == false -> conn origin_allowed?(check_origin, URI.parse(origin), endpoint) -> conn true -> Logger.error """ Could not check origin for Phoenix.Socket transport. This happens when you are attempting a socket connection to a different host than the one configured in your config/ files. For example, in development the host is configured to "localhost" but you may be trying to access it from "127.0.0.1". To fix this issue, you may either: 1. update [url: [host: ...]] to your actual host in the config file for your current environment (recommended) 2. pass the :check_origin option when configuring your endpoint or when configuring the transport in your UserSocket module, explicitly outlining which origins are allowed: check_origin: ["https://example.com", "//another.com:888", "//other.com"] """ resp(conn, :forbidden, "") |> sender.() |> halt() end end defp check_origin_config(handler, endpoint, opts) do Phoenix.Config.cache(endpoint, {:check_origin, handler}, fn _ -> check_origin = case Keyword.get(opts, :check_origin, endpoint.config(:check_origin)) do origins when is_list(origins) -> Enum.map(origins, &parse_origin/1) boolean when is_boolean(boolean) -> boolean end {:cache, check_origin} end) end defp parse_origin(origin) do case URI.parse(origin) do %{host: nil} -> raise ArgumentError, "invalid check_origin: #{inspect origin} (expected an origin with a host)" %{scheme: scheme, port: port, host: host} -> {scheme, host, port} end end defp origin_allowed?(_check_origin, %URI{host: nil}, _endpoint), do: true defp origin_allowed?(true, uri, endpoint), do: compare?(uri.host, endpoint.config(:url)[:host]) defp origin_allowed?(check_origin, uri, _endpoint) when is_list(check_origin), do: origin_allowed?(uri, check_origin) defp origin_allowed?(uri, allowed_origins) do %{scheme: origin_scheme, host: origin_host, port: origin_port} = uri Enum.any?(allowed_origins, fn {allowed_scheme, allowed_host, allowed_port} -> compare?(origin_scheme, allowed_scheme) and compare?(origin_port, allowed_port) and compare_host?(origin_host, allowed_host) end) end defp compare?(request_val, allowed_val) do is_nil(allowed_val) or request_val == allowed_val end defp compare_host?(_request_host, nil), do: true defp compare_host?(request_host, "*." <> allowed_host), do: String.ends_with?(request_host, allowed_host) defp compare_host?(request_host, allowed_host), do: request_host == allowed_host end
34.704327
113
0.67424
73389818646d7001c8a76d5129c725f2ddb54906
1,525
ex
Elixir
test/support/data_case.ex
nickel/ticote
ba35d1d11772c068e2ef29064d135e30dcf8ff5a
[ "MIT" ]
null
null
null
test/support/data_case.ex
nickel/ticote
ba35d1d11772c068e2ef29064d135e30dcf8ff5a
[ "MIT" ]
null
null
null
test/support/data_case.ex
nickel/ticote
ba35d1d11772c068e2ef29064d135e30dcf8ff5a
[ "MIT" ]
null
null
null
defmodule Ticote.DataCase do @moduledoc """ This module defines the setup for tests requiring access to the application's data layer. You may define functions here to be used as helpers in your tests. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use Ticote.DataCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate alias Ecto.Adapters.SQL using do quote do alias Ticote.Repo import Ecto import Ecto.Changeset import Ecto.Query import Ticote.DataCase end end setup tags do :ok = SQL.Sandbox.checkout(Ticote.Repo) unless tags[:async] do SQL.Sandbox.mode(Ticote.Repo, {:shared, self()}) end :ok end @doc """ A helper that transforms changeset errors into a map of messages. assert {:error, changeset} = Accounts.create_user(%{password: "short"}) assert "password is too short" in errors_on(changeset).password assert %{password: ["password is too short"]} = errors_on(changeset) """ def errors_on(changeset) do Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> Regex.replace(~r"%{(\w+)}", message, fn _, key -> opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() end) end) end end
26.293103
77
0.685246
73389998e971e9fee02294ea451524cc6562e654
629
ex
Elixir
lib/kepler/users/user.ex
SAAF-Alex-and-Ashton-Forces/kepler
06cea361e5972b5ebe4e19f70793d921aca25664
[ "MIT" ]
null
null
null
lib/kepler/users/user.ex
SAAF-Alex-and-Ashton-Forces/kepler
06cea361e5972b5ebe4e19f70793d921aca25664
[ "MIT" ]
null
null
null
lib/kepler/users/user.ex
SAAF-Alex-and-Ashton-Forces/kepler
06cea361e5972b5ebe4e19f70793d921aca25664
[ "MIT" ]
null
null
null
defmodule Kepler.Users.User do use Ecto.Schema use Pow.Ecto.Schema use PowAssent.Ecto.Schema @primary_key {:id, :binary_id, autogenerate: true} @foreign_key_type :binary_id schema "users" do field :name, :string field :username, :string pow_user_fields() timestamps() end @impl PowAssent.Ecto.Schema def user_identity_changeset(user_or_changeset, user_identity, attrs, user_id_attrs) do IO.inspect(attrs, label: "attrs") user_or_changeset |> Ecto.Changeset.cast(attrs, [:name, :username]) |> pow_assent_user_identity_changeset(user_identity, attrs, user_id_attrs) end end
24.192308
88
0.73132
733899b7baedfc081ede1618df92978ac1ed1f64
4,609
ex
Elixir
lib/oracleex.ex
MikeAlbertFleetSolutions/oracleex
71c096af28531d3e8f52a7ba6eebfa369f0759fa
[ "Apache-2.0" ]
1
2020-02-28T15:13:32.000Z
2020-02-28T15:13:32.000Z
lib/oracleex.ex
MikeAlbertFleetSolutions/oracleex
71c096af28531d3e8f52a7ba6eebfa369f0759fa
[ "Apache-2.0" ]
null
null
null
lib/oracleex.ex
MikeAlbertFleetSolutions/oracleex
71c096af28531d3e8f52a7ba6eebfa369f0759fa
[ "Apache-2.0" ]
null
null
null
defmodule Oracleex do @moduledoc """ Interface for interacting with an Oracle Server via an ODBC driver for Elixir. It implements `DBConnection` behaviour, using `:odbc` to connect to the system's ODBC driver. Requires an Oracle ODBC driver, see [README](readme.html) for installation instructions. """ alias Oracleex.Query alias Oracleex.Type @doc """ Connect to an Oracle Server using ODBC. `opts` expects a keyword list with zero or more of: * `:dsn` - The ODBC DSN the adapter will use. * environment variable: `ORACLE_DSN` * default value: OracleODBC-12c * `:service` - TNS service name. * environment variable: `ORACLE_SERVICE` * `:username` - Username. * environment variable: `ORACLE_USR` * `:password` - User's password. * environment variable: `ORACLE_PWD` `Oracleex` uses the `DBConnection` framework and supports all `DBConnection` options like `:idle`, `:after_connect` etc. See `DBConnection.start_link/2` for more information. ## Examples iex> {:ok, pid} = Oracleex.start_link(database: "mr_microsoft") {:ok, #PID<0.70.0>} """ @spec start_link(Keyword.t) :: {:ok, pid} def start_link(opts) do DBConnection.start_link(Oracleex.Protocol, opts) end @doc """ Executes a query against an Oracle Server with ODBC. `conn` expects a `Oracleex` process identifier. `statement` expects a SQL query string. `params` expects a list of values in one of the following formats: * Strings with only valid ASCII characters, which will be sent to the database as strings. * Other binaries, which will be converted to UTF16 Little Endian binaries (which is what SQL Server expects for its unicode fields). * `Decimal` structs, which will be encoded as strings so they can be sent to the database with arbitrary precision. * Integers, which will be sent as-is if under 10 digits or encoded as strings for larger numbers. * Floats, which will be encoded as strings. * Time as `{hour, minute, sec, usec}` tuples, which will be encoded as strings. * Dates as `{year, month, day}` tuples, which will be encoded as strings. * Datetime as `{{hour, minute, sec, usec}, {year, month, day}}` tuples which will be encoded as strings. Note that attempting to insert a value with usec > 0 into a 'datetime' or 'smalldatetime' column is an error since those column types don't have enough precision to store usec data. `opts` expects a keyword list with zero or more of: * `:preserve_encoding`: If `true`, doesn't convert returned binaries from UTF16LE to UTF8. Default: `false`. * `:mode` - set to `:savepoint` to use a savepoint to rollback to before the query on error, otherwise set to `:transaction` (default: `:transaction`); Result values will be encoded according to the following conversions: * char and varchar: strings. * nchar and nvarchar: strings unless `:preserve_encoding` is set to `true` in which case they will be returned as UTF16 Little Endian binaries. * int, smallint, tinyint, decimal and numeric when precision < 10 and scale = 0 (i.e. effectively integers): integers. * float, real, double precision, decimal and numeric when precision between 10 and 15 and/or scale between 1 and 15: `Decimal` structs. * bigint, money, decimal and numeric when precision > 15: strings. * date: `{year, month, day}` * smalldatetime, datetime, dateime2: `{{YY, MM, DD}, {HH, MM, SS, 0}}` (note that fractional second data is lost due to limitations of the ODBC adapter. To preserve it you can convert these columns to varchar during selection.) * uniqueidentifier, time, binary, varbinary, rowversion: not currently supported due to adapter limitations. Select statements for columns of these types must convert them to supported types (e.g. varchar). """ @spec query(pid(), binary(), [Type.param()], Keyword.t) :: {:ok, iodata(), Oracleex.Result.t} def query(conn, statement, params, opts \\ []) do DBConnection.prepare_execute( conn, %Query{name: "", statement: statement}, params, opts) end @doc """ Executes a query against an Oracle Server with ODBC. Raises an error on failure. See `query/4` for details. """ @spec query!(pid(), binary(), [Type.param()], Keyword.t) :: {iodata(), Oracleex.Result.t} def query!(conn, statement, params, opts \\ []) do DBConnection.prepare_execute!( conn, %Query{name: "", statement: statement}, params, opts) end end
41.151786
96
0.687134
7338b078d5f72d57d95f001cd08ecbdd984d3a1d
2,583
exs
Elixir
test/risk_logic_test.exs
dmyers87/lowendinsight
5c5426d521a97d8a754261da5328ebeb52beb1fa
[ "BSD-3-Clause" ]
9
2020-04-07T17:22:15.000Z
2022-01-29T21:56:07.000Z
test/risk_logic_test.exs
dmyers87/lowendinsight
5c5426d521a97d8a754261da5328ebeb52beb1fa
[ "BSD-3-Clause" ]
49
2020-03-03T16:18:50.000Z
2021-05-29T13:48:04.000Z
test/risk_logic_test.exs
dmyers87/lowendinsight
5c5426d521a97d8a754261da5328ebeb52beb1fa
[ "BSD-3-Clause" ]
3
2020-05-14T16:26:03.000Z
2022-01-24T22:03:40.000Z
# Copyright (C) 2020 by the Georgia Tech Research Institute (GTRI) # This software may be modified and distributed under the terms of # the BSD 3-Clause license. See the LICENSE file for details. defmodule RiskLogicTest do use ExUnit.Case, async: true doctest RiskLogic test "confirm contributor critical" do assert RiskLogic.contributor_risk(1) == {:ok, "critical"} end test "confirm contributor high" do assert RiskLogic.contributor_risk(2) == {:ok, "high"} end test "confirm contributor medium" do assert RiskLogic.contributor_risk(4) == {:ok, "medium"} end test "confirm contributor low" do assert RiskLogic.contributor_risk(5) == {:ok, "low"} end test "confirm currency critical" do assert RiskLogic.commit_currency_risk(104) == {:ok, "critical"} end test "confirm currency more than critical" do assert RiskLogic.commit_currency_risk(105) == {:ok, "critical"} end test "confirm currency high" do assert RiskLogic.commit_currency_risk(52) == {:ok, "high"} end test "confirm currency more than high" do assert RiskLogic.commit_currency_risk(53) == {:ok, "high"} end test "confirm currency medium" do assert RiskLogic.commit_currency_risk(26) == {:ok, "medium"} end test "confirm currency more than medium" do assert RiskLogic.commit_currency_risk(27) == {:ok, "medium"} end test "confirm currency low" do assert RiskLogic.commit_currency_risk(25) == {:ok, "low"} end test "confirm large commit low" do assert RiskLogic.commit_change_size_risk(0.04) == {:ok, "low"} end test "confirm large commit medium" do assert RiskLogic.commit_change_size_risk(0.20) == {:ok, "medium"} end test "confirm large commit high" do assert RiskLogic.commit_change_size_risk(0.16) == {:ok, "low"} end test "confirm large commit critical" do assert RiskLogic.commit_change_size_risk(0.45) == {:ok, "critical"} end test "confirm functional commiters low" do assert RiskLogic.functional_contributors_risk(6) == {:ok, "low"} assert RiskLogic.functional_contributors_risk(5) == {:ok, "low"} end test "confirm functional commiters medium" do assert RiskLogic.functional_contributors_risk(4) == {:ok, "medium"} assert RiskLogic.functional_contributors_risk(3) == {:ok, "medium"} end test "confirm functional commiters high" do assert RiskLogic.functional_contributors_risk(2) == {:ok, "high"} end test "confirm functional commiters critical" do assert RiskLogic.functional_contributors_risk(1) == {:ok, "critical"} end end
29.689655
73
0.710801
7338b9d3db171b303cb92542363b2a2832a056f7
1,079
ex
Elixir
lib/neko/rules/simple_rule/worker.ex
Boogiep0p/neko-achievements
d26c969b9ebd88060d6278ccb9dc01e746cb002b
[ "MIT" ]
null
null
null
lib/neko/rules/simple_rule/worker.ex
Boogiep0p/neko-achievements
d26c969b9ebd88060d6278ccb9dc01e746cb002b
[ "MIT" ]
null
null
null
lib/neko/rules/simple_rule/worker.ex
Boogiep0p/neko-achievements
d26c969b9ebd88060d6278ccb9dc01e746cb002b
[ "MIT" ]
null
null
null
defmodule Neko.Rules.SimpleRule.Worker do @moduledoc false use GenServer require Logger #------------------------------------------------------------------ # Client API #------------------------------------------------------------------ def start_link(state \\ []) do GenServer.start_link(__MODULE__, state) end def achievements(pid, user_id) do GenServer.call(pid, {:achievements, user_id}) end # reload rules from store def reload(pid) do GenServer.call(pid, {:reload}) end #------------------------------------------------------------------ # Server API #------------------------------------------------------------------ def init(_) do Logger.info("simple rule worker started...") {:ok, rules()} end def handle_call({:achievements, user_id}, _from, rules) do achievements = Neko.Rules.SimpleRule.achievements(rules, user_id) {:reply, achievements, rules} end def handle_call({:reload}, _from, _rules) do {:reply, :ok, rules()} end defp rules do Neko.Rules.SimpleRule.all() end end
23.456522
69
0.499537
7338bbc1c45bbb4e5f1b6add9232692a01b88d65
101
exs
Elixir
elixir/.formatter.exs
TreywRoberts/web-homework
d19b17dd384341d9e6e7e3174372673584289b83
[ "MIT" ]
14
2018-11-28T11:33:47.000Z
2021-09-12T08:30:40.000Z
elixir/.formatter.exs
TreywRoberts/web-homework
d19b17dd384341d9e6e7e3174372673584289b83
[ "MIT" ]
1
2019-07-01T22:57:18.000Z
2019-07-01T22:57:18.000Z
elixir/.formatter.exs
TreywRoberts/web-homework
d19b17dd384341d9e6e7e3174372673584289b83
[ "MIT" ]
3
2019-08-07T06:41:34.000Z
2022-03-22T16:02:06.000Z
# Used by "mix format" [ inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] ]
20.2
70
0.534653
7338c9f5e86612b6abe3ace8cd32fc916c5d5cba
1,760
ex
Elixir
clients/content/lib/google_api/content/v2/model/orders_get_test_order_template_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/content/lib/google_api/content/v2/model/orders_get_test_order_template_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/content/lib/google_api/content/v2/model/orders_get_test_order_template_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Content.V2.Model.OrdersGetTestOrderTemplateResponse do @moduledoc """ ## Attributes * `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "content#ordersGetTestOrderTemplateResponse". * `template` (*type:* `GoogleApi.Content.V2.Model.TestOrder.t`, *default:* `nil`) - The requested test order template. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :kind => String.t() | nil, :template => GoogleApi.Content.V2.Model.TestOrder.t() | nil } field(:kind) field(:template, as: GoogleApi.Content.V2.Model.TestOrder) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.OrdersGetTestOrderTemplateResponse do def decode(value, options) do GoogleApi.Content.V2.Model.OrdersGetTestOrderTemplateResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.OrdersGetTestOrderTemplateResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.2
165
0.740341
7338d03eb2312d260183dbfbf787859dc3c4b7d5
1,821
exs
Elixir
clients/sql_admin/mix.exs
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
clients/sql_admin/mix.exs
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
clients/sql_admin/mix.exs
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.SQLAdmin.Mixfile do use Mix.Project @version "0.41.2" def project() do [ app: :google_api_sql_admin, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/sql_admin" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Cloud SQL Admin API client library. API for Cloud SQL database instance management """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/sql_admin", "Homepage" => "https://developers.google.com/cloud-sql/" } ] end end
27.179104
100
0.653487
7338f6243af3e1516818f336994cda9de39df85f
8,735
ex
Elixir
lib/binance_futures.ex
dwarvesf/ex_binance
ed55e4b363c1cca54401b3b7d0e76c34e8797877
[ "MIT" ]
null
null
null
lib/binance_futures.ex
dwarvesf/ex_binance
ed55e4b363c1cca54401b3b7d0e76c34e8797877
[ "MIT" ]
null
null
null
lib/binance_futures.ex
dwarvesf/ex_binance
ed55e4b363c1cca54401b3b7d0e76c34e8797877
[ "MIT" ]
null
null
null
defmodule Dwarves.BinanceFutures do alias Binance.Rest.HTTPClient require Logger # Server @spec ping :: {:error, {:http_error, HTTPoison.Error.t()} | {:poison_decode_error, Poison.ParseError.t()} | map} | {:ok, false | nil | true | binary | list | number | map} @doc """ Pings binance API. Returns `{:ok, %{}}` if successful, `{:error, reason}` otherwise """ def ping(is_testnet \\ false) do HTTPClient.get_binance("/fapi/v1/ping", is_testnet) end # Ticker @doc """ Get all symbols and current prices listed in binance Returns `{:ok, [%Binance.SymbolPrice{}]}` or `{:error, reason}`. ## Example ``` {:ok, [%Binance.SymbolPrice{price: "0.07579300", symbol: "ETHBTC"}, %Binance.SymbolPrice{price: "0.01670200", symbol: "LTCBTC"}, %Binance.SymbolPrice{price: "0.00114550", symbol: "BNBBTC"}, %Binance.SymbolPrice{price: "0.00640000", symbol: "NEOBTC"}, %Binance.SymbolPrice{price: "0.00030000", symbol: "123456"}, %Binance.SymbolPrice{price: "0.04895000", symbol: "QTUMETH"}, ...]} ``` """ def get_all_prices(is_testnet \\ false) do case HTTPClient.get_binance("/fapi/v1/ticker/price", is_testnet) do {:ok, data} -> {:ok, Enum.map(data, &Binance.SymbolPrice.new(&1))} err -> err end end # Order @doc """ Creates a new order on binance Returns `{:ok, %{}}` or `{:error, reason}`. In the case of a error on binance, for example with invalid parameters, `{:error, {:binance_error, %{code: code, msg: msg}}}` will be returned. Please read https://www.binance.com/restapipub.html#user-content-account-endpoints to understand all the parameters """ def create_order( %{"symbol" => symbol, "side" => side, "type" => type, "quantity" => quantity} = params, api_secret, api_key, is_testnet \\ false ) do timestamp = case params["timestamp"] do # timestamp needs to be in milliseconds nil -> :os.system_time(:millisecond) t -> t end receiving_window = case params["receiving_window"] do nil -> 1000 t -> t end arguments = %{ symbol: symbol, side: side, type: type, quantity: quantity, recvWindow: receiving_window, timestamp: timestamp } |> Map.merge( unless( is_nil(params["new_client_order_id"]), do: %{newClientOrderId: params["new_client_order_id"]}, else: %{} ) ) |> Map.merge( unless(is_nil(params["stop_price"]), do: %{stopPrice: format_price(params["stop_price"])}, else: %{} ) ) |> Map.merge( unless(is_nil(params["new_client_order_id"]), do: %{icebergQty: params["iceberg_quantity"]}, else: %{} ) ) |> Map.merge( unless(is_nil(params["time_in_force"]), do: %{timeInForce: params["time_in_force"]}, else: %{} ) ) |> Map.merge( unless(is_nil(params["price"]), do: %{price: format_price(params["price"])}, else: %{}) ) case HTTPClient.signed_request_binance( "/fapi/v1/order", arguments, :post, api_secret, api_key, is_testnet ) do {:ok, %{"code" => code, "msg" => msg}} -> {:error, {:binance_error, %{code: code, msg: msg}}} data -> data end end @doc """ Creates a new **limit** **buy** order Symbol can be a binance symbol in the form of `"ETHBTC"` or `%Binance.TradePair{}`. Returns `{:ok, %{}}` or `{:error, reason}` """ def order_limit_buy( %{"symbol" => symbol, "quantity" => quantity, "price" => price} = params, api_secret, api_key, is_testnet \\ false ) when is_binary(symbol) when is_number(quantity) when is_number(price) do params |> Map.merge(%{"side" => "BUY", "type" => "LIMIT"}) |> create_order( api_secret, api_key, is_testnet ) |> parse_order_response end @doc """ Creates a new **limit** **sell** order Symbol can be a binance symbol in the form of `"ETHBTC"` or `%Binance.TradePair{}`. Returns `{:ok, %{}}` or `{:error, reason}` """ def order_limit_sell( %{"symbol" => symbol, "quantity" => quantity, "price" => price} = params, api_secret, api_key, is_testnet \\ false ) when is_binary(symbol) when is_number(quantity) when is_number(price) do params |> Map.merge(%{"side" => "SELL", "type" => "LIMIT"}) |> create_order( api_secret, api_key, is_testnet ) |> parse_order_response end @doc """ Creates a new **market** **buy** order Symbol can be a binance symbol in the form of `"ETHBTC"` or `%Binance.TradePair{}`. Returns `{:ok, %{}}` or `{:error, reason}` """ def order_market_buy(%Binance.TradePair{from: from, to: to} = symbol, quantity) when is_number(quantity) when is_binary(from) when is_binary(to) do case find_symbol(symbol) do {:ok, binance_symbol} -> order_market_buy(binance_symbol, quantity) e -> e end end def order_market_buy( %{"symbol" => symbol, "quantity" => quantity} = params, api_secret, api_key, is_testnet \\ false ) when is_binary(symbol) when is_number(quantity) do params |> Map.merge(%{"side" => "BUY", "type" => "MARKET"}) |> create_order( api_secret, api_key, is_testnet ) end @doc """ Creates a new **market** **sell** order Symbol can be a binance symbol in the form of `"ETHBTC"` or `%Binance.TradePair{}`. Returns `{:ok, %{}}` or `{:error, reason}` """ def order_market_sell(%Binance.TradePair{from: from, to: to} = symbol, quantity) when is_number(quantity) when is_binary(from) when is_binary(to) do case find_symbol(symbol) do {:ok, binance_symbol} -> order_market_sell(binance_symbol, quantity) e -> e end end def order_market_sell( %{"symbol" => symbol, "quantity" => quantity} = params, api_secret, api_key, is_testnet \\ false ) when is_binary(symbol) when is_number(quantity) do params |> Map.merge(%{"side" => "SELL", "type" => "MARKET"}) |> create_order( api_secret, api_key, is_testnet ) end defp parse_order_response({:ok, response}) do {:ok, Binance.OrderResponse.new(response)} end defp parse_order_response({ :error, { :binance_error, %{code: -2010, msg: "Account has insufficient balance for requested action."} = reason } }) do {:error, %Binance.InsufficientBalanceError{reason: reason}} end # Misc defp format_price(num) when is_float(num), do: :erlang.float_to_binary(num, [{:decimals, 8}]) defp format_price(num) when is_integer(num), do: inspect(num) defp format_price(num) when is_binary(num), do: num @doc """ Searches and normalizes the symbol as it is listed on binance. To retrieve this information, a request to the binance API is done. The result is then **cached** to ensure the request is done only once. Order of which symbol comes first, and case sensitivity does not matter. Returns `{:ok, "SYMBOL"}` if successfully, or `{:error, reason}` otherwise. ## Examples These 3 calls will result in the same result string: ``` find_symbol(%Binance.TradePair{from: "ETH", to: "REQ"}) ``` ``` find_symbol(%Binance.TradePair{from: "REQ", to: "ETH"}) ``` ``` find_symbol(%Binance.TradePair{from: "rEq", to: "eTH"}) ``` Result: `{:ok, "REQETH"}` """ def find_symbol(%Binance.TradePair{from: from, to: to} = tp) when is_binary(from) when is_binary(to) do case Binance.SymbolCache.get() do # cache hit {:ok, data} -> from = String.upcase(from) to = String.upcase(to) found = Enum.filter(data, &Enum.member?([from <> to, to <> from], &1)) case Enum.count(found) do 1 -> {:ok, found |> List.first()} 0 -> {:error, :symbol_not_found} end # cache miss {:error, :not_initialized} -> case get_all_prices() do {:ok, price_data} -> price_data |> Enum.map(fn x -> x.symbol end) |> Binance.SymbolCache.store() find_symbol(tp) err -> err end err -> err end end end
25.766962
145
0.56806
733947d391a9e4de25573197c1ab929399e87929
3,306
exs
Elixir
mix.exs
naramore/highstorm
1150ffd48e147b1a5e4f507e59eb788dc7d824c4
[ "MIT" ]
null
null
null
mix.exs
naramore/highstorm
1150ffd48e147b1a5e4f507e59eb788dc7d824c4
[ "MIT" ]
null
null
null
mix.exs
naramore/highstorm
1150ffd48e147b1a5e4f507e59eb788dc7d824c4
[ "MIT" ]
null
null
null
defmodule Highstorm.MixProject do use Mix.Project @in_production Mix.env() == :prod @version "0.0.1" @author "naramore" @source_url "https://github.com/naramore/highstorm" @description """ Datalog """ def project do [ app: :highstorm, version: @version, elixir: "~> 1.11", elixirc_paths: elixirc_paths(Mix.env()), compilers: [:boundary] ++ Mix.compilers(), build_embedded: @in_production, start_permanent: @in_production, aliases: aliases(), deps: deps(), description: @description, package: package(), name: "Highstorm", docs: docs(), test_coverage: [tool: ExCoveralls], boundary: [externals_mode: :relaxed], preferred_cli_env: [ format: :test, credo: :test, dialyzer: :test, check: :test, coveralls: :test ], boundary: [ default: [ check: [ apps: [:stream_data, {:mix, :runtime}] ] ] ], dialyzer: [ flags: [ :underspecs, :error_handling, :unmatched_returns, :unknown, :race_conditions ], plt_add_deps: :apps_direct, ignore_warnings: ".dialyzer_ignore.exs", list_unused_filters: true, plt_core_path: "priv/plts" ] ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end defp package do [ contributors: [@author], maintainers: [@author], source_ref: "v#{@version}", links: %{"GitHub" => @source_url}, files: ~w(lib .formatter.exs mix.exs README.md) ] end defp docs do [ main: "readme", source_ref: "v#{@version}", source_url: @source_url, extras: ["README.md"] ] end # Specifies which paths to compile per environment. defp elixirc_paths(env) when env in [:dev, :test], do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Run "mix help deps" to learn about dependencies. defp deps do [ {:stream_data, "~> 0.5"}, # {:benchee, "~> 1.0", only: [:dev, :test]}, {:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false}, {:credo, "~> 1.5", only: [:dev, :test], runtime: false}, {:excoveralls, "~> 0.13", only: [:dev, :test]}, # {:inch_ex, github: "rrrene/inch_ex", only: [:dev, :test]}, # {:ex_doc, "~> 0.23", only: :dev, runtime: false}, {:boundary, "~> 0.7", runtime: false} ] end defp aliases do [ home: &home/1, otp_vsn: &otp_version/1, check: [ "compile --warnings-as-errors", "credo", "dialyzer", "test", "format" ] ] end defp home(_) do Mix.shell().info("#{Mix.Utils.mix_home()}") end defp otp_version(_) do Mix.shell().info("#{otp_vsn()}") end defp otp_vsn(major \\ otp_release()) do Path.join([:code.root_dir(), "releases", major, "OTP_VERSION"]) |> File.read!() |> String.split(["\r\n", "\r", "\n"], trim: true) |> case do [full | _] -> full _ -> major end catch _ -> major end defp otp_release() do :erlang.system_info(:otp_release) |> List.to_string() end end
23.446809
80
0.540835
73396d36610b22eaaaaf873e46ebfa3eaf624771
767
ex
Elixir
lib/postgrex/result.ex
MSch/postgrex
92ca73697094205a6cd4274c10b4bda986ab4f20
[ "Apache-2.0" ]
null
null
null
lib/postgrex/result.ex
MSch/postgrex
92ca73697094205a6cd4274c10b4bda986ab4f20
[ "Apache-2.0" ]
null
null
null
lib/postgrex/result.ex
MSch/postgrex
92ca73697094205a6cd4274c10b4bda986ab4f20
[ "Apache-2.0" ]
null
null
null
defmodule Postgrex.Result do @moduledoc """ Result struct returned from any successful query. Its fields are: * `command` - An atom of the query command, for example: `:select` or `:insert`; * `columns` - The column names; * `rows` - The result set. A list of tuples, each tuple corresponding to a row, each element in the tuple corresponds to a column; * `num_rows` - The number of fetched or affected rows; * `decoder` - Terms used to decode the query in the client; """ @type t :: %__MODULE__{ command: atom, columns: [String.t] | nil, rows: [[term]] | nil, num_rows: integer, decoder: {term, term} | :done} defstruct [:command, :columns, :rows, :num_rows, :decoder] end
33.347826
78
0.621904
7339dbe47aee39efa87554b3f3db7db8a9c69c7e
3,740
ex
Elixir
lib/ex_ical/parser.ex
clekstro/ex_ical
9f26d92291daac7a21a6749db365021d894d79fc
[ "MIT" ]
23
2016-03-18T11:30:24.000Z
2019-05-27T17:23:35.000Z
lib/ex_ical/parser.ex
hiro-riveros/ex_ical
34276ad2475b3491630fd75d8c27a4f1de48ed88
[ "MIT" ]
16
2016-06-11T05:15:00.000Z
2019-05-10T11:57:50.000Z
lib/ex_ical/parser.ex
hiro-riveros/ex_ical
34276ad2475b3491630fd75d8c27a4f1de48ed88
[ "MIT" ]
17
2016-05-20T11:59:37.000Z
2021-01-24T07:14:14.000Z
defmodule ExIcal.Parser do @moduledoc """ Responsible for parsing an iCal string into a list of events. This module contains one public function, `parse/1`. Most of the most frequently used iCalendar properties can be parsed from the file (for example: start/end time, description, recurrence rules, and more; see `ExIcal.Event` for a full list). However, there is not yet full coverage of all properties available in the iCalendar spec. More properties will be added over time, but if you need a legal iCalendar property that `ExIcal` does not yet support, please sumbit an issue on GitHub. """ alias ExIcal.{DateParser,Event} @doc """ Parses an iCal string into a list of events. This function takes a single argument–a string in iCalendar format–and returns a list of `%ExIcal.Event{}`. ## Example ```elixir HTTPotion.get("url-for-icalendar").body |> ExIcal.parse |> ExIcal.by_range(DateTime.utc_now(), DateTime.utc_now() |> Timex.shift(days: 7)) ``` """ @spec parse(String.t) :: [%Event{}] def parse(data) do data |> String.replace(~s"\n\t", ~S"\n") |> String.replace(~s"\n\x20", ~S"\n") |> String.replace(~s"\"", "") |> String.split("\n") |> Enum.reduce(%{events: []}, fn(line, data) -> line |> String.trim() |> parse_line(data) end) |> Map.get(:events) end defp parse_line("BEGIN:VEVENT" <> _, data), do: %{data | events: [%Event{} | data[:events]]} defp parse_line("DTSTART" <> start, data), do: data |> put_to_map(:start, process_date(start, data[:tzid])) defp parse_line("DTEND" <> endd, data), do: data |> put_to_map(:end, process_date(endd, data[:tzid])) defp parse_line("DTSTAMP" <> stamp, data), do: data |> put_to_map(:stamp, process_date(stamp, data[:tzid])) defp parse_line("SUMMARY:" <> summary, data), do: data |> put_to_map(:summary, process_string(summary)) defp parse_line("DESCRIPTION:" <> description, data), do: data |> put_to_map(:description, process_string(description)) defp parse_line("UID:" <> uid, data), do: data |> put_to_map(:uid, uid) defp parse_line("RRULE:" <> rrule, data), do: data |> put_to_map(:rrule, process_rrule(rrule, data[:tzid])) defp parse_line("TZID:" <> tzid, data), do: data |> Map.put(:tzid, tzid) defp parse_line("CATEGORIES:" <> categories, data), do: data |> put_to_map(:categories, String.split(categories, ",")) defp parse_line(_, data), do: data defp put_to_map(%{events: [event | events]} = data, key, value) do updated_event = %{event | key => value} %{data | events: [updated_event | events]} end defp put_to_map(data, _key, _value), do: data defp process_date(":" <> date, tzid), do: DateParser.parse(date, tzid) defp process_date(";" <> date, _) do [timezone, date] = date |> String.split(":") timezone = case timezone do "TZID=" <> timezone -> timezone _ -> nil end DateParser.parse(date, timezone) end defp process_rrule(rrule, tzid) do rrule |> String.split(";") |> Enum.reduce(%{}, fn(rule, hash) -> [key, value] = rule |> String.split("=") case key |> String.downcase |> String.to_atom do :until -> hash |> Map.put(:until, DateParser.parse(value, tzid)) :interval -> hash |> Map.put(:interval, String.to_integer(value)) :count -> hash |> Map.put(:count, String.to_integer(value)) :freq -> hash |> Map.put(:freq, value) _ -> hash end end) end defp process_string(string) when is_binary(string) do string |> String.replace(~S",", ~s",") |> String.replace(~S"\n", ~s"\n") end end
38.958333
123
0.621658
7339ebb22e8e7bff106475d261e9bc7fffec7185
7,045
ex
Elixir
deps/mime/lib/mime.ex
matin360/TaksoWebApp
4dd8fef625ecc2364fe1d6e18e73c96c59d15349
[ "MIT" ]
1
2019-11-11T21:48:20.000Z
2019-11-11T21:48:20.000Z
deps/mime/lib/mime.ex
matin360/TaksoWebApp
4dd8fef625ecc2364fe1d6e18e73c96c59d15349
[ "MIT" ]
2
2021-03-09T09:26:25.000Z
2021-05-09T08:58:51.000Z
deps/mime/lib/mime.ex
matin360/TaksoWebApp
4dd8fef625ecc2364fe1d6e18e73c96c59d15349
[ "MIT" ]
null
null
null
defmodule MIME do @moduledoc """ Maps MIME types to its file extensions and vice versa. MIME types can be extended in your application configuration as follows: config :mime, :types, %{ "application/vnd.api+json" => ["json-api"] } After adding the configuration, MIME needs to be recompiled. If you are using mix, it can be done with: $ mix deps.clean mime --build """ types = %{ "application/epub+zip" => ["epub"], "application/gzip" => ["gz"], "application/java-archive" => ["jar"], "application/javascript" => ["js"], "application/json" => ["json"], "application/json-patch+json" => ["json-patch"], "application/ld+json" => ["jsonld"], "application/manifest+json" => ["webmanifest"], "application/msword" => ["doc"], "application/octet-stream" => ["bin"], "application/ogg" => ["ogx"], "application/pdf" => ["pdf"], "application/postscript" => ["ps", "eps", "ai"], "application/rtf" => ["rtf"], "application/vnd.amazon.ebook" => ["azw"], "application/vnd.api+json" => ["json-api"], "application/vnd.apple.installer+xml" => ["mpkg"], "application/vnd.mozilla.xul+xml" => ["xul"], "application/vnd.ms-excel" => ["xls"], "application/vnd.ms-fontobject" => ["eot"], "application/vnd.ms-powerpoint" => ["ppt"], "application/vnd.oasis.opendocument.presentation" => ["odp"], "application/vnd.oasis.opendocument.spreadsheet" => ["ods"], "application/vnd.oasis.opendocument.text" => ["odt"], "application/vnd.openxmlformats-officedocument.presentationml.presentation" => ["pptx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => ["xlsx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => ["docx"], "application/vnd.rar" => ["rar"], "application/vnd.visio" => ["vsd"], "application/x-7z-compressed" => ["7z"], "application/x-abiword" => ["abw"], "application/x-bzip" => ["bz"], "application/x-bzip2" => ["bz2"], "application/x-cdf" => ["cda"], "application/x-csh" => ["csh"], "application/x-freearc" => ["arc"], "application/x-httpd-php" => ["php"], "application/x-msaccess" => ["mdb"], "application/x-sh" => ["sh"], "application/x-shockwave-flash" => ["swf"], "application/x-tar" => ["tar"], "application/xhtml+xml" => ["xhtml"], "application/xml" => ["xml"], "application/wasm" => ["wasm"], "application/zip" => ["zip"], "audio/3gpp" => ["3gp"], "audio/3gpp2" => ["3g2"], "audio/aac" => ["aac"], "audio/midi" => ["mid", "midi"], "audio/mpeg" => ["mp3"], "audio/ogg" => ["oga"], "audio/opus" => ["opus"], "audio/wav" => ["wav"], "audio/webm" => ["weba"], "font/otf" => ["otf"], "font/ttf" => ["ttf"], "font/woff" => ["woff"], "font/woff2" => ["woff2"], "image/avif" => ["avif"], "image/bmp" => ["bmp"], "image/gif" => ["gif"], "image/jpeg" => ["jpg", "jpeg"], "image/png" => ["png"], "image/svg+xml" => ["svg", "svgz"], "image/tiff" => ["tiff", "tif"], "image/vnd.microsoft.icon" => ["ico"], "image/webp" => ["webp"], "text/calendar" => ["ics"], "text/css" => ["css"], "text/csv" => ["csv"], "text/html" => ["html", "htm"], "text/javascript" => ["js", "mjs"], "text/plain" => ["txt", "text"], "text/xml" => ["xml"], "video/3gpp" => ["3gp"], "video/3gpp2" => ["3g2"], "video/quicktime" => ["mov"], "video/mp2t" => ["ts"], "video/mp4" => ["mp4"], "video/mpeg" => ["mpeg", "mpg"], "video/ogg" => ["ogv"], "video/webm" => ["webm"], "video/x-msvideo" => ["avi"], "video/x-ms-wmv" => ["wmv"] } custom_types = Application.compile_env(:mime, :types, %{}) to_exts = fn map -> for {media, exts} <- map, ext <- exts, reduce: %{} do acc -> Map.update(acc, ext, [media], &[media | &1]) end end exts = Map.merge(to_exts.(types), %{ "3g2" => ["video/3gpp2"], "3gp" => ["video/3gpp"], "js" => ["text/javascript"], "xml" => ["text/xml"] }) for {ext, [_, _ | _] = mimes} <- exts do raise "conflicting MIMEs for extension .#{ext}, please override: #{inspect(mimes)}" end all_exts = Map.merge(exts, to_exts.(custom_types)) all_types = Map.merge(types, custom_types) @doc """ Returns the custom types compiled into the MIME module. """ def compiled_custom_types do unquote(Macro.escape(custom_types)) end @doc """ Returns the extensions associated with a given MIME type. ## Examples iex> MIME.extensions("text/html") ["html", "htm"] iex> MIME.extensions("application/json") ["json"] iex> MIME.extensions("application/vnd.custom+xml") ["xml"] iex> MIME.extensions("foo/bar") [] """ @spec extensions(String.t()) :: [String.t()] def extensions(type) do mime = type |> strip_params() |> downcase("") mime_to_ext(mime) || suffix(mime) || [] end defp suffix(type) do case String.split(type, "+") do [_type_subtype_without_suffix, suffix] -> [suffix] _ -> nil end end @default_type "application/octet-stream" @doc """ Returns the MIME type associated with a file extension. If no MIME type is known for `file_extension`, `#{inspect(@default_type)}` is returned. ## Examples iex> MIME.type("txt") "text/plain" iex> MIME.type("foobarbaz") #{inspect(@default_type)} """ @spec type(String.t()) :: String.t() def type(file_extension) do ext_to_mime(file_extension) || @default_type end @doc """ Returns whether an extension has a MIME type registered. ## Examples iex> MIME.has_type?("txt") true iex> MIME.has_type?("foobarbaz") false """ @spec has_type?(String.t()) :: boolean def has_type?(file_extension) do is_binary(ext_to_mime(file_extension)) end @doc """ Guesses the MIME type based on the path's extension. See `type/1`. ## Examples iex> MIME.from_path("index.html") "text/html" """ @spec from_path(Path.t()) :: String.t() def from_path(path) do case Path.extname(path) do "." <> ext -> type(downcase(ext, "")) _ -> @default_type end end defp strip_params(string) do string |> :binary.split(";") |> hd() end defp downcase(<<h, t::binary>>, acc) when h in ?A..?Z, do: downcase(t, <<acc::binary, h + 32>>) defp downcase(<<h, t::binary>>, acc), do: downcase(t, <<acc::binary, h>>) defp downcase(<<>>, acc), do: acc @spec ext_to_mime(String.t()) :: String.t() | nil defp ext_to_mime(type) for {ext, [type | _]} <- all_exts do defp ext_to_mime(unquote(ext)), do: unquote(type) end defp ext_to_mime(_ext), do: nil @spec mime_to_ext(String.t()) :: list(String.t()) | nil defp mime_to_ext(type) for {type, exts} <- all_types do defp mime_to_ext(unquote(type)), do: unquote(List.wrap(exts)) end defp mime_to_ext(_type), do: nil end
27.627451
92
0.571611
7339f9529f2412304fa80f66f64d03c8376dbcdc
485
ex
Elixir
brainiac/lib/brainiac.ex
sullivanse13/otp_p2
4af73170c9ad7b42ec5469cd279a3ce3b73c5e86
[ "MIT" ]
null
null
null
brainiac/lib/brainiac.ex
sullivanse13/otp_p2
4af73170c9ad7b42ec5469cd279a3ce3b73c5e86
[ "MIT" ]
null
null
null
brainiac/lib/brainiac.ex
sullivanse13/otp_p2
4af73170c9ad7b42ec5469cd279a3ce3b73c5e86
[ "MIT" ]
5
2021-07-08T19:04:14.000Z
2021-07-13T15:03:19.000Z
defmodule Brainiac do def start_game(name) do {:ok, _} = DynamicSupervisor.start_child(Brainiac.DynamicSupervisor, {Brainiac.Server, name}) end def maybe_end_game(_name, :playing), do: :ok def maybe_end_game(name, _) do DynamicSupervisor.terminate_child(Brainiac.DynamicSupervisor, GenServer.whereis(name)) end def guess(name, guess) do result = Brainiac.Server.guess(name, guess) IO.puts(result.pretty) maybe_end_game(name, result.status) end end
26.944444
97
0.740206
733a0cfbb893e896b691e8d393c3538c577cf10c
205
ex
Elixir
lib/galnora.ex
kortirso/galnora
e10a4a9bacc1be0a68a1ac191b7fa9b335988cb6
[ "MIT" ]
null
null
null
lib/galnora.ex
kortirso/galnora
e10a4a9bacc1be0a68a1ac191b7fa9b335988cb6
[ "MIT" ]
null
null
null
lib/galnora.ex
kortirso/galnora
e10a4a9bacc1be0a68a1ac191b7fa9b335988cb6
[ "MIT" ]
null
null
null
defmodule Galnora do @moduledoc false use Application @doc """ Starts the Galnora Application (and its Supervision Tree) """ def start(_type, _args) do Galnora.Supervisor.start end end
15.769231
59
0.707317
733a0ed2ce34e32822a150dc0de66ae8beb156ab
2,183
ex
Elixir
lib/cryptozaur/drivers/bithumb_rest.ex
DenisGorbachev/crypto-cli
94e5097ff24237fbc5fdd3fea371a5c9a1f727e4
[ "MIT" ]
5
2018-09-19T09:13:15.000Z
2021-10-20T23:29:57.000Z
lib/cryptozaur/drivers/bithumb_rest.ex
DenisGorbachev/crypto-cli
94e5097ff24237fbc5fdd3fea371a5c9a1f727e4
[ "MIT" ]
6
2018-07-29T05:33:02.000Z
2018-09-18T20:42:19.000Z
lib/cryptozaur/drivers/bithumb_rest.ex
DenisGorbachev/crypto-cli
94e5097ff24237fbc5fdd3fea371a5c9a1f727e4
[ "MIT" ]
3
2018-07-24T05:55:04.000Z
2018-09-19T09:14:08.000Z
defmodule Cryptozaur.Drivers.BithumbRest do use GenServer require OK import OK, only: [success: 1, failure: 1] import Logger import Cryptozaur.Utils @timeout 600_000 @http_timeout 60000 @base_url "https://api.bithumb.com" def start_link(state, opts \\ []) do GenServer.start_link(__MODULE__, state, opts) end def init(state) do {:ok, state} end # Client def get_ticker(pid, base, quote) do GenServer.call(pid, {:get_ticker, base, quote}, @timeout) end def get_tickers(pid) do GenServer.call(pid, {:get_tickers}, @timeout) end # Server def handle_call({:get_ticker, base, _quote}, _from, state) do path = "/public/ticker/#{base}" params = %{} result = get(path, params) {:reply, result, state} end def handle_call({:get_tickers}, _from, state) do path = "/public/ticker/ALL" result = get(path) {:reply, result, state} end defp get(path, params \\ [], headers \\ [], options \\ []) do request(:get, path, "", headers, options ++ [params: params]) end defp request(method, path, body, headers, options) do GenRetry.Task.async(fn -> request_task(method, path, body, headers, options ++ [timeout: @http_timeout, recv_timeout: @http_timeout]) end, retries: 10, delay: 2_000, jitter: 0.1, exp_base: 1.1) |> Task.await(@timeout) |> validate() end defp request_task(method, path, body, headers, options) do url = @base_url <> path case HTTPoison.request(method, url, body, headers, options) do failure(%HTTPoison.Error{reason: reason}) when reason in [:timeout, :connect_timeout, :closed] -> warn("~~ Okex.request(#{inspect(method)}, #{inspect(url)}, #{inspect(body)}, #{inspect(headers)}, #{inspect(options)}) # timeout") raise "retry" failure(error) -> failure(error) success(response) -> parse!(response.body) end end # defp to_symbol(base, quote) do # "#{base}_#{quote}" |> String.downcase() # end defp validate(response) do case response do %{"status" => "0000", "data" => data} -> success(data) %{"status" => error_code} -> failure(error_code) end end end
26.621951
197
0.635822
733a143a518aee5df4d869ece56f1d0bb590d5ec
3,089
ex
Elixir
lib/guss/storage_v2_signer.ex
gullitmiranda/guss
feaf14a251ee2673ddff4b1a76fdf626705ffb46
[ "MIT" ]
3
2018-11-29T01:04:51.000Z
2020-01-29T17:55:37.000Z
lib/guss/storage_v2_signer.ex
gullitmiranda/guss
feaf14a251ee2673ddff4b1a76fdf626705ffb46
[ "MIT" ]
3
2018-12-14T00:33:44.000Z
2020-02-24T03:53:28.000Z
lib/guss/storage_v2_signer.ex
gullitmiranda/guss
feaf14a251ee2673ddff4b1a76fdf626705ffb46
[ "MIT" ]
3
2019-08-24T21:01:07.000Z
2020-02-20T18:43:23.000Z
defmodule Guss.StorageV2Signer do @moduledoc """ Sign a `Guss.Resource` using the Cloud Storage V2 Signing Process for Service Accounts. This module generates the _string to sign_ for a ` Guss.Resource`, and signs it using the given `private_key`. The signature is then added to the URL, along with any required query string parameters. For more information, see: [V2 Signing Process](https://cloud.google.com/storage/docs/access-control/signed-urls-v2). """ alias Guss.{Resource, RequestHeaders, Signature} @doc """ Sign a URL for the given `Guss.Resource` using the `private_key`. """ @spec sign(resource :: Guss.Resource.t(), private_key :: binary()) :: {:ok, String.t()} def sign(%Resource{} = resource, private_key) when is_binary(private_key) do s2s = string_to_sign(resource) with {:ok, signature} <- Signature.generate(s2s, private_key) do signed_url = build_url(resource, signature) {:ok, signed_url} end end @doc """ Generates the _string to sign_ for a `Guss.Resource`. The _string to sign_ is a canonical representation of the request to be made with the Signed URL. """ @spec string_to_sign(Guss.Resource.t()) :: String.t() def string_to_sign(%Resource{} = resource) do http_verb = http_verb(resource.http_verb) content_md5 = if is_nil(resource.content_md5), do: "", else: resource.content_md5 content_type = if is_nil(resource.content_type), do: "", else: resource.content_type canonicalize = canonicalize(resource) [ http_verb, content_md5, content_type, Integer.to_string(resource.expires), canonicalize ] |> Enum.intersperse(?\n) |> IO.iodata_to_binary() end defp resource_name(%{bucket: bucket, objectname: objectname}) do [?/, bucket, ?/, objectname] end defp http_verb(method) when is_atom(method), do: http_verb(Atom.to_string(method)) defp http_verb(method) when is_binary(method), do: String.upcase(method) defp canonicalize(resource) do resource |> Resource.signed_headers() |> headers_to_sign() |> case do [] -> resource_name(resource) headers_to_sign -> [headers_to_sign, ?\n, resource_name(resource)] end end defp headers_to_sign([]), do: [] defp headers_to_sign(headers) when is_list(headers) do for {k, v} <- RequestHeaders.deduplicate(headers), filter_extension({k, v}) do [k, ?:, v] end |> Enum.intersperse(?\n) |> List.wrap() end defp filter_extension({"x-goog-encryption" <> _rest, _}), do: false defp filter_extension({"x-goog-" <> _rest, _}), do: true defp filter_extension(_kv), do: false defp build_url(%Guss.Resource{} = resource, signature) when is_binary(signature) do query = resource |> build_signed_query(signature) |> URI.encode_query() Enum.join([to_string(resource), "?", query]) end defp build_signed_query(%Guss.Resource{account: account, expires: expires}, signature) do %{ "GoogleAccessId" => account, "Expires" => expires, "Signature" => signature } end end
31.845361
92
0.682098
733a149e1b1a54a63cf8963970b9a0868e69155f
49
exs
Elixir
apps/my_app/config/config.exs
robmckinnon/phoenix-umbrella-with-node-js-example
48cce2d9d9fc4564bc5983840c66d09c6594462d
[ "MIT" ]
44
2017-11-12T17:12:55.000Z
2022-03-29T18:21:08.000Z
apps/ex_figment/config/config.exs
rishenko/ex_figment
7cb578a0da26dd50a947f6c155adc0c69a37ad4b
[ "Apache-2.0" ]
7
2017-09-11T12:17:36.000Z
2017-09-25T13:15:21.000Z
apps/ex_figment/config/config.exs
rishenko/ex_figment
7cb578a0da26dd50a947f6c155adc0c69a37ad4b
[ "Apache-2.0" ]
4
2019-04-15T08:03:30.000Z
2021-12-15T16:00:02.000Z
use Mix.Config import_config "#{Mix.env}.exs"
8.166667
30
0.693878
733a470083a28f4b04a9d289a5bcf5fd8cc844e6
836
ex
Elixir
lib/exceptional.ex
gballet/exceptional
2ae2c08023382c6bbe7b135e9adec1e63a0a1fc3
[ "MIT" ]
284
2016-08-28T13:04:13.000Z
2022-03-28T18:30:58.000Z
lib/exceptional.ex
gballet/exceptional
2ae2c08023382c6bbe7b135e9adec1e63a0a1fc3
[ "MIT" ]
23
2016-09-12T03:28:59.000Z
2021-06-25T15:18:09.000Z
lib/exceptional.ex
gballet/exceptional
2ae2c08023382c6bbe7b135e9adec1e63a0a1fc3
[ "MIT" ]
10
2017-02-09T03:48:15.000Z
2019-12-23T08:30:03.000Z
defmodule Exceptional do @moduledoc ~S""" Top-level `use` aliases In almost all cases, you want: use Exceptional If you only want the operators: use Exceptional, only: :operators If you only want named functions: use Exceptional, only: :named_functions If you like to live extremely dangerously. This is _not recommended_. Please be certain that you want to override the standard lib before using. use Exceptional, include: :overload_pipe """ defmacro __using__(opts \\ []) do quote bind_quoted: [opts: opts] do use Exceptional.Control, opts use Exceptional.Normalize, opts use Exceptional.Pipe, opts use Exceptional.Raise, opts use Exceptional.Safe, opts use Exceptional.TaggedStatus, opts use Exceptional.Value, opts end end end
23.222222
76
0.694976
733a57c35009eaa4331dffb6b4f7a2f3640bca84
2,486
exs
Elixir
test/events_tools_web/controllers/status_controller_test.exs
community-tools/community-tools
40b0e6cc9234b44593d2ab60bb2303d7224deb30
[ "Apache-2.0" ]
2
2017-10-06T01:14:35.000Z
2017-11-18T16:44:44.000Z
test/events_tools_web/controllers/status_controller_test.exs
community-tools/community-tools
40b0e6cc9234b44593d2ab60bb2303d7224deb30
[ "Apache-2.0" ]
6
2017-10-06T00:04:59.000Z
2017-10-06T00:09:27.000Z
test/events_tools_web/controllers/status_controller_test.exs
apps-team/community-tools
40b0e6cc9234b44593d2ab60bb2303d7224deb30
[ "Apache-2.0" ]
1
2017-10-06T01:17:35.000Z
2017-10-06T01:17:35.000Z
defmodule CommunityToolsWeb.StatusControllerTest do use CommunityToolsWeb.ConnCase alias CommunityTools.Status @create_attrs %{summary: "some summary", title: "some title"} @update_attrs %{summary: "some updated summary", title: "some updated title"} @invalid_attrs %{summary: nil, title: nil} def fixture(:status) do {:ok, status} = Status.create_status(@create_attrs) status end test "lists all entries on index", %{conn: conn} do conn = get conn, status_path(conn, :index) assert html_response(conn, 200) =~ "Listing Status" end test "renders form for new status", %{conn: conn} do conn = get conn, status_path(conn, :new) assert html_response(conn, 200) =~ "New Status" end test "creates status and redirects to show when data is valid", %{conn: conn} do conn = post conn, status_path(conn, :create), status: @create_attrs assert %{id: id} = redirected_params(conn) assert redirected_to(conn) == status_path(conn, :show, id) conn = get conn, status_path(conn, :show, id) assert html_response(conn, 200) =~ "Show Status" end test "does not create status and renders errors when data is invalid", %{conn: conn} do conn = post conn, status_path(conn, :create), status: @invalid_attrs assert html_response(conn, 200) =~ "New Status" end test "renders form for editing chosen status", %{conn: conn} do status = fixture(:status) conn = get conn, status_path(conn, :edit, status) assert html_response(conn, 200) =~ "Edit Status" end test "updates chosen status and redirects when data is valid", %{conn: conn} do status = fixture(:status) conn = put conn, status_path(conn, :update, status), status: @update_attrs assert redirected_to(conn) == status_path(conn, :show, status) conn = get conn, status_path(conn, :show, status) assert html_response(conn, 200) =~ "some updated summary" end test "does not update chosen status and renders errors when data is invalid", %{conn: conn} do status = fixture(:status) conn = put conn, status_path(conn, :update, status), status: @invalid_attrs assert html_response(conn, 200) =~ "Edit Status" end test "deletes chosen status", %{conn: conn} do status = fixture(:status) conn = delete conn, status_path(conn, :delete, status) assert redirected_to(conn) == status_path(conn, :index) assert_error_sent 404, fn -> get conn, status_path(conn, :show, status) end end end
35.514286
96
0.691472
733a5e75ee97e0c9c702a5dc0b1115c864eb48e1
2,436
exs
Elixir
test/seren_web/controllers/composer_controller_test.exs
allen-garvey/seren
f61cb7edcd7d3f927d2929db14b2a4a1578a3925
[ "MIT" ]
4
2019-10-04T16:11:15.000Z
2021-08-18T21:00:13.000Z
apps/seren/test/seren_web/controllers/composer_controller_test.exs
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
5
2020-03-16T23:52:25.000Z
2021-09-03T16:52:17.000Z
test/seren_web/controllers/composer_controller_test.exs
allen-garvey/seren
f61cb7edcd7d3f927d2929db14b2a4a1578a3925
[ "MIT" ]
null
null
null
defmodule SerenWeb.ComposerControllerTest do use SerenWeb.ConnCase alias Seren.Player alias Seren.Player.Composer @create_attrs %{name: "some name"} @update_attrs %{name: "some updated name"} @invalid_attrs %{name: nil} def fixture(:composer) do {:ok, composer} = Player.create_composer(@create_attrs) composer end setup %{conn: conn} do {:ok, conn: put_req_header(conn, "accept", "application/json")} end describe "index" do test "lists all composers", %{conn: conn} do conn = get conn, composer_path(conn, :index) assert json_response(conn, 200)["data"] == [] end end describe "create composer" do test "renders composer when data is valid", %{conn: conn} do conn = post conn, composer_path(conn, :create), composer: @create_attrs assert %{"id" => id} = json_response(conn, 201)["data"] conn = get conn, composer_path(conn, :show, id) assert json_response(conn, 200)["data"] == %{ "id" => id, "name" => "some name"} end test "renders errors when data is invalid", %{conn: conn} do conn = post conn, composer_path(conn, :create), composer: @invalid_attrs assert json_response(conn, 422)["errors"] != %{} end end describe "update composer" do setup [:create_composer] test "renders composer when data is valid", %{conn: conn, composer: %Composer{id: id} = composer} do conn = put conn, composer_path(conn, :update, composer), composer: @update_attrs assert %{"id" => ^id} = json_response(conn, 200)["data"] conn = get conn, composer_path(conn, :show, id) assert json_response(conn, 200)["data"] == %{ "id" => id, "name" => "some updated name"} end test "renders errors when data is invalid", %{conn: conn, composer: composer} do conn = put conn, composer_path(conn, :update, composer), composer: @invalid_attrs assert json_response(conn, 422)["errors"] != %{} end end describe "delete composer" do setup [:create_composer] test "deletes chosen composer", %{conn: conn, composer: composer} do conn = delete conn, composer_path(conn, :delete, composer) assert response(conn, 204) assert_error_sent 404, fn -> get conn, composer_path(conn, :show, composer) end end end defp create_composer(_) do composer = fixture(:composer) {:ok, composer: composer} end end
30.45
104
0.642447
733ac4578504a3e6080f3605b61ae47fea808f93
637
ex
Elixir
ControlStructures.ex
IgorVieira/learning-elixir
6f1136723cba79bce0fd746790cc2fea78b08c61
[ "MIT" ]
null
null
null
ControlStructures.ex
IgorVieira/learning-elixir
6f1136723cba79bce0fd746790cc2fea78b08c61
[ "MIT" ]
null
null
null
ControlStructures.ex
IgorVieira/learning-elixir
6f1136723cba79bce0fd746790cc2fea78b08c61
[ "MIT" ]
null
null
null
# If and Unless if String.valid?("Hello") do IO.puts "Valid string!" else IO.puts "Invalid string." end # Unless unless is_integer("Hell") do IO.puts "Not an Int" end # Case pie = 3.14 case "cherry pie" do ^pie -> IO.puts "Not so tasty" pie -> IO.puts "I bet #{pie} is tasty" end # Cond cond do 2 + 2 == 5 -> IO.puts "This will not be true" 2 * 2 == 3 -> IO.puts "Nor this" 1 + 1 == 2 -> IO.puts "But this will" end # Structure with user = %{first: "Sean", last: "Callan"} with {:ok, first} <- Map.fetch(user, :first), {:ok, last} <- Map.fetch(user, :last), do: IO.puts last <> ", " <> first
15.536585
46
0.576138
733ad026102eb431d42102b3705296558e21a356
9,540
ex
Elixir
lib/phoenix_datatables/query.ex
smartmetals/phoenix_datatables
40c9074742ee7643327ac735defa9960abc50250
[ "MIT" ]
12
2017-10-20T21:08:33.000Z
2021-11-08T13:04:43.000Z
lib/phoenix_datatables/query.ex
smartmetals/phoenix_datatables
40c9074742ee7643327ac735defa9960abc50250
[ "MIT" ]
8
2017-11-07T19:53:02.000Z
2021-01-18T22:15:35.000Z
lib/phoenix_datatables/query.ex
smartmetals/phoenix_datatables
40c9074742ee7643327ac735defa9960abc50250
[ "MIT" ]
7
2018-07-03T08:18:17.000Z
2020-05-28T03:06:02.000Z
defmodule PhoenixDatatables.Query do @moduledoc """ Functions for updating an `Ecto.Query` based on Datatables request parameters. """ import Ecto.Query use PhoenixDatatables.Query.Macros alias Ecto.Query.JoinExpr alias PhoenixDatatables.Query.Attribute alias PhoenixDatatables.QueryException alias PhoenixDatatables.Request.Column alias PhoenixDatatables.Request.Params alias PhoenixDatatables.Request.Search @doc """ Add order_by clauses to the provided queryable based on the "order" params provided in the Datatables request. For some queries, `:columns` need to be passed - see documentation for `PhoenixDatatables.execute` for details. """ def sort(queryable, params, options \\ nil) do sorts = if options && Keyword.has_key?(options, :columns) do build_column_sorts(params, options[:columns]) else build_schema_sorts(queryable, params) end do_sorts(queryable, sorts, options) end defp build_column_sorts(%Params{order: orders} = params, columns) do for order <- orders do with dir when is_atom(dir) <- cast_dir(order.dir), %Column{} = column <- params.columns[order.column], true <- column.orderable, {column, join_index} when is_number(join_index) <- cast_column(column.data, columns) do {dir, column, join_index} end end end defp build_schema_sorts(queryable, %Params{order: orders} = params) do schema = schema(queryable) for order <- orders do with dir when is_atom(dir) <- cast_dir(order.dir), %Column{} = column <- params.columns[order.column], true <- column.orderable, %Attribute{} = attribute <- Attribute.extract(column.data, schema), join_index when is_number(join_index) <- join_order(queryable, attribute.parent) do {dir, attribute.name, join_index} end end end defp do_sorts(queryable, sorts, options) do Enum.reduce(sorts, queryable, fn {dir, column, join_index}, queryable -> order_relation(queryable, join_index, dir, column, options) end) end @doc false def join_order(_, nil), do: 0 def join_order(%Ecto.Query{} = queryable, parent) do case Enum.find_index(queryable.joins, &(join_relation(&1) == parent)) do nil -> nil number when is_number(number) -> number + 1 end end def join_order(queryable, parent) do QueryException.raise(:join_order, """ An attempt was made to interrogate the join structure of #{inspect(queryable)} This is not an %Ecto.Query{}. The most likely cause for this error is using dot-notation(e.g. 'category.name') in the column name defined in the datatables client config but a simple Schema (no join) is used as the underlying queryable. Please check the client config for the fields belonging to #{inspect(parent)}. If the required field does belong to a different parent schema, that schema needs to be joined in the Ecto query. """) end defp join_relation(%JoinExpr{assoc: {_, relation}}), do: relation defp join_relation(_) do QueryException.raise(:join_relation, """ PhoenixDatatables queryables with non-assoc joins must be accompanied by :columns options to define sortable column names and join orders. See docs for PhoenixDatatables.execute for more information. """) end defp schema(%Ecto.Query{} = query), do: query.from.source |> check_from() |> elem(1) defp schema(schema) when is_atom(schema), do: schema defp check_from(%Ecto.SubQuery{}) do QueryException.raise(:schema, """ PhoenixDatatables queryables containing subqueries must be accompanied by :columns options to define sortable column names and join orders. See docs for PhoenixDatatables.execute for more information. """) end defp check_from(from), do: from defp cast_column(column_name, sortable) # Keyword when is_list(sortable) and is_tuple(hd(sortable)) and is_atom(elem(hd(sortable), 0)) do [parent | child] = String.split(column_name, ".") if parent in Enum.map(Keyword.keys(sortable), &Atom.to_string/1) do member = Keyword.fetch!(sortable, String.to_atom(parent)) case member do children when is_list(children) -> with [child] <- child, [child] <- Enum.filter( Keyword.keys(children), &(Atom.to_string(&1) == child) ), {:ok, order} when is_number(order) <- Keyword.fetch(children, child) do {child, order} else _ -> {:error, "#{column_name} is not a sortable column."} end order when is_number(order) -> {String.to_atom(parent), order} end else {:error, "#{column_name} is not a sortable column."} end end defp cast_column(column_name, sortable) do if column_name in Enum.map(sortable, &Atom.to_string/1) do {String.to_atom(column_name), 0} end end defp cast_dir("asc"), do: :asc defp cast_dir("desc"), do: :desc defp cast_dir(wrong), do: {:error, "#{wrong} is not a valid sort order."} @doc """ Add offset and limit clauses to the provided queryable based on the "length" and "start" parameters passed in the Datatables request. """ def paginate(queryable, params) do length = convert_to_number_if_string(params.length) start = convert_to_number_if_string(params.start) if length == -1 do queryable else queryable |> limit(^length) |> offset(^start) end end defp convert_to_number_if_string(num) do case is_binary(num) do true -> {num, _} = Integer.parse(num) num false -> num end end @doc """ Add AND where clause to the provided queryable based on the "search" parameter passed in the Datatables request. For some queries, `:columns` need to be passed - see documentation for `PhoenixDatatables.execute` for details. """ def search(queryable, params, options \\ []) do columns = options[:columns] do_search(queryable, params, columns) end defp do_search(queryable, %Params{search: %Search{value: ""}}, _), do: queryable defp do_search(queryable, %Params{} = params, searchable) when is_list(searchable) do search_term = "%#{params.search.value}%" dynamic = dynamic([], false) dynamic = Enum.reduce(params.columns, dynamic, fn {_, v}, acc_dynamic -> with {column, join_index} when is_number(join_index) <- v.data |> cast_column(searchable), true <- v.searchable do acc_dynamic |> search_relation( join_index, column, search_term ) else _ -> acc_dynamic end end) where(queryable, [], ^dynamic) end defp do_search(queryable, %Params{search: search, columns: columns}, _searchable) do search_term = "%#{search.value}%" schema = schema(queryable) dynamic = dynamic([], false) dynamic = Enum.reduce(columns, dynamic, fn {_, v}, acc_dynamic -> with %Attribute{} = attribute <- v.data |> Attribute.extract(schema), true <- v.searchable do acc_dynamic |> search_relation( join_order(queryable, attribute.parent), attribute.name, search_term ) else _ -> acc_dynamic end end) where(queryable, [], ^dynamic) end def search_columns(queryable, params, options \\ []) do if has_column_search?(params.columns) do columns = options[:columns] || [] do_search_columns(queryable, params, columns) else queryable end end def has_column_search?(columns) when is_map(columns) do columns = Map.values(columns) Enum.any?(columns, &(&1.search.value != "")) end def has_column_search?(_), do: false defp do_search_columns(queryable, params, columns) do dynamic = dynamic([], true) dynamic = Enum.reduce(params.columns, dynamic, fn {_, v}, acc_dynamic -> with {column, join_index} when is_number(join_index) <- cast_column(v.data, columns), true <- v.searchable, true <- v.search.value != "" do acc_dynamic |> search_relation_and( join_index, column, "%#{v.search.value}%" ) else _ -> acc_dynamic end end) where(queryable, [], ^dynamic) end # credo:disable-for-lines:2 # credit to scrivener library: # https://github.com/drewolson/scrivener_ecto/blob/master/lib/scrivener/paginater/ecto/query.ex # Copyright (c) 2016 Andrew Olson @doc """ Calculate the number of records that will retrieved with the provided queryable. """ def total_entries(queryable, repo) do total_entries = queryable |> exclude(:preload) |> exclude(:select) |> exclude(:order_by) |> exclude(:limit) |> exclude(:offset) |> subquery |> select(count("*")) |> repo.one total_entries || 0 end end defmodule PhoenixDatatables.QueryException do defexception [:message, :operation] # yes we know it raises @dialyzer {:no_return, raise: 1} def raise(operation, message \\ "") do Kernel.raise(__MODULE__, operation: operation, message: message) end end
29.8125
100
0.636583
733af695b5498a562ed97e11b7922655536a7da7
2,289
ex
Elixir
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3_conversation_turn.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3_conversation_turn.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3_conversation_turn.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3ConversationTurn do @moduledoc """ One interaction between a human and virtual agent. The human provides some input and the virtual agent provides a response. ## Attributes * `userInput` (*type:* `GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3ConversationTurnUserInput.t`, *default:* `nil`) - The user input. * `virtualAgentOutput` (*type:* `GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3ConversationTurnVirtualAgentOutput.t`, *default:* `nil`) - The virtual agent output. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :userInput => GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3ConversationTurnUserInput.t(), :virtualAgentOutput => GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3ConversationTurnVirtualAgentOutput.t() } field(:userInput, as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3ConversationTurnUserInput ) field(:virtualAgentOutput, as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3ConversationTurnVirtualAgentOutput ) end defimpl Poison.Decoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3ConversationTurn do def decode(value, options) do GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3ConversationTurn.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3ConversationTurn do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.79661
176
0.7737
733b1d6f664f922fe2a9e88559f5a79199bc57ae
1,477
ex
Elixir
lib/twitter_web/views/error_helpers.ex
SkullDarth/upnid-challenge-twitter-api
799f2bfa8864848423eeddc24d3a5993152eb464
[ "MIT" ]
2
2019-12-05T21:37:48.000Z
2020-01-02T02:43:33.000Z
lib/twitter_web/views/error_helpers.ex
SkullDarth/upnid-challenge-twitter-api
799f2bfa8864848423eeddc24d3a5993152eb464
[ "MIT" ]
null
null
null
lib/twitter_web/views/error_helpers.ex
SkullDarth/upnid-challenge-twitter-api
799f2bfa8864848423eeddc24d3a5993152eb464
[ "MIT" ]
null
null
null
defmodule TwitterWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn error -> content_tag(:span, translate_error(error), class: "help-block") end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # When using gettext, we typically pass the strings we want # to translate as a static argument: # # # Translate "is invalid" in the "errors" domain # dgettext("errors", "is invalid") # # # Translate the number of files with plural rules # dngettext("errors", "1 file", "%{count} files", count) # # Because the error messages we show in our forms and APIs # are defined inside Ecto, we need to translate them dynamically. # This requires us to call the Gettext module passing our gettext # backend as first argument. # # Note we use the "errors" domain, which means translations # should be written to the errors.po file. The :count option is # set by Ecto and indicates we should also apply plural rules. if count = opts[:count] do Gettext.dngettext(TwitterWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(TwitterWeb.Gettext, "errors", msg, opts) end end end
32.822222
76
0.670278
733b55b7f5aa3c2ddfd99ae082210d7d69891074
2,131
ex
Elixir
clients/slides/lib/google_api/slides/v1/model/page_background_fill.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/slides/lib/google_api/slides/v1/model/page_background_fill.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/slides/lib/google_api/slides/v1/model/page_background_fill.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Slides.V1.Model.PageBackgroundFill do @moduledoc """ The page background fill. ## Attributes - propertyState (String): The background fill property state. Updating the fill on a page will implicitly update this field to &#x60;RENDERED&#x60;, unless another value is specified in the same request. To have no fill on a page, set this field to &#x60;NOT_RENDERED&#x60;. In this case, any other fill fields set in the same request will be ignored. Defaults to: `null`. - Enum - one of [RENDERED, NOT_RENDERED, INHERIT] - solidFill (SolidFill): Solid color fill. Defaults to: `null`. - stretchedPictureFill (StretchedPictureFill): Stretched picture fill. Defaults to: `null`. """ defstruct [ :"propertyState", :"solidFill", :"stretchedPictureFill" ] end defimpl Poison.Decoder, for: GoogleApi.Slides.V1.Model.PageBackgroundFill do import GoogleApi.Slides.V1.Deserializer def decode(value, options) do value |> deserialize(:"solidFill", :struct, GoogleApi.Slides.V1.Model.SolidFill, options) |> deserialize(:"stretchedPictureFill", :struct, GoogleApi.Slides.V1.Model.StretchedPictureFill, options) end end defimpl Poison.Encoder, for: GoogleApi.Slides.V1.Model.PageBackgroundFill do def encode(value, options) do GoogleApi.Slides.V1.Deserializer.serialize_non_nil(value, options) end end
39.462963
375
0.752229
733b6aa1d95451f01284a71272ce1d75a63c18af
781
exs
Elixir
test/soft_delete_migration_test.exs
netflakes/ecto_soft_delete
e2d0afab30ad0cd87cc2234766ec5bf056bcf70b
[ "MIT" ]
97
2016-09-30T20:05:44.000Z
2022-03-29T19:09:27.000Z
test/soft_delete_migration_test.exs
netflakes/ecto_soft_delete
e2d0afab30ad0cd87cc2234766ec5bf056bcf70b
[ "MIT" ]
110
2017-07-21T20:21:26.000Z
2022-03-10T17:34:51.000Z
test/soft_delete_migration_test.exs
netflakes/ecto_soft_delete
e2d0afab30ad0cd87cc2234766ec5bf056bcf70b
[ "MIT" ]
18
2017-12-19T22:30:49.000Z
2021-07-20T22:09:51.000Z
defmodule Ecto.SoftDelete.Migration.Test do use ExUnit.Case use Ecto.Migration alias Ecto.SoftDelete.Test.Repo import Ecto.SoftDelete.Migration alias Ecto.Migration.Runner setup meta do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Repo) {:ok, runner} = Runner.start_link({self(), Repo, __MODULE__, meta[:direction] || :forward, :up, %{level: false, sql: false}}) Runner.metadata(runner, meta) {:ok, runner: runner} end test "soft_delete_columns adds deleted_at column", %{runner: runner} do create table(:posts, primary_key: false) do soft_delete_columns() end [create_command] = Agent.get(runner, & &1.commands) flush() assert {:create, _, [{:add, :deleted_at, :utc_datetime_usec, []}]} = create_command end end
27.892857
129
0.685019
733b7ec073ea092bb222a80d580377daf9862596
27
ex
Elixir
lib/raft/util.ex
lerencao/raft.ex
f8fc21874354073d1831f9ad0cc933128392935b
[ "MIT" ]
5
2016-05-23T16:28:53.000Z
2016-08-17T09:56:00.000Z
lib/raft/util.ex
lerencao/raft.ex
f8fc21874354073d1831f9ad0cc933128392935b
[ "MIT" ]
5
2016-05-27T03:01:11.000Z
2016-07-06T15:22:19.000Z
lib/raft/util.ex
lerencao/raft.ex
f8fc21874354073d1831f9ad0cc933128392935b
[ "MIT" ]
null
null
null
defmodule Raft.Util do end
9
22
0.814815
733b8611a2efb32ffd734c13d51fb6155a995ef4
1,822
ex
Elixir
lib/hello_genserver/application.ex
sreecodeslayer/hello-phoenix-genserver
a30b95af71cacb7df53222bd34dcbae682b98282
[ "MIT" ]
1
2020-01-31T20:38:34.000Z
2020-01-31T20:38:34.000Z
lib/hello_genserver/application.ex
sreecodeslayer/hello-phoenix-genserver
a30b95af71cacb7df53222bd34dcbae682b98282
[ "MIT" ]
null
null
null
lib/hello_genserver/application.ex
sreecodeslayer/hello-phoenix-genserver
a30b95af71cacb7df53222bd34dcbae682b98282
[ "MIT" ]
null
null
null
defmodule HelloGenserver.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application require Logger @name "hello-genserver" def start(_type, _args) do # List all child processes to be supervised children = [ # Start the cluster supervisor {Cluster.Supervisor, [config_clustering(), [name: HelloGenserver.ClusterSupervisor]]}, # Start the endpoint when the application starts HelloGenserverWeb.Endpoint ] register_or_skip() # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: HelloGenserver.Spv] 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 HelloGenserverWeb.Endpoint.config_change(changed, removed) :ok end defp config_clustering() do # Libcluster configuration case Mix.env() do :dev -> Logger.info("Clustering using Gossip") [ nodes: [ strategy: Cluster.Strategy.Gossip ] ] :prod -> Logger.info("Clustering using K8s DNS") [ k8s: [ strategy: Cluster.Strategy.Kubernetes.DNS ] ] end end defp register_or_skip() do # Link supervisor HelloGenserver.Supervisor.start_link() case Swarm.whereis_or_register_name(@name, HelloGenserver.Supervisor, :register, [@name]) do {:ok, _pid} -> Logger.debug("Worker registered or exists on another node") {:error, reason} -> Logger.warn("Error registering name from Swarm: #{inspect(reason)}") end end end
25.661972
96
0.660263
733b99649614c227ab80c57126d55803ab670c70
14,195
ex
Elixir
lib/phoenix_live_view/utils.ex
forkkit/phoenix_live_view
4ef219cd72db8a3cf58a90f7f118ef9c6eda503f
[ "MIT" ]
null
null
null
lib/phoenix_live_view/utils.ex
forkkit/phoenix_live_view
4ef219cd72db8a3cf58a90f7f118ef9c6eda503f
[ "MIT" ]
null
null
null
lib/phoenix_live_view/utils.ex
forkkit/phoenix_live_view
4ef219cd72db8a3cf58a90f7f118ef9c6eda503f
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveView.Utils do # Shared helpers used mostly by Channel and Diff, # but also Static, and LiveViewTest. @moduledoc false alias Phoenix.LiveView.Rendered alias Phoenix.LiveView.Socket # All available mount options @mount_opts [:temporary_assigns, :layout] @max_flash_age :timer.seconds(60) @doc """ Assigns a value if it changed change. """ def assign(%Socket{} = socket, key, value) do case socket do %{assigns: %{^key => ^value}} -> socket %{} -> force_assign(socket, key, value) end end @doc """ Forces an assign. """ def force_assign(%Socket{assigns: assigns, changed: changed} = socket, key, val) do current_val = Map.get(assigns, key) # If the current value is a map, we store it in changed so # we can perform nested change tracking. Also note the use # of put_new is important. We want to keep the original value # from assigns and not any intermediate ones that may appear. new_changed = Map.put_new(changed, key, if(is_map(current_val), do: current_val, else: true)) new_assigns = Map.put(assigns, key, val) %{socket | assigns: new_assigns, changed: new_changed} end @doc """ Clears the changes from the socket assigns. """ def clear_changed(%Socket{private: private, assigns: assigns} = socket) do temporary = Map.get(private, :temporary_assigns, %{}) %Socket{socket | changed: %{}, assigns: Map.merge(assigns, temporary)} end @doc """ Checks if the socket changed. """ def changed?(%Socket{changed: changed}), do: changed != %{} @doc """ Checks if the given assign changed. """ def changed?(%Socket{changed: %{} = changed}, assign), do: Map.has_key?(changed, assign) def changed?(%Socket{}, _), do: false @doc """ Configures the socket for use. """ def configure_socket(%Socket{id: nil} = socket, private, action, flash, host_uri) do %{ socket | id: random_id(), private: private, assigns: configure_assigns(socket.assigns, socket.view, action, flash), host_uri: prune_uri(host_uri) } end def configure_socket(%Socket{} = socket, private, action, flash, host_uri) do assigns = configure_assigns(socket.assigns, socket.view, action, flash) %{socket | host_uri: prune_uri(host_uri), private: private, assigns: assigns} end defp configure_assigns(assigns, view, action, flash) do Map.merge(assigns, %{live_module: view, live_action: action, flash: flash}) end defp prune_uri(:not_mounted_at_router), do: :not_mounted_at_router defp prune_uri(url) do %URI{host: host, port: port, scheme: scheme} = url if host == nil do raise "client did not send full URL, missing host in #{url}" end %URI{host: host, port: port, scheme: scheme} end @doc """ Returns a random ID with valid DOM tokens """ def random_id do "phx-" |> Kernel.<>(random_encoded_bytes()) |> String.replace(["/", "+"], "-") end @doc """ Prunes any data no longer needed after mount. """ def post_mount_prune(%Socket{} = socket) do socket |> clear_changed() |> drop_private([:connect_info, :connect_params, :assign_new]) end @doc """ Renders the view with socket into a rendered struct. """ def to_rendered(socket, view) do assigns = render_assigns(socket) inner_content = assigns |> view.render() |> check_rendered!(view) case layout(socket, view) do {layout_mod, layout_template} -> assigns = put_in(assigns[:inner_content], inner_content) assigns = put_in(assigns.__changed__[:inner_content], true) layout_template |> layout_mod.render(assigns) |> check_rendered!(layout_mod) false -> inner_content end end defp check_rendered!(%Rendered{} = rendered, _view), do: rendered defp check_rendered!(other, view) do raise RuntimeError, """ expected #{inspect(view)} to return a %Phoenix.LiveView.Rendered{} struct Ensure your render function uses ~L, or your eex template uses the .leex extension. Got: #{inspect(other)} """ end @doc """ Returns the socket's flash messages. """ def get_flash(%Socket{assigns: assigns}), do: assigns.flash def get_flash(%{} = flash, key), do: flash[key] @doc """ Puts a new flash with the socket's flash messages. """ def replace_flash(%Socket{} = socket, %{} = new_flash) do assign(socket, :flash, new_flash) end @doc """ Clears the flash. """ def clear_flash(%Socket{} = socket) do socket |> assign(:flash, %{}) |> Map.update!(:changed, &Map.delete(&1, {:private, :flash})) end @doc """ Clears the key from the flash. """ def clear_flash(%Socket{} = socket, key) do key = flash_key(key) new_flash = Map.delete(socket.assigns.flash, key) socket |> assign(:flash, new_flash) |> update_changed({:private, :flash}, &Map.delete(&1 || %{}, key)) end @doc """ Puts a flash message in the socket. """ def put_flash(%Socket{assigns: assigns} = socket, key, msg) do key = flash_key(key) new_flash = Map.put(assigns.flash, key, msg) socket |> assign(:flash, new_flash) |> update_changed({:private, :flash}, &Map.put(&1 || %{}, key, msg)) end @doc """ Returns a map of the flash messages which have changed. """ def changed_flash(%Socket{} = socket) do socket.changed[{:private, :flash}] || %{} end defp flash_key(binary) when is_binary(binary), do: binary defp flash_key(atom) when is_atom(atom), do: Atom.to_string(atom) defp update_changed(%Socket{} = socket, key, func) do update_in(socket.changed[key], func) end @doc """ Returns the configured signing salt for the endpoint. """ def salt!(endpoint) when is_atom(endpoint) do endpoint.config(:live_view)[:signing_salt] || raise ArgumentError, """ no signing salt found for #{inspect(endpoint)}. Add the following LiveView configuration to your config/config.exs: config :my_app, MyAppWeb.Endpoint, ..., live_view: [signing_salt: "#{random_encoded_bytes()}"] """ end @doc """ Returns the internal or external matched LiveView route info for the given uri """ def live_link_info!(%Socket{router: nil}, view, _uri) do raise ArgumentError, "cannot invoke handle_params/3 on #{inspect(view)} " <> "because it is not mounted nor accessed through the router live/3 macro" end def live_link_info!(%Socket{router: router, endpoint: endpoint} = socket, view, uri) do %URI{host: host, path: path, query: query} = parsed_uri = URI.parse(uri) host = host || socket.host_uri.host query_params = if query, do: Plug.Conn.Query.decode(query), else: %{} decoded_path = URI.decode(path || "") split_path = for segment <- String.split(decoded_path, "/"), segment != "", do: segment route_path = strip_segments(endpoint.script_name(), split_path) || split_path case Phoenix.Router.route_info(router, "GET", route_path, host) do %{plug: Phoenix.LiveView.Plug, phoenix_live_view: {^view, action}, path_params: path_params} -> {:internal, Map.merge(query_params, path_params), action, parsed_uri} %{} -> {:external, parsed_uri} :error -> raise ArgumentError, "cannot invoke handle_params nor live_redirect/live_patch to #{inspect(uri)} " <> "because it isn't defined in #{inspect(router)}" end end defp strip_segments([head | tail1], [head | tail2]), do: strip_segments(tail1, tail2) defp strip_segments([], tail2), do: tail2 defp strip_segments(_, _), do: nil @doc """ Raises error message for bad live patch on mount. """ def raise_bad_mount_and_live_patch!() do raise RuntimeError, """ attempted to live patch while mounting. a LiveView cannot be mounted while issuing a live patch to the client. \ Use push_redirect/2 or redirect/2 instead if you wish to mount and redirect. """ end @doc """ Calls the `c:Phoenix.LiveView.mount/3` callback, otherwise returns the socket as is. """ def maybe_call_live_view_mount!(%Socket{} = socket, view, params, session) do if function_exported?(view, :mount, 3) do :telemetry.span( [:phoenix, :live_view, :mount], %{socket: socket, params: params, session: session}, fn -> socket = params |> view.mount(session, socket) |> handle_mount_result!({:mount, 3, view}) {socket, %{socket: socket, params: params, session: session}} end ) else socket end end @doc """ Calls the `c:Phoenix.LiveComponent.mount/1` callback, otherwise returns the socket as is. """ def maybe_call_live_component_mount!(%Socket{} = socket, view) do if function_exported?(view, :mount, 1) do socket |> view.mount() |> handle_mount_result!({:mount, 1, view}) else socket end end defp handle_mount_result!({:ok, %Socket{} = socket, opts}, {:mount, arity, _view}) when is_list(opts) do validate_mount_redirect!(socket.redirected) Enum.reduce(opts, socket, fn {key, val}, acc -> mount_opt(acc, key, val, arity) end) end defp handle_mount_result!({:ok, %Socket{} = socket}, {:mount, _arity, _view}) do validate_mount_redirect!(socket.redirected) socket end defp handle_mount_result!(response, {:mount, arity, view}) do raise ArgumentError, """ invalid result returned from #{inspect(view)}.mount/#{arity}. Expected {:ok, socket} | {:ok, socket, opts}, got: #{inspect(response)} """ end defp validate_mount_redirect!({:live, {_, _}, _}), do: raise_bad_mount_and_live_patch!() defp validate_mount_redirect!(_), do: :ok @doc """ Calls the `handle_params/3` callback, and returns the result. This function expects the calling code has checked to see if this function has been exported. Raises an `ArgumentError` on unexpected return types. """ def call_handle_params!(%Socket{} = socket, view, params, uri) do :telemetry.span( [:phoenix, :live_view, :handle_params], %{socket: socket, params: params, uri: uri}, fn -> case view.handle_params(params, uri, socket) do {:noreply, %Socket{} = socket} -> {{:noreply, socket}, %{socket: socket, params: params, uri: uri}} other -> raise ArgumentError, """ invalid result returned from #{inspect(view)}.handle_params/3. Expected {:noreply, socket}, got: #{inspect(other)} """ end end ) end @doc """ Calls the optional `update/2` callback, otherwise update the socket directly. """ def maybe_call_update!(socket, component, assigns) do if function_exported?(component, :update, 2) do socket = case component.update(assigns, socket) do {:ok, %Socket{} = socket} -> socket other -> raise ArgumentError, """ invalid result returned from #{inspect(component)}.update/2. Expected {:ok, socket}, got: #{inspect(other)} """ end if socket.redirected do raise "cannot redirect socket on update/2" end socket else Enum.reduce(assigns, socket, fn {k, v}, acc -> assign(acc, k, v) end) end end @doc """ Signs the socket's flash into a token if it has been set. """ def sign_flash(endpoint_mod, %{} = flash) do Phoenix.Token.sign(endpoint_mod, flash_salt(endpoint_mod), flash) end @doc """ Verifies the socket's flash token. """ def verify_flash(endpoint_mod, flash_token) do salt = flash_salt(endpoint_mod) case Phoenix.Token.verify(endpoint_mod, salt, flash_token, max_age: @max_flash_age) do {:ok, flash} -> flash {:error, _reason} -> %{} end end defp random_encoded_bytes do binary = << System.system_time(:nanosecond)::64, :erlang.phash2({node(), self()})::16, :erlang.unique_integer()::16 >> Base.url_encode64(binary) end defp mount_opt(%Socket{} = socket, key, val, _arity) when key in @mount_opts do do_mount_opt(socket, key, val) end defp mount_opt(%Socket{view: view}, key, val, arity) do raise ArgumentError, """ invalid option returned from #{inspect(view)}.mount/#{arity}. Expected keys to be one of #{inspect(@mount_opts)} got: #{inspect(key)}: #{inspect(val)} """ end defp do_mount_opt(socket, :layout, {mod, template}) when is_atom(mod) and is_binary(template) do %Socket{socket | private: Map.put(socket.private, :phoenix_live_layout, {mod, template})} end defp do_mount_opt(socket, :layout, false) do %Socket{socket | private: Map.put(socket.private, :phoenix_live_layout, false)} end defp do_mount_opt(_socket, :layout, bad_layout) do raise ArgumentError, "the :layout mount option expects a tuple of the form {MyLayoutView, \"my_template.html\"}, " <> "got: #{inspect(bad_layout)}" end defp do_mount_opt(socket, :temporary_assigns, temp_assigns) do unless Keyword.keyword?(temp_assigns) do raise "the :temporary_assigns mount option must be keyword list" end temp_assigns = Map.new(temp_assigns) %Socket{ socket | assigns: Map.merge(temp_assigns, socket.assigns), private: Map.put(socket.private, :temporary_assigns, temp_assigns) } end defp drop_private(%Socket{private: private} = socket, keys) do %Socket{socket | private: Map.drop(private, keys)} end defp render_assigns(%{assigns: assigns, changed: changed} = socket) do socket = %Socket{socket | assigns: %Socket.AssignsNotInSocket{__assigns__: assigns}} assigns |> Map.put(:socket, socket) |> Map.put(:__changed__, changed) end defp layout(socket, view) do case socket.private do %{phoenix_live_layout: layout} -> layout %{} -> view.__live__()[:layout] || false end end defp flash_salt(endpoint_mod) when is_atom(endpoint_mod) do "flash:" <> salt!(endpoint_mod) end end
29.634656
106
0.644945
733bb4da26800929bac49a384483d361e333444a
2,719
ex
Elixir
lib/etherscan/util.ex
devlin-Smith/etherscan
c56d6f3f8eefa49c9ac8884461387a3af44fac03
[ "MIT" ]
14
2017-10-20T03:10:44.000Z
2021-10-04T03:00:07.000Z
lib/etherscan/util.ex
devlin-Smith/etherscan
c56d6f3f8eefa49c9ac8884461387a3af44fac03
[ "MIT" ]
5
2017-10-20T03:36:37.000Z
2018-03-25T00:58:01.000Z
lib/etherscan/util.ex
devlin-Smith/etherscan
c56d6f3f8eefa49c9ac8884461387a3af44fac03
[ "MIT" ]
4
2018-03-25T00:49:18.000Z
2019-11-28T00:33:06.000Z
defmodule Etherscan.Util do @moduledoc false @denominations [ wei: 1, kwei: 1000, mwei: 1_000_000, gwei: 1_000_000_000, shannon: 1_000_000_000, nano: 1_000_000_000, szabo: 1_000_000_000_000, micro: 1_000_000_000_000, finney: 1_000_000_000_000_000, milli: 1_000_000_000_000_000, ether: 1_000_000_000_000_000_000 ] @doc """ Formats a string representing an Ethereum balance """ @spec format_balance(balance :: String.t()) :: String.t() def format_balance(balance) do balance |> String.to_integer() |> convert() end @spec convert(number :: integer() | float(), opts :: Keyword.t()) :: String.t() def convert(number, opts \\ []) def convert(number, opts) when is_number(number) do denom = @denominations |> List.keyfind(Keyword.get(opts, :denomination, :ether), 0) |> elem(1) pretty_float(number / denom, Keyword.get(opts, :decimals, 20)) end def convert(number, opts) when is_binary(number) do number |> String.to_integer() |> convert(opts) end @doc """ Converts a float to a nicely formatted string """ @spec pretty_float(number :: float() | String.t(), decimals :: integer()) :: String.t() def pretty_float(number, decimals \\ 20) def pretty_float(number, decimals) when is_number(number) do :erlang.float_to_binary(number, [:compact, decimals: decimals]) end def pretty_float(number, decimals) when is_binary(number) do number |> String.to_float() |> pretty_float(decimals) end @doc """ Wraps a value inside a tagged Tuple using the provided tag. """ @spec wrap(value :: any(), tag :: atom()) :: {atom(), any()} def wrap(value, tag) when is_atom(tag), do: {tag, value} @spec hex_to_number(hex :: String.t()) :: {:ok, integer()} | {:error, String.t()} def hex_to_number("0x" <> hex) do hex |> Integer.parse(16) |> case do {integer, _} -> integer |> wrap(:ok) :error -> "invalid hex - #{inspect("0x" <> hex)}" |> wrap(:error) end end def hex_to_number(hex), do: "invalid hex - #{inspect(hex)}" |> wrap(:error) @spec safe_hex_to_number(hex :: String.t()) :: integer() def safe_hex_to_number(hex) do hex |> hex_to_number() |> case do {:ok, integer} -> integer {:error, _reason} -> 0 end end @spec number_to_hex(number :: integer() | String.t()) :: String.t() def number_to_hex(number) when is_integer(number) do number |> Integer.to_string(16) |> (&Kernel.<>("0x", &1)).() end def number_to_hex(number) when is_binary(number) do number |> String.to_integer() |> number_to_hex() end end
24.495495
89
0.619345
733be2a5d4c440f4efc0bd3de357b66e53b29e27
1,877
ex
Elixir
clients/cloud_tasks/lib/google_api/cloud_tasks/v2/model/list_queues_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/cloud_tasks/lib/google_api/cloud_tasks/v2/model/list_queues_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/cloud_tasks/lib/google_api/cloud_tasks/v2/model/list_queues_response.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.CloudTasks.V2.Model.ListQueuesResponse do @moduledoc """ Response message for ListQueues. ## Attributes * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - A token to retrieve next page of results. To return the next page of results, call ListQueues with this value as the page_token. If the next_page_token is empty, there are no more results. The page token is valid for only 2 hours. * `queues` (*type:* `list(GoogleApi.CloudTasks.V2.Model.Queue.t)`, *default:* `nil`) - The list of queues. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :nextPageToken => String.t(), :queues => list(GoogleApi.CloudTasks.V2.Model.Queue.t()) } field(:nextPageToken) field(:queues, as: GoogleApi.CloudTasks.V2.Model.Queue, type: :list) end defimpl Poison.Decoder, for: GoogleApi.CloudTasks.V2.Model.ListQueuesResponse do def decode(value, options) do GoogleApi.CloudTasks.V2.Model.ListQueuesResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudTasks.V2.Model.ListQueuesResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.54
293
0.736281
733c20074b138268ad5494530b6bfac698c6976e
1,014
exs
Elixir
test/parser/get_rpc_methods_test.exs
smiyabe/cwmp_ex
9db322497aa3208b5985ccf496ada5286cde3925
[ "Artistic-2.0" ]
3
2017-11-29T05:07:35.000Z
2019-12-18T17:16:41.000Z
test/parser/get_rpc_methods_test.exs
smiyabe/cwmp_ex
9db322497aa3208b5985ccf496ada5286cde3925
[ "Artistic-2.0" ]
1
2021-12-02T19:35:28.000Z
2022-03-29T09:40:52.000Z
test/parser/get_rpc_methods_test.exs
smiyabe/cwmp_ex
9db322497aa3208b5985ccf496ada5286cde3925
[ "Artistic-2.0" ]
2
2017-11-29T05:07:30.000Z
2020-11-10T07:10:42.000Z
defmodule CWMP.Protocol.Parser.GetRPCMethodsTest do use ExUnit.Case, async: true @sample """ <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cwmp="urn:dslforum-org:cwmp-1-0"> <SOAP-ENV:Header> <cwmp:ID SOAP-ENV:mustUnderstand="1">API_aa0642e34b23820801e7642ad7cb536c</cwmp:ID> </SOAP-ENV:Header> <SOAP-ENV:Body> <cwmp:GetRPCMethods/> </SOAP-ENV:Body> </SOAP-ENV:Envelope> """ @sample_result {:ok,%{cwmp_version: "1-0", entries: [%CWMP.Protocol.Messages.GetRPCMethods{naught: nil}], header: %CWMP.Protocol.Messages.Header{hold_requests: false, id: "API_aa0642e34b23820801e7642ad7cb536c", session_timeout: 30, no_more_requests: false}}} test "parses GetRPCMethods request" do assert(CWMP.Protocol.Parser.parse(@sample) == @sample_result) end end
34.965517
108
0.712032
733c4e539820d0da85512640e33b93a88f54f544
1,969
exs
Elixir
mix.exs
coder-from-hell/instream
f062e924b74a403e0f41b5374d9ed0e00ae59507
[ "Apache-2.0" ]
null
null
null
mix.exs
coder-from-hell/instream
f062e924b74a403e0f41b5374d9ed0e00ae59507
[ "Apache-2.0" ]
null
null
null
mix.exs
coder-from-hell/instream
f062e924b74a403e0f41b5374d9ed0e00ae59507
[ "Apache-2.0" ]
null
null
null
defmodule Instream.MixProject do use Mix.Project @url_github "https://github.com/mneudert/instream" def project do [ app: :instream, name: "Instream", version: "2.0.0-dev", elixir: "~> 1.7", aliases: aliases(), deps: deps(), description: "InfluxDB driver for Elixir", dialyzer: dialyzer(), docs: docs(), elixirc_paths: elixirc_paths(Mix.env()), package: package(), preferred_cli_env: [ "bench.line_encoder": :bench, coveralls: :test, "coveralls.detail": :test ], test_coverage: [tool: ExCoveralls] ] end def application do [ extra_applications: [:logger] ] end defp aliases do [ "bench.line_encoder": ["run bench/line_encoder.exs"] ] end defp deps do [ {:benchee, "~> 1.0", only: :bench, runtime: false}, {:credo, "~> 1.0", only: :dev, runtime: false}, {:dialyxir, "~> 1.0", only: :dev, runtime: false}, {:ex_doc, ">= 0.0.0", only: :dev, runtime: false}, {:excoveralls, "~> 0.14.0", only: :test, runtime: false}, {:hackney, "~> 1.17"}, {:influxql, "~> 0.2.0"}, {:jason, "~> 1.0"}, {:mox, "~> 1.0", only: :test}, {:poolboy, "~> 1.5"}, {:ranch, "~> 1.7", only: :test} ] end defp dialyzer do [ flags: [ :error_handling, :race_conditions, :underspecs, :unmatched_returns ], plt_core_path: "plts", plt_file: {:no_warn, "plts/dialyzer.plt"} ] end defp docs do [ main: "Instream", source_ref: "master", source_url: @url_github ] end defp elixirc_paths(:test), do: ["lib", "test/helpers"] defp elixirc_paths(_), do: ["lib"] defp package do %{ files: [".formatter.exs", "CHANGELOG.md", "LICENSE", "mix.exs", "README.md", "lib"], licenses: ["Apache 2.0"], links: %{"GitHub" => @url_github} } end end
22.375
90
0.530726
733c54a2df0389a1f765adc12f49203df44d3438
1,314
ex
Elixir
test/support/test_helpers.ex
inspired-consulting/liquex
2ba530727aa87a93dbe9b981b4a90e962b34f4a3
[ "MIT" ]
19
2020-02-29T01:37:11.000Z
2022-03-15T06:45:20.000Z
test/support/test_helpers.ex
inspired-consulting/liquex
2ba530727aa87a93dbe9b981b4a90e962b34f4a3
[ "MIT" ]
19
2020-09-02T19:35:08.000Z
2022-03-31T21:42:16.000Z
test/support/test_helpers.ex
inspired-consulting/liquex
2ba530727aa87a93dbe9b981b4a90e962b34f4a3
[ "MIT" ]
4
2020-10-20T08:22:43.000Z
2022-01-19T17:21:32.000Z
defmodule Liquex.TestHelpers do @moduledoc false import ExUnit.Assertions def assert_parse(doc, match), do: assert({:ok, ^match, "", _, _, _} = Liquex.Parser.Base.parse(doc)) def assert_match_liquid(path) do {:ok, archive} = Hrx.load(path) object_json = get_file_contents(archive, ".json") liquid = get_file_contents(archive, ".liquid") context = Jason.decode!(object_json) with {:ok, ast} <- Liquex.parse(liquid), {data, _} <- Liquex.render(ast, context), {liquid_result, 0} <- liquid_render(liquid, object_json) do assert liquid_result == to_string(data) else {:error, msg, _} -> flunk("Unable to parse: #{msg}") {response, exit_code} when is_integer(exit_code) -> flunk("Unable to parse: '#{response}', exit code: #{exit_code}") _r -> IO.warn("Could not execute liquid for ruby. Ignoring...") :ok end end defp get_file_contents(%Hrx.Archive{entries: entries}, extension) do entries |> Enum.filter(&(Path.extname(elem(&1, 0)) == extension)) |> Enum.map(&elem(&1, 1)) |> case do [%Hrx.Entry{contents: {:file, contents}}] -> contents _ -> nil end end def liquid_render(liquid, json), do: System.cmd("ruby", ["test/render.rb", liquid, json]) end
27.957447
74
0.617199
733c92c98c6bb037f6912a0ab159a24f39274e74
202
ex
Elixir
lib/elixir_jobs/ecto_enums.ex
savekirk/elixir_jobs
d7ec0f088a1365f3ae5cbbd6c07c2b3fdde9a946
[ "MIT" ]
null
null
null
lib/elixir_jobs/ecto_enums.ex
savekirk/elixir_jobs
d7ec0f088a1365f3ae5cbbd6c07c2b3fdde9a946
[ "MIT" ]
null
null
null
lib/elixir_jobs/ecto_enums.ex
savekirk/elixir_jobs
d7ec0f088a1365f3ae5cbbd6c07c2b3fdde9a946
[ "MIT" ]
null
null
null
defmodule ElixirJobs.EctoEnums do import EctoEnum defenum JobType, :job_type, [:unknown, :full_time, :part_time, :freelance] defenum JobPlace, :job_place, [:unknown, :onsite, :remote, :both] end
28.857143
76
0.742574
733c9875b0c8f8ff14cda1f5bf983afcb9ede4ec
1,180
exs
Elixir
mix.exs
coverflex-tech/elixlsx
ddc4284bd1ef24103487210709ca5b54cc54c78b
[ "MIT" ]
null
null
null
mix.exs
coverflex-tech/elixlsx
ddc4284bd1ef24103487210709ca5b54cc54c78b
[ "MIT" ]
null
null
null
mix.exs
coverflex-tech/elixlsx
ddc4284bd1ef24103487210709ca5b54cc54c78b
[ "MIT" ]
1
2021-07-13T16:21:25.000Z
2021-07-13T16:21:25.000Z
defmodule Elixlsx.Mixfile do use Mix.Project @source_url "https://github.com/xou/elixlsx" @version "0.4.2" def project do [ app: :elixlsx, version: @version, elixir: "~> 1.3", package: package(), description: "Elixlsx is a writer for the MS Excel OpenXML format (`.xlsx`).", build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, deps: deps(), docs: docs() ] end def application do [] end defp deps do [ {:excheck, "~> 0.5", only: :test}, {:triq, "~> 1.0", only: :test}, {:credo, "~> 0.5", only: [:dev, :test]}, {:ex_doc, ">= 0.0.0", only: [:docs], runtime: false}, {:dialyxir, "~> 0.5", only: [:dev], runtime: false} ] end defp docs do [ extras: ["CHANGELOG.md", "README.md"], main: "readme", source_url: @source_url, source_ref: "v#{@version}" ] end defp package do [ maintainers: ["Nikolai Weh <[email protected]>"], licenses: ["MIT"], links: %{ "Changelog" => "https://hexdocs.pm/elixlsx/changelog.html", "GitHub" => @source_url } ] end end
21.454545
84
0.525424
733c9c2f494a29a23241a3c151f2ec755c1177dc
602
exs
Elixir
mix.exs
erpuno/asic
75e79bade217b4b978fe01a412d33dd6e1e72129
[ "0BSD" ]
null
null
null
mix.exs
erpuno/asic
75e79bade217b4b978fe01a412d33dd6e1e72129
[ "0BSD" ]
null
null
null
mix.exs
erpuno/asic
75e79bade217b4b978fe01a412d33dd6e1e72129
[ "0BSD" ]
null
null
null
defmodule ASiC.Mixfile do use Mix.Project def project() do [ app: :asic, version: "0.4.1", elixir: "~> 1.8", description: "ASiC Document Container ISO 21320-1", package: package(), deps: deps() ] end def package do [ files: ~w(doc src mix.exs LICENSE), licenses: ["ISC"], maintainers: ["Namdak Tonpa"], name: :asic, links: %{"GitHub" => "https://github.com/erpuno/asic"} ] end def application() do [mod: {:asic, []}] end def deps() do [ {:ex_doc, "~> 0.11", only: :dev} ] end end
17.2
60
0.516611
733d13a3830d6a54113d7de9931839fc144f4d97
4,244
exs
Elixir
test/integrations/confirm_account_test.exs
MatthieuSegret/yummy-phoenix-graphql
f0b258293697b0b120ef8e8a3b3905043c998617
[ "MIT" ]
122
2017-11-24T11:28:17.000Z
2022-02-25T17:05:20.000Z
test/integrations/confirm_account_test.exs
MatthieuSegret/yummy-phoenix-graphql
f0b258293697b0b120ef8e8a3b3905043c998617
[ "MIT" ]
6
2018-01-11T22:07:44.000Z
2021-11-21T15:41:42.000Z
test/integrations/confirm_account_test.exs
MatthieuSegret/yummy-phoenix-graphql
f0b258293697b0b120ef8e8a3b3905043c998617
[ "MIT" ]
25
2018-04-01T02:43:21.000Z
2022-02-15T03:22:54.000Z
defmodule YummyWeb.Integrations.ConfirmAccountTest do use YummyWeb.IntegrationCase, async: false use Bamboo.Test, shared: true alias Yummy.Repo alias Yummy.Accounts.User setup do user = insert( :user, confirmed_at: nil, confirmation_code: "123123", confirmation_sent_at: Timex.now() ) confirmation_url = "/users/confirmation-needed/#{URI.encode(user.email)}" {:ok, %{user: user, confirmation_url: confirmation_url}} end describe "when user confirm account" do test "with successful", %{session: session, user: user, confirmation_url: confirmation_url} do path = session |> visit(confirmation_url) |> fill_in(css("input[name='code']"), with: user.confirmation_code) |> click(button("Valider")) |> assert_eq(notice_msg(), text: "Votre compte a été validé.") |> assert_eq(signed_in_user(), text: user.name) |> current_path() assert path == "/" end test "with invalid format", %{session: session, confirmation_url: confirmation_url} do path = session |> visit(confirmation_url) |> fill_in(css("input[name='code']"), with: "invalid") |> click(button("Valider")) |> assert_eq(error_msg(), text: "Le code doit être composé de 6 chiffres.") |> current_path() assert path == confirmation_url end test "with wrong code", %{session: session, confirmation_url: confirmation_url} do path = session |> visit(confirmation_url) |> fill_in(css("input[name='code']"), with: "987654") |> click(button("Valider")) |> assert_eq(error_msg(), text: "Ce code est invalide. Essayez avec un autre code.") |> current_path() assert path == confirmation_url end test "with expirated date", %{session: session} do user = insert( :user, confirmed_at: nil, confirmation_code: "123123", confirmation_sent_at: Timex.shift(Timex.now(), hours: -7) ) confirmation_url = "/users/confirmation-needed/#{URI.encode(user.email)}" path = session |> visit(confirmation_url) |> fill_in(css("input[name='code']"), with: user.confirmation_code) |> click(button("Valider")) |> assert_eq(error_msg(), text: "Ce code est expiré. Veuillez en redemander un nouveau.") |> current_path() assert path == confirmation_url end test "with account already confirmed", %{session: session} do user = insert(:user) confirmation_url = "/users/confirmation-needed/#{URI.encode(user.email)}" path = session |> visit(confirmation_url) |> fill_in(css("input[name='code']"), with: "123123") |> click(button("Valider")) |> assert_eq(error_msg(), text: "Ce compte a déjà été validé. Vous pouvez vous connecter.") |> current_path() assert path == "/users/signin" end end describe "when user ask new code" do test "with successful", %{session: session, user: user, confirmation_url: confirmation_url} do current_session = session |> visit(confirmation_url) |> click(button("Renvoyer l'email")) |> assert_eq(notice_msg(), text: "L'email de confirmation a bien été renvoyé") assert current_path(current_session) == confirmation_url u = User |> Repo.get_by(email: user.email) assert_email_delivered_with( subject: "Nouveau code pour valider votre compte", text_body: ~r/#{u.confirmation_code}/, html_body: ~r/#{u.confirmation_code}/ ) assert u.confirmation_code assert u.confirmation_sent_at refute u.confirmed_at end test "with account already confirmed", %{session: session} do user = insert(:user) confirmation_url = "/users/confirmation-needed/#{URI.encode(user.email)}" path = session |> visit(confirmation_url) |> click(button("Renvoyer l'email")) |> assert_eq(error_msg(), text: "Ce compte a déjà été validé. Vous pouvez vous connecter.") |> current_path() assert path == "/users/signin" end end end
31.437037
99
0.618992
733d2da36727631f26c1367d7057203c2617bd80
101
ex
Elixir
lib/hai_elixir.ex
shawnHartsell/hai-elixir
384383fa4e69f541a41247d4454b73eba31486e2
[ "MIT" ]
null
null
null
lib/hai_elixir.ex
shawnHartsell/hai-elixir
384383fa4e69f541a41247d4454b73eba31486e2
[ "MIT" ]
null
null
null
lib/hai_elixir.ex
shawnHartsell/hai-elixir
384383fa4e69f541a41247d4454b73eba31486e2
[ "MIT" ]
null
null
null
defmodule HaiElixir do import HaiElixir.Cli def main(args) do run(args) end end
12.625
24
0.633663
733d8a33aa2c836d11b75b0e76bdc3def0c6a408
1,371
ex
Elixir
test/support/data_case.ex
ryan-senn/ryan
84bf5303a5aa384562e79d0a68364b2009b92ea5
[ "MIT" ]
1
2019-07-31T13:43:21.000Z
2019-07-31T13:43:21.000Z
test/support/data_case.ex
ryan-senn/ryan
84bf5303a5aa384562e79d0a68364b2009b92ea5
[ "MIT" ]
null
null
null
test/support/data_case.ex
ryan-senn/ryan
84bf5303a5aa384562e79d0a68364b2009b92ea5
[ "MIT" ]
null
null
null
defmodule Ryan.DataCase do @moduledoc """ This module defines the setup for tests requiring access to the application's data layer. You may define functions here to be used as helpers in your tests. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do alias Ryan.Repo import Ecto import Ecto.Changeset import Ecto.Query import Ryan.DataCase end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Ryan.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Ryan.Repo, {:shared, self()}) end :ok end @doc """ A helper that transforms changeset errors into a map of messages. assert {:error, changeset} = Accounts.create_user(%{password: "short"}) assert "password is too short" in errors_on(changeset).password assert %{password: ["password is too short"]} = errors_on(changeset) """ def errors_on(changeset) do Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> Enum.reduce(opts, message, fn {key, value}, acc -> String.replace(acc, "%{#{key}}", to_string(value)) end) end) end end
25.388889
77
0.676878
733dbddb28a9c2be22e4d37c4f1691b88b776274
2,085
ex
Elixir
apps/utils/lib/helpers/encoding.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
322
2018-02-28T07:38:44.000Z
2020-05-27T23:09:55.000Z
apps/utils/lib/helpers/encoding.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
643
2018-02-28T12:05:20.000Z
2020-05-22T08:34:38.000Z
apps/utils/lib/helpers/encoding.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
63
2018-02-28T10:57:06.000Z
2020-05-27T23:10:38.000Z
# Copyright 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 Utils.Helpers.Encoding do @moduledoc false @spec to_hex(binary | non_neg_integer) :: binary def to_hex(non_hex) def to_hex(raw) when is_binary(raw), do: "0x" <> Base.encode16(raw, case: :lower) def to_hex(int) when is_integer(int), do: "0x" <> Integer.to_string(int, 16) @doc """ Decodes to a raw binary, see `to_hex` """ # because https://github.com/rrrene/credo/issues/583, we need to: # credo:disable-for-next-line Credo.Check.Consistency.SpaceAroundOperators @spec from_hex(<<_::16, _::_*8>>) :: binary def from_hex("0x" <> encoded) when is_binary(encoded) and rem(byte_size(encoded), 2) == 1 do from_hex("0x0#{encoded}") end def from_hex("0x" <> encoded) when is_binary(encoded) and rem(byte_size(encoded), 2) == 0 do Base.decode16!(encoded, case: :lower) end def from_hex(encoded) when is_binary(encoded) do Base.decode16!(encoded, case: :lower) end def sliced("0x" <> data) do data end @doc """ Decodes to an integer, see `to_hex` """ # because https://github.com/rrrene/credo/issues/583, we need to: # credo:disable-for-next-line Credo.Check.Consistency.SpaceAroundOperators @spec int_from_hex(<<_::16, _::_*8>>) :: non_neg_integer def int_from_hex("0x" <> encoded) do case Integer.parse(encoded, 16) do {result, ""} -> result :error -> 0 end end @spec encode_unsigned(number()) :: binary() def encode_unsigned(0), do: <<>> def encode_unsigned(n), do: :binary.encode_unsigned(n) end
33.095238
94
0.696403
733dd5dfd93227e12c8f64e3e3cd6baba6fb754e
4,565
ex
Elixir
clients/composer/lib/google_api/composer/v1/model/environment_config.ex
jamesvl/elixir-google-api
6c87fb31d996f08fb42ce6066317e9d652a87acc
[ "Apache-2.0" ]
null
null
null
clients/composer/lib/google_api/composer/v1/model/environment_config.ex
jamesvl/elixir-google-api
6c87fb31d996f08fb42ce6066317e9d652a87acc
[ "Apache-2.0" ]
null
null
null
clients/composer/lib/google_api/composer/v1/model/environment_config.ex
jamesvl/elixir-google-api
6c87fb31d996f08fb42ce6066317e9d652a87acc
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Composer.V1.Model.EnvironmentConfig do @moduledoc """ Configuration information for an environment. ## Attributes * `airflowUri` (*type:* `String.t`, *default:* `nil`) - Output only. The URI of the Apache Airflow Web UI hosted within this environment (see [Airflow web interface](/composer/docs/how-to/accessing/airflow-web-interface)). * `dagGcsPrefix` (*type:* `String.t`, *default:* `nil`) - Output only. The Cloud Storage prefix of the DAGs for this environment. Although Cloud Storage objects reside in a flat namespace, a hierarchical file tree can be simulated using "/"-delimited object name prefixes. DAG objects for this environment reside in a simulated directory with the given prefix. * `databaseConfig` (*type:* `GoogleApi.Composer.V1.Model.DatabaseConfig.t`, *default:* `nil`) - Optional. The configuration settings for Cloud SQL instance used internally by Apache Airflow software. * `gkeCluster` (*type:* `String.t`, *default:* `nil`) - Output only. The Kubernetes Engine cluster used to run this environment. * `nodeConfig` (*type:* `GoogleApi.Composer.V1.Model.NodeConfig.t`, *default:* `nil`) - The configuration used for the Kubernetes Engine cluster. * `nodeCount` (*type:* `integer()`, *default:* `nil`) - The number of nodes in the Kubernetes Engine cluster that will be used to run this environment. * `privateEnvironmentConfig` (*type:* `GoogleApi.Composer.V1.Model.PrivateEnvironmentConfig.t`, *default:* `nil`) - The configuration used for the Private IP Cloud Composer environment. * `softwareConfig` (*type:* `GoogleApi.Composer.V1.Model.SoftwareConfig.t`, *default:* `nil`) - The configuration settings for software inside the environment. * `webServerConfig` (*type:* `GoogleApi.Composer.V1.Model.WebServerConfig.t`, *default:* `nil`) - Optional. The configuration settings for the Airflow web server App Engine instance. * `webServerNetworkAccessControl` (*type:* `GoogleApi.Composer.V1.Model.WebServerNetworkAccessControl.t`, *default:* `nil`) - Optional. The network-level access control policy for the Airflow web server. If unspecified, no network-level access restrictions will be applied. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :airflowUri => String.t(), :dagGcsPrefix => String.t(), :databaseConfig => GoogleApi.Composer.V1.Model.DatabaseConfig.t(), :gkeCluster => String.t(), :nodeConfig => GoogleApi.Composer.V1.Model.NodeConfig.t(), :nodeCount => integer(), :privateEnvironmentConfig => GoogleApi.Composer.V1.Model.PrivateEnvironmentConfig.t(), :softwareConfig => GoogleApi.Composer.V1.Model.SoftwareConfig.t(), :webServerConfig => GoogleApi.Composer.V1.Model.WebServerConfig.t(), :webServerNetworkAccessControl => GoogleApi.Composer.V1.Model.WebServerNetworkAccessControl.t() } field(:airflowUri) field(:dagGcsPrefix) field(:databaseConfig, as: GoogleApi.Composer.V1.Model.DatabaseConfig) field(:gkeCluster) field(:nodeConfig, as: GoogleApi.Composer.V1.Model.NodeConfig) field(:nodeCount) field(:privateEnvironmentConfig, as: GoogleApi.Composer.V1.Model.PrivateEnvironmentConfig) field(:softwareConfig, as: GoogleApi.Composer.V1.Model.SoftwareConfig) field(:webServerConfig, as: GoogleApi.Composer.V1.Model.WebServerConfig) field(:webServerNetworkAccessControl, as: GoogleApi.Composer.V1.Model.WebServerNetworkAccessControl ) end defimpl Poison.Decoder, for: GoogleApi.Composer.V1.Model.EnvironmentConfig do def decode(value, options) do GoogleApi.Composer.V1.Model.EnvironmentConfig.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Composer.V1.Model.EnvironmentConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
58.525641
364
0.741512