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
79505afe93826c93e972bf12bc4f29f5a8d34a54
4,931
exs
Elixir
lib/mix/test/mix_test.exs
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
19,291
2015-01-01T02:42:49.000Z
2022-03-31T21:01:40.000Z
lib/mix/test/mix_test.exs
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
8,082
2015-01-01T04:16:23.000Z
2022-03-31T22:08:02.000Z
lib/mix/test/mix_test.exs
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
3,472
2015-01-03T04:11:56.000Z
2022-03-29T02:07:30.000Z
Code.require_file("test_helper.exs", __DIR__) defmodule MixTest do use MixTest.Case test "shell" do assert Mix.shell() == Mix.Shell.Process end test "env" do assert Mix.env() == :dev Mix.env(:prod) assert Mix.env() == :prod end test "debug" do refute Mix.debug?() Mix.debug(true) assert Mix.debug?() Mix.debug(false) end describe "install" do @describetag :tmp_dir setup %{tmp_dir: tmp_dir} do System.put_env("MIX_INSTALL_DIR", Path.join(tmp_dir, "installs")) end setup :test_project test "default options", %{tmp_dir: tmp_dir} do Mix.install([ {:install_test, path: Path.join(tmp_dir, "install_test")} ]) assert File.dir?(Path.join(tmp_dir, "installs")) assert Protocol.consolidated?(InstallTest.Protocol) assert_received {:mix_shell, :info, ["==> install_test"]} assert_received {:mix_shell, :info, ["Compiling 1 file (.ex)"]} assert_received {:mix_shell, :info, ["Generated install_test app"]} refute_received _ assert List.keyfind(Application.started_applications(), :install_test, 0) assert apply(InstallTest, :hello, []) == :world end test "works with same deps twice", %{tmp_dir: tmp_dir} do Mix.install([ {:install_test, path: Path.join(tmp_dir, "install_test")} ]) Mix.install([ {:install_test, path: Path.join(tmp_dir, "install_test")} ]) end test "errors on Elixir version mismatch", %{tmp_dir: tmp_dir} do assert_raise Mix.Error, ~r"Mix.install/2 declared it supports only Elixir ~> 2.0", fn -> Mix.install( [ {:install_test, path: Path.join(tmp_dir, "install_test")} ], elixir: "~> 2.0" ) end end test "errors with same deps and force", %{tmp_dir: tmp_dir} do Mix.install([ {:install_test, path: Path.join(tmp_dir, "install_test")} ]) assert_raise Mix.Error, ~r"Mix.install/2 can only be called", fn -> Mix.install( [ {:install_test, path: Path.join(tmp_dir, "install_test")} ], force: true ) end end test "errors with different deps in the same VM", %{tmp_dir: tmp_dir} do Mix.install([ {:install_test, path: Path.join(tmp_dir, "install_test")} ]) assert_raise Mix.Error, ~r"Mix.install/2 can only be called", fn -> Mix.install([ {:install_test, path: Path.join(tmp_dir, "install_test")}, :foo ]) end end test "install after errors", %{tmp_dir: tmp_dir} do assert_raise Mix.Error, "Can't continue due to errors on dependencies", fn -> Mix.install([ {:bad, path: Path.join(tmp_dir, "bad")} ]) end Mix.install([ {:install_test, path: Path.join(tmp_dir, "install_test")} ]) assert apply(InstallTest, :hello, []) == :world end test "consolidate_protocols: false", %{tmp_dir: tmp_dir} do Mix.install( [ {:install_test, path: Path.join(tmp_dir, "install_test")} ], consolidate_protocols: false ) refute Protocol.consolidated?(InstallTest.Protocol) end test "config and system_env", %{tmp_dir: tmp_dir} do Mix.install( [ {:install_test, path: Path.join(tmp_dir, "install_test")} ], config: [unknown_app: [foo: :bar]], system_env: %{"MIX_INSTALL_FOO" => "BAR"} ) assert Application.fetch_env!(:unknown_app, :foo) == :bar assert System.fetch_env!("MIX_INSTALL_FOO") == "BAR" after System.delete_env("MIX_INSTALL_FOO") Application.delete_env(:unknown_app, :foo, persistent: true) end test "install?", %{tmp_dir: tmp_dir} do refute Mix.installed?() Mix.install([ {:install_test, path: Path.join(tmp_dir, "install_test")} ]) assert Mix.installed?() end defp test_project(%{tmp_dir: tmp_dir}) do path = :code.get_path() on_exit(fn -> :code.set_path(path) purge([InstallTest, InstallTest.MixProject, InstallTest.Protocol]) Application.stop(:install_test) Application.unload(:install_test) end) Mix.State.put(:installed, nil) File.mkdir_p!("#{tmp_dir}/install_test/lib") File.write!("#{tmp_dir}/install_test/mix.exs", """ defmodule InstallTest.MixProject do use Mix.Project def project do [ app: :install_test, version: "0.1.0" ] end end """) File.write!("#{tmp_dir}/install_test/lib/install_test.ex", """ defmodule InstallTest do def hello do :world end end defprotocol InstallTest.Protocol do def foo(x) end """) [tmp_dir: tmp_dir] end end end
25.549223
94
0.58548
79509aebf4a7ecd77ad2d1749782d7864dc5ab86
1,292
exs
Elixir
mix.exs
kundi/clickhouse_ecto
3251221bd63a159c0e8af8336663b0bef855bbca
[ "Apache-2.0" ]
null
null
null
mix.exs
kundi/clickhouse_ecto
3251221bd63a159c0e8af8336663b0bef855bbca
[ "Apache-2.0" ]
null
null
null
mix.exs
kundi/clickhouse_ecto
3251221bd63a159c0e8af8336663b0bef855bbca
[ "Apache-2.0" ]
null
null
null
defmodule ClickhouseEcto.Mixfile do use Mix.Project def project do [ app: :clickhouse_ecto, version: "0.2.8", elixir: "~> 1.5", start_permanent: Mix.env == :prod, deps: deps(), description: description(), package: package(), source_url: "https://github.com/appodeal/clickhouse_ecto", preffered_cli_env: [espec: :test] ] end # Run "mix help compile.app" to learn about applications. def application do [ applications: [:logger, :ecto] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:ecto_sql, "~> 3.2.0"}, {:clickhousex, git: "https://github.com/kundi/clickhousex.git"}, {:ex_doc, "~> 0.19", only: :dev}, {:espec, "~> 1.7.0", only: :test} ] end defp package do [ name: "clickhouse_ecto", maintainers: maintainers(), licenses: ["Apache 2.0"], files: ["lib", "test", "config", "mix.exs", "README*", "LICENSE*"], links: %{"GitHub" => "https://github.com/appodeal/clickhouse_ecto"} ] end defp description do "Ecto adapter for ClickHouse database (uses clickhousex driver)" end defp maintainers do ["Roman Chudov", "Konstantin Grabar", "Evgeniy Shurmin", "Alexey Lukyanov"] end end
24.377358
79
0.598297
7950b29a536483996e5da75a602c5f55aacf8e55
2,561
exs
Elixir
test/run_workflows/source_paths_template_test.exs
nipierre/ex_step_flow
4345ee57bd4e5eb79138df68d10579ba1b9ec6a1
[ "MIT" ]
null
null
null
test/run_workflows/source_paths_template_test.exs
nipierre/ex_step_flow
4345ee57bd4e5eb79138df68d10579ba1b9ec6a1
[ "MIT" ]
null
null
null
test/run_workflows/source_paths_template_test.exs
nipierre/ex_step_flow
4345ee57bd4e5eb79138df68d10579ba1b9ec6a1
[ "MIT" ]
null
null
null
defmodule StepFlow.RunWorkflows.SourcePathsTemplateTest do use ExUnit.Case use Plug.Test alias Ecto.Adapters.SQL.Sandbox alias StepFlow.Step doctest StepFlow setup do # Explicitly get a connection before each test :ok = Sandbox.checkout(StepFlow.Repo) {_conn, channel} = StepFlow.HelpersTest.get_amqp_connection() on_exit(fn -> StepFlow.HelpersTest.consume_messages(channel, "job_test", 1) end) :ok end describe "workflows" do @workflow_definition %{ schema_version: "1.8", identifier: "id", version_major: 6, version_minor: 5, version_micro: 4, reference: "some-identifier", icon: "custom_icon", label: "Source paths template", tags: ["test"], steps: [ %{ id: 0, name: "job_test", mode: "one_for_many", icon: "step_icon", label: "My first step", parameters: [ %{ id: "source_paths", type: "array_of_templates", value: [ "{work_directory}/{workflow_id}", "{work_directory}/folder" ] } ] } ], parameters: [], rights: [ %{ action: "create", groups: ["administrator"] } ] } test "run destination path with template" do workflow = StepFlow.HelpersTest.workflow_fixture(@workflow_definition) {:ok, "started"} = Step.start_next(workflow) StepFlow.HelpersTest.check(workflow.id, 1) StepFlow.HelpersTest.check(workflow.id, 0, 1) parameters = StepFlow.Jobs.list_jobs(%{ "job_type" => "job_test", "workflow_id" => workflow.id |> Integer.to_string(), "size" => 50 }) |> Map.get(:data) |> List.first() |> Map.get(:parameters) directories = ["/test_work_dir/" <> Integer.to_string(workflow.id), "/test_work_dir/folder"] assert parameters == [ %{ "id" => "source_paths", "type" => "array_of_strings", "value" => directories }, %{ "id" => "requirements", "type" => "requirements", "value" => %{"paths" => directories} } ] StepFlow.HelpersTest.complete_jobs(workflow.id, 0) {:ok, "completed"} = Step.start_next(workflow) StepFlow.HelpersTest.check(workflow.id, 1) end end end
25.356436
98
0.525576
79513213291d1734cc68b622b28977aea690921b
547
ex
Elixir
lib/groupher_server/accounts/models/education_background.ex
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
240
2018-11-06T09:36:54.000Z
2022-02-20T07:12:36.000Z
lib/groupher_server/accounts/models/education_background.ex
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
363
2018-07-11T03:38:14.000Z
2021-12-14T01:42:40.000Z
lib/groupher_server/accounts/models/education_background.ex
mydearxym/mastani_server
f24034a4a5449200165cf4a547964a0961793eab
[ "Apache-2.0" ]
22
2019-01-27T11:47:56.000Z
2021-02-28T13:17:52.000Z
defmodule GroupherServer.Accounts.Model.EducationBackground do @moduledoc false alias __MODULE__ use Ecto.Schema import Ecto.Changeset @required_fields ~w(school)a @optional_fields ~w(major)a @type t :: %EducationBackground{} embedded_schema do field(:school, :string) field(:major, :string) end @doc false def changeset(%EducationBackground{} = education_background, attrs) do education_background |> cast(attrs, @optional_fields ++ @required_fields) |> validate_required(@required_fields) end end
22.791667
72
0.736746
795143c6cd7123e216fed3c43f6098c9e9497550
33,420
ex
Elixir
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/api/organizations.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/api/organizations.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/api/organizations.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.CloudResourceManager.V1.Api.Organizations do @moduledoc """ API calls for all endpoints tagged `Organizations`. """ alias GoogleApi.CloudResourceManager.V1.Connection alias GoogleApi.Gax.{Request, Response} @doc """ Clears a &#x60;Policy&#x60; from a resource. ## Parameters - connection (GoogleApi.CloudResourceManager.V1.Connection): Connection to server - organizations_id (String.t): Part of &#x60;resource&#x60;. Name of the resource for the &#x60;Policy&#x60; to clear. - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :body (ClearOrgPolicyRequest): ## Returns {:ok, %GoogleApi.CloudResourceManager.V1.Model.Empty{}} on success {:error, info} on failure """ @spec cloudresourcemanager_organizations_clear_org_policy( Tesla.Env.client(), String.t(), keyword() ) :: {:ok, GoogleApi.CloudResourceManager.V1.Model.Empty.t()} | {:error, Tesla.Env.t()} def cloudresourcemanager_organizations_clear_org_policy( connection, organizations_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/organizations/{organizationsId}:clearOrgPolicy", %{ "organizationsId" => URI.encode_www_form(organizations_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.CloudResourceManager.V1.Model.Empty{}]) end @doc """ Fetches an Organization resource identified by the specified resource name. ## Parameters - connection (GoogleApi.CloudResourceManager.V1.Connection): Connection to server - organizations_id (String.t): Part of &#x60;name&#x60;. The resource name of the Organization to fetch, e.g. \&quot;organizations/1234\&quot;. - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). ## Returns {:ok, %GoogleApi.CloudResourceManager.V1.Model.Organization{}} on success {:error, info} on failure """ @spec cloudresourcemanager_organizations_get(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.CloudResourceManager.V1.Model.Organization.t()} | {:error, Tesla.Env.t()} def cloudresourcemanager_organizations_get( connection, organizations_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/organizations/{organizationsId}", %{ "organizationsId" => URI.encode_www_form(organizations_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.CloudResourceManager.V1.Model.Organization{}]) end @doc """ Gets the effective &#x60;Policy&#x60; on a resource. This is the result of merging &#x60;Policies&#x60; in the resource hierarchy. The returned &#x60;Policy&#x60; will not have an &#x60;etag&#x60;set because it is a computed &#x60;Policy&#x60; across multiple resources. Subtrees of Resource Manager resource hierarchy with &#39;under:&#39; prefix will not be expanded. ## Parameters - connection (GoogleApi.CloudResourceManager.V1.Connection): Connection to server - organizations_id (String.t): Part of &#x60;resource&#x60;. The name of the resource to start computing the effective &#x60;Policy&#x60;. - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :body (GetEffectiveOrgPolicyRequest): ## Returns {:ok, %GoogleApi.CloudResourceManager.V1.Model.OrgPolicy{}} on success {:error, info} on failure """ @spec cloudresourcemanager_organizations_get_effective_org_policy( Tesla.Env.client(), String.t(), keyword() ) :: {:ok, GoogleApi.CloudResourceManager.V1.Model.OrgPolicy.t()} | {:error, Tesla.Env.t()} def cloudresourcemanager_organizations_get_effective_org_policy( connection, organizations_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/organizations/{organizationsId}:getEffectiveOrgPolicy", %{ "organizationsId" => URI.encode_www_form(organizations_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.CloudResourceManager.V1.Model.OrgPolicy{}]) end @doc """ Gets the access control policy for an Organization resource. May be empty if no such policy or resource exists. The &#x60;resource&#x60; field should be the organization&#39;s resource name, e.g. \&quot;organizations/123\&quot;. Authorization requires the Google IAM permission &#x60;resourcemanager.organizations.getIamPolicy&#x60; on the specified organization ## Parameters - connection (GoogleApi.CloudResourceManager.V1.Connection): Connection to server - organizations_id (String.t): Part of &#x60;resource&#x60;. REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :body (GetIamPolicyRequest): ## Returns {:ok, %GoogleApi.CloudResourceManager.V1.Model.Policy{}} on success {:error, info} on failure """ @spec cloudresourcemanager_organizations_get_iam_policy( Tesla.Env.client(), String.t(), keyword() ) :: {:ok, GoogleApi.CloudResourceManager.V1.Model.Policy.t()} | {:error, Tesla.Env.t()} def cloudresourcemanager_organizations_get_iam_policy( connection, organizations_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/organizations/{organizationsId}:getIamPolicy", %{ "organizationsId" => URI.encode_www_form(organizations_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.CloudResourceManager.V1.Model.Policy{}]) end @doc """ Gets a &#x60;Policy&#x60; on a resource. If no &#x60;Policy&#x60; is set on the resource, a &#x60;Policy&#x60; is returned with default values including &#x60;POLICY_TYPE_NOT_SET&#x60; for the &#x60;policy_type oneof&#x60;. The &#x60;etag&#x60; value can be used with &#x60;SetOrgPolicy()&#x60; to create or update a &#x60;Policy&#x60; during read-modify-write. ## Parameters - connection (GoogleApi.CloudResourceManager.V1.Connection): Connection to server - organizations_id (String.t): Part of &#x60;resource&#x60;. Name of the resource the &#x60;Policy&#x60; is set on. - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :body (GetOrgPolicyRequest): ## Returns {:ok, %GoogleApi.CloudResourceManager.V1.Model.OrgPolicy{}} on success {:error, info} on failure """ @spec cloudresourcemanager_organizations_get_org_policy( Tesla.Env.client(), String.t(), keyword() ) :: {:ok, GoogleApi.CloudResourceManager.V1.Model.OrgPolicy.t()} | {:error, Tesla.Env.t()} def cloudresourcemanager_organizations_get_org_policy( connection, organizations_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/organizations/{organizationsId}:getOrgPolicy", %{ "organizationsId" => URI.encode_www_form(organizations_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.CloudResourceManager.V1.Model.OrgPolicy{}]) end @doc """ Lists &#x60;Constraints&#x60; that could be applied on the specified resource. ## Parameters - connection (GoogleApi.CloudResourceManager.V1.Connection): Connection to server - organizations_id (String.t): Part of &#x60;resource&#x60;. Name of the resource to list &#x60;Constraints&#x60; for. - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :body (ListAvailableOrgPolicyConstraintsRequest): ## Returns {:ok, %GoogleApi.CloudResourceManager.V1.Model.ListAvailableOrgPolicyConstraintsResponse{}} on success {:error, info} on failure """ @spec cloudresourcemanager_organizations_list_available_org_policy_constraints( Tesla.Env.client(), String.t(), keyword() ) :: {:ok, GoogleApi.CloudResourceManager.V1.Model.ListAvailableOrgPolicyConstraintsResponse.t()} | {:error, Tesla.Env.t()} def cloudresourcemanager_organizations_list_available_org_policy_constraints( connection, organizations_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/organizations/{organizationsId}:listAvailableOrgPolicyConstraints", %{ "organizationsId" => URI.encode_www_form(organizations_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [ struct: %GoogleApi.CloudResourceManager.V1.Model.ListAvailableOrgPolicyConstraintsResponse{} ] ) end @doc """ Lists all the &#x60;Policies&#x60; set for a particular resource. ## Parameters - connection (GoogleApi.CloudResourceManager.V1.Connection): Connection to server - organizations_id (String.t): Part of &#x60;resource&#x60;. Name of the resource to list Policies for. - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :body (ListOrgPoliciesRequest): ## Returns {:ok, %GoogleApi.CloudResourceManager.V1.Model.ListOrgPoliciesResponse{}} on success {:error, info} on failure """ @spec cloudresourcemanager_organizations_list_org_policies( Tesla.Env.client(), String.t(), keyword() ) :: {:ok, GoogleApi.CloudResourceManager.V1.Model.ListOrgPoliciesResponse.t()} | {:error, Tesla.Env.t()} def cloudresourcemanager_organizations_list_org_policies( connection, organizations_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/organizations/{organizationsId}:listOrgPolicies", %{ "organizationsId" => URI.encode_www_form(organizations_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.CloudResourceManager.V1.Model.ListOrgPoliciesResponse{}] ) end @doc """ Searches Organization resources that are visible to the user and satisfy the specified filter. This method returns Organizations in an unspecified order. New Organizations do not necessarily appear at the end of the results. Search will only return organizations on which the user has the permission &#x60;resourcemanager.organizations.get&#x60; ## Parameters - connection (GoogleApi.CloudResourceManager.V1.Connection): Connection to server - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :body (SearchOrganizationsRequest): ## Returns {:ok, %GoogleApi.CloudResourceManager.V1.Model.SearchOrganizationsResponse{}} on success {:error, info} on failure """ @spec cloudresourcemanager_organizations_search(Tesla.Env.client(), keyword()) :: {:ok, GoogleApi.CloudResourceManager.V1.Model.SearchOrganizationsResponse.t()} | {:error, Tesla.Env.t()} def cloudresourcemanager_organizations_search(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/organizations:search") |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.CloudResourceManager.V1.Model.SearchOrganizationsResponse{}] ) end @doc """ Sets the access control policy on an Organization resource. Replaces any existing policy. The &#x60;resource&#x60; field should be the organization&#39;s resource name, e.g. \&quot;organizations/123\&quot;. Authorization requires the Google IAM permission &#x60;resourcemanager.organizations.setIamPolicy&#x60; on the specified organization ## Parameters - connection (GoogleApi.CloudResourceManager.V1.Connection): Connection to server - organizations_id (String.t): Part of &#x60;resource&#x60;. REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :body (SetIamPolicyRequest): ## Returns {:ok, %GoogleApi.CloudResourceManager.V1.Model.Policy{}} on success {:error, info} on failure """ @spec cloudresourcemanager_organizations_set_iam_policy( Tesla.Env.client(), String.t(), keyword() ) :: {:ok, GoogleApi.CloudResourceManager.V1.Model.Policy.t()} | {:error, Tesla.Env.t()} def cloudresourcemanager_organizations_set_iam_policy( connection, organizations_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/organizations/{organizationsId}:setIamPolicy", %{ "organizationsId" => URI.encode_www_form(organizations_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.CloudResourceManager.V1.Model.Policy{}]) end @doc """ Updates the specified &#x60;Policy&#x60; on the resource. Creates a new &#x60;Policy&#x60; for that &#x60;Constraint&#x60; on the resource if one does not exist. Not supplying an &#x60;etag&#x60; on the request &#x60;Policy&#x60; results in an unconditional write of the &#x60;Policy&#x60;. ## Parameters - connection (GoogleApi.CloudResourceManager.V1.Connection): Connection to server - organizations_id (String.t): Part of &#x60;resource&#x60;. Resource name of the resource to attach the &#x60;Policy&#x60;. - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :body (SetOrgPolicyRequest): ## Returns {:ok, %GoogleApi.CloudResourceManager.V1.Model.OrgPolicy{}} on success {:error, info} on failure """ @spec cloudresourcemanager_organizations_set_org_policy( Tesla.Env.client(), String.t(), keyword() ) :: {:ok, GoogleApi.CloudResourceManager.V1.Model.OrgPolicy.t()} | {:error, Tesla.Env.t()} def cloudresourcemanager_organizations_set_org_policy( connection, organizations_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/organizations/{organizationsId}:setOrgPolicy", %{ "organizationsId" => URI.encode_www_form(organizations_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.CloudResourceManager.V1.Model.OrgPolicy{}]) end @doc """ Returns permissions that a caller has on the specified Organization. The &#x60;resource&#x60; field should be the organization&#39;s resource name, e.g. \&quot;organizations/123\&quot;. There are no permissions required for making this API call. ## Parameters - connection (GoogleApi.CloudResourceManager.V1.Connection): Connection to server - organizations_id (String.t): Part of &#x60;resource&#x60;. REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :body (TestIamPermissionsRequest): ## Returns {:ok, %GoogleApi.CloudResourceManager.V1.Model.TestIamPermissionsResponse{}} on success {:error, info} on failure """ @spec cloudresourcemanager_organizations_test_iam_permissions( Tesla.Env.client(), String.t(), keyword() ) :: {:ok, GoogleApi.CloudResourceManager.V1.Model.TestIamPermissionsResponse.t()} | {:error, Tesla.Env.t()} def cloudresourcemanager_organizations_test_iam_permissions( connection, organizations_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/organizations/{organizationsId}:testIamPermissions", %{ "organizationsId" => URI.encode_www_form(organizations_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.CloudResourceManager.V1.Model.TestIamPermissionsResponse{}] ) end end
44.56
371
0.672172
7951454498295191f92a892d63e6192c2e860753
2,159
exs
Elixir
config/prod.exs
boqolo/boqolo
ba9a2ebcf379f5056b3836756179b49163f91d72
[ "BSD-3-Clause" ]
null
null
null
config/prod.exs
boqolo/boqolo
ba9a2ebcf379f5056b3836756179b49163f91d72
[ "BSD-3-Clause" ]
null
null
null
config/prod.exs
boqolo/boqolo
ba9a2ebcf379f5056b3836756179b49163f91d72
[ "BSD-3-Clause" ]
null
null
null
use Mix.Config # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :rayyan_site, RayyanSiteWeb.Endpoint, http: [port: {:system, "PORT"}], url: [host: "boqolo.com", port: {:system, "PORT"}], cache_static_manifest: "priv/static/cache_manifest.json", server: true, root: ".", version: Application.spec(:rayyan_web, :vsn) # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :rayyan_site, RayyanSiteWeb.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [ # port: 443, # cipher_suite: :strong, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH"), # transport_options: [socket_opts: [:inet6]] # ] # # The `cipher_suite` is set to `:strong` to support only the # latest and more secure SSL ciphers. This means old browsers # and clients may not be supported. You can set it to # `:compatible` for wider support. # # `:keyfile` and `:certfile` expect an absolute path to the key # and cert in disk or a relative path inside priv, for example # "priv/ssl/server.key". For all supported SSL configuration # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 # # We also recommend setting `force_ssl` in your endpoint, ensuring # no data is ever sent via http, always redirecting to https: # # config :rayyan_site, RayyanSiteWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # Finally import the config/prod.secret.exs which loads secrets # and configuration from environment variables. import_config "prod.secret.exs"
35.983333
66
0.710051
795166d503fd409cc06864ab2806173d7444d38e
2,710
ex
Elixir
clients/games_management/lib/google_api/games_management/v1management/model/games_player_experience_info_resource.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/games_management/lib/google_api/games_management/v1management/model/games_player_experience_info_resource.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/games_management/lib/google_api/games_management/v1management/model/games_player_experience_info_resource.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.GamesManagement.V1management.Model.GamesPlayerExperienceInfoResource do @moduledoc """ This is a JSON template for 1P/3P metadata about the player's experience. ## Attributes * `currentExperiencePoints` (*type:* `String.t`, *default:* `nil`) - The current number of experience points for the player. * `currentLevel` (*type:* `GoogleApi.GamesManagement.V1management.Model.GamesPlayerLevelResource.t`, *default:* `nil`) - The current level of the player. * `lastLevelUpTimestampMillis` (*type:* `String.t`, *default:* `nil`) - The timestamp when the player was leveled up, in millis since Unix epoch UTC. * `nextLevel` (*type:* `GoogleApi.GamesManagement.V1management.Model.GamesPlayerLevelResource.t`, *default:* `nil`) - The next level of the player. If the current level is the maximum level, this should be same as the current level. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :currentExperiencePoints => String.t(), :currentLevel => GoogleApi.GamesManagement.V1management.Model.GamesPlayerLevelResource.t(), :lastLevelUpTimestampMillis => String.t(), :nextLevel => GoogleApi.GamesManagement.V1management.Model.GamesPlayerLevelResource.t() } field(:currentExperiencePoints) field(:currentLevel, as: GoogleApi.GamesManagement.V1management.Model.GamesPlayerLevelResource) field(:lastLevelUpTimestampMillis) field(:nextLevel, as: GoogleApi.GamesManagement.V1management.Model.GamesPlayerLevelResource) end defimpl Poison.Decoder, for: GoogleApi.GamesManagement.V1management.Model.GamesPlayerExperienceInfoResource do def decode(value, options) do GoogleApi.GamesManagement.V1management.Model.GamesPlayerExperienceInfoResource.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.GamesManagement.V1management.Model.GamesPlayerExperienceInfoResource do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
43.709677
236
0.756089
7951883e9be488d5234470e42e80a4d7c726df0b
4,372
ex
Elixir
lib/glimesh_web/controllers/user_auth.ex
YFG-Online/glimesh.tv
5d9bb6f4ab383897c383bf33bbfac783b09e294e
[ "MIT" ]
null
null
null
lib/glimesh_web/controllers/user_auth.ex
YFG-Online/glimesh.tv
5d9bb6f4ab383897c383bf33bbfac783b09e294e
[ "MIT" ]
null
null
null
lib/glimesh_web/controllers/user_auth.ex
YFG-Online/glimesh.tv
5d9bb6f4ab383897c383bf33bbfac783b09e294e
[ "MIT" ]
null
null
null
defmodule GlimeshWeb.UserAuth do import Plug.Conn import Phoenix.Controller alias Glimesh.Accounts alias GlimeshWeb.Router.Helpers, as: Routes # Make the remember me cookie valid for 60 days. # If you want bump or reduce this value, also change # the token expiry itself in UserToken. @max_age 60 * 60 * 24 * 60 @remember_me_cookie "user_remember_me" @remember_me_options [sign: true, max_age: @max_age] @doc """ Logs the user in. It renews the session ID and clears the whole session to avoid fixation attacks. See the renew_session function to customize this behaviour. It also sets a `:live_socket_id` key in the session, so LiveView sessions are identified and automatically disconnected on log out. The line can be safely removed if you are not using LiveView. """ def log_in_user(conn, user, params \\ %{}) do token = Accounts.generate_user_session_token(user) user_return_to = get_session(conn, :user_return_to) conn |> renew_session() |> put_session(:user_token, token) |> put_session(:live_socket_id, "users_sessions:#{Base.url_encode64(token)}") |> maybe_write_remember_me_cookie(token, params) |> redirect(to: user_return_to || signed_in_path(conn)) end defp maybe_write_remember_me_cookie(conn, token, %{"remember_me" => "true"}) do put_resp_cookie(conn, @remember_me_cookie, token, @remember_me_options) end defp maybe_write_remember_me_cookie(conn, _token, _params) do conn end # This function renews the session ID and erases the whole # session to avoid fixation attacks. If there is any data # in the session you may want to preserve after log in/log out, # you must explicitly fetch the session data before clearing # and then immediately set it after clearing, for example: # # defp renew_session(conn) do # preferred_locale = get_session(conn, :preferred_locale) # # conn # |> configure_session(renew: true) # |> clear_session() # |> put_session(:preferred_locale, preferred_locale) # end # defp renew_session(conn) do conn |> configure_session(renew: true) |> clear_session() end @doc """ Logs the user out. It clears all session data for safety. See renew_session. """ def log_out_user(conn) do user_token = get_session(conn, :user_token) user_token && Accounts.delete_session_token(user_token) if live_socket_id = get_session(conn, :live_socket_id) do GlimeshWeb.Endpoint.broadcast(live_socket_id, "disconnect", %{}) end conn |> renew_session() |> delete_resp_cookie(@remember_me_cookie) |> redirect(to: "/") end @doc """ Authenticates the user by looking into the session and remember me token. """ def fetch_current_user(conn, _opts) do {user_token, conn} = ensure_user_token(conn) user = user_token && Accounts.get_user_by_session_token(user_token) assign(conn, :current_user, user) end defp ensure_user_token(conn) do if user_token = get_session(conn, :user_token) do {user_token, conn} else conn = fetch_cookies(conn, signed: [@remember_me_cookie]) if user_token = conn.cookies[@remember_me_cookie] do {user_token, put_session(conn, :user_token, user_token)} else {nil, conn} end end end @doc """ Used for routes that require the user to not be authenticated. """ def redirect_if_user_is_authenticated(conn, _opts) do if conn.assigns[:current_user] do conn |> redirect(to: signed_in_path(conn)) |> halt() else conn end end @doc """ Used for routes that require the user to be authenticated. If you want to enforce the user e-mail is confirmed before they use the application at all, here would be a good place. """ def require_authenticated_user(conn, _opts) do if conn.assigns[:current_user] do conn else conn |> put_flash(:error, "You must log in to access this page.") |> maybe_store_return_to() |> redirect(to: Routes.user_session_path(conn, :new)) |> halt() end end defp maybe_store_return_to(%{method: "GET", request_path: request_path} = conn) do put_session(conn, :user_return_to, request_path) end defp maybe_store_return_to(conn), do: conn defp signed_in_path(_conn), do: "/" end
29.146667
84
0.694876
79518b3c87760fc5205aeb0bbf0e0402b99ef714
489
ex
Elixir
bowman/lib/bowman_web/views/error_view.ex
mudphone/bowman
e916d0921f259f2c9dcba9313a64402b0bc43f9e
[ "MIT" ]
null
null
null
bowman/lib/bowman_web/views/error_view.ex
mudphone/bowman
e916d0921f259f2c9dcba9313a64402b0bc43f9e
[ "MIT" ]
3
2020-07-17T01:30:50.000Z
2021-05-08T20:23:35.000Z
bowman/lib/bowman_web/views/error_view.ex
mudphone/bowman
e916d0921f259f2c9dcba9313a64402b0bc43f9e
[ "MIT" ]
null
null
null
defmodule BowmanWeb.ErrorView do use BowmanWeb, :view # If you want to customize a particular status code # for a certain format, you may uncomment below. # def render("500.html", _assigns) do # "Internal Server Error" # end # By default, Phoenix returns the status message from # the template name. For example, "404.html" becomes # "Not Found". def template_not_found(template, _assigns) do Phoenix.Controller.status_message_from_template(template) end end
28.764706
61
0.734151
7951a3e92d647f5bc5ab12a90e846e31cf1de497
5,679
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/http_route_rule.ex
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/http_route_rule.ex
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/http_route_rule.ex
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "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.HttpRouteRule do @moduledoc """ An HttpRouteRule specifies how to match an HTTP request and the corresponding routing action that load balancing proxies will perform. ## Attributes * `description` (*type:* `String.t`, *default:* `nil`) - The short description conveying the intent of this routeRule. The description can have a maximum length of 1024 characters. * `headerAction` (*type:* `GoogleApi.Compute.V1.Model.HttpHeaderAction.t`, *default:* `nil`) - Specifies changes to request and response headers that need to take effect for the selected backendService. The headerAction specified here are applied before the matching pathMatchers[].headerAction and after pathMatchers[].routeRules[].routeAction.weightedBackendService.backendServiceWeightAction[].headerAction Note that headerAction is not supported for Loadbalancers that have their loadBalancingScheme set to EXTERNAL. * `matchRules` (*type:* `list(GoogleApi.Compute.V1.Model.HttpRouteRuleMatch.t)`, *default:* `nil`) - The list of criteria for matching attributes of a request to this routeRule. This list has OR semantics: the request matches this routeRule when any of the matchRules are satisfied. However predicates within a given matchRule have AND semantics. All predicates within a matchRule must match for the request to match the rule. * `priority` (*type:* `integer()`, *default:* `nil`) - For routeRules within a given pathMatcher, priority determines the order in which load balancer will interpret routeRules. RouteRules are evaluated in order of priority, from the lowest to highest number. The priority of a rule decreases as its number increases (1, 2, 3, N+1). The first rule that matches the request is applied. You cannot configure two or more routeRules with the same priority. Priority for each rule must be set to a number between 0 and 2147483647 inclusive. Priority numbers can have gaps, which enable you to add or remove rules in the future without affecting the rest of the rules. For example, 1, 2, 3, 4, 5, 9, 12, 16 is a valid series of priority numbers to which you could add rules numbered from 6 to 8, 10 to 11, and 13 to 15 in the future without any impact on existing rules. * `routeAction` (*type:* `GoogleApi.Compute.V1.Model.HttpRouteAction.t`, *default:* `nil`) - In response to a matching matchRule, the load balancer performs advanced routing actions like URL rewrites, header transformations, etc. prior to forwarding the request to the selected backend. If routeAction specifies any weightedBackendServices, service must not be set. Conversely if service is set, routeAction cannot contain any weightedBackendServices. Only one of urlRedirect, service or routeAction.weightedBackendService must be set. UrlMaps for external HTTP(S) load balancers support only the urlRewrite action within a routeRule's routeAction. * `service` (*type:* `String.t`, *default:* `nil`) - The full or partial URL of the backend service resource to which traffic is directed if this rule is matched. If routeAction is additionally specified, advanced routing actions like URL Rewrites, etc. take effect prior to sending the request to the backend. However, if service is specified, routeAction cannot contain any weightedBackendService s. Conversely, if routeAction specifies any weightedBackendServices, service must not be specified. Only one of urlRedirect, service or routeAction.weightedBackendService must be set. * `urlRedirect` (*type:* `GoogleApi.Compute.V1.Model.HttpRedirectAction.t`, *default:* `nil`) - When this rule is matched, the request is redirected to a URL specified by urlRedirect. If urlRedirect is specified, service or routeAction must not be set. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :description => String.t(), :headerAction => GoogleApi.Compute.V1.Model.HttpHeaderAction.t(), :matchRules => list(GoogleApi.Compute.V1.Model.HttpRouteRuleMatch.t()), :priority => integer(), :routeAction => GoogleApi.Compute.V1.Model.HttpRouteAction.t(), :service => String.t(), :urlRedirect => GoogleApi.Compute.V1.Model.HttpRedirectAction.t() } field(:description) field(:headerAction, as: GoogleApi.Compute.V1.Model.HttpHeaderAction) field(:matchRules, as: GoogleApi.Compute.V1.Model.HttpRouteRuleMatch, type: :list) field(:priority) field(:routeAction, as: GoogleApi.Compute.V1.Model.HttpRouteAction) field(:service) field(:urlRedirect, as: GoogleApi.Compute.V1.Model.HttpRedirectAction) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.HttpRouteRule do def decode(value, options) do GoogleApi.Compute.V1.Model.HttpRouteRule.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.HttpRouteRule do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
76.743243
503
0.760697
7951a87727c152af2bff2b7cf8870d6fe75ab5b5
313
ex
Elixir
lib/hologram/compiler/module_def_aggregators/elixir_atom.ex
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
40
2022-01-19T20:27:36.000Z
2022-03-31T18:17:41.000Z
lib/hologram/compiler/module_def_aggregators/elixir_atom.ex
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
42
2022-02-03T22:52:43.000Z
2022-03-26T20:57:32.000Z
lib/hologram/compiler/module_def_aggregators/elixir_atom.ex
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
3
2022-02-10T04:00:37.000Z
2022-03-08T22:07:45.000Z
# TODO: test alias Hologram.Compiler.{ModuleDefAggregator, Reflection} alias Hologram.Compiler.IR.ModuleType defimpl ModuleDefAggregator, for: Atom do def aggregate(module) do if Reflection.is_module?(module) do %ModuleType{module: module} |> ModuleDefAggregator.aggregate() end end end
22.357143
57
0.747604
7951bfe5af7f402e8489dd26af22e56ff2fd7aec
114
ex
Elixir
lib/control/monoid/list.ex
slogsdon/elixir-control
4136ce4fa6b62368b5f3bdf38708c7e28c4b256b
[ "MIT" ]
23
2015-10-04T20:49:56.000Z
2022-01-09T19:35:52.000Z
lib/control/monoid/list.ex
slogsdon/elixir-control
4136ce4fa6b62368b5f3bdf38708c7e28c4b256b
[ "MIT" ]
null
null
null
lib/control/monoid/list.ex
slogsdon/elixir-control
4136ce4fa6b62368b5f3bdf38708c7e28c4b256b
[ "MIT" ]
2
2015-10-11T22:07:56.000Z
2015-12-21T13:56:07.000Z
defimpl Control.Monoid, for: List do def mempty(_), do: [] defdelegate mappend(a, b), to: Kernel, as: :++ end
22.8
48
0.649123
7951c3a40a11090d882471d72a270ccd047897c1
1,581
ex
Elixir
clients/composer/lib/google_api/composer/v1/model/encryption_config.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/composer/lib/google_api/composer/v1/model/encryption_config.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/composer/lib/google_api/composer/v1/model/encryption_config.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.Composer.V1.Model.EncryptionConfig do @moduledoc """ The encryption options for the Cloud Composer environment and its dependencies. ## Attributes * `kmsKeyName` (*type:* `String.t`, *default:* `nil`) - Optional. Customer-managed Encryption Key available through Google's Key Management Service. Cannot be updated. If not specified, Google-managed key will be used. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :kmsKeyName => String.t() } field(:kmsKeyName) end defimpl Poison.Decoder, for: GoogleApi.Composer.V1.Model.EncryptionConfig do def decode(value, options) do GoogleApi.Composer.V1.Model.EncryptionConfig.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Composer.V1.Model.EncryptionConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.638298
222
0.748261
7951d1334f66b27f608ab4c21cab8036fa11b05f
623
ex
Elixir
lib/hacker_news.ex
vasuadari/hacker_news_alert
9d256714bfd940ed083681e0e2b6d2ea1fa3f98e
[ "MIT" ]
3
2020-03-30T08:40:46.000Z
2020-04-14T05:53:13.000Z
lib/hacker_news.ex
vasuadari/hacker_news_alert
9d256714bfd940ed083681e0e2b6d2ea1fa3f98e
[ "MIT" ]
3
2020-03-28T21:31:07.000Z
2020-03-30T09:10:36.000Z
lib/hacker_news.ex
vasuadari/hacker_news_alert
9d256714bfd940ed083681e0e2b6d2ea1fa3f98e
[ "MIT" ]
3
2020-03-30T08:48:09.000Z
2020-04-24T14:35:09.000Z
defmodule HackerNews do alias HackerNews.{RSSReader, EmailComposer} @from Application.get_env(:hacker_news_alert, HackerNews.Mailer) |> Keyword.get(:username) def send_top_news_alert(name, email, news_items \\ fetch_top_news()) do compose_email_with_top_news(name, email, news_items) |> HackerNews.Mailer.deliver() end def compose_email_with_top_news(name, email, news_items \\ fetch_top_news()) do EmailComposer.compose( {"Hacker News", @from}, {name, email}, %{items: news_items}, EmailComposer.TopNews ) end def fetch_top_news do RSSReader.items() end end
25.958333
92
0.714286
79521ea28516eb8ee49d6cd51a4349158c19456d
2,225
ex
Elixir
lib/utils.ex
RiverFinancial/bitcoinex
c3797213425d50b4932ab0d2f0e7a0cb43fa2c7b
[ "Unlicense" ]
24
2020-03-18T02:05:54.000Z
2022-03-29T18:13:54.000Z
lib/utils.ex
RiverFinancial/bitcoinex
c3797213425d50b4932ab0d2f0e7a0cb43fa2c7b
[ "Unlicense" ]
18
2020-01-23T16:39:12.000Z
2022-03-02T14:35:26.000Z
lib/utils.ex
SachinMeier/bitcoinex
3b74de9889ab44ad3d204e1bbfd124f8e7419208
[ "Unlicense" ]
7
2020-02-11T10:22:54.000Z
2021-12-23T21:35:01.000Z
defmodule Bitcoinex.Utils do @moduledoc """ Contains useful utility functions used in Bitcoinex. """ @spec sha256(iodata()) :: binary def sha256(str) do :crypto.hash(:sha256, str) end @spec replicate(term(), integer()) :: list(term()) def replicate(_num, 0) do [] end def replicate(x, num) when x > 0 do for _ <- 1..num, do: x end @spec double_sha256(iodata()) :: binary def double_sha256(preimage) do :crypto.hash( :sha256, :crypto.hash(:sha256, preimage) ) end @spec hash160(iodata()) :: binary def hash160(preimage) do :crypto.hash( :ripemd160, :crypto.hash(:sha256, preimage) ) end @typedoc """ The pad_type describes the padding to use. """ @type pad_type :: :leading | :trailing @doc """ pads binary according to the byte length and the padding type. A binary can be padded with leading or trailing zeros. """ @spec pad(bin :: binary, byte_len :: integer, pad_type :: pad_type) :: binary def pad(bin, byte_len, _pad_type) when is_binary(bin) and byte_size(bin) == byte_len do bin end def pad(bin, byte_len, pad_type) when is_binary(bin) and pad_type == :leading do pad_len = 8 * byte_len - byte_size(bin) * 8 <<0::size(pad_len)>> <> bin end def pad(bin, byte_len, pad_type) when is_binary(bin) and pad_type == :trailing do pad_len = 8 * byte_len - byte_size(bin) * 8 bin <> <<0::size(pad_len)>> end def int_to_little(i, p) do i |> :binary.encode_unsigned(:little) |> pad(p, :trailing) end def little_to_int(i), do: :binary.decode_unsigned(i, :little) def encode_int(i) when i > 0 do cond do i < 0xFD -> :binary.encode_unsigned(i) i <= 0xFFFF -> <<0xFD>> <> int_to_little(i, 2) i <= 0xFFFFFFFF -> <<0xFE>> <> int_to_little(i, 4) i <= 0xFFFFFFFFFFFFFFFF -> <<0xFF>> <> int_to_little(i, 8) true -> {:error, "invalid integer size"} end end def hex_to_bin(str) do str |> String.downcase() |> Base.decode16(case: :lower) |> case do # In case of error, its already binary or its invalid :error -> {:error, "invalid string"} # valid binary {:ok, bin} -> bin end end end
25
119
0.616629
795229fb5e76d1acf701a9913309bad68851b75f
5,418
ex
Elixir
clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/identitytoolkit_relyingparty_set_account_info_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/identitytoolkit_relyingparty_set_account_info_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/identitytoolkit_relyingparty_set_account_info_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.IdentityToolkit.V3.Model.IdentitytoolkitRelyingpartySetAccountInfoRequest do @moduledoc """ Request to set the account information. ## Attributes * `captchaChallenge` (*type:* `String.t`, *default:* `nil`) - The captcha challenge. * `captchaResponse` (*type:* `String.t`, *default:* `nil`) - Response to the captcha. * `createdAt` (*type:* `String.t`, *default:* `nil`) - The timestamp when the account is created. * `customAttributes` (*type:* `String.t`, *default:* `nil`) - The custom attributes to be set in the user's id token. * `delegatedProjectNumber` (*type:* `String.t`, *default:* `nil`) - GCP project number of the requesting delegated app. Currently only intended for Firebase V1 migration. * `deleteAttribute` (*type:* `list(String.t)`, *default:* `nil`) - The attributes users request to delete. * `deleteProvider` (*type:* `list(String.t)`, *default:* `nil`) - The IDPs the user request to delete. * `disableUser` (*type:* `boolean()`, *default:* `nil`) - Whether to disable the user. * `displayName` (*type:* `String.t`, *default:* `nil`) - The name of the user. * `email` (*type:* `String.t`, *default:* `nil`) - The email of the user. * `emailVerified` (*type:* `boolean()`, *default:* `nil`) - Mark the email as verified or not. * `idToken` (*type:* `String.t`, *default:* `nil`) - The GITKit token of the authenticated user. * `instanceId` (*type:* `String.t`, *default:* `nil`) - Instance id token of the app. * `lastLoginAt` (*type:* `String.t`, *default:* `nil`) - Last login timestamp. * `localId` (*type:* `String.t`, *default:* `nil`) - The local ID of the user. * `oobCode` (*type:* `String.t`, *default:* `nil`) - The out-of-band code of the change email request. * `password` (*type:* `String.t`, *default:* `nil`) - The new password of the user. * `phoneNumber` (*type:* `String.t`, *default:* `nil`) - Privileged caller can update user with specified phone number. * `photoUrl` (*type:* `String.t`, *default:* `nil`) - The photo url of the user. * `provider` (*type:* `list(String.t)`, *default:* `nil`) - The associated IDPs of the user. * `returnSecureToken` (*type:* `boolean()`, *default:* `nil`) - Whether return sts id token and refresh token instead of gitkit token. * `upgradeToFederatedLogin` (*type:* `boolean()`, *default:* `nil`) - Mark the user to upgrade to federated login. * `validSince` (*type:* `String.t`, *default:* `nil`) - Timestamp in seconds for valid login token. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :captchaChallenge => String.t() | nil, :captchaResponse => String.t() | nil, :createdAt => String.t() | nil, :customAttributes => String.t() | nil, :delegatedProjectNumber => String.t() | nil, :deleteAttribute => list(String.t()) | nil, :deleteProvider => list(String.t()) | nil, :disableUser => boolean() | nil, :displayName => String.t() | nil, :email => String.t() | nil, :emailVerified => boolean() | nil, :idToken => String.t() | nil, :instanceId => String.t() | nil, :lastLoginAt => String.t() | nil, :localId => String.t() | nil, :oobCode => String.t() | nil, :password => String.t() | nil, :phoneNumber => String.t() | nil, :photoUrl => String.t() | nil, :provider => list(String.t()) | nil, :returnSecureToken => boolean() | nil, :upgradeToFederatedLogin => boolean() | nil, :validSince => String.t() | nil } field(:captchaChallenge) field(:captchaResponse) field(:createdAt) field(:customAttributes) field(:delegatedProjectNumber) field(:deleteAttribute, type: :list) field(:deleteProvider, type: :list) field(:disableUser) field(:displayName) field(:email) field(:emailVerified) field(:idToken) field(:instanceId) field(:lastLoginAt) field(:localId) field(:oobCode) field(:password) field(:phoneNumber) field(:photoUrl) field(:provider, type: :list) field(:returnSecureToken) field(:upgradeToFederatedLogin) field(:validSince) end defimpl Poison.Decoder, for: GoogleApi.IdentityToolkit.V3.Model.IdentitytoolkitRelyingpartySetAccountInfoRequest do def decode(value, options) do GoogleApi.IdentityToolkit.V3.Model.IdentitytoolkitRelyingpartySetAccountInfoRequest.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.IdentityToolkit.V3.Model.IdentitytoolkitRelyingpartySetAccountInfoRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
45.915254
174
0.653378
795260996a7cdcbee8892ff047384551f4929709
1,396
exs
Elixir
test/controllers/load_tariff_plan_controller_test.exs
zombalo/cgrates_web_jsonapi
47845be4311839fe180cc9f2c7c6795649da4430
[ "MIT" ]
null
null
null
test/controllers/load_tariff_plan_controller_test.exs
zombalo/cgrates_web_jsonapi
47845be4311839fe180cc9f2c7c6795649da4430
[ "MIT" ]
null
null
null
test/controllers/load_tariff_plan_controller_test.exs
zombalo/cgrates_web_jsonapi
47845be4311839fe180cc9f2c7c6795649da4430
[ "MIT" ]
null
null
null
defmodule CgratesWebJsonapi.LoadTariffPlanControllerTest do use CgratesWebJsonapi.ConnCase import CgratesWebJsonapi.Factory import Mock setup do user = insert :user conn = build_conn() |> put_req_header("accept", "application/vnd.api+json") |> put_req_header("content-type", "application/vnd.api+json") |> Guardian.Plug.api_sign_in( user, :token, perms: %{default: [:read, :write]} ) {:ok, conn: conn} end test "executes LoadTariffPlanFromStorDb when data is valid", %{conn: conn} do with_mock CgratesWebJsonapi.Cgrates.Adapter, [ execute: fn(_params) -> %{ "result" => "OK", "error" => nil, "id" => nil } end ] do conn = post(conn, load_tariff_plan_path(conn, :create), %{ "meta" => %{}, "data" => %{ "attributes" => %{ "tpid" => "tp", "flush-db" => false, "dry-run" => false, "validate" => true }, } }) |> doc assert json_response(conn, 201) end end test "does not executes LoadTariffPlanFromStorDb when data is invalid", %{conn: conn} do assert_error_sent 400, fn -> conn = post(conn, load_tariff_plan_path(conn, :create), %{ "data" => %{ "attributes" => %{} } }) |> doc end end end
24.068966
90
0.539398
7952782cc3a21a8cc07ff881cbf7567a4126a675
3,929
exs
Elixir
mix.exs
phanmn/swoosh
02faff95dc586d57130c598a498263a1f37f7d72
[ "MIT" ]
null
null
null
mix.exs
phanmn/swoosh
02faff95dc586d57130c598a498263a1f37f7d72
[ "MIT" ]
null
null
null
mix.exs
phanmn/swoosh
02faff95dc586d57130c598a498263a1f37f7d72
[ "MIT" ]
null
null
null
defmodule Swoosh.Mixfile do use Mix.Project @source_url "https://github.com/swoosh/swoosh" @version "1.6.3" def project do [ app: :swoosh, version: @version, elixir: "~> 1.10", elixirc_paths: elixirc_paths(Mix.env()), consolidate_protocols: Mix.env() != :test, build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, deps: deps(), aliases: aliases(), # Hex description: description(), package: package(), # Docs name: "Swoosh", source_url: @source_url, homepage_url: @source_url, docs: docs(), preferred_cli_env: [ docs: :docs, "hex.publish": :docs ], # Suppress warnings xref: [ exclude: [ :hackney, :gen_smtp_client, :mimemail, Finch, Plug.Adapters.Cowboy, Plug.Conn.Query, Plug.Cowboy, Mail, Mail.Message, Mail.Renderers.RFC2822, {IEx, :started?, 0} ] ] ] end def application do [ extra_applications: [:logger, :xmerl], mod: {Swoosh.Application, []}, env: [json_library: Jason, api_client: Swoosh.ApiClient.Hackney] ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] defp deps do [ {:mime, "~> 1.1 or ~> 2.0"}, {:jason, "~> 1.0"}, {:telemetry, "~> 0.4.2 or ~> 1.0"}, {:hackney, "~> 1.9", optional: true}, {:finch, "~> 0.6", optional: true}, {:mail, "~> 0.2", optional: true}, {:gen_smtp, "~> 0.13 or ~> 1.0", optional: true}, {:cowboy, "~> 1.1 or ~> 2.4", optional: true}, {:plug_cowboy, ">= 1.0.0", optional: true}, {:bypass, "~> 2.1", only: :test}, {:ex_doc, "~> 0.26", only: :docs, runtime: false} ] end defp docs do [ source_ref: "v#{@version}", main: "Swoosh", canonical: "http://hexdocs.pm/swoosh", source_url: @source_url, extras: [ "CHANGELOG.md", "CODE_OF_CONDUCT.md", "CONTRIBUTING.md" ], groups_for_modules: [ Email: [ Swoosh.Email, Swoosh.Email.Recipient ], Adapters: adapter_modules(), "Api Client": [ Swoosh.ApiClient, Swoosh.ApiClient.Finch, Swoosh.ApiClient.Hackney ], Plug: Plug.Swoosh.MailboxPreview, Test: Swoosh.TestAssertions, Deprecated: Swoosh.Adapters.OhMySmtp ] ] end defp adapter_modules do Path.wildcard("lib/swoosh/adapters/*.ex") |> Enum.map(fn path -> content = File.read!(path) [_, module] = Regex.run(~r/\Adefmodule (.+) do/, content) module |> String.split(".") |> Module.concat() end) |> Kernel.--([Swoosh.Adapters.OhMySmtp]) end defp aliases do ["test.ci": &test_ci/1] end defp test_ci(args) do args = if IO.ANSI.enabled?(), do: ["--color" | args], else: ["--no-color" | args] args = if System.get_env("TRAVIS_SECURE_ENV_VARS") == "true", do: ["--include=integration" | args], else: args {_, res} = System.cmd( "mix", ["test" | args], into: IO.binstream(:stdio, :line), env: [{"MIX_ENV", "test"}] ) if res > 0 do System.at_exit(fn _ -> exit({:shutdown, 1}) end) end end defp description do """ Compose, deliver and test your emails easily in Elixir. Supports SMTP, Sendgrid, Mandrill, Postmark and Mailgun out of the box. Preview your mails in the browser. Great integration with Phoenix. """ end defp package do [ maintainers: ["Steve Domin", "Baris Balic", "Po Chen"], licenses: ["MIT"], links: %{ "Changelog" => "#{@source_url}/blob/main/CHANGELOG.md", "GitHub" => @source_url } ] end end
24.253086
85
0.531178
7952868c287cced43e309aef61a02b4dee2636c7
15,694
ex
Elixir
lib/phoenix/live_dashboard/system_info.ex
wojtekmach/phoenix_live_dashboard
5b0a001bd5772ffc1e9de82b954a62c860490fc5
[ "MIT" ]
1
2020-06-11T00:39:12.000Z
2020-06-11T00:39:12.000Z
lib/phoenix/live_dashboard/system_info.ex
wojtekmach/phoenix_live_dashboard
5b0a001bd5772ffc1e9de82b954a62c860490fc5
[ "MIT" ]
1
2020-06-11T01:43:00.000Z
2020-06-16T04:48:00.000Z
lib/phoenix/live_dashboard/system_info.ex
wojtekmach/phoenix_live_dashboard
5b0a001bd5772ffc1e9de82b954a62c860490fc5
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveDashboard.SystemInfo do # Helpers for fetching and formatting system info. @moduledoc false def ensure_loaded(node) do case :rpc.call(node, :code, :is_loaded, [__MODULE__]) do {:file, _} -> maybe_replace(node, fetch_capabilities(node)) false -> load(node) {:error, reason} -> raise("Failed to load #{__MODULE__} on #{node}: #{inspect(reason)}") end end defp maybe_replace(node, capabilities) do if !capabilities.dashboard && capabilities.system_info != __MODULE__.__info__(:md5) do load(node) else capabilities end end defp load(node) do {_module, binary, filename} = :code.get_object_code(__MODULE__) :rpc.call(node, :code, :load_binary, [__MODULE__, filename, binary]) fetch_capabilities(node) end ## Fetchers def fetch_processes(node, search, sort_by, sort_dir, limit) do search = search && String.downcase(search) :rpc.call(node, __MODULE__, :processes_callback, [search, sort_by, sort_dir, limit]) end def fetch_ets(node, search, sort_by, sort_dir, limit) do search = search && String.downcase(search) :rpc.call(node, __MODULE__, :ets_callback, [search, sort_by, sort_dir, limit]) end def fetch_sockets(node, search, sort_by, sort_dir, limit) do search = search && String.downcase(search) :rpc.call(node, __MODULE__, :sockets_callback, [search, sort_by, sort_dir, limit]) end def fetch_socket_info(port, keys) do :rpc.call(node(port), __MODULE__, :socket_info_callback, [port, keys]) end def fetch_process_info(pid, keys) do :rpc.call(node(pid), __MODULE__, :process_info_callback, [pid, keys]) end def fetch_ports(node, search, sort_by, sort_dir, limit) do search = search && String.downcase(search) :rpc.call(node, __MODULE__, :ports_callback, [search, sort_by, sort_dir, limit]) end def fetch_applications(node, search, sort_by, sort_dir, limit) do :rpc.call(node, __MODULE__, :applications_info_callback, [search, sort_by, sort_dir, limit]) end def fetch_port_info(port, keys) do :rpc.call(node(port), __MODULE__, :port_info_callback, [port, keys]) end def fetch_ets_info(node, ref) do :rpc.call(node, __MODULE__, :ets_info_callback, [ref]) end def fetch_system_info(node, keys) do :rpc.call(node, __MODULE__, :info_callback, [keys]) end def fetch_system_usage(node) do :rpc.call(node, __MODULE__, :usage_callback, []) end def fetch_os_mon_info(node) do :rpc.call(node, __MODULE__, :os_mon_callback, []) end def fetch_capabilities(node) do :rpc.call(node, __MODULE__, :capabilities_callback, []) end def fetch_app_tree(node, application) do :rpc.call(node, __MODULE__, :app_tree_callback, [application]) end ## System callbacks @doc false def info_callback(keys) do %{ system_info: %{ banner: :erlang.system_info(:system_version), elixir_version: System.version(), phoenix_version: Application.spec(:phoenix, :vsn) || "None", dashboard_version: Application.spec(:phoenix_live_dashboard, :vsn) || "None", system_architecture: :erlang.system_info(:system_architecture) }, system_limits: %{ atoms: :erlang.system_info(:atom_limit), ports: :erlang.system_info(:port_limit), processes: :erlang.system_info(:process_limit) }, system_usage: usage_callback(), environment: env_info_callback(keys) } end @doc false def usage_callback do %{ atoms: :erlang.system_info(:atom_count), ports: :erlang.system_info(:port_count), processes: :erlang.system_info(:process_count), io: io(), uptime: :erlang.statistics(:wall_clock) |> elem(0), memory: memory(), total_run_queue: :erlang.statistics(:total_run_queue_lengths_all), cpu_run_queue: :erlang.statistics(:total_run_queue_lengths) } end @doc false def capabilities_callback do %{ system_info: __MODULE__.__info__(:md5), dashboard: Process.whereis(Phoenix.LiveDashboard.DynamicSupervisor), os_mon: Application.get_application(:os_mon) } end defp io() do {{:input, input}, {:output, output}} = :erlang.statistics(:io) {input, output} end defp memory() do memory = :erlang.memory() total = memory[:total] process = memory[:processes] atom = memory[:atom] binary = memory[:binary] code = memory[:code] ets = memory[:ets] %{ total: total, process: process, atom: atom, binary: binary, code: code, ets: ets, other: total - process - atom - binary - code - ets } end ## Process Callbacks @process_info [ :registered_name, :initial_call, :memory, :reductions, :message_queue_len, :current_function ] @doc false def processes_callback(search, sort_by, sort_dir, limit) do multiplier = sort_dir_multipler(sort_dir) processes = for pid <- Process.list(), info = process_info(pid), show_process?(info, search) do sorter = info[sort_by] * multiplier {sorter, info} end count = if search, do: length(processes), else: :erlang.system_info(:process_count) processes = processes |> Enum.sort() |> Enum.take(limit) |> Enum.map(&elem(&1, 1)) {processes, count} end defp process_info(pid) do if info = Process.info(pid, @process_info) do [{:registered_name, name}, {:initial_call, initial_call} | rest] = info name_or_initial_call = if is_atom(name), do: inspect(name), else: format_call(initial_call) [pid: pid, name_or_initial_call: name_or_initial_call] ++ rest end end defp show_process?(_, nil) do true end defp show_process?(info, search) do pid = info[:pid] |> :erlang.pid_to_list() |> List.to_string() name_or_call = info[:name_or_initial_call] pid =~ search or String.downcase(name_or_call) =~ search end def process_info_callback(pid, keys) do case Process.info(pid, keys) do [_ | _] = info -> {:ok, info} nil -> :error end end ## Applications callbacks def applications_info_callback(search, sort_by, sort_dir, limit) do sorter = if sort_dir == :asc, do: &<=/2, else: &>=/2 started_apps_set = started_apps_set() apps = for {name, desc, version} <- Application.loaded_applications(), description = List.to_string(desc), version = List.to_string(version), show_application?(name, description, version, search) do {state, tree?} = if name in started_apps_set, do: {:started, is_pid(:application_controller.get_master(name))}, else: {:loaded, false} [name: name, description: description, version: version, state: state, tree?: tree?] end count = length(apps) apps = apps |> Enum.sort_by(&Keyword.fetch!(&1, sort_by), sorter) |> Enum.take(limit) {apps, count} end defp show_application?(_, _, _, nil) do true end defp show_application?(name, desc, version, search) do Atom.to_string(name) =~ search or String.downcase(desc) =~ search or version =~ search end defp started_apps_set() do Application.started_applications() |> Enum.map(fn {name, _, _} -> name end) |> MapSet.new() end def app_tree_callback(app) do case :application_controller.get_master(app) do :undefined -> :error master -> {child, _app} = :application_master.get_child(master) {children, seen} = sup_tree(child, %{master => true, child => true}) {children, _seen} = links_tree(children, master, seen) case get_ancestor(child) do nil -> {{:master, master, []}, [to_node(:supervisor, child, children)]} ancestor -> {{:master, master, []}, [{{:ancestor, ancestor, []}, [to_node(:supervisor, child, children)]}]} end end end defp get_ancestor(master) do {_, dictionary} = :erlang.process_info(master, :dictionary) case Keyword.get(dictionary, :"$ancestors") do [parent] -> parent _ -> nil end end defp sup_tree(pid, seen) do try do :supervisor.which_children(pid) catch _, _ -> {[], seen} else children -> children |> Enum.reverse() |> Enum.flat_map_reduce(seen, fn {_id, child, type, _modules}, seen -> if is_pid(child) do {children, seen} = if type == :worker, do: {[], seen}, else: sup_tree(child, seen) {[{type, child, children}], put_child(seen, child)} else {[], seen} end end) end end defp links_tree(nodes, master, seen) do Enum.map_reduce(nodes, seen, fn {type, pid, children}, seen -> {children, seen} = if children == [], do: links_children(type, pid, master, seen), else: {children, seen} {children, seen} = links_tree(children, master, seen) {to_node(type, pid, children), seen} end) end defp links_children(parent_type, pid, master, seen) do # If the parent type is a supervisor and we have no children, # then this may be a supervisor bridge, so we tag its children # as workers, otherwise they are links. type = if parent_type == :supervisor, do: :worker, else: :link case Process.info(pid, :links) do {:links, children} -> children |> Enum.reverse() |> Enum.flat_map_reduce(seen, fn child, seen -> if is_pid(child) and not has_child?(seen, child) and has_leader?(child, master) do {[{type, child, []}], put_child(seen, child)} else {[], seen} end end) _ -> {[], seen} end end defp to_node(type, pid, children) do {:registered_name, registered_name} = Process.info(pid, :registered_name) {{type, pid, registered_name}, children} end defp has_child?(seen, child), do: Map.has_key?(seen, child) defp put_child(seen, child), do: Map.put(seen, child, true) defp has_leader?(pid, gl), do: Process.info(pid, :group_leader) == {:group_leader, gl} ## Ports callbacks @inet_ports ['tcp_inet', 'udp_inet', 'sctp_inet'] @doc false def ports_callback(search, sort_by, sort_dir, limit) do multiplier = sort_dir_multipler(sort_dir) ports = for port <- Port.list(), port_info = port_info(port), show_port?(port_info, search) do sorter = port_info[sort_by] sorter = if is_integer(sorter), do: sorter * multiplier, else: 0 {sorter, port_info} end count = length(ports) ports = ports |> Enum.sort() |> Enum.take(limit) |> Enum.map(&elem(&1, 1)) {ports, count} end @doc false def port_info_callback(port, _keys) do case Port.info(port) do [_ | _] = info -> {:ok, info} nil -> :error end end defp port_info(port) do info = Port.info(port) if info && info[:name] not in @inet_ports do [port: port] ++ info end end defp show_port?(_, nil) do true end defp show_port?(info, search) do port = info[:port] |> :erlang.port_to_list() |> List.to_string() port =~ search or String.downcase(List.to_string(info[:name])) =~ search end ## ETS callbacks def ets_callback(search, sort_by, sort_dir, limit) do multiplier = sort_dir_multipler(sort_dir) tables = for ref <- :ets.all(), info = ets_info(ref), show_ets?(info, search) do sorter = info[sort_by] * multiplier {sorter, info} end count = length(tables) tables = tables |> Enum.sort() |> Enum.take(limit) |> Enum.map(&elem(&1, 1)) {tables, count} end defp ets_info(ref) do case :ets.info(ref) do :undefined -> nil info -> [name: inspect(info[:name])] ++ Keyword.delete(info, :name) end end defp show_ets?(_, nil) do true end defp show_ets?(info, search) do String.downcase(info[:name]) =~ search end def ets_info_callback(ref) do case :ets.info(ref) do :undefined -> :error info -> {:ok, info} end end ## Socket callbacks def sockets_callback(search, sort_by, sort_dir, limit) do sorter = if sort_dir == :asc, do: &<=/2, else: &>=/2 sockets = for port <- Port.list(), info = socket_info(port), show_socket?(info, search), do: info count = length(sockets) sockets = sockets |> Enum.sort_by(&Keyword.fetch!(&1, sort_by), sorter) |> Enum.take(limit) {sockets, count} end def socket_info_callback(port, keys) do case socket_info(port) do nil -> :error info -> {:ok, Keyword.take(info, keys)} end end defp socket_info(port) do with info when not is_nil(info) <- Port.info(port), true <- info[:name] in @inet_ports, {:ok, stat} <- :inet.getstat(port, [:send_oct, :recv_oct]), {:ok, state} <- :prim_inet.getstatus(port), {:ok, {_, type}} <- :prim_inet.gettype(port), module <- inet_module_lookup(port) do [ port: port, module: module, local_address: format_address(:inet.sockname(port)), foreign_address: format_address(:inet.peername(port)), state: format_socket_state(state), type: type ] ++ info ++ stat else _ -> nil end end defp show_socket?(_info, nil), do: true defp show_socket?(info, search) do info[:local_address] =~ search || info[:foreign_address] =~ search end defp inet_module_lookup(port) do case :inet_db.lookup_socket(port) do {:ok, module} -> module _ -> "prim_inet" end end ### OS_Mon callbacks def os_mon_callback() do cpu_per_core = case :cpu_sup.util([:detailed, :per_cpu]) do {:all, 0, 0, []} -> [] cores -> Enum.map(cores, fn {n, busy, non_b, _} -> {n, Map.new(busy ++ non_b)} end) end disk = case :disksup.get_disk_data() do [{'none', 0, 0}] -> [] other -> other end %{ cpu_avg1: :cpu_sup.avg1(), cpu_avg5: :cpu_sup.avg5(), cpu_avg15: :cpu_sup.avg15(), cpu_nprocs: :cpu_sup.nprocs(), cpu_per_core: cpu_per_core, disk: disk, system_mem: :memsup.get_system_memory_data() } end ### Environment info callbacks def env_info_callback(nil), do: nil def env_info_callback(keys) do Enum.map(keys, fn key -> {key, System.get_env(key)} end) end ## Helpers defp format_call({m, f, a}), do: Exception.format_mfa(m, f, a) # The address is formatted based on the implementation of `:inet.fmt_addr/2` defp format_address({:error, :enotconn}), do: "*:*" defp format_address({:error, _}), do: " " defp format_address({:ok, address}) do case address do {{0, 0, 0, 0}, port} -> "*:#{port}" {{0, 0, 0, 0, 0, 0, 0, 0}, port} -> "*:#{port}" {{127, 0, 0, 1}, port} -> "localhost:#{port}" {{0, 0, 0, 0, 0, 0, 0, 1}, port} -> "localhost:#{port}" {:local, path} -> "local:#{path}" {ip, port} -> "#{:inet.ntoa(ip)}:#{port}" end end # See `:inet.fmt_status` defp format_socket_state(flags) do case Enum.sort(flags) do [:accepting | _] -> "ACCEPTING" [:bound, :busy, :connected | _] -> "BUSY" [:bound, :connected | _] -> "CONNECTED" [:bound, :listen, :listening | _] -> "LISTENING" [:bound, :listen | _] -> "LISTEN" [:bound, :connecting | _] -> "CONNECTING" [:bound, :open] -> "BOUND" [:connected, :open] -> "CONNECTED" [:open] -> "IDLE" [] -> "CLOSED" sorted -> inspect(sorted) end end defp sort_dir_multipler(:asc), do: 1 defp sort_dir_multipler(:desc), do: -1 end
28.226619
97
0.620683
795297ada00f81bdc973e62bd2c239bd09bc9ffe
108
ex
Elixir
lib/roshambo/repo.ex
xaviRodri/roshambo
7cfd465cc40a7dc405c2854e9135f516df3809bd
[ "MIT" ]
null
null
null
lib/roshambo/repo.ex
xaviRodri/roshambo
7cfd465cc40a7dc405c2854e9135f516df3809bd
[ "MIT" ]
null
null
null
lib/roshambo/repo.ex
xaviRodri/roshambo
7cfd465cc40a7dc405c2854e9135f516df3809bd
[ "MIT" ]
null
null
null
defmodule Roshambo.Repo do use Ecto.Repo, otp_app: :roshambo, adapter: Ecto.Adapters.Postgres end
18
35
0.731481
7952aae8502cdb6cd5ef045738f3fb4d408de011
1,684
ex
Elixir
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/video_content.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/video_content.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/video_content.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.AdExchangeBuyer.V2beta1.Model.VideoContent do @moduledoc """ Video content for a creative. ## Attributes * `videoUrl` (*type:* `String.t`, *default:* `nil`) - The URL to fetch a video ad. * `videoVastXml` (*type:* `String.t`, *default:* `nil`) - The contents of a VAST document for a video ad. This document should conform to the VAST 2.0 or 3.0 standard. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :videoUrl => String.t(), :videoVastXml => String.t() } field(:videoUrl) field(:videoVastXml) end defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.VideoContent do def decode(value, options) do GoogleApi.AdExchangeBuyer.V2beta1.Model.VideoContent.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.VideoContent do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.019608
109
0.726247
7952bac1e3e5737fb690f4548b5b5dac602a9778
950
exs
Elixir
config/config.exs
meilab/meilab_blog
86fca779c8b01559440ea3f686695700e8cf5ed2
[ "MIT" ]
null
null
null
config/config.exs
meilab/meilab_blog
86fca779c8b01559440ea3f686695700e8cf5ed2
[ "MIT" ]
null
null
null
config/config.exs
meilab/meilab_blog
86fca779c8b01559440ea3f686695700e8cf5ed2
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. use Mix.Config # General application configuration config :meilab_blog, ecto_repos: [MeilabBlog.Repo] # Configures the endpoint config :meilab_blog, MeilabBlog.Endpoint, url: [host: "localhost"], secret_key_base: "D4ezXQZMVwEIU9+AbWilfP+a4ZRITHEeJPiAJVK/0KQDV+VnRM2EYhvPQRpnkH1v", render_errors: [view: MeilabBlog.ErrorView, accepts: ~w(html json)], pubsub: [name: MeilabBlog.PubSub, adapter: Phoenix.PubSub.PG2] # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{Mix.env}.exs"
33.928571
86
0.764211
7952d29e0f6a10e5305413962fa25f0115fbe147
570
ex
Elixir
lib/sipper/progress_bar.ex
jordelver/rubytapas
145b92a33e12c4b7f06d10819dafe309b395642d
[ "MIT" ]
114
2015-09-18T10:55:37.000Z
2021-02-20T01:49:49.000Z
lib/sipper/progress_bar.ex
jordelver/rubytapas
145b92a33e12c4b7f06d10819dafe309b395642d
[ "MIT" ]
26
2015-09-18T07:03:13.000Z
2017-11-06T12:35:27.000Z
lib/sipper/progress_bar.ex
jordelver/rubytapas
145b92a33e12c4b7f06d10819dafe309b395642d
[ "MIT" ]
26
2015-09-19T03:46:16.000Z
2018-10-14T21:39:22.000Z
defmodule Sipper.ProgressBar do @bar_format [ bar: "█", blank: "░", left: "", right: "", bar_color: IO.ANSI.magenta, blank_color: IO.ANSI.magenta, bytes: true, ] @spinner_format [ frames: :braille, spinner_color: IO.ANSI.magenta, ] def render(acc, total) do ProgressBar.render(acc, total, @bar_format) end def render_spinner(text, done, fun) do format = @spinner_format ++ [ text: text, done: [IO.ANSI.green, "✓", IO.ANSI.reset, " ", done], ] ProgressBar.render_spinner(format, fun) end end
20.357143
59
0.610526
7952d41cd80cffa9f1c157c7c1da018a792285e2
6,271
ex
Elixir
clients/content/lib/google_api/content/v21/api/regionalinventory.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v21/api/regionalinventory.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v21/api/regionalinventory.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Content.V21.Api.Regionalinventory do @moduledoc """ API calls for all endpoints tagged `Regionalinventory`. """ alias GoogleApi.Content.V21.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Updates regional inventory for multiple products or regions in a single request. ## Parameters * `connection` (*type:* `GoogleApi.Content.V21.Connection.t`) - Connection to server * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:body` (*type:* `GoogleApi.Content.V21.Model.RegionalinventoryCustomBatchRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Content.V21.Model.RegionalinventoryCustomBatchResponse{}}` on success * `{:error, info}` on failure """ @spec content_regionalinventory_custombatch(Tesla.Env.client(), keyword(), keyword()) :: {:ok, GoogleApi.Content.V21.Model.RegionalinventoryCustomBatchResponse.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def content_regionalinventory_custombatch(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/regionalinventory/batch", %{}) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V21.Model.RegionalinventoryCustomBatchResponse{}] ) end @doc """ Update the regional inventory of a product in your Merchant Center account. If a regional inventory with the same region ID already exists, this method updates that entry. ## Parameters * `connection` (*type:* `GoogleApi.Content.V21.Connection.t`) - Connection to server * `merchant_id` (*type:* `String.t`) - The ID of the account that contains the product. This account cannot be a multi-client account. * `product_id` (*type:* `String.t`) - The REST ID of the product for which to update the regional inventory. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:body` (*type:* `GoogleApi.Content.V21.Model.RegionalInventory.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Content.V21.Model.RegionalInventory{}}` on success * `{:error, info}` on failure """ @spec content_regionalinventory_insert( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Content.V21.Model.RegionalInventory.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def content_regionalinventory_insert( connection, merchant_id, product_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/products/{productId}/regionalinventory", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "productId" => URI.encode(product_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Content.V21.Model.RegionalInventory{}]) end end
42.659864
187
0.651092
7952d578f5ea98d96911aabff29928237d7f6293
4,125
ex
Elixir
clients/vision/lib/google_api/vision/v1/model/entity_annotation.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/vision/lib/google_api/vision/v1/model/entity_annotation.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/vision/lib/google_api/vision/v1/model/entity_annotation.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Vision.V1.Model.EntityAnnotation do @moduledoc """ Set of detected entity features. ## Attributes * `boundingPoly` (*type:* `GoogleApi.Vision.V1.Model.BoundingPoly.t`, *default:* `nil`) - Image region to which this entity belongs. Not produced for `LABEL_DETECTION` features. * `confidence` (*type:* `number()`, *default:* `nil`) - **Deprecated. Use `score` instead.** The accuracy of the entity detection in an image. For example, for an image in which the "Eiffel Tower" entity is detected, this field represents the confidence that there is a tower in the query image. Range [0, 1]. * `description` (*type:* `String.t`, *default:* `nil`) - Entity textual description, expressed in its `locale` language. * `locale` (*type:* `String.t`, *default:* `nil`) - The language code for the locale in which the entity textual `description` is expressed. * `locations` (*type:* `list(GoogleApi.Vision.V1.Model.LocationInfo.t)`, *default:* `nil`) - The location information for the detected entity. Multiple `LocationInfo` elements can be present because one location may indicate the location of the scene in the image, and another location may indicate the location of the place where the image was taken. Location information is usually present for landmarks. * `mid` (*type:* `String.t`, *default:* `nil`) - Opaque entity ID. Some IDs may be available in [Google Knowledge Graph Search API](https://developers.google.com/knowledge-graph/). * `properties` (*type:* `list(GoogleApi.Vision.V1.Model.Property.t)`, *default:* `nil`) - Some entities may have optional user-supplied `Property` (name/value) fields, such a score or string that qualifies the entity. * `score` (*type:* `number()`, *default:* `nil`) - Overall score of the result. Range [0, 1]. * `topicality` (*type:* `number()`, *default:* `nil`) - The relevancy of the ICA (Image Content Annotation) label to the image. For example, the relevancy of "tower" is likely higher to an image containing the detected "Eiffel Tower" than to an image containing a detected distant towering building, even though the confidence that there is a tower in each image may be the same. Range [0, 1]. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :boundingPoly => GoogleApi.Vision.V1.Model.BoundingPoly.t() | nil, :confidence => number() | nil, :description => String.t() | nil, :locale => String.t() | nil, :locations => list(GoogleApi.Vision.V1.Model.LocationInfo.t()) | nil, :mid => String.t() | nil, :properties => list(GoogleApi.Vision.V1.Model.Property.t()) | nil, :score => number() | nil, :topicality => number() | nil } field(:boundingPoly, as: GoogleApi.Vision.V1.Model.BoundingPoly) field(:confidence) field(:description) field(:locale) field(:locations, as: GoogleApi.Vision.V1.Model.LocationInfo, type: :list) field(:mid) field(:properties, as: GoogleApi.Vision.V1.Model.Property, type: :list) field(:score) field(:topicality) end defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.EntityAnnotation do def decode(value, options) do GoogleApi.Vision.V1.Model.EntityAnnotation.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.EntityAnnotation do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
58.098592
410
0.710303
7952f29b9cad0a1f2afc5635e95ce5b5b2ed6858
1,926
ex
Elixir
lib/sparklinex/bullet.ex
aselder/sparklinex
5b6e6cad22ea101302857e0c0920c39416418ce3
[ "MIT" ]
2
2018-12-26T19:52:00.000Z
2021-02-09T09:32:50.000Z
lib/sparklinex/bullet.ex
aselder/sparklinex
5b6e6cad22ea101302857e0c0920c39416418ce3
[ "MIT" ]
null
null
null
lib/sparklinex/bullet.ex
aselder/sparklinex
5b6e6cad22ea101302857e0c0920c39416418ce3
[ "MIT" ]
null
null
null
defmodule Sparklinex.Bullet do alias Sparklinex.Bullet.Options alias Sparklinex.MogrifyDraw def draw( data, spec = %Options{height: height, width: width, good_color: good_color} ) do canvas = MogrifyDraw.create_canvas(width, height, good_color) canvas |> draw_sat_background(data, spec) |> draw_bad_background(data, spec) |> draw_target(data, spec) |> draw_bullet(data, spec) end defp draw_bad_background(canvas, %{good: good, bad: bad}, %Options{ bad_color: bad_color, width: width, height: height }) do box_width = width * (bad / good) MogrifyDraw.rectangle(canvas, {0, 0}, {box_width, height}, bad_color) end defp draw_bad_background(canvas, _, _) do canvas end defp draw_sat_background(canvas, %{good: good, satisfactory: sat}, %Options{ satisfactory_color: sat_color, width: width, height: height }) do box_width = width * (sat / good) MogrifyDraw.rectangle(canvas, {0, 0}, {box_width, height}, sat_color) end defp draw_sat_background(canvas, _, _) do canvas end defp draw_target(canvas, _, %Options{target: nil}) do canvas end defp draw_target(canvas, %{good: good}, %Options{ height: height, target: target, width: width, bullet_color: bullet_color }) do target_x = width * (target / good) thickness = height / 3 MogrifyDraw.rectangle( canvas, {target_x, thickness / 2}, {target_x + 1, thickness * 2.5}, bullet_color ) end defp draw_bullet(canvas, %{value: value, good: good}, %Options{ height: height, width: width, bullet_color: bullet_color }) do target_x = width * (value / good) thickness = height / 3 MogrifyDraw.rectangle(canvas, {0, thickness}, {target_x, thickness * 2}, bullet_color) end end
25.68
90
0.62513
7952fce0b54a965c0ef76c7ed8b278e0ddffb9eb
780
ex
Elixir
test/support/channel_case.ex
benlime/dashwallet
90754cf9cda72b289d5b802cd9fd7eb094f08acb
[ "MIT" ]
2
2017-11-15T20:47:47.000Z
2017-12-02T11:29:10.000Z
test/support/channel_case.ex
benlime/dashwallet
90754cf9cda72b289d5b802cd9fd7eb094f08acb
[ "MIT" ]
null
null
null
test/support/channel_case.ex
benlime/dashwallet
90754cf9cda72b289d5b802cd9fd7eb094f08acb
[ "MIT" ]
null
null
null
defmodule DashwalletWeb.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` and also import other functionality to make it easier to build common datastructures and query the data layer. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with channels use Phoenix.ChannelTest # The default endpoint for testing @endpoint DashwalletWeb.Endpoint end end setup _tags do :ok end end
22.941176
58
0.728205
795311643cb1091bde90b63285b43e9effe23160
477
ex
Elixir
lib/plug/conn/unfetched.ex
falood/plug
6022465ed2e44cf092d16ae3d564648615eab87b
[ "Apache-2.0" ]
null
null
null
lib/plug/conn/unfetched.ex
falood/plug
6022465ed2e44cf092d16ae3d564648615eab87b
[ "Apache-2.0" ]
null
null
null
lib/plug/conn/unfetched.ex
falood/plug
6022465ed2e44cf092d16ae3d564648615eab87b
[ "Apache-2.0" ]
null
null
null
defmodule Plug.Conn.Unfetched do @moduledoc """ A struct used as default on unfetched fields. """ defstruct [:aspect] defimpl Access do def get(%Plug.Conn.Unfetched{aspect: aspect}, key) do raise ArgumentError, message: "trying to access key #{inspect key} but they were not yet fetched. " <> "Please call Plug.Conn.fetch_#{aspect} before accessing it" end def access(unfetched, key) do get(unfetched, key) end end end
25.105263
80
0.66457
79531e526ead7a52039641a16ff166f051746c3e
753
ex
Elixir
lib/whistler_news_reader_web/controllers/api/import_controller.ex
fdietz/whistler_news_reader
501f3f95e1ba3a684da8b34b60e426da85e7852d
[ "MIT" ]
8
2016-06-12T20:11:26.000Z
2017-05-02T04:36:41.000Z
lib/whistler_news_reader_web/controllers/api/import_controller.ex
fdietz/whistler_news_reader
501f3f95e1ba3a684da8b34b60e426da85e7852d
[ "MIT" ]
2
2016-06-12T15:49:06.000Z
2016-06-12T20:00:02.000Z
lib/whistler_news_reader_web/controllers/api/import_controller.ex
fdietz/whistler_news_reader
501f3f95e1ba3a684da8b34b60e426da85e7852d
[ "MIT" ]
null
null
null
defmodule WhistlerNewsReaderWeb.Api.ImportController do use WhistlerNewsReaderWeb, :controller plug Guardian.Plug.EnsureAuthenticated, handler: WhistlerNewsReaderWeb.Api.SessionController plug :scrub_params, "file" when action in [:create] alias WhistlerNewsReader.OpmlImport require Logger def create(conn, %{"file" => %Plug.Upload{filename: _filename, path: path}} = _params) do case OpmlImport.import(current_user(conn), File.read!(path)) do :ok -> conn |> send_resp(204, "") error -> Logger.error "ImportController - error #{inspect(error)}" conn |> send_resp(422, inspect(error)) end end defp current_user(conn) do Guardian.Plug.current_resource(conn) end end
26.892857
94
0.695883
79533761cfe94724c9bb55ed55c5199e0fa6d74a
308
exs
Elixir
test/test_helper.exs
hlavacek/redix_pubsub
97879a171c2e264abd865e1d51db8855935c146f
[ "0BSD" ]
59
2016-05-25T12:18:09.000Z
2019-04-28T11:27:30.000Z
test/test_helper.exs
hlavacek/redix_pubsub
97879a171c2e264abd865e1d51db8855935c146f
[ "0BSD" ]
21
2016-05-29T14:08:28.000Z
2019-01-31T09:42:32.000Z
test/test_helper.exs
hlavacek/redix_pubsub
97879a171c2e264abd865e1d51db8855935c146f
[ "0BSD" ]
13
2016-06-19T02:08:32.000Z
2018-09-20T13:14:08.000Z
ExUnit.configure(assert_receive_timeout: 500, refute_receive_timeout: 500) ExUnit.start() case :gen_tcp.connect('localhost', 6379, []) do {:ok, socket} -> :gen_tcp.close(socket) {:error, reason} -> Mix.raise("Cannot connect to Redis (http://localhost:6379): #{:inet.format_error(reason)}") end
28
95
0.701299
795352379f09b70cd3ed6af97114fe76fecef448
17,136
ex
Elixir
lib/ex_doc/retriever.ex
Dalgona/ex_doc
814627067175bfe894461cc3f235ee1d9b71b487
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
lib/ex_doc/retriever.ex
Dalgona/ex_doc
814627067175bfe894461cc3f235ee1d9b71b487
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
lib/ex_doc/retriever.ex
Dalgona/ex_doc
814627067175bfe894461cc3f235ee1d9b71b487
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
defmodule ExDoc.Retriever do # Functions to extract documentation information from modules. @moduledoc false defmodule Error do @moduledoc false defexception [:message] end alias ExDoc.{GroupMatcher} alias ExDoc.Retriever.Error @doc """ Extract documentation from all modules in the specified directory or directories. """ @spec docs_from_dir(Path.t() | [Path.t()], ExDoc.Config.t()) :: [ExDoc.ModuleNode.t()] def docs_from_dir(dir, config) when is_binary(dir) do pattern = if config.filter_prefix, do: "Elixir.#{config.filter_prefix}*.beam", else: "*.beam" files = Path.wildcard(Path.expand(pattern, dir)) docs_from_files(files, config) end def docs_from_dir(dirs, config) when is_list(dirs) do Enum.flat_map(dirs, &docs_from_dir(&1, config)) end @doc """ Extract documentation from all modules in the specified list of files """ @spec docs_from_files([Path.t()], ExDoc.Config.t()) :: [ExDoc.ModuleNode.t()] def docs_from_files(files, config) when is_list(files) do files |> Enum.map(&filename_to_module(&1)) |> docs_from_modules(config) end @doc """ Extract documentation from all modules in the list `modules` """ @spec docs_from_modules([atom], ExDoc.Config.t()) :: [ExDoc.ModuleNode.t()] def docs_from_modules(modules, config) when is_list(modules) do modules |> Enum.flat_map(&get_module(&1, config)) |> Enum.sort_by(fn module -> {GroupMatcher.group_index(config.groups_for_modules, module.group), module.id} end) end defp filename_to_module(name) do name = Path.basename(name, ".beam") String.to_atom(name) end # Get all the information from the module and compile # it. If there is an error while retrieving the information (like # the module is not available or it was not compiled # with --docs flag), we raise an exception. defp get_module(module, config) do unless Code.ensure_loaded?(module) do raise Error, "module #{inspect(module)} is not defined/available" end if docs_chunk = docs_chunk(module) do generate_node(module, docs_chunk, config) else [] end end defp nesting_info(title, prefixes) do prefixes |> Enum.find(&String.starts_with?(title, &1 <> ".")) |> case do nil -> {nil, nil} prefix -> {String.trim_leading(title, prefix <> "."), prefix} end end # Special case required for Elixir defp docs_chunk(:elixir_bootstrap), do: false defp docs_chunk(module) do unless function_exported?(Code, :fetch_docs, 1) do raise Error, "ExDoc 0.19+ requires Elixir v1.7 and later. " <> "For earlier Elixir versions, make sure to depend on {:ex_doc, \"~> 0.18.0\"}" end if function_exported?(module, :__info__, 1) do case Code.fetch_docs(module) do {:docs_v1, _, _, _, :hidden, _, _} -> false {:docs_v1, _, _, _, _, _, _} = docs -> docs {:error, reason} -> raise Error, "module #{inspect(module)} was not compiled with flag --docs: #{inspect(reason)}" _ -> raise Error, "unknown format in Docs chunk. This likely means you are running on " <> "a more recent Elixir version that is not supported by ExDoc. Please update." end else false end end defp generate_node(module, docs_chunk, config) do module_data = get_module_data(module, docs_chunk) case module_data do %{type: :impl} -> [] _ -> [do_generate_node(module, module_data, config)] end end defp do_generate_node(module, module_data, config) do source_url = config.source_url_pattern source_path = source_path(module, config) source = %{url: source_url, path: source_path} {doc_line, moduledoc, metadata} = get_module_docs(module_data) line = find_module_line(module_data) || doc_line {function_groups, function_docs} = get_docs(module_data, source, config) docs = function_docs ++ get_callbacks(module_data, source) types = get_types(module_data, source) {title, id} = module_title_and_id(module_data) module_group = GroupMatcher.match_module(config.groups_for_modules, module, id) {nested_title, nested_context} = nesting_info(title, config.nest_modules_by_prefix) %ExDoc.ModuleNode{ id: id, title: title, nested_title: nested_title, nested_context: nested_context, module: module_data.name, group: module_group, type: module_data.type, deprecated: metadata[:deprecated], function_groups: function_groups, docs: Enum.sort_by(docs, &{&1.name, &1.arity}), doc: moduledoc, doc_line: doc_line, typespecs: Enum.sort_by(types, &{&1.name, &1.arity}), source_path: source_path, source_url: source_link(source, line) } end # Module Helpers defp get_module_data(module, docs_chunk) do %{ name: module, type: get_type(module), specs: get_specs(module), impls: get_impls(module), abst_code: get_abstract_code(module), docs: docs_chunk } end defp get_type(module) do cond do function_exported?(module, :__struct__, 0) and match?(%{__exception__: true}, module.__struct__) -> :exception function_exported?(module, :__protocol__, 1) -> :protocol function_exported?(module, :__impl__, 1) -> :impl function_exported?(module, :behaviour_info, 1) -> :behaviour match?("Elixir.Mix.Tasks." <> _, Atom.to_string(module)) -> :task true -> :module end end defp get_module_docs(%{docs: {:docs_v1, anno, _, _, moduledoc, metadata, _}}) do {anno_line(anno), docstring(moduledoc), metadata} end defp get_abstract_code(module) do {^module, binary, _file} = :code.get_object_code(module) case :beam_lib.chunks(binary, [:abstract_code]) do {:ok, {_, [{:abstract_code, {_vsn, abstract_code}}]}} -> abstract_code _otherwise -> [] end end ## Function helpers defp get_docs(%{type: type, docs: docs} = module_data, source, config) do {:docs_v1, _, _, _, _, _, docs} = docs groups_for_functions = Enum.map(config.groups_for_functions, fn {group, filter} -> {Atom.to_string(group), filter} end) ++ [{"Functions", fn _ -> true end}] function_docs = for doc <- docs, doc?(doc, type) do get_function(doc, source, module_data, groups_for_functions) end {Enum.map(groups_for_functions, &elem(&1, 0)), function_docs} end # We are only interested in functions and macros for now defp doc?({{kind, _, _}, _, _, _, _}, _) when kind not in [:function, :macro] do false end # Skip impl_for and impl_for! for protocols defp doc?({{_, name, _}, _, _, :none, _}, :protocol) when name in [:impl_for, :impl_for!] do false end # Skip docs explicitly marked as hidden defp doc?({_, _, _, :hidden, _}, _) do false end # Skip default docs if starting with _ defp doc?({{_, name, _}, _, _, :none, _}, _type) do hd(Atom.to_charlist(name)) != ?_ end # Everything else is ok defp doc?(_, _) do true end defp get_function(function, source, module_data, groups_for_functions) do {{type, name, arity}, anno, signature, doc, metadata} = function actual_def = actual_def(name, arity, type) doc_line = anno_line(anno) annotations = annotations_from_metadata(metadata) line = find_function_line(module_data, actual_def) || doc_line doc = docstring(doc, name, arity, type, Map.fetch(module_data.impls, {name, arity})) defaults = get_defaults(name, arity, Map.get(metadata, :defaults, 0)) specs = module_data.specs |> Map.get(actual_def, []) |> Enum.map(&Code.Typespec.spec_to_quoted(name, &1)) specs = if type == :macro do Enum.map(specs, &remove_first_macro_arg/1) else specs end annotations = case {type, name, arity} do {:macro, _, _} -> ["macro" | annotations] {_, :__struct__, 0} -> ["struct" | annotations] _ -> annotations end group = Enum.find_value(groups_for_functions, fn {group, filter} -> filter.(metadata) && group end) %ExDoc.FunctionNode{ id: "#{name}/#{arity}", name: name, arity: arity, deprecated: metadata[:deprecated], doc: doc || delegate_doc(metadata[:delegate_to]), doc_line: doc_line, defaults: defaults, signature: Enum.join(signature, " "), specs: specs, source_path: source.path, source_url: source_link(source, line), type: type, group: group, annotations: annotations } end defp delegate_doc(nil), do: nil defp delegate_doc({m, f, a}), do: "See `#{Exception.format_mfa(m, f, a)}`." defp docstring(:none, name, arity, type, {:ok, behaviour}) do info = "Callback implementation for `c:#{inspect(behaviour)}.#{name}/#{arity}`." with {:docs_v1, _, _, _, _, _, docs} <- Code.fetch_docs(behaviour), key = {definition_to_callback(type), name, arity}, {_, _, _, doc, _} <- List.keyfind(docs, key, 0), docstring when is_binary(docstring) <- docstring(doc) do "#{docstring}\n\n#{info}" else _ -> info end end defp docstring(doc, _, _, _, _), do: docstring(doc) defp definition_to_callback(:function), do: :callback defp definition_to_callback(:macro), do: :macrocallback defp get_defaults(_name, _arity, 0), do: [] defp get_defaults(name, arity, defaults) do for default <- (arity - defaults)..(arity - 1), do: "#{name}/#{default}" end ## Callback helpers defp get_callbacks(%{type: :behaviour, name: name, abst_code: abst_code, docs: docs}, source) do {:docs_v1, _, _, _, _, _, docs} = docs optional_callbacks = name.behaviour_info(:optional_callbacks) for {{kind, _, _}, _, _, _, _} = doc <- docs, kind in [:callback, :macrocallback] do get_callback(doc, source, optional_callbacks, abst_code) end end defp get_callbacks(_, _), do: [] defp get_callback(callback, source, optional_callbacks, abst_code) do {{kind, name, arity}, anno, _, doc, metadata} = callback actual_def = actual_def(name, arity, kind) doc_line = anno_line(anno) annotations = annotations_from_metadata(metadata) {:attribute, anno, :callback, {^actual_def, specs}} = Enum.find(abst_code, &match?({:attribute, _, :callback, {^actual_def, _}}, &1)) line = anno_line(anno) || doc_line specs = Enum.map(specs, &Code.Typespec.spec_to_quoted(name, &1)) annotations = if actual_def in optional_callbacks, do: ["optional" | annotations], else: annotations %ExDoc.FunctionNode{ id: "#{name}/#{arity}", name: name, arity: arity, deprecated: metadata[:deprecated], doc: docstring(doc), doc_line: doc_line, signature: get_typespec_signature(hd(specs), arity), specs: specs, source_path: source.path, source_url: source_link(source, line), type: kind, annotations: annotations } end ## Typespecs # Returns a map of {name, arity} => spec. defp get_specs(module) do case Code.Typespec.fetch_specs(module) do {:ok, specs} -> Map.new(specs) :error -> %{} end end # Returns a map of {name, arity} => behaviour. defp get_impls(module) do for behaviour <- behaviours_implemented_by(module), callback <- callbacks_defined_by(behaviour), do: {callback, behaviour}, into: %{} end defp callbacks_defined_by(module) do case Code.Typespec.fetch_callbacks(module) do {:ok, callbacks} -> Keyword.keys(callbacks) :error -> [] end end defp behaviours_implemented_by(module) do for {:behaviour, list} <- module.module_info(:attributes), behaviour <- list, do: behaviour end defp get_types(%{docs: docs} = module_data, source) do {:docs_v1, _, _, _, _, _, docs} = docs for {{:type, _, _}, _, _, content, _} = doc <- docs, content != :hidden do get_type(doc, source, module_data.abst_code) end end defp get_type(type, source, abst_code) do {{_, name, arity}, anno, _, doc, metadata} = type doc_line = anno_line(anno) annotations = annotations_from_metadata(metadata) {:attribute, anno, type, spec} = Enum.find(abst_code, fn {:attribute, _, type, {^name, _, args}} -> type in [:opaque, :type] and length(args) == arity _ -> false end) spec = spec |> Code.Typespec.type_to_quoted() |> process_type_ast(type) line = anno_line(anno) || doc_line annotations = if type == :opaque, do: ["opaque" | annotations], else: annotations %ExDoc.TypeNode{ id: "#{name}/#{arity}", name: name, arity: arity, type: type, spec: spec, deprecated: metadata[:deprecated], doc: docstring(doc), doc_line: doc_line, signature: get_typespec_signature(spec, arity), source_path: source.path, source_url: source_link(source, line), annotations: annotations } end # Cut off the body of an opaque type while leaving it on a normal type. defp process_type_ast({:::, _, [d | _]}, :opaque), do: d defp process_type_ast(ast, _), do: ast defp get_typespec_signature({:when, _, [{:::, _, [{name, meta, args}, _]}, _]}, arity) do Macro.to_string({name, meta, strip_types(args, arity)}) end defp get_typespec_signature({:::, _, [{name, meta, args}, _]}, arity) do Macro.to_string({name, meta, strip_types(args, arity)}) end defp get_typespec_signature({name, meta, args}, arity) do Macro.to_string({name, meta, strip_types(args, arity)}) end defp strip_types(args, arity) do args |> Enum.take(-arity) |> Enum.with_index(1) |> Enum.map(fn {{:::, _, [left, _]}, position} -> to_var(left, position) {{:|, _, _}, position} -> to_var({}, position) {left, position} -> to_var(left, position) end) end defp to_var({:%, meta, [name, _]}, _), do: {:%, meta, [name, {:%{}, meta, []}]} defp to_var({name, meta, _}, _) when is_atom(name), do: {name, meta, nil} defp to_var([{:->, _, _} | _], _), do: {:function, [], nil} defp to_var({:<<>>, _, _}, _), do: {:binary, [], nil} defp to_var({:%{}, _, _}, _), do: {:map, [], nil} defp to_var({:{}, _, _}, _), do: {:tuple, [], nil} defp to_var({_, _}, _), do: {:tuple, [], nil} defp to_var(integer, _) when is_integer(integer), do: {:integer, [], nil} defp to_var(float, _) when is_integer(float), do: {:float, [], nil} defp to_var(list, _) when is_list(list), do: {:list, [], nil} defp to_var(atom, _) when is_atom(atom), do: {:atom, [], nil} defp to_var(_, position), do: {:"arg#{position}", [], nil} ## General helpers defp actual_def(name, arity, :macrocallback) do {String.to_atom("MACRO-" <> to_string(name)), arity + 1} end defp actual_def(name, arity, :macro) do {String.to_atom("MACRO-" <> to_string(name)), arity + 1} end defp actual_def(name, arity, _), do: {name, arity} defp annotations_from_metadata(metadata) do annotations = [] annotations = if since = metadata[:since] do ["since #{since}" | annotations] else annotations end annotations end defp remove_first_macro_arg({:::, info, [{name, info2, [_term_arg | rest_args]}, return]}) do {:::, info, [{name, info2, rest_args}, return]} end defp find_module_line(%{abst_code: abst_code, name: name}) do Enum.find_value(abst_code, fn {:attribute, anno, :module, ^name} -> anno_line(anno) _ -> nil end) end defp find_function_line(%{abst_code: abst_code}, {name, arity}) do Enum.find_value(abst_code, fn {:function, anno, ^name, ^arity, _} -> anno_line(anno) _ -> nil end) end defp docstring(%{"en" => doc}), do: doc defp docstring(_), do: nil defp anno_line(line) when is_integer(line), do: abs(line) defp anno_line(anno), do: anno |> :erl_anno.line() |> abs() defp source_link(%{path: _, url: nil}, _line), do: nil defp source_link(source, line) do source_url = Regex.replace(~r/%{path}/, source.url, source.path) Regex.replace(~r/%{line}/, source_url, to_string(line)) end defp source_path(module, config) do source = String.Chars.to_string(module.__info__(:compile)[:source]) if root = config.source_root do Path.relative_to(source, root) else source end end defp module_title_and_id(%{name: module, type: :task}) do {"mix " <> task_name(module), module_id(module)} end defp module_title_and_id(%{name: module}) do id = module_id(module) {id, id} end defp module_id(module) do case inspect(module) do ":" <> inspected -> inspected inspected -> inspected end end defp task_name(module) do "Elixir.Mix.Tasks." <> name = Atom.to_string(module) name |> String.split(".") |> Enum.map_join(".", &Macro.underscore/1) end end
29.905759
98
0.631303
79535354dae622148a3ff0eea046ae24f3b94a35
740
ex
Elixir
lib/utxo.ex
hlongvu/elixium_core
9d01e0bfea44d5014f44e1417ab84c81222a914d
[ "MIT" ]
164
2018-06-23T01:17:51.000Z
2021-08-19T03:16:31.000Z
lib/utxo.ex
alexdovzhanyn/ultradark
85014da4b0683ab8ec86c893b7c1146161da114a
[ "MIT" ]
37
2018-06-28T18:07:27.000Z
2019-08-22T18:43:43.000Z
lib/utxo.ex
alexdovzhanyn/ultradark
85014da4b0683ab8ec86c893b7c1146161da114a
[ "MIT" ]
26
2018-06-22T00:58:34.000Z
2021-08-19T03:16:40.000Z
defmodule Elixium.Utxo do alias Elixium.Utxo defstruct [:addr, :amount, :txoid] @moduledoc """ Functionality specific to UTXOs """ @doc """ Takes in a utxo received from a peer which may have malicious or extra attributes attached. Removes all extra parameters which are not defined explicitly by the utxo struct. """ @spec sanitize(Utxo) :: Utxo def sanitize(unsanitized_utxo) do struct(Utxo, Map.delete(unsanitized_utxo, :__struct__)) end @doc """ Returns a hash representation of a given utxo (to be used as an input for signature) """ @spec hash(Utxo) :: binary def hash(utxo) do :crypto.hash(:sha256, [utxo.txoid, utxo.addr, :erlang.term_to_binary(utxo.amount)]) end end
25.517241
87
0.691892
79536883e44e64304f5ad036d5aaa2f647956894
1,609
ex
Elixir
plugins/ucc_chat/lib/ucc_chat_web/channel_controllers/room/room_setting_controller.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
plugins/ucc_chat/lib/ucc_chat_web/channel_controllers/room/room_setting_controller.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
plugins/ucc_chat/lib/ucc_chat_web/channel_controllers/room/room_setting_controller.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
defmodule UccChatWeb.RoomSettingChannelController do use UccChatWeb, :channel_controller alias UccChat.{Subscription, Web.FlexBarView, Channel, ChannelService} alias UccChatWeb.FlexBarView alias UccChat.ServiceHelpers, as: Helpers require Logger def edit(%{assigns: assigns} = socket, params) do channel = Channel.get(assigns[:channel_id]) field_name = String.to_atom(params["field_name"]) value = Map.get channel, field_name html = "channel_form_text_input.html" |> FlexBarView.render(field: %{name: field_name, value: value}) |> Helpers.safe_to_string {:reply, {:ok, %{html: html}}, socket} end def update_field(%{assigns: assigns} = socket, channel, _user, %{"field_name" => "archived", "value" => true}) do ChannelService.channel_command(socket, :archive, channel, assigns.user_id, channel.id) end def update_field(%{assigns: assigns} = socket, channel, _user, %{"field_name" => "archived"}) do ChannelService.channel_command(socket, :unarchive, channel, assigns.user_id, channel.id) end def update_field(%{assigns: _assigns} = _socket, channel, user, %{"field_name" => field_name, "value" => value}) do channel |> Channel.changeset_settings(user, [{field_name, value}]) |> Repo.update end def update_archive_hidden(%{id: id} = channel, "archived", value) do value = if value == true, do: true, else: false Subscription.get_by(channel_id: id) |> Repo.update_all(set: [hidden: value]) channel end def update_archive_hidden(channel, _type, _value), do: channel end
30.358491
72
0.691734
795368a5b6a5a248515337bdbcee5e07772331f8
175
ex
Elixir
lib/neural_network/sigmoid.ex
Markonis/BrainElixir
7f1d193827b7ca8113424e7debedd920f75a0a10
[ "MIT" ]
null
null
null
lib/neural_network/sigmoid.ex
Markonis/BrainElixir
7f1d193827b7ca8113424e7debedd920f75a0a10
[ "MIT" ]
null
null
null
lib/neural_network/sigmoid.ex
Markonis/BrainElixir
7f1d193827b7ca8113424e7debedd920f75a0a10
[ "MIT" ]
null
null
null
defmodule NeuralNetwork.Sigmoid do def value(x) do e = 2.718281828459045 1 / (1 + :math.pow(e, -x)) end def deriv(x) do value(x) * (1 - value(x)) end end
15.909091
34
0.588571
79539e6a4e4abb275b820c92b2ec84bd65f29a54
249
ex
Elixir
app/lib/rocdev.ex
kylemacey/rocdev
a70e80b9b853803bc9771b7f0ff712b6da27af8f
[ "MIT" ]
14
2017-10-10T19:11:21.000Z
2019-04-20T20:11:01.000Z
app/lib/rocdev.ex
kylemacey/rocdev
a70e80b9b853803bc9771b7f0ff712b6da27af8f
[ "MIT" ]
41
2017-10-08T03:07:20.000Z
2018-10-15T12:47:34.000Z
app/lib/rocdev.ex
kylemacey/rocdev
a70e80b9b853803bc9771b7f0ff712b6da27af8f
[ "MIT" ]
7
2017-10-18T10:44:04.000Z
2019-04-15T20:44:49.000Z
defmodule Rocdev do @moduledoc """ Rocdev keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ end
24.9
66
0.751004
7953ac7b021cf073c39294de2f3b9b8092972e82
1,590
ex
Elixir
clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_entity_type_excluded_phrase.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_entity_type_excluded_phrase.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_entity_type_excluded_phrase.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3EntityTypeExcludedPhrase do @moduledoc """ An excluded entity phrase that should not be matched. ## Attributes * `value` (*type:* `String.t`, *default:* `nil`) - Required. The word or phrase to be excluded. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :value => String.t() | nil } field(:value) end defimpl Poison.Decoder, for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3EntityTypeExcludedPhrase do def decode(value, options) do GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3EntityTypeExcludedPhrase.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3EntityTypeExcludedPhrase do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
30.576923
99
0.74717
79544945a906311898823f00ceafa5764b7540db
2,327
exs
Elixir
mix.exs
van-mronov/ecto
d0511f539353f556c7ae74d98924eb89a67aa3c5
[ "Apache-2.0" ]
null
null
null
mix.exs
van-mronov/ecto
d0511f539353f556c7ae74d98924eb89a67aa3c5
[ "Apache-2.0" ]
null
null
null
mix.exs
van-mronov/ecto
d0511f539353f556c7ae74d98924eb89a67aa3c5
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.MixProject do use Mix.Project @version "3.0.6-dev" def project do [ app: :ecto, version: @version, elixir: "~> 1.4", deps: deps(), consolidate_protocols: Mix.env() != :test, # Hex description: "A toolkit for data mapping and language integrated query for Elixir", package: package(), # Docs name: "Ecto", docs: docs() ] end def application do [ extra_applications: [:logger, :crypto], mod: {Ecto.Application, []} ] end defp deps do [ {:decimal, "~> 1.6"}, # Optional {:poison, "~> 2.2 or ~> 3.0", optional: true}, {:jason, "~> 1.0", optional: true}, # Docs {:ex_doc, "~> 0.19", only: :docs} ] end defp package do [ maintainers: ["Eric Meadows-Jönsson", "José Valim", "James Fish", "Michał Muskała"], licenses: ["Apache 2.0"], links: %{"GitHub" => "https://github.com/elixir-ecto/ecto"}, files: ~w(.formatter.exs mix.exs README.md CHANGELOG.md lib) ++ ~w(integration_test/cases integration_test/support) ] end defp docs do [ main: "Ecto", source_ref: "v#{@version}", canonical: "http://hexdocs.pm/ecto", logo: "guides/images/e.png", source_url: "https://github.com/elixir-ecto/ecto", extras: [ "guides/Getting Started.md", "guides/Testing with Ecto.md" ], groups_for_modules: [ # Ecto, # Ecto.Changeset, # Ecto.LogEntry, # Ecto.Multi, # Ecto.Query, # Ecto.Repo, # Ecto.Schema, # Ecto.Schema.Metadata, # Ecto.Type, # Ecto.UUID, # Mix.Ecto, "Query APIs": [ Ecto.Query.API, Ecto.Query.WindowAPI, Ecto.Queryable, Ecto.SubQuery ], "Adapter specification": [ Ecto.Adapter, Ecto.Adapter.Queryable, Ecto.Adapter.Schema, Ecto.Adapter.Storage, Ecto.Adapter.Transaction ], "Association structs": [ Ecto.Association.BelongsTo, Ecto.Association.Has, Ecto.Association.HasThrough, Ecto.Association.ManyToMany, Ecto.Association.NotLoaded ] ] ] end end
22.592233
90
0.528148
7954a5d524dc1584a2b2d826be5bd018ee24130b
11,993
ex
Elixir
lib/livebook_web/live/session_live/cell_component.ex
PeteJodo/livebook
4badf40afcbe489deda92812e72a99a0e54f11a7
[ "Apache-2.0" ]
null
null
null
lib/livebook_web/live/session_live/cell_component.ex
PeteJodo/livebook
4badf40afcbe489deda92812e72a99a0e54f11a7
[ "Apache-2.0" ]
null
null
null
lib/livebook_web/live/session_live/cell_component.ex
PeteJodo/livebook
4badf40afcbe489deda92812e72a99a0e54f11a7
[ "Apache-2.0" ]
null
null
null
defmodule LivebookWeb.SessionLive.CellComponent do use LivebookWeb, :live_component @impl true def render(assigns) do ~H""" <div class="flex flex-col relative" data-element="cell" id={"cell-#{@cell_view.id}"} phx-hook="Cell" data-cell-id={@cell_view.id} data-focusable-id={@cell_view.id} data-type={@cell_view.type} data-session-path={Routes.session_path(@socket, :page, @session_id)}> <%= render_cell(assigns) %> </div> """ end defp render_cell(%{cell_view: %{type: :markdown}} = assigns) do ~H""" <div class="mb-1 flex items-center justify-end"> <div class="relative z-20 flex items-center justify-end space-x-2" role="toolbar" aria-label="cell actions" data-element="actions"> <span class="tooltip top" data-tooltip="Edit content" data-element="enable-insert-mode-button"> <button class="icon-button" aria-label="edit content"> <.remix_icon icon="pencil-line" class="text-xl" /> </button> </span> <span class="tooltip top" data-tooltip="Insert image" data-element="insert-image-button"> <%= live_patch to: Routes.session_path(@socket, :cell_upload, @session_id, @cell_view.id), class: "icon-button", aria_label: "insert image", role: "button" do %> <.remix_icon icon="image-add-line" class="text-xl" /> <% end %> </span> <.cell_link_button cell_id={@cell_view.id} /> <.move_cell_up_button cell_id={@cell_view.id} /> <.move_cell_down_button cell_id={@cell_view.id} /> <.delete_cell_button cell_id={@cell_view.id} /> </div> </div> <.cell_body> <div class="pb-4" data-element="editor-box"> <.editor cell_view={@cell_view} /> </div> <div class="markdown" data-element="markdown-container" id={"markdown-container-#{@cell_view.id}"} phx-update="ignore"> <.content_placeholder bg_class="bg-gray-200" empty={@cell_view.empty?} /> </div> </.cell_body> """ end defp render_cell(%{cell_view: %{type: :elixir}} = assigns) do ~H""" <div class="mb-1 flex items-center justify-between"> <div class="relative z-20 flex items-center justify-end space-x-2" data-element="actions" data-primary> <%= if @cell_view.evaluation_status == :ready do %> <%= if @cell_view.validity_status != :fresh and @cell_view.reevaluate_automatically do %> <%= live_patch to: Routes.session_path(@socket, :cell_settings, @session_id, @cell_view.id), class: "text-gray-600 hover:text-gray-800 focus:text-gray-800 flex space-x-1 items-center" do %> <.remix_icon icon="check-line" class="text-xl" /> <span class="text-sm font-medium"> Reevaluates automatically </span> <% end %> <% else %> <button class="text-gray-600 hover:text-gray-800 focus:text-gray-800 flex space-x-1 items-center" phx-click="queue_cell_evaluation" phx-value-cell_id={@cell_view.id}> <.remix_icon icon="play-circle-fill" class="text-xl" /> <span class="text-sm font-medium"> <%= if(@cell_view.validity_status == :evaluated, do: "Reevaluate", else: "Evaluate") %> </span> </button> <% end %> <% else %> <button class="text-gray-600 hover:text-gray-800 focus:text-gray-800 flex space-x-1 items-center" phx-click="cancel_cell_evaluation" phx-value-cell_id={@cell_view.id}> <.remix_icon icon="stop-circle-fill" class="text-xl" /> <span class="text-sm font-medium"> Stop </span> </button> <% end %> </div> <div class="relative z-20 flex items-center justify-end space-x-2" role="toolbar" aria-label="cell actions" data-element="actions"> <span class="tooltip top" data-tooltip="Amplify output" data-element="amplify-outputs-button"> <button class="icon-button" aria-label="amplify outputs"> <.remix_icon icon="zoom-in-line" class="text-xl" data-element="zoom-in-icon" /> <.remix_icon icon="zoom-out-line" class="text-xl" data-element="zoom-out-icon" /> </button> </span> <.cell_settings_button cell_id={@cell_view.id} socket={@socket} session_id={@session_id} /> <.cell_link_button cell_id={@cell_view.id} /> <.move_cell_up_button cell_id={@cell_view.id} /> <.move_cell_down_button cell_id={@cell_view.id} /> <.delete_cell_button cell_id={@cell_view.id} /> </div> </div> <.cell_body> <.editor cell_view={@cell_view} /> <%= if @cell_view.outputs != [] do %> <div class="mt-2" data-element="outputs-container"> <%# There is an akin render in LivebookWeb.Output.FrameDynamicLive %> <LivebookWeb.Output.outputs outputs={@cell_view.outputs} id={"cell-#{@cell_view.id}-evaluation#{evaluation_number(@cell_view.evaluation_status, @cell_view.number_of_evaluations)}-outputs"} socket={@socket} runtime={@runtime} cell_validity_status={@cell_view.validity_status} input_values={@cell_view.input_values} /> </div> <% end %> </.cell_body> """ end defp cell_body(assigns) do ~H""" <!-- By setting tabindex we can programmatically focus this element, also we actually want to make this element tab-focusable --> <div class="flex relative" data-element="cell-body" tabindex="0"> <div class="w-1 h-full rounded-lg absolute top-0 -left-3" data-element="cell-focus-indicator"> </div> <div class="w-full"> <%= render_slot(@inner_block) %> </div> </div> """ end defp cell_link_button(assigns) do ~H""" <span class="tooltip top" data-tooltip="Link"> <a href={"#cell-#{@cell_id}"} class="icon-button" aria-label="link to cell"> <.remix_icon icon="link" class="text-xl" /> </a> </span> """ end defp cell_settings_button(assigns) do ~H""" <span class="tooltip top" data-tooltip="Cell settings"> <%= live_patch to: Routes.session_path(@socket, :cell_settings, @session_id, @cell_id), class: "icon-button", aria_label: "cell settings", role: "button" do %> <.remix_icon icon="settings-3-line" class="text-xl" /> <% end %> </span> """ end defp move_cell_up_button(assigns) do ~H""" <span class="tooltip top" data-tooltip="Move up"> <button class="icon-button" aria-label="move cell up" phx-click="move_cell" phx-value-cell_id={@cell_id} phx-value-offset="-1"> <.remix_icon icon="arrow-up-s-line" class="text-xl" /> </button> </span> """ end defp move_cell_down_button(assigns) do ~H""" <span class="tooltip top" data-tooltip="Move down"> <button class="icon-button" aria-label="move cell down" phx-click="move_cell" phx-value-cell_id={@cell_id} phx-value-offset="1"> <.remix_icon icon="arrow-down-s-line" class="text-xl" /> </button> </span> """ end defp delete_cell_button(assigns) do ~H""" <span class="tooltip top" data-tooltip="Delete"> <button class="icon-button" aria-label="delete cell" phx-click="delete_cell" phx-value-cell_id={@cell_id}> <.remix_icon icon="delete-bin-6-line" class="text-xl" /> </button> </span> """ end defp editor(assigns) do ~H""" <div class="py-3 rounded-lg bg-editor relative"> <div id={"editor-container-#{@cell_view.id}"} data-element="editor-container" phx-update="ignore"> <div class="px-8"> <.content_placeholder bg_class="bg-gray-500" empty={@cell_view.empty?} /> </div> </div> <%= if @cell_view.type == :elixir do %> <div class="absolute bottom-2 right-2"> <.cell_status cell_view={@cell_view} /> </div> <% end %> </div> """ end # The whole page has to load and then hooks are mounted. # There may be a tiny delay before the markdown is rendered # or editors are mounted, so show neat placeholders immediately. defp content_placeholder(assigns) do ~H""" <%= if @empty do %> <div class="h-4"></div> <% else %> <div class="max-w-2xl w-full animate-pulse"> <div class="flex-1 space-y-4"> <div class={"#{@bg_class} h-4 rounded-lg w-3/4"}></div> <div class={"#{@bg_class} h-4 rounded-lg"}></div> <div class={"#{@bg_class} h-4 rounded-lg w-5/6"}></div> </div> </div> <% end %> """ end defp cell_status(%{cell_view: %{evaluation_status: :evaluating}} = assigns) do ~H""" <.status_indicator circle_class="bg-blue-500" animated_circle_class="bg-blue-400" change_indicator={true}> <span class="font-mono" id={"cell-timer-#{@cell_view.id}-evaluation-#{@cell_view.number_of_evaluations}"} phx-hook="Timer" phx-update="ignore" data-start={DateTime.to_iso8601(@cell_view.evaluation_start)}> </span> </.status_indicator> """ end defp cell_status(%{cell_view: %{evaluation_status: :queued}} = assigns) do ~H""" <.status_indicator circle_class="bg-gray-400" animated_circle_class="bg-gray-300"> Queued </.status_indicator> """ end defp cell_status(%{cell_view: %{validity_status: :evaluated}} = assigns) do ~H""" <.status_indicator circle_class="bg-green-400" change_indicator={true} tooltip={evaluated_label(@cell_view.evaluation_time_ms)}> Evaluated </.status_indicator> """ end defp cell_status(%{cell_view: %{validity_status: :stale}} = assigns) do ~H""" <.status_indicator circle_class="bg-yellow-200" change_indicator={true}> Stale </.status_indicator> """ end defp cell_status(%{cell_view: %{validity_status: :aborted}} = assigns) do ~H""" <.status_indicator circle_class="bg-gray-500"> Aborted </.status_indicator> """ end defp cell_status(assigns), do: ~H"" defp status_indicator(assigns) do assigns = assigns |> assign_new(:animated_circle_class, fn -> nil end) |> assign_new(:change_indicator, fn -> false end) |> assign_new(:tooltip, fn -> nil end) ~H""" <div class={"#{if(@tooltip, do: "tooltip")} bottom distant-medium"} data-tooltip={@tooltip}> <div class="flex items-center space-x-1"> <div class="flex text-xs text-gray-400" data-element="cell-status"> <%= render_slot(@inner_block) %> <%= if @change_indicator do %> <span data-element="change-indicator">*</span> <% end %> </div> <span class="flex relative h-3 w-3"> <%= if @animated_circle_class do %> <span class={"#{@animated_circle_class} animate-ping absolute inline-flex h-3 w-3 rounded-full opacity-75"}></span> <% end %> <span class={"#{@circle_class} relative inline-flex rounded-full h-3 w-3"}></span> </span> </div> </div> """ end defp evaluated_label(time_ms) when is_integer(time_ms) do evaluation_time = if time_ms > 100 do seconds = time_ms |> Kernel./(1000) |> Float.floor(1) "#{seconds}s" else "#{time_ms}ms" end "Took " <> evaluation_time end defp evaluated_label(_time_ms), do: nil defp evaluation_number(:evaluating, number_of_evaluations), do: number_of_evaluations + 1 defp evaluation_number(_evaluation_status, number_of_evaluations), do: number_of_evaluations end
34.56196
143
0.591428
7954d54e4a278921a87d9d617fc2119e43360a3b
756
ex
Elixir
lib/sanbase_web/graphql/prometheus/histogram_instrumenter.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
81
2017-11-20T01:20:22.000Z
2022-03-05T12:04:25.000Z
lib/sanbase_web/graphql/prometheus/histogram_instrumenter.ex
rmoorman/sanbase2
226784ab43a24219e7332c49156b198d09a6dd85
[ "MIT" ]
359
2017-10-15T14:40:53.000Z
2022-01-25T13:34:20.000Z
lib/sanbase_web/graphql/prometheus/histogram_instrumenter.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
16
2017-11-19T13:57:40.000Z
2022-02-07T08:13:02.000Z
defmodule SanbaseWeb.Graphql.Prometheus.HistogramInstrumenter do @moduledoc ~s""" Stores data about the queries that is used to build prometheus histograms https://prometheus.io/docs/practices/histograms/ Each bucket's number represents milliseconds. A query with a runtime of X seconds falls in the last bucket with value Y where X < Y """ use AbsintheMetrics, adapter: AbsintheMetrics.Backend.PrometheusHistogram, arguments: [ buckets: [10, 50, 100, 200, 300, 400, 500, 700, 1000, 1500] ++ buckets(2000, 1000, 30) ] # Returns a list of `number` elements starting from `from` with a step `step` defp buckets(from, step, number) do Stream.unfold(from, fn x -> {x, x + step} end) |> Enum.take(number) end end
36
92
0.708995
7954df18eabfac10d321229cb8dd1ab999fd5c19
466
ex
Elixir
lib/madari/api/command.ex
yoossaland/yoossa
1e1ab968d12c7690a76fc670c47c91c29efb2979
[ "BSD-2-Clause" ]
null
null
null
lib/madari/api/command.ex
yoossaland/yoossa
1e1ab968d12c7690a76fc670c47c91c29efb2979
[ "BSD-2-Clause" ]
null
null
null
lib/madari/api/command.ex
yoossaland/yoossa
1e1ab968d12c7690a76fc670c47c91c29efb2979
[ "BSD-2-Clause" ]
null
null
null
defmodule Madari.Api.Command do def execute(cmd, args) do if is_root_user() do {out, status} = System.cmd(cmd, args) { out |> String.trim(), status } else {out, status} = System.cmd("doas", [cmd] ++ args) { out |> String.trim(), status } end end defp is_root_user() do {out, status} = System.cmd("whoami", []) out |> String.trim() |> String.equivalent?("root") end end
20.26087
55
0.525751
7954e268ab6aa2d46afe6d05174f646ba3468988
2,834
ex
Elixir
apps/mishka_html/lib/mishka_html_web/live/components/admin/blog/post/delete_error_component.ex
mojtaba-naserei/mishka-cms
1f31f61347bab1aae6ba0d47c5515a61815db6c9
[ "Apache-2.0" ]
1
2021-11-14T11:13:25.000Z
2021-11-14T11:13:25.000Z
apps/mishka_html/lib/mishka_html_web/live/components/admin/blog/post/delete_error_component.ex
iArazar/mishka-cms
8b579101d607d91e80834527c1508fe5f4ceefef
[ "Apache-2.0" ]
null
null
null
apps/mishka_html/lib/mishka_html_web/live/components/admin/blog/post/delete_error_component.ex
iArazar/mishka-cms
8b579101d607d91e80834527c1508fe5f4ceefef
[ "Apache-2.0" ]
null
null
null
defmodule MishkaHtmlWeb.Admin.Blog.Post.DeleteErrorComponent do use MishkaHtmlWeb, :live_component def render(assigns) do ~H""" <div class="error-card-modal col"> <div class="alert alert-danger vazir rtl" role="alert"> <div class="col-sm-6 svg-div-error-modal"> <svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" fill="currentColor" class="bi bi-exclamation-triangle-fill flex-shrink-0 me-2" viewBox="0 0 16 16" role="img" aria-label="Warning:"> <path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/> </svg> </div> <div class="clearfix"></div> <div class="col space30"> </div> <span class="error-card-modal-main-text"> <%= MishkaTranslator.Gettext.dgettext("html_live_component", "شما نمی توانید این مطلب را حذف کنید. دلیل این موضوع می توانید به وابستگی های احتمالی به این مطلب ربط داشته باشد. از جمله مواردی که محتمل می باشد:") %> <ul> <li> <%= MishkaTranslator.Gettext.dgettext("html_live_component", "تخصیص نویسندگان به این مطلب") %> </li> <li> <%= MishkaTranslator.Gettext.dgettext("html_live_component", "لایک شدن این پست به وسیله کاربران") %> </li> <li> <%= MishkaTranslator.Gettext.dgettext("html_live_component", "تخصیص دادن یک یا چند برچسبب به این مطلب.") %> </li> </ul> <%= MishkaTranslator.Gettext.dgettext("html_live_component", "لازم به ذکر است اگر از حذف کامل این مطلب اطمینان دارید شما می توانید روی دکمه") %> </span> <span class="badge bg-dark vazir rtl error-modal-badage-dark"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "حذف همه") %></span> <%= MishkaTranslator.Gettext.dgettext("html_live_component", "کلیک کنید.") %> <div class="clearfix"></div> <div class="col space30"> </div> <div class="alert alert-warning d-flex align-items-center" role="alert"> <svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Warning:"><use xlink:href="#exclamation-triangle-fill"/></svg> <div> <%= MishkaTranslator.Gettext.dgettext("html_live_component", "اگر روی حذف کامل کلیک کنید دیگر این مطلب و تمام وابستگی های آن قابل برگشت نیست.") %> </div> </div> <div class="col space30"> </div> <div class="modal-close-btn"> <button type="button" class="btn btn-danger" phx-click="close_modal"><%= MishkaTranslator.Gettext.dgettext("html_live_component", "بستن") %></button> </div> </div> </div> """ end end
53.471698
270
0.622442
7954f390b91b1846ba95efee082f36b6f9a53837
63
ex
Elixir
user_api/lib/user_api_web/views/layout_view.ex
uttamk/sip-of-elixr-talk
08b4f2fddea5c3c60ecb7f646071c2ce0a46dc59
[ "MIT" ]
null
null
null
user_api/lib/user_api_web/views/layout_view.ex
uttamk/sip-of-elixr-talk
08b4f2fddea5c3c60ecb7f646071c2ce0a46dc59
[ "MIT" ]
null
null
null
user_api/lib/user_api_web/views/layout_view.ex
uttamk/sip-of-elixr-talk
08b4f2fddea5c3c60ecb7f646071c2ce0a46dc59
[ "MIT" ]
null
null
null
defmodule UserApiWeb.LayoutView do use UserApiWeb, :view end
15.75
34
0.809524
79558b2c9bac0dc51e9ccee9ce1469fe58d834f4
349
exs
Elixir
priv/repo/seeds.exs
rosswilson/turret-elixir
effbc34a14e95d73db2075c66fe78f8432f83977
[ "MIT" ]
1
2021-02-03T23:34:04.000Z
2021-02-03T23:34:04.000Z
priv/repo/seeds.exs
rosswilson/turret-elixir
effbc34a14e95d73db2075c66fe78f8432f83977
[ "MIT" ]
58
2021-02-16T10:16:08.000Z
2022-03-07T10:57:32.000Z
priv/repo/seeds.exs
rosswilson/turret-elixir
effbc34a14e95d73db2075c66fe78f8432f83977
[ "MIT" ]
null
null
null
# Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # Turret.Repo.insert!(%Turret.SomeSchema{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong.
29.083333
61
0.704871
795593c6e48ed79f88f8ee4bf1c611e41365ef55
814
exs
Elixir
examples/apps/redix_example/mix.exs
simonprev/elixir_agent
56e6bf32259706ba45f3a158079f8e5a26f28b91
[ "Apache-2.0" ]
null
null
null
examples/apps/redix_example/mix.exs
simonprev/elixir_agent
56e6bf32259706ba45f3a158079f8e5a26f28b91
[ "Apache-2.0" ]
null
null
null
examples/apps/redix_example/mix.exs
simonprev/elixir_agent
56e6bf32259706ba45f3a158079f8e5a26f28b91
[ "Apache-2.0" ]
null
null
null
defmodule RedixExample.MixProject do use Mix.Project def project do [ app: :redix_example, version: "0.1.0", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", lockfile: "../../mix.lock", elixir: "~> 1.9", elixirc_paths: ["lib", Path.expand("../../../test/support")], start_permanent: Mix.env() == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger], mod: {RedixExample.Application, []} ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:new_relic_agent, path: "../../../"}, {:plug_cowboy, "~> 2.0"}, {:redix, "~> 0.11"} ] end end
22.611111
67
0.542998
79559a80e27de315834a7e5be65b4090fadd3a8f
10,223
ex
Elixir
lib/web/controllers/webhook_controller.ex
bundler/bors-ng
4a805006a2b5983b23345d01e9a8d7459edd5855
[ "Apache-2.0" ]
null
null
null
lib/web/controllers/webhook_controller.ex
bundler/bors-ng
4a805006a2b5983b23345d01e9a8d7459edd5855
[ "Apache-2.0" ]
null
null
null
lib/web/controllers/webhook_controller.ex
bundler/bors-ng
4a805006a2b5983b23345d01e9a8d7459edd5855
[ "Apache-2.0" ]
3
2020-11-15T16:17:58.000Z
2021-06-04T11:26:42.000Z
defmodule BorsNG.WebhookController do @moduledoc """ The webhook controller responds to HTTP requests that are initiated from other services (currently, just GitHub). For example, I can run `iex -S mix phoenix.server` and do this: iex> # Push state to "GitHub" iex> alias BorsNG.GitHub iex> alias BorsNG.GitHub.ServerMock iex> alias BorsNG.Database iex> ServerMock.put_state(%{ ...> {:installation, 91} => %{ repos: [ ...> %GitHub.Repo{ ...> id: 14, ...> name: "test/repo", ...> owner: %{ ...> id: 6, ...> login: "bors-fanboi", ...> avatar_url: "data:image/svg+xml,<svg></svg>", ...> type: :user ...> }} ...> ] }, ...> {{:installation, 91}, 14} => %{ ...> branches: %{}, ...> comments: %{1 => []}, ...> pulls: %{ ...> 1 => %GitHub.Pr{ ...> number: 1, ...> title: "Test", ...> body: "Mess", ...> state: :open, ...> base_ref: "master", ...> head_sha: "00000001", ...> user: %GitHub.User{ ...> id: 6, ...> login: "bors-fanboi", ...> avatar_url: "data:image/svg+xml,<svg></svg>"}}}, ...> statuses: %{}, ...> files: %{}}}) iex> # The installation now exists; notify bors about it. iex> BorsNG.WebhookController.do_webhook(%{ ...> body_params: %{ ...> "installation" => %{ "id" => 91 }, ...> "sender" => %{ ...> "id" => 6, ...> "login" => "bors-fanboi", ...> "avatar_url" => "" }, ...> "action" => "created" }}, "github", "installation") iex> # This starts a background sync process with the installation. iex> # Watch it happen in the user interface. iex> BorsNG.Worker.SyncerInstallation.wait_hot_spin_xref(91) iex> proj = Database.Repo.get_by!(Database.Project, repo_xref: 14) iex> proj.name "test/repo" iex> patch = Database.Repo.get_by!(Database.Patch, pr_xref: 1) iex> patch.title "Test" """ use BorsNG.Web, :controller require Logger alias BorsNG.Worker.Attemptor alias BorsNG.Worker.Batcher alias BorsNG.Worker.BranchDeleter alias BorsNG.Command alias BorsNG.Database.Batch alias BorsNG.Database.Installation alias BorsNG.Database.Patch alias BorsNG.Database.Project alias BorsNG.Database.Repo alias BorsNG.GitHub alias BorsNG.Worker.Syncer alias BorsNG.Worker.SyncerInstallation @doc """ This action is reached via `/webhook/:provider` """ def webhook(conn, %{"provider" => "github"}) do event = hd(get_req_header(conn, "x-github-event")) do_webhook conn, "github", event conn |> send_resp(200, "") end def do_webhook(_conn, "github", "ping") do :ok end def do_webhook(conn, "github", "repository"), do: do_webhook_installation_sync(conn) def do_webhook(conn, "github", "member"), do: do_webhook_installation_sync(conn) def do_webhook(conn, "github", "membership"), do: do_webhook_installation_sync(conn) def do_webhook(conn, "github", "team"), do: do_webhook_installation_sync(conn) def do_webhook(conn, "github", "organization"), do: do_webhook_installation_sync(conn) def do_webhook(conn, "github", "installation") do payload = conn.body_params installation_xref = payload["installation"]["id"] case payload["action"] do "deleted" -> Repo.delete_all(from( i in Installation, where: i.installation_xref == ^installation_xref )) "created" -> SyncerInstallation.start_synchronize_installation( %Installation{ installation_xref: installation_xref } ) _ -> nil end :ok end def do_webhook(conn, "github", "installation_repositories") do SyncerInstallation.start_synchronize_installation(%Installation{ installation_xref: conn.body_params["installation"]["id"] }) end def do_webhook(conn, "github", "pull_request") do repo_xref = conn.body_params["repository"]["id"] project = Repo.get_by!(Project, repo_xref: repo_xref) pr = BorsNG.GitHub.Pr.from_json!(conn.body_params["pull_request"]) patch = Syncer.sync_patch(project.id, pr) do_webhook_pr(conn, %{ action: conn.body_params["action"], project: project, patch: patch, author: patch.author, pr: pr}) end def do_webhook(conn, "github", "issue_comment") do is_created = conn.body_params["action"] == "created" is_pr = Map.has_key?(conn.body_params["issue"], "pull_request") if is_created and is_pr do project = Repo.get_by!(Project, repo_xref: conn.body_params["repository"]["id"]) commenter = conn.body_params["comment"]["user"] |> GitHub.User.from_json!() |> Syncer.sync_user() comment = conn.body_params["comment"]["body"] %Command{ project: project, commenter: commenter, comment: comment, pr_xref: conn.body_params["issue"]["number"]} |> Command.run() end end def do_webhook(conn, "github", "pull_request_review_comment") do is_created = conn.body_params["action"] == "created" if is_created do project = Repo.get_by!(Project, repo_xref: conn.body_params["repository"]["id"]) commenter = conn.body_params["comment"]["user"] |> GitHub.User.from_json!() |> Syncer.sync_user() comment = conn.body_params["comment"]["body"] pr = GitHub.Pr.from_json!(conn.body_params["pull_request"]) %Command{ project: project, commenter: commenter, comment: comment, pr_xref: conn.body_params["pull_request"]["number"], pr: pr, patch: Syncer.sync_patch(project.id, pr)} |> Command.run() end end def do_webhook(conn, "github", "pull_request_review") do is_submitted = conn.body_params["action"] == "submitted" if is_submitted do project = Repo.get_by!(Project, repo_xref: conn.body_params["repository"]["id"]) commenter = conn.body_params["review"]["user"] |> GitHub.User.from_json!() |> Syncer.sync_user() comment = conn.body_params["review"]["body"] pr = GitHub.Pr.from_json!(conn.body_params["pull_request"]) %Command{ project: project, commenter: commenter, comment: comment, pr_xref: conn.body_params["pull_request"]["number"], pr: pr, patch: Syncer.sync_patch(project.id, pr)} |> Command.run() end end # The check suite is automatically added by GitHub. # But don't start until the user writes "r+" def do_webhook(conn, "github", "check_suite") do repo_xref = conn.body_params["repository"]["id"] branch = conn.body_params["check_suite"]["head_branch"] sha = conn.body_params["check_suite"]["head_sha"] action = conn.body_params["action"] project = Repo.get_by!(Project, repo_xref: repo_xref) staging_branch = project.staging_branch trying_branch = project.trying_branch case {action, branch} do {"completed", ^staging_branch} -> Batch |> Repo.get_by!(commit: sha, project_id: project.id) |> Batch.changeset(%{last_polled: 0}) |> Repo.update!() batcher = Batcher.Registry.get(project.id) Batcher.poll(batcher) {"completed", ^trying_branch} -> attemptor = Attemptor.Registry.get(project.id) Attemptor.poll(attemptor) _ -> :ok end end def do_webhook(conn, "github", "check_run") do :ok end def do_webhook(conn, "github", "status") do repo_xref = conn.body_params["repository"]["id"] commit = conn.body_params["commit"]["sha"] identifier = conn.body_params["context"] |> GitHub.map_changed_status() url = conn.body_params["target_url"] state = GitHub.map_state_to_status(conn.body_params["state"]) project = Repo.get_by!(Project, repo_xref: repo_xref) batcher = Batcher.Registry.get(project.id) Batcher.status(batcher, {commit, identifier, state, url}) attemptor = Attemptor.Registry.get(project.id) Attemptor.status(attemptor, {commit, identifier, state, url}) end def do_webhook_installation_sync(conn) do payload = conn.body_params installation_xref = payload["installation"]["id"] SyncerInstallation.start_synchronize_installation( %Installation{ installation_xref: installation_xref } ) end def do_webhook_pr(conn, %{ action: "opened", project: project, author: author, pr: pr, patch: patch }) do Project.ping!(project.id) %{ "pull_request" => %{ "body" => body, "number" => number, }, } = conn.body_params %Command{ project: project, commenter: author, comment: body, pr_xref: number, pr: pr, patch: patch} |> Command.run() end def do_webhook_pr(_conn, %{action: "closed", project: project, patch: p}) do Project.ping!(project.id) Repo.update!(Patch.changeset(p, %{open: false})) BranchDeleter.delete(p) end def do_webhook_pr(conn, %{action: "reopened", project: project, patch: p}) do Project.ping!(project.id) commit = conn.body_params["pull_request"]["head"]["sha"] Repo.update!(Patch.changeset(p, %{open: true, commit: commit})) end def do_webhook_pr(conn, %{action: "synchronize", project: pro, patch: p}) do batcher = Batcher.Registry.get(pro.id) Batcher.cancel(batcher, p.id) commit = conn.body_params["pull_request"]["head"]["sha"] Repo.update!(Patch.changeset(p, %{commit: commit})) end def do_webhook_pr(conn, %{action: "edited", patch: patch}) do %{ "pull_request" => %{ "title" => title, "body" => body, "base" => %{"ref" => base_ref}, }, } = conn.body_params Repo.update!(Patch.changeset(patch, %{ title: title, body: body, into_branch: base_ref})) end def do_webhook_pr(_conn, %{action: action}) do Logger.info(["WebhookController: Got unknown action: ", action]) end end
32.977419
88
0.609997
7955a42e7a83767496bf7b6c0cacd5bd67098273
1,600
ex
Elixir
lib/ucx_chat/robot/adapters/ucx_chat/connection.ex
smpallen99/ucx_chat
0dd98d0eb5e0537521844520ea2ba63a08fd3f19
[ "MIT" ]
60
2017-05-09T19:08:26.000Z
2021-01-20T11:09:42.000Z
lib/ucx_chat/robot/adapters/ucx_chat/connection.ex
smpallen99/ucx_chat
0dd98d0eb5e0537521844520ea2ba63a08fd3f19
[ "MIT" ]
6
2017-05-10T15:43:16.000Z
2020-07-15T07:14:41.000Z
lib/ucx_chat/robot/adapters/ucx_chat/connection.ex
smpallen99/ucx_chat
0dd98d0eb5e0537521844520ea2ba63a08fd3f19
[ "MIT" ]
10
2017-05-10T04:13:54.000Z
2020-12-28T10:30:27.000Z
defmodule UcxChat.Robot.Adapters.UcxChat.Connection do @moduledoc false use GenServer alias UcxChat.Robot.Adapters.UcxChat.{Connection} @name :robot require Logger defstruct name: nil, owner: nil, user: nil def start(opts) do name = Keyword.get(opts, :name) # user = Keyword.get(opts, :user, get_system_user()) user = nil GenServer.start(__MODULE__, {self(), name, user}, name: @name) end def init({owner, name, user}) do GenServer.cast(self(), :after_init) {:ok, %Connection{name: name, owner: owner, user: user}} end def handle_cast(:after_init, %{name: name, user: user} = state) do {:noreply, state} end def handle_info({:reply, %{text: text, room: room, user: %{id: user_id, name: name}}}, %{} = state) do body = if Regex.match? ~r/^http.+?(jpg|jpeg|png|gif)$/, text do # body = String.replace(text, ~r/^https?:\/\//, "") ~s(<img src="#{text}" class="bot-img">) else text end # this is where we send a message to the users. # need to figure out if this is a private message, or a channel message # Logger.error "reply text: #{inspect text} " UcxChat.MessageService.broadcast_bot_message room, user_id, body {:noreply, state} end @doc false def handle_info({:message, text, channel, user}, %{owner: owner} = state) do Logger.warn "message text: #{inspect text}, channel.id: #{inspect channel.id}" spawn fn -> :timer.sleep 200 Kernel.send(owner, {:message, %{"text" => text, "user" => user, "channel" => channel}}) end {:noreply, state} end end
28.571429
104
0.634375
7955c78778d216b81c07d0a1f48bbe3fca353d63
859
exs
Elixir
config/config.exs
chrismccord/phorechat
26c5b2f752f5c8e50d07d49b2b20d9341d8b2464
[ "MIT" ]
1
2021-01-19T05:40:52.000Z
2021-01-19T05:40:52.000Z
config/config.exs
chrismccord/phorechat
26c5b2f752f5c8e50d07d49b2b20d9341d8b2464
[ "MIT" ]
null
null
null
config/config.exs
chrismccord/phorechat
26c5b2f752f5c8e50d07d49b2b20d9341d8b2464
[ "MIT" ]
1
2015-10-02T15:58:09.000Z
2015-10-02T15:58:09.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. use Mix.Config # Configures the endpoint config :phorechat, Phorechat.Endpoint, url: [host: "localhost"], root: Path.dirname(__DIR__), secret_key_base: "uvTVl2jYQG6IIz0y6ZAQvGH1AOihZTdT6Nlr6uNpEJwBwYGLKmsdHA3xgqiAvwJ5", render_errors: [default_format: "html"], pubsub: [name: Phorechat.PubSub, adapter: Phoenix.PubSub.PG2] # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{Mix.env}.exs"
34.36
86
0.762515
7955cb67549426ea524f28c44e7c5a4366ee52e9
497
ex
Elixir
lib/bike_brigade/messaging/slack.ex
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
28
2021-10-11T01:53:53.000Z
2022-03-24T17:45:55.000Z
lib/bike_brigade/messaging/slack.ex
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
20
2021-10-21T08:12:31.000Z
2022-03-31T13:35:53.000Z
lib/bike_brigade/messaging/slack.ex
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
null
null
null
defmodule BikeBrigade.Messaging.Slack do alias BikeBrigade.SlackApi import BikeBrigade.Utils defmodule RiderSms do def post_message!(message) do payload = SlackApi.PayloadBuilder.build(get_config(:channel_id), message) :ok = SlackApi.post_message!(payload) end end defmodule Operations do def post_message!(message) do payload = SlackApi.PayloadBuilder.build(get_config(:channel_id), message) :ok = SlackApi.post_message!(payload) end end end
26.157895
79
0.734406
7955d1ced3ac4b10bdbab035722ebb09171be271
3,001
exs
Elixir
test/deferred_config_test.exs
Financial-Times/deferred_config
f8992e76d5e5dde69608fe96c75d9277dc546dd3
[ "MIT" ]
null
null
null
test/deferred_config_test.exs
Financial-Times/deferred_config
f8992e76d5e5dde69608fe96c75d9277dc546dd3
[ "MIT" ]
null
null
null
test/deferred_config_test.exs
Financial-Times/deferred_config
f8992e76d5e5dde69608fe96c75d9277dc546dd3
[ "MIT" ]
null
null
null
defmodule DeferredConfigTest do use ExUnit.Case doctest DeferredConfig @app :lazy_cfg_test_appname defmodule MyMod do def get_my_key(""<>_bin), do: "your key is 1234. write it down." end setup do delete_all_env(@app) # give each test a fake env that looks like this env = %{"PORT" => "4000"} System.put_env(env) system_transform = fn {:system, k} -> Map.get(env, k) {:system, k, {m, f}} -> apply m, f, [Map.get(env, k)] {:system, k, d} -> Map.get(env, k, d) {:system, k, d, {m, f}} -> apply( m, f, [Map.get(env, k)]) || d end # our mock stack -- only changes env var retrieval transforms = [ {&DeferredConfig.recognize_system_tuple/1, system_transform}, {&DeferredConfig.recognize_mfa_tuple/1, &DeferredConfig.transform_mfa_tuple/1} ] [transforms: transforms, system_transform: system_transform] end test "{:system, var}" do assert "4000" == DeferredConfig.get_system_tuple({:system, "PORT"}) end test "{:system, var, default}" do assert "4000" == DeferredConfig.get_system_tuple({:system, "PORT", "5000"}) assert "5000" == DeferredConfig.get_system_tuple({:system, "FAIL", "5000"}) end test "system tuples support", %{system_transform: transform} do cfg = [ port1: {:system, "PORT"}, port2: {:system, "PORT", "1111"}, port3: {:system, "FAIL", "1111"}, port4: {:system, "PORT", {String, :to_integer}}, port5: [{:system, "PORT", 3000, {String, :to_integer}}], ] actual = cfg |> DeferredConfig.transform_cfg([ {&DeferredConfig.recognize_system_tuple/1, transform} ]) assert actual[:port1] == "4000" assert actual[:port2] == "4000" assert actual[:port3] == "1111" assert actual[:port4] == 4000 assert actual[:port5] == [4000] actual |> DeferredConfig.apply_transformed_cfg!(@app) actual = Application.get_all_env @app assert actual[:port1] == "4000" assert actual[:port2] == "4000" assert actual[:port3] == "1111" assert actual[:port4] == 4000 assert actual[:port5] == [4000] end test "non-existent tuple values are handled" do r = DeferredConfig.transform_cfg([key: {:system, "ASDF"}]) assert r[:key] == nil end test "readme sys/mfa example", %{transforms: transforms} do readme_example = [ http: %{ # even inside nested data # the common 'system tuple' pattern is fully supported port: {:system, "PORT", {String, :to_integer}} }, # more general 'mfa tuple' pattern is also supported key: {:apply, {MyMod, :get_my_key, ["arg"]}} ] actual = readme_example |> DeferredConfig.transform_cfg(transforms) assert "your key is" <> _ = actual[:key] assert actual[:http][:port] == 4000 end defp delete_all_env(app) do app |> Application.get_all_env |> Enum.each(fn {k, _v} -> Application.delete_env( app, k ) end) end end
30.313131
79
0.612129
7955d7a69e76adb0e609ecd0ec89b3c88e58f633
984
ex
Elixir
lib/cog/util/ets_wrapper.ex
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
1,003
2016-02-23T17:21:12.000Z
2022-02-20T14:39:35.000Z
lib/cog/util/ets_wrapper.ex
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
906
2016-02-22T22:54:19.000Z
2022-03-11T15:19:43.000Z
lib/cog/util/ets_wrapper.ex
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
95
2016-02-23T13:42:31.000Z
2021-11-30T14:39:55.000Z
defmodule Cog.Util.ETSWrapper do def lookup(table, key) do case :ets.lookup(table, key) do [{^key, value}] -> {:ok, value} [] -> {:error, :unknown_key} end end def insert(table, key, value) do true = :ets.insert(table, {key, value}) {:ok, value} end def delete(table, key) do case lookup(table, key) do {:ok, value} -> true = :ets.delete(table, key) {:ok, value} error -> error end end def match_delete(table, query) do :ets.match_delete(table, query) end def each(table, fun) do :ets.safe_fixtable(table, true) do_each(table, :ets.first(table), fun) :ets.safe_fixtable(table, false) end defp do_each(_table, :'$end_of_table', _fun), do: :ok defp do_each(table, key, fun) do case lookup(table, key) do {:ok, value} -> fun.(key, value) _error -> :ok end do_each(table, :ets.next(table, key), fun) end end
20.081633
47
0.566057
7955e448cd9889f352deeca217ff25dc4c7727f4
1,388
exs
Elixir
config/dev.exs
WillsonSmith/similarfilms_phoenix
2466a3796ace5e0a09d345da3c76d90cf7747c13
[ "MIT" ]
null
null
null
config/dev.exs
WillsonSmith/similarfilms_phoenix
2466a3796ace5e0a09d345da3c76d90cf7747c13
[ "MIT" ]
null
null
null
config/dev.exs
WillsonSmith/similarfilms_phoenix
2466a3796ace5e0a09d345da3c76d90cf7747c13
[ "MIT" ]
null
null
null
use Mix.Config # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with brunch.io to recompile .js and .css sources. config :similarfilms_phoenix, SimilarfilmsPhoenix.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin", cd: Path.expand("../", __DIR__)]] # Watch static and templates for browser reloading. config :similarfilms_phoenix, SimilarfilmsPhoenix.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{priv/gettext/.*(po)$}, ~r{web/views/.*(ex)$}, ~r{web/templates/.*(eex)$} ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Configure your database config :similarfilms_phoenix, SimilarfilmsPhoenix.Repo, adapter: Ecto.Adapters.Postgres, username: "postgres", password: "postgres", database: "similarfilms_phoenix_dev", hostname: "localhost", pool_size: 10
31.545455
73
0.713256
7955eabd5cca354ee4df5bdae3e4eb1132f8ba39
897
ex
Elixir
test/support/channel_case.ex
Fudoshiki/vega
0577024afc734933048645976705784512fbc1f4
[ "MIT" ]
4
2020-03-22T22:12:29.000Z
2020-07-01T22:32:01.000Z
test/support/channel_case.ex
Fudoshiki/vega
0577024afc734933048645976705784512fbc1f4
[ "MIT" ]
3
2021-03-10T11:53:41.000Z
2021-10-17T11:18:54.000Z
test/support/channel_case.ex
Fudoshiki/vega
0577024afc734933048645976705784512fbc1f4
[ "MIT" ]
3
2020-03-30T19:03:23.000Z
2022-01-17T20:21:42.000Z
defmodule VegaWeb.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use VegaWeb.ChannelCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with channels use Phoenix.ChannelTest # The default endpoint for testing @endpoint VegaWeb.Endpoint end end setup tags do :ok end end
26.382353
61
0.734671
7956034f7b537294e82706015b478fea319cc015
1,666
ex
Elixir
lib/ectoproj/identity/identity.ex
Galanda/ectoproj
9dadeb27cc7b54034ab19363bc569d0fc4be671b
[ "MIT" ]
null
null
null
lib/ectoproj/identity/identity.ex
Galanda/ectoproj
9dadeb27cc7b54034ab19363bc569d0fc4be671b
[ "MIT" ]
null
null
null
lib/ectoproj/identity/identity.ex
Galanda/ectoproj
9dadeb27cc7b54034ab19363bc569d0fc4be671b
[ "MIT" ]
null
null
null
defmodule Ectoproj.Identity do @moduledoc """ The Identity context. """ import Ecto.Query, warn: false alias Ectoproj.Repo alias Ectoproj.Identity.User @doc """ Returns the list of users. ## Examples iex> list_users() [%User{}, ...] """ def list_users do Repo.all(User) end @doc """ Gets a single user. Raises `Ecto.NoResultsError` if the User does not exist. ## Examples iex> get_user!(123) %User{} iex> get_user!(456) ** (Ecto.NoResultsError) """ def get_user!(id), do: Repo.get!(User, id) @doc """ Creates a user. ## Examples iex> create_user(%{field: value}) {:ok, %User{}} iex> create_user(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ def create_user(attrs \\ %{}) do %User{} |> User.changeset(attrs) |> Repo.insert() end @doc """ Updates a user. ## Examples iex> update_user(user, %{field: new_value}) {:ok, %User{}} iex> update_user(user, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ def update_user(%User{} = user, attrs) do user |> User.changeset(attrs) |> Repo.update() end @doc """ Deletes a User. ## Examples iex> delete_user(user) {:ok, %User{}} iex> delete_user(user) {:error, %Ecto.Changeset{}} """ def delete_user(%User{} = user) do Repo.delete(user) end @doc """ Returns an `%Ecto.Changeset{}` for tracking user changes. ## Examples iex> change_user(user) %Ecto.Changeset{source: %User{}} """ def change_user(%User{} = user) do User.changeset(user, %{}) end end
15.866667
59
0.566627
79561a6e8915df4c489f35bfa0388fff4be66ccf
1,065
ex
Elixir
lib/date/date_convert.ex
appcues/timex
700643279531bbf1711cd721b3851f025cc28a95
[ "MIT" ]
null
null
null
lib/date/date_convert.ex
appcues/timex
700643279531bbf1711cd721b3851f025cc28a95
[ "MIT" ]
null
null
null
lib/date/date_convert.ex
appcues/timex
700643279531bbf1711cd721b3851f025cc28a95
[ "MIT" ]
null
null
null
defprotocol Timex.Date.Convert do def to_gregorian(date) def to_erlang_datetime(date) end defimpl Timex.Date.Convert, for: Timex.DateTime do alias Timex.DateTime, as: DateTime alias Timex.TimezoneInfo, as: TimezoneInfo @doc """ Converts a DateTime struct to an Erlang datetime tuple + timezone tuple ## Examples: iex> {{2015, 3, 5}, {12, 0, 0}} |> Date.from("America/Chicago") |> Date.Convert.to_gregorian {{2015, 3, 5}, {12, 0, 0}, {5, "CDT"}} """ def to_gregorian( %DateTime{ :year => y, :month => m, :day => d, :hour => h, :minute => min, :second => sec, :timezone => %TimezoneInfo{:abbreviation => abbrev, :offset_std => std} }) do # Use the correct abbreviation depending on whether we're in DST or not { {y, m, d}, {h, min, sec}, {std / 60, abbrev}} end @doc """ Converts a DateTime struct to an Erlang datetime tuple """ def to_erlang_datetime(%DateTime{:year => y, :month => m, :day => d, :hour => h, :minute => min, :second => sec}) do { {y, m, d}, {h, min, sec} } end end
31.323529
118
0.612207
7956264a9b0ec536a224dd1ad42a3bce42c9c743
1,393
ex
Elixir
clients/spanner/lib/google_api/spanner/v1/model/request_options.ex
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
clients/spanner/lib/google_api/spanner/v1/model/request_options.ex
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
clients/spanner/lib/google_api/spanner/v1/model/request_options.ex
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Spanner.V1.Model.RequestOptions do @moduledoc """ Common request options for various APIs. ## Attributes * `priority` (*type:* `String.t`, *default:* `nil`) - Priority for the request. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :priority => String.t() | nil } field(:priority) end defimpl Poison.Decoder, for: GoogleApi.Spanner.V1.Model.RequestOptions do def decode(value, options) do GoogleApi.Spanner.V1.Model.RequestOptions.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Spanner.V1.Model.RequestOptions do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
29.638298
83
0.73295
7956a56b9ddd568bdffa904a23893dcfc88963fc
1,125
exs
Elixir
day05/config/config.exs
bjorng/advent-of-code-2017
bd58a36864a4d82809253770f8a6d0c4e02cb59a
[ "Apache-2.0" ]
null
null
null
day05/config/config.exs
bjorng/advent-of-code-2017
bd58a36864a4d82809253770f8a6d0c4e02cb59a
[ "Apache-2.0" ]
null
null
null
day05/config/config.exs
bjorng/advent-of-code-2017
bd58a36864a4d82809253770f8a6d0c4e02cb59a
[ "Apache-2.0" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # third-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :day05, key: :value # # and access this configuration in your application as: # # Application.get_env(:day05, :key) # # You can also configure a third-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.290323
73
0.750222
7956b210ae0ef2bee31385621df4dcf1cd3f0caa
1,486
ex
Elixir
clients/vault/lib/google_api/vault/v1/model/close_matter_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/vault/lib/google_api/vault/v1/model/close_matter_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/vault/lib/google_api/vault/v1/model/close_matter_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Vault.V1.Model.CloseMatterResponse do @moduledoc """ Response to a CloseMatterRequest. ## Attributes * `matter` (*type:* `GoogleApi.Vault.V1.Model.Matter.t`, *default:* `nil`) - The updated matter, with state CLOSED. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :matter => GoogleApi.Vault.V1.Model.Matter.t() } field(:matter, as: GoogleApi.Vault.V1.Model.Matter) end defimpl Poison.Decoder, for: GoogleApi.Vault.V1.Model.CloseMatterResponse do def decode(value, options) do GoogleApi.Vault.V1.Model.CloseMatterResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Vault.V1.Model.CloseMatterResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.617021
119
0.740242
7956b80a516534bcac40b3608582e65831c0a6d6
1,590
exs
Elixir
apps/artemis_web/test/artemis_web/live/recognition_controller_live_test.exs
artemis-platform/artemis_teams
9930c3d9528e37b76f0525390e32b66eed7eadde
[ "MIT" ]
2
2020-04-23T02:29:18.000Z
2020-07-07T13:13:17.000Z
apps/artemis_web/test/artemis_web/live/recognition_controller_live_test.exs
chrislaskey/artemis_teams
9930c3d9528e37b76f0525390e32b66eed7eadde
[ "MIT" ]
4
2020-04-26T20:35:36.000Z
2020-11-10T22:13:19.000Z
apps/artemis_web/test/artemis_web/live/recognition_controller_live_test.exs
chrislaskey/artemis_teams
9930c3d9528e37b76f0525390e32b66eed7eadde
[ "MIT" ]
null
null
null
defmodule ArtemisWeb.RecognitionControllerLiveTest do # use ArtemisWeb.ConnCase # import Artemis.Factories # import Phoenix.LiveViewTest # setup %{conn: conn} do # {:ok, conn: sign_in(conn)} # end # describe "new recognition" do # test "renders new form", %{conn: conn} do # {:ok, _view, html} = live(conn, Routes.recognition_show_path(conn, :new)) # assert html =~ "New Recognition" # end # end # describe "show" do # setup [:create_record] # test "shows recognition", %{conn: conn, record: record} do # {:ok, _view, html} = live(conn, Routes.recognition_show_path(conn, :show, record)) # assert html =~ record.description # end # end # describe "edit recognition" do # setup [:create_record] # test "renders form for editing chosen recognition", %{conn: conn, record: record} do # {:ok, _view, html} = live(conn, Routes.recognition_show_path(conn, :edit, record)) # assert html =~ "Edit Recognition" # end # end # describe "delete recognition" do # setup [:create_record] # test "deletes chosen recognition", %{conn: conn, record: record} do # result = live(conn, Routes.recognition_show_path(conn, :delete, record)) # assert live_redirected_to(result) == Routes.recognition_path(conn, :index) # assert_error_sent 404, fn -> # {:ok, _view, _html} = live(conn, Routes.recognition_show_path(conn, :show, record)) # end # end # end # defp create_record(_) do # record = insert(:recognition) # {:ok, record: record} # end end
28.909091
93
0.642138
7956b8ca3bca303041146756a957c6ac5cfc09d6
1,925
ex
Elixir
lib/issues/cli.ex
leomindez/GithubIssues
57c3ef6000c6adc414d7de01df4a714e1242a64e
[ "MIT" ]
null
null
null
lib/issues/cli.ex
leomindez/GithubIssues
57c3ef6000c6adc414d7de01df4a714e1242a64e
[ "MIT" ]
null
null
null
lib/issues/cli.ex
leomindez/GithubIssues
57c3ef6000c6adc414d7de01df4a714e1242a64e
[ "MIT" ]
null
null
null
defmodule Issues.CLI do @default_count 4 import Issues.TableFormatter, only: [print_table_for_columns: 2] @moduledoc """ Handle the command line parsing and the dispatch to the various functions that end up generating a table of the last _n_ issues in a github project """ def main(argv) do argv |> parse_args |> process end @doc """ `argv` can be -h or --help, which returns :help. Otherwise it is a github user name, project name, and (optionally) the number of entries to format. Return a tuple of `{user, project, count}`, or `:help` if help was given. """ def parse_args(argv) do parse = OptionParser.parse(argv,switches: [help: :boolean], aliases: [h: :help]) case parse do {[help: true], _, _} -> :help {_, [user, project, count], _ } -> {user, project, String.to_integer(count)} {_, [user, project], _ } -> {user, project, @default_count} _ -> :help end end def process(:help) do IO.puts """ usage: issues <user> <project> [count | #{@default_count}] """ System.halt(0) end def process({user, project, count}) do Issues.GithubIssues.fetch(user, project) |> decode_response |> sort_into_ascending_order |> Enum.take(count) |> print_table_for_columns(["number","created_at","title"]) end def decode_response({:ok, body}), do: body def decode_response({:error, error}) do {_, message} = List.keyfind(error, "message", 0) IO.puts "Error fetching from github: #{message}" System.halt(2) end def sort_into_ascending_order(list_of_issues) do Enum.sort list_of_issues, fn i1, i2 -> Map.get(i1, "created_at") <= Map.get(i2, "created_at") end end end
28.308824
105
0.578701
7956f661aad897e0a6e0bd46179428aa858384dd
719
exs
Elixir
test/tiny_earl/link_test.exs
rossta/tiny-earl
60dca22617c38c75da384c432da6c6ae9a95df94
[ "MIT" ]
null
null
null
test/tiny_earl/link_test.exs
rossta/tiny-earl
60dca22617c38c75da384c432da6c6ae9a95df94
[ "MIT" ]
null
null
null
test/tiny_earl/link_test.exs
rossta/tiny-earl
60dca22617c38c75da384c432da6c6ae9a95df94
[ "MIT" ]
null
null
null
defmodule TinyEarl.LinkTest do use ExUnit.Case alias TinyEarl.Link test "link struct has url, token, uuid" do link = %Link{url: "url", token: "token", uuid: 123} %Link{url: url, token: token, uuid: _uuid} = link assert url == "url" assert token == "token" end test ".shorten produces a new token and uuid from url" do link = Link.shorten("http://example.org") assert link.url == "http://example.org" assert String.length(link.token) < 7, "Expected link token to be six characters or less" assert Regex.match?(~r/[A-Za-z0-9]+/, link.token), "Expected link token to be letters and numbers only" assert is_integer(link.uuid), "Expected link uuid to be an integer" end end
35.95
107
0.673157
7957151a0de50ffec309b76cdf0d04ddbdc05cf4
5,570
exs
Elixir
mix.exs
sascha-wolf/phoenix
92f13d685fee2e18f6d6d1f7785542ab3cc94261
[ "MIT" ]
1
2020-07-23T18:03:42.000Z
2020-07-23T18:03:42.000Z
mix.exs
sascha-wolf/phoenix
92f13d685fee2e18f6d6d1f7785542ab3cc94261
[ "MIT" ]
null
null
null
mix.exs
sascha-wolf/phoenix
92f13d685fee2e18f6d6d1f7785542ab3cc94261
[ "MIT" ]
null
null
null
defmodule Phoenix.MixProject do use Mix.Project @version "1.6.0-dev" # If the elixir requirement is updated, we need to make the installer # use at least the minimum requirement used here. Although often the # installer is ahead of Phoenix itself. @elixir_requirement "~> 1.9" def project do [ app: :phoenix, version: @version, elixir: @elixir_requirement, deps: deps(), package: package(), preferred_cli_env: [docs: :docs], consolidate_protocols: Mix.env() != :test, xref: [ exclude: [ {IEx, :started?, 0}, Ecto.Type, :ranch, :cowboy_req, Plug.Cowboy.Conn, Plug.Cowboy ] ], elixirc_paths: elixirc_paths(Mix.env()), name: "Phoenix", docs: docs(), aliases: aliases(), source_url: "https://github.com/phoenixframework/phoenix", homepage_url: "https://www.phoenixframework.org", description: """ Productive. Reliable. Fast. A productive web framework that does not compromise speed or maintainability. """ ] end defp elixirc_paths(:docs), do: ["lib", "installer/lib"] defp elixirc_paths(_), do: ["lib"] def application do [ mod: {Phoenix, []}, extra_applications: [:logger, :eex, :crypto, :public_key], env: [ logger: true, stacktrace_depth: nil, template_engines: [], format_encoders: [], filter_parameters: ["password"], serve_endpoints: false, gzippable_exts: ~w(.js .css .txt .text .html .json .svg .eot .ttf), static_compressors: [Phoenix.Digester.Gzip], trim_on_html_eex_engine: true ] ] end defp deps do [ {:plug, "~> 1.10"}, {:plug_crypto, "~> 1.1.2 or ~> 1.2"}, {:telemetry, "~> 0.4"}, {:phoenix_pubsub, "~> 2.0"}, # Optional deps {:plug_cowboy, "~> 2.2", optional: true}, {:jason, "~> 1.0", optional: true}, {:phoenix_html, "~> 2.14.2 or ~> 2.15", optional: true}, # Docs dependencies {:ex_doc, "~> 0.22", only: :docs}, {:inch_ex, "~> 0.2", only: :docs}, # Test dependencies (some also include :docs for cross references) {:gettext, "~> 0.15.0", only: [:docs, :test]}, {:telemetry_poller, "~> 0.4", only: [:docs, :test]}, {:telemetry_metrics, "~> 0.4", only: [:docs, :test]}, {:websocket_client, git: "https://github.com/jeremyong/websocket_client.git", only: :test} ] end defp package do [ maintainers: ["Chris McCord", "José Valim", "Gary Rennie", "Jason Stiebs"], licenses: ["MIT"], links: %{github: "https://github.com/phoenixframework/phoenix"}, files: ~w(assets/js lib priv CHANGELOG.md LICENSE.md mix.exs package.json README.md .formatter.exs) ] end defp docs do [ source_ref: "v#{@version}", main: "overview", logo: "logo.png", extra_section: "GUIDES", assets: "guides/assets", formatters: ["html", "epub"], groups_for_modules: groups_for_modules(), extras: extras(), groups_for_extras: groups_for_extras() ] end defp extras do [ "guides/introduction/overview.md", "guides/introduction/installation.md", "guides/introduction/up_and_running.md", "guides/introduction/community.md", "guides/directory_structure.md", "guides/request_lifecycle.md", "guides/plug.md", "guides/routing.md", "guides/controllers.md", "guides/views.md", "guides/ecto.md", "guides/contexts.md", "guides/mix_tasks.md", "guides/telemetry.md", "guides/realtime/channels.md", "guides/realtime/presence.md", "guides/testing/testing.md", "guides/testing/testing_contexts.md", "guides/testing/testing_controllers.md", "guides/testing/testing_channels.md", "guides/deployment/deployment.md", "guides/deployment/releases.md", "guides/deployment/gigalixir.md", "guides/deployment/heroku.md", "guides/howto/custom_error_pages.md", "guides/howto/using_ssl.md" ] end defp groups_for_extras do [ Introduction: ~r/guides\/introduction\/.?/, Guides: ~r/guides\/[^\/]+\.md/, "Real-time components": ~r/guides\/realtime\/.?/, Testing: ~r/guides\/testing\/.?/, Deployment: ~r/guides\/deployment\/.?/, "How-to's": ~r/guides\/howto\/.?/ ] end defp groups_for_modules do # Ungrouped Modules: # # Phoenix # Phoenix.Channel # Phoenix.Controller # Phoenix.Endpoint # Phoenix.Naming # Phoenix.Logger # Phoenix.Param # Phoenix.Presence # Phoenix.Router # Phoenix.Token # Phoenix.View [ Testing: [ Phoenix.ChannelTest, Phoenix.ConnTest ], "Adapters and Plugs": [ Phoenix.CodeReloader, Phoenix.Endpoint.Cowboy2Adapter ], "Socket and Transport": [ Phoenix.Socket, Phoenix.Socket.Broadcast, Phoenix.Socket.Message, Phoenix.Socket.Reply, Phoenix.Socket.Serializer, Phoenix.Socket.Transport ], Templating: [ Phoenix.Template, Phoenix.Template.EExEngine, Phoenix.Template.Engine, Phoenix.Template.ExsEngine ] ] end defp aliases do [ docs: ["docs", &generate_js_docs/1] ] end def generate_js_docs(_) do Mix.Task.run("app.start") System.cmd("npm", ["run", "docs"], cd: "assets") end end
27.038835
100
0.586894
79571a2247b08a71aede18ffa24e6a8abcf3bbe7
308
exs
Elixir
test/elm_phoenix_web_socket_example_web/views/layout_view_test.exs
phollyer/elm-phoenix-websocket-example
147da038b5ca4f9304924124c546284f12ecfaa8
[ "BSD-3-Clause" ]
null
null
null
test/elm_phoenix_web_socket_example_web/views/layout_view_test.exs
phollyer/elm-phoenix-websocket-example
147da038b5ca4f9304924124c546284f12ecfaa8
[ "BSD-3-Clause" ]
2
2020-12-29T15:13:39.000Z
2020-12-30T01:01:02.000Z
test/elm_phoenix_web_socket_example_web/views/layout_view_test.exs
phollyer/elm-phoenix-websocket-example
147da038b5ca4f9304924124c546284f12ecfaa8
[ "BSD-3-Clause" ]
null
null
null
defmodule ElmPhoenixWebSocketExampleWeb.LayoutViewTest do use ElmPhoenixWebSocketExampleWeb.ConnCase, async: true # When testing helpers, you may want to import Phoenix.HTML and # use functions such as safe_to_string() to convert the helper # result into an HTML string. # import Phoenix.HTML end
34.222222
65
0.795455
79572130b2d18625ed82ff0a32464e3037cfbb0a
129
ex
Elixir
debian/pcloudfs.cron.d.ex
rzr/pfs
d0381a0366d0b42f58ea0e9cc54d02c73211be5f
[ "BSD-2-Clause" ]
17
2016-02-19T14:47:33.000Z
2022-02-18T01:12:59.000Z
debian/pcloudfs.cron.d.ex
rzr/pfs
d0381a0366d0b42f58ea0e9cc54d02c73211be5f
[ "BSD-2-Clause" ]
2
2015-02-20T23:06:39.000Z
2017-10-03T11:33:04.000Z
debian/pcloudfs.cron.d.ex
rzr/pfs
d0381a0366d0b42f58ea0e9cc54d02c73211be5f
[ "BSD-2-Clause" ]
5
2015-10-13T20:20:39.000Z
2019-10-24T06:12:13.000Z
# # Regular cron jobs for the pcloudfs package # 0 4 * * * root [ -x /usr/bin/pcloudfs_maintenance ] && /usr/bin/pfs_maintenance
25.8
79
0.697674
7957263f4fe2add594ca6b79a9c0923712e71935
2,249
ex
Elixir
lib/openapi_compiler/typespec/api/response.ex
jshmrtn/openapi-compiler
72ce58321bcaf7310b1286fa90dd2feaa2a7b565
[ "MIT" ]
3
2021-09-07T13:13:44.000Z
2022-01-16T22:25:11.000Z
lib/openapi_compiler/typespec/api/response.ex
jshmrtn/openapi-compiler
72ce58321bcaf7310b1286fa90dd2feaa2a7b565
[ "MIT" ]
26
2020-03-31T17:26:58.000Z
2020-04-01T17:32:21.000Z
lib/openapi_compiler/typespec/api/response.ex
jshmrtn/openapi-compiler
72ce58321bcaf7310b1286fa90dd2feaa2a7b565
[ "MIT" ]
1
2020-10-27T13:32:07.000Z
2020-10-27T13:32:07.000Z
defmodule OpenAPICompiler.Typespec.Api.Response do @moduledoc false alias OpenAPICompiler.Typespec.Schema defmacro base_typespecs do quote location: :keep do @type response(possible_responses) :: {:ok, possible_responses} | {:error, {:unexpected_response, Tesla.Env.t()} | any} end end defmacro typespec(name, definition, context) do quote location: :keep, bind_quoted: [name: name, definition: definition, context: context, caller: __MODULE__] do type = caller.type(definition, context, __MODULE__) options_name = :"#{name}_options" @type unquote(options_name)() :: unquote(type) @type unquote(name)() :: response(unquote(options_name)()) end end @spec type(definition :: map, context :: OpenAPICompiler.Context.t(), caller :: atom) :: Macro.t() def type(definition, context, caller) do definition |> Map.get("responses", %{}) |> Enum.flat_map(fn {code, media_types} -> media_types |> Map.get("content", %{}) |> Enum.map(fn {_media_type, media_type_definition = %{}} -> media_type_definition["schema"] _ -> nil end) |> Enum.uniq() |> Enum.map(&{code, &1}) |> case do [] -> [{code, nil}] other -> other end end) |> Enum.map(fn {code, nil} -> {code, quote location: :keep do any() end} {code, type} -> {code, Schema.type(type, :read, context, caller)} end) |> Enum.map(fn {"default", typespec} -> quote location: :keep do {Tesla.Env.status(), unquote(typespec), Tesla.Env.t()} end {code, typespec} when is_binary(code) -> code = String.to_integer(code) quote location: :keep do {unquote(code), unquote(typespec), Tesla.Env.t()} end {code, typespec} when is_integer(code) -> quote location: :keep do {unquote(code), unquote(typespec), Tesla.Env.t()} end end) |> Enum.reduce( quote location: :keep do any() end, fn value, {:any, _, _} -> value value, acc -> {:|, [], [value, acc]} end ) end end
26.458824
100
0.558026
79578998f6dd9c14290b2d99c4488103454e1cdb
15,516
ex
Elixir
lib/patch/mock/code.ex
kianmeng/patch
d7d8d70a0285129ec67a43473db587011524fe0c
[ "MIT" ]
57
2020-04-22T00:19:04.000Z
2022-03-20T11:57:00.000Z
lib/patch/mock/code.ex
kianmeng/patch
d7d8d70a0285129ec67a43473db587011524fe0c
[ "MIT" ]
9
2021-10-29T20:54:56.000Z
2022-02-19T03:41:01.000Z
lib/patch/mock/code.ex
kianmeng/patch
d7d8d70a0285129ec67a43473db587011524fe0c
[ "MIT" ]
2
2021-07-02T14:41:48.000Z
2022-01-12T11:47:26.000Z
defmodule Patch.Mock.Code do @moduledoc """ Patch mocks out modules by generating mock modules and recompiling them for a `target` module. Patch's approach to mocking a module provides some powerful affordances. - Private functions can be mocked. - Internal function calls are effected by mocks regardless of the function's visibility without having to change the way code is written. - Private functions can be optionally exposed in the facade to make it possible to test a private function directly without changing its visibility in code. # Mocking Strategy There are 4 logical modules and 1 GenServer that are involved when mocking a module. The 4 logical modules: - `target` - The module to be mocked. - `facade` - The `target` module is replaced by a `facade` module that intercepts all external calls and redirects them to the `delegate` module. - `original` - The `target` module is preserved as the `original` module, with the important transformation that all local calls are redirected to the `delegate` module. - `delegate` - This module is responsible for checking with the `server` to see if a call is mocked and should be intercepted. If so, the mock value is returned, otherwise the `original` function is called. Each `target` module has an associated GenServer, a `Patch.Mock.Server` that has keeps state about the history of function calls and holds the mock data to be returned on interception. See `Patch.Mock.Server` for more information. ## Example Target Module To better understand how Patch works, consider the following example module. ```elixir defmodule Example do def public_function(argument_1, argument_2) do {:public, private_function(argument_1, argument_2)} end defp private_function(argument_1, argument_2) do {:private, argument_1, argument_2} end end ``` ### `facade` module The `facade` module is automatically generated based off the exports of the `target` module. It takes on the name of the `provided` module. For each exported function, a function is generated in the `facade` module that calls the `delegate` module. ```elixir defmodule Example do def public_function(argument_1, argument_2) do Patch.Mock.Delegate.For.Example.public_function(argument_1, argument_2) end end ``` ### `delegate` module The `delegate` module is automatically generated based off all the functions of the `target` module. It takes on a name based off the `target` module, see `Patch.Mock.Naming.delegate/1`. For each function, a function is generated in the `delegate` module that calls `Patch.Mock.Server.delegate/3` delegating to the server named for the `target` module, see `Patch.Mock.Naming.server/1`. ```elixir defmodule Patch.Mock.Delegate.For.Example do def public_function(argument_1, argument_2) do Patch.Mock.Server.delegate( Patch.Mock.Server.For.Example, :public_function, [argument_1, argument_2] ) end def private_function(argument_1, argument_2) do Patch.Mock.Server.delegate( Patch.Mock.Server.For.Example, :private_function, [argument_1, argument_2] ) end end ``` ### `original` module The `original` module takes on a name based off the `provided` module, see `Patch.Mock.Naming.original/1`. The code is transformed in the following ways. - All local calls are converted into remote calls to the `delegate` module. - All functions are exported ```elixir defmodule Patch.Mock.Original.For.Example do def public_function(argument_1, argument_2) do {:public, Patch.Mock.Delegate.For.Example.private_function(argument_1, argument_2)} end def private_function(argument_1, argument_2) do {:private, argument_1, argument_2} end end ``` ## External Function Calls First, let's examine how calls from outside the module are treated. ### Public Function Calls Code calling `Example.public_function/2` has the following call flow. ```text [Caller] -> facade -> delegate -> server -> mocked? -> yes (Intercepted) [Mock Value] <----------------------------|----' -> no -> original (Run Original Code) [Original Value] <--------------------------------------' ``` Calling a public funtion will either return the mocked value if it exists, or fall back to calling the original function. ### Private Function Calls Code calling `Example.private_function/2` has the following call flow. ```text [Caller] --------------------------> facade [UndefinedFunctionError] <-----' ``` Calling a private function continues to be an error from the external caller's point of view. The `expose` option does allow the facade to expose private functions, in those cases the call flow just follows the public call flow. ## Internal Calls Next, let's examine how calls from outside the module are treated. ### Public Function Calls Code in the `original` module calling public functions have their code transformed to call the `delegate` module. ```text original -> delegate -> server -> mocked? -> yes (Intercepted) [Mock Value] <------------------|----' -> no -> original (Run Original Code) [Original Value] <----------------------------' ``` Since the call is redirected to the `delegate`, calling a public funtion will either return the mocked value if it exists, or fall back to calling the original function. ### Private Function Call Flow Code in the `original` module calling private functions have their code transformed to call the `delegate` module ```text original -> delegate -> server -> mocked? -> yes (Intercepted) [Mock Value] <------------------|----' -> no -> original (Run Original Code) [Original Value] <----------------------------' ``` Since the call is redirected to the `delegate`, calling a private funtion will either return the mocked value if it exists, or fall back to calling the original function. ## Code Generation For additional details on how Code Generation works, see the `Patch.Mock.Code.Generate` module. """ alias Patch.Mock alias Patch.Mock.Code.Generate alias Patch.Mock.Code.Query alias Patch.Mock.Code.Unit @type binary_error :: :badfile | :nofile | :not_purged | :on_load_failure | :sticky_directory @type chunk_error :: :chunk_too_big | :file_error | :invalid_beam_file | :key_missing_or_invalid | :missing_backend | :missing_chunk | :not_a_beam_file | :unknown_chunk @type load_error :: :embedded | :badfile | :nofile | :on_load_failure @type compiler_option :: term() @type form :: term() @type export_classification :: :builtin | :generated | :normal @type exports :: Keyword.t(arity()) @typedoc """ Sum-type of all valid options """ @type option :: Mock.exposes_option() @doc """ Extracts the abstract_forms from a module """ @spec abstract_forms(module :: module) :: {:ok, [form()]} | {:error, :abstract_forms_unavailable} | {:error, chunk_error()} | {:error, load_error()} def abstract_forms(module) do with :ok <- ensure_loaded(module), {:ok, binary} <- binary(module) do case :beam_lib.chunks(binary, [:abstract_code]) do {:ok, {_, [abstract_code: {:raw_abstract_v1, abstract_forms}]}} -> {:ok, abstract_forms} {:error, :beam_lib, details} -> reason = elem(details, 0) {:error, reason} _ -> {:error, :abstract_forms_unavailable} end end end @doc """ Extracts the attribtues from a module """ @spec attributes(module :: module()) :: {:ok, Keyword.t()} | {:error, :attributes_unavailable} def attributes(module) do with :ok <- ensure_loaded(module) do try do Keyword.get(module.module_info(), :attributes, []) catch _, _ -> {:error, :attributes_unavailable} end end end @doc """ Classifies an exported mfa into one of the following classifications - :builtin - Export is a BIF. - :generated - Export is a generated function. - :normal - Export is a user defined function. """ @spec classify_export(module :: module(), function :: atom(), arity :: arity()) :: export_classification() def classify_export(_, :module_info, 0), do: :generated def classify_export(_, :module_info, 1), do: :generated def classify_export(module, function, arity) do if :erlang.is_builtin(module, function, arity) do :builtin else :normal end end @doc """ Compiles the provided abstract_form with the given compiler_options In addition to compiling, the module will be loaded. """ @spec compile(abstract_forms :: [form()], compiler_options :: [compiler_option()]) :: :ok | {:error, binary_error()} | {:error, {:abstract_forms_invalid, [form()], term()}} def compile(abstract_forms, compiler_options \\ []) do case :compile.forms(abstract_forms, [:return_errors | compiler_options]) do {:ok, module, binary} -> load_binary(module, binary) {:ok, module, binary, _} -> load_binary(module, binary) errors -> {:error, {:abstract_forms_invalid, abstract_forms, errors}} end end @doc """ Extracts the compiler options from a module. """ @spec compiler_options(module :: module()) :: {:ok, [compiler_option()]} | {:error, :compiler_options_unavailable} | {:error, chunk_error()} | {:error, load_error()} def compiler_options(module) do with :ok <- ensure_loaded(module), {:ok, binary} <- binary(module) do case :beam_lib.chunks(binary, [:compile_info]) do {:ok, {_, [compile_info: info]}} -> filtered_options = case Keyword.fetch(info, :options) do {:ok, options} -> filter_compiler_options(options) :error -> [] end {:ok, filtered_options} {:error, :beam_lib, details} -> reason = elem(details, 0) {:error, reason} _ -> {:error, :compiler_options_unavailable} end end end @doc """ Extracts the exports from the provided abstract_forms for the module. The exports returned can be controlled by the exposes argument. """ @spec exports(abstract_forms :: [form()], module :: module(), exposes :: Mock.exposes()) :: exports() def exports(abstract_forms, module, :public) do exports = Query.exports(abstract_forms) filter_exports(module, exports, :normal) end def exports(abstract_forms, module, :all) do exports = Query.functions(abstract_forms) filter_exports(module, exports, :normal) end def exports(abstract_forms, module, exposes) do exports = exposes ++ Query.exports(abstract_forms) filter_exports(module, exports, :normal) end @doc """ Given a module and a list of exports filters the list of exports to those that have the given classification. See `classify_export/3` for information about export classification """ @spec filter_exports(module :: module, exports :: exports(), classification :: export_classification()) :: exports() def filter_exports(module, exports, classification) do Enum.filter(exports, fn {name, arity} -> classify_export(module, name, arity) == classification end) end @doc """ Freezes a module by generating a copy of it under a frozen name with all remote calls to the `target` module re-routed to the frozen module. """ @spec freeze(module :: module) :: :ok | {:error, term} def freeze(module) do with {:ok, compiler_options} <- compiler_options(module), {:ok, _} <- unstick_module(module), {:ok, abstract_forms} <- abstract_forms(module), frozen_forms = Generate.frozen(abstract_forms, module), :ok <- compile(frozen_forms, compiler_options) do :ok end end @doc """ Mocks a module by generating a set of modules based on the `target` module. The `target` module's Unit is returned on success. """ @spec module(module :: module(), options :: [option()]) :: {:ok, Unit.t()} | {:error, term} def module(module, options \\ []) do exposes = options[:exposes] || :public with {:ok, compiler_options} <- compiler_options(module), {:ok, sticky?} <- unstick_module(module), {:ok, abstract_forms} <- abstract_forms(module), local_exports = exports(abstract_forms, module, :all), remote_exports = exports(abstract_forms, module, exposes), delegate_forms = Generate.delegate(abstract_forms, module, local_exports), facade_forms = Generate.facade(abstract_forms, module, remote_exports), original_forms = Generate.original(abstract_forms, module, local_exports), :ok <- compile(delegate_forms), :ok <- compile(original_forms, compiler_options), :ok <- compile(facade_forms) do unit = %Unit{ abstract_forms: abstract_forms, compiler_options: compiler_options, module: module, sticky?: sticky? } {:ok, unit} end end @doc """ Purges a module from the code server """ @spec purge(module :: module()) :: boolean() def purge(module) do :code.purge(module) :code.delete(module) end @doc """ Marks a module a sticky """ @spec stick_module(module :: module()) :: :ok | {:error, load_error()} def stick_module(module) do :code.stick_mod(module) ensure_loaded(module) end @doc """ Unsticks a module Returns `{:ok, was_sticky?}` on success, `{:error, reason}` otherwise """ @spec unstick_module(module :: module()) :: {:ok, boolean()} | {:error, load_error()} def unstick_module(module) do with :ok <- ensure_loaded(module) do if :code.is_sticky(module) do {:ok, :code.unstick_mod(module)} else {:ok, false} end end end ## Private @spec binary(module :: module()) :: {:ok, binary()} | {:error, :binary_unavailable} defp binary(module) do case :code.get_object_code(module) do {^module, binary, _} -> {:ok, binary} :error -> {:error, :binary_unavailable} end end @spec ensure_loaded(module :: module()) :: :ok | {:error, load_error()} defp ensure_loaded(module) do with {:module, ^module} <- Code.ensure_loaded(module) do :ok end end @spec filter_compiler_options(options :: [term()]) :: [term()] defp filter_compiler_options(options) do Enum.filter(options, fn {:parse_transform, _} -> false :makedeps_side_effects -> false :from_core -> false _ -> true end) end @spec load_binary(module :: module(), binary :: binary()) :: :ok | {:error, binary_error()} defp load_binary(module, binary) do with {:module, ^module} <- :code.load_binary(module, '', binary) do :ok end end end
30.846918
118
0.636504
79579163ae5c4954fec2315609dc769af2d24f0f
688
exs
Elixir
test/mix/tasks/ecto.migrate_test.exs
knewter/ecto
faacfeef25e35c42b1e97323b03d5bed9ba51416
[ "Apache-2.0" ]
null
null
null
test/mix/tasks/ecto.migrate_test.exs
knewter/ecto
faacfeef25e35c42b1e97323b03d5bed9ba51416
[ "Apache-2.0" ]
null
null
null
test/mix/tasks/ecto.migrate_test.exs
knewter/ecto
faacfeef25e35c42b1e97323b03d5bed9ba51416
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Ecto.MigrateTest do use ExUnit.Case, async: true import Mix.Tasks.Ecto.Migrate, only: [run: 2] defmodule Repo do def start_link do Process.put(:started, true) :ok end def priv do "hello" end def __repo__ do true end end test "runs the migrator" do run [to_string(Repo)], fn _, _ -> Process.put(:migrated, true) end assert Process.get(:migrated) assert Process.get(:started) end test "runs the migrator yielding the repository and migrations path" do run [to_string(Repo)], fn repo, path -> assert repo == Repo assert path == "hello/migrations" end end end
19.111111
73
0.630814
7957a9645b2a361314effedd41234b661ae13e77
1,509
exs
Elixir
mix.exs
software-mansion-labs/elixir-ibm-speech-to-text
2d1dec2f429071bb30a0568af8fec24787b8cd57
[ "Apache-2.0" ]
5
2019-11-15T10:44:36.000Z
2021-05-15T21:14:49.000Z
mix.exs
software-mansion-labs/elixir-ibm-speech-to-text
2d1dec2f429071bb30a0568af8fec24787b8cd57
[ "Apache-2.0" ]
null
null
null
mix.exs
software-mansion-labs/elixir-ibm-speech-to-text
2d1dec2f429071bb30a0568af8fec24787b8cd57
[ "Apache-2.0" ]
null
null
null
defmodule IbmSpeechToText.MixProject do use Mix.Project @version "0.3.0" @github_url "https://github.com/SoftwareMansion/elixir-ibm-speech-to-text" def project do [ app: :ibm_speech_to_text, version: @version, elixir: "~> 1.7", start_permanent: Mix.env() == :prod, deps: deps(), # hex description: "Elixir client for IBM Cloud Speech to Text service", package: package(), # docs name: "IBM Speech to Text", source_url: @github_url, docs: docs() ] end def application do [ extra_applications: [] ] end defp deps do [ {:ex_doc, "~> 0.19", only: :dev, runtime: false}, {:gun, "~> 1.3"}, {:jason, "~> 1.1"}, {:certifi, "~> 2.5"} ] end defp package do [ maintainers: ["Bartosz Błaszków"], licenses: ["Apache 2.0"], links: %{ "GitHub" => @github_url } ] end defp docs do alias IBMSpeechToText.{ Response, RecognitionResult, RecognitionAlternative, SpeakerLabelsResult } [ main: "readme", extras: ["README.md"], source_ref: "v#{@version}", nest_modules_by_prefix: [IBMSpeechToText, IBMSpeechToText.Message], groups_for_modules: [ Messages: ~r/IBMSpeechToText.Message/, "API Responses": [ Response, RecognitionResult, RecognitionAlternative, SpeakerLabelsResult ] ] ] end end
19.855263
76
0.555997
7957b0809d92f0d1b33a24044ede2490ec4893ca
485
ex
Elixir
lib/loom_web/views/error_view.ex
simonfraserduncan/my-copy
03c618035a06a63d8fcf9f6511ef59d3e4cf2da9
[ "Apache-2.0" ]
4
2021-02-20T02:47:36.000Z
2021-06-08T18:42:40.000Z
lib/loom_web/views/error_view.ex
DataStax-Examples/astra-loom
767c55200d08a6c592773d7af7da95873c4c3445
[ "Apache-2.0" ]
null
null
null
lib/loom_web/views/error_view.ex
DataStax-Examples/astra-loom
767c55200d08a6c592773d7af7da95873c4c3445
[ "Apache-2.0" ]
1
2021-02-17T18:28:35.000Z
2021-02-17T18:28:35.000Z
defmodule LoomWeb.ErrorView do use LoomWeb, :view # If you want to customize a particular status code # for a certain format, you may uncomment below. # def render("500.html", _assigns) do # "Internal Server Error" # end # By default, Phoenix returns the status message from # the template name. For example, "404.html" becomes # "Not Found". def template_not_found(template, _assigns) do Phoenix.Controller.status_message_from_template(template) end end
28.529412
61
0.731959
7957bdf6a93524a9d3325bc6c2918f48a38ca40b
1,267
ex
Elixir
lib/cast_decorator.ex
dvjoness/construct_params
d3dd21b9682cca0481e1a516b7448757a49d7a57
[ "MIT" ]
null
null
null
lib/cast_decorator.ex
dvjoness/construct_params
d3dd21b9682cca0481e1a516b7448757a49d7a57
[ "MIT" ]
null
null
null
lib/cast_decorator.ex
dvjoness/construct_params
d3dd21b9682cca0481e1a516b7448757a49d7a57
[ "MIT" ]
null
null
null
defmodule ConstructParams.CastDecorator do @moduledoc """ The macro allows casting the incoming controller parameters. This macro uses the [construct](https://hexdocs.pm/construct/readme.html) library for params validation. In case of a successful casting, the controller action params are replaced with the casted data. Otherwise the `FallbackController` is called with `{:error, errors}` parameters. ## Examples defmodule MyApp.MyController do use ConstructParams.CastDecorator @decorate cast(MyApp.ConstructCastModule) def create(conn, params) end end """ use Decorator.Define, cast: 1 def cast(cast_module, body, %{args: [conn, params], module: module}) do fallback_module = get_fallback_module(module) quote do case unquote(cast_module).make(unquote(params), make_map: true) do {:ok, casted_params} -> unquote(params) = casted_params unquote(body) {:error, errors} -> unquote(fallback_module).call(unquote(conn), {:error, :invalid_params, errors}) end end end defp get_fallback_module(module) do module |> Module.split() |> List.replace_at(-1, "FallbackController") |> Module.safe_concat() end end
28.155556
106
0.682715
7957fd5c90d208d5826cae63a188b887866636f7
2,044
ex
Elixir
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/option.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/option.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/option.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.ServiceConsumerManagement.V1.Model.Option do @moduledoc """ A protocol buffer option, which can be attached to a message, field, enumeration, etc. ## Attributes * `name` (*type:* `String.t`, *default:* `nil`) - The option's name. For protobuf built-in options (options defined in descriptor.proto), this is the short name. For example, `"map_entry"`. For custom options, it should be the fully-qualified name. For example, `"google.api.http"`. * `value` (*type:* `map()`, *default:* `nil`) - The option's value packed in an Any message. If the value is a primitive, the corresponding wrapper type defined in google/protobuf/wrappers.proto should be used. If the value is an enum, it should be stored as an int32 value using the google.protobuf.Int32Value type. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :name => String.t(), :value => map() } field(:name) field(:value, type: :map) end defimpl Poison.Decoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.Option do def decode(value, options) do GoogleApi.ServiceConsumerManagement.V1.Model.Option.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.Option do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.88
320
0.733366
795815fe05ae8ed7a7c0bde18b8eac44b1113bee
337
ex
Elixir
lib/apns/callback.ex
chvanikoff/apns4ex
7691a3ff660a722a37567f1a987e47583886a669
[ "MIT" ]
80
2015-09-08T16:35:52.000Z
2021-12-03T19:10:47.000Z
lib/apns/callback.ex
chvanikoff/apns4ex
7691a3ff660a722a37567f1a987e47583886a669
[ "MIT" ]
45
2015-09-10T19:33:12.000Z
2019-09-25T11:45:10.000Z
lib/apns/callback.ex
chvanikoff/apns4ex
7691a3ff660a722a37567f1a987e47583886a669
[ "MIT" ]
38
2015-09-08T16:37:27.000Z
2020-07-17T10:12:39.000Z
defmodule APNS.Callback do def error(%APNS.Error{error: error, message_id: message_id}, token \\ "unknown token") do APNS.Logger.warn(~s(error "#{error}" for message #{inspect(message_id)} to #{token})) end def feedback(%APNS.Feedback{token: token}) do APNS.Logger.info(~s(feedback received for token #{token})) end end
33.7
91
0.700297
79581c8622aac096b442270bbd251d9be2bed63d
3,343
ex
Elixir
clients/big_query/lib/google_api/big_query/v2/model/job_list_jobs.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/big_query/lib/google_api/big_query/v2/model/job_list_jobs.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/big_query/lib/google_api/big_query/v2/model/job_list_jobs.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.BigQuery.V2.Model.JobListJobs do @moduledoc """ ## Attributes * `configuration` (*type:* `GoogleApi.BigQuery.V2.Model.JobConfiguration.t`, *default:* `nil`) - [Full-projection-only] Specifies the job configuration. * `errorResult` (*type:* `GoogleApi.BigQuery.V2.Model.ErrorProto.t`, *default:* `nil`) - A result object that will be present only if the job has failed. * `id` (*type:* `String.t`, *default:* `nil`) - Unique opaque ID of the job. * `jobReference` (*type:* `GoogleApi.BigQuery.V2.Model.JobReference.t`, *default:* `nil`) - Job reference uniquely identifying the job. * `kind` (*type:* `String.t`, *default:* `bigquery#job`) - The resource type. * `state` (*type:* `String.t`, *default:* `nil`) - Running state of the job. When the state is DONE, errorResult can be checked to determine whether the job succeeded or failed. * `statistics` (*type:* `GoogleApi.BigQuery.V2.Model.JobStatistics.t`, *default:* `nil`) - [Output-only] Information about the job, including starting time and ending time of the job. * `status` (*type:* `GoogleApi.BigQuery.V2.Model.JobStatus.t`, *default:* `nil`) - [Full-projection-only] Describes the state of the job. * `user_email` (*type:* `String.t`, *default:* `nil`) - [Full-projection-only] Email address of the user who ran the job. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :configuration => GoogleApi.BigQuery.V2.Model.JobConfiguration.t(), :errorResult => GoogleApi.BigQuery.V2.Model.ErrorProto.t(), :id => String.t(), :jobReference => GoogleApi.BigQuery.V2.Model.JobReference.t(), :kind => String.t(), :state => String.t(), :statistics => GoogleApi.BigQuery.V2.Model.JobStatistics.t(), :status => GoogleApi.BigQuery.V2.Model.JobStatus.t(), :user_email => String.t() } field(:configuration, as: GoogleApi.BigQuery.V2.Model.JobConfiguration) field(:errorResult, as: GoogleApi.BigQuery.V2.Model.ErrorProto) field(:id) field(:jobReference, as: GoogleApi.BigQuery.V2.Model.JobReference) field(:kind) field(:state) field(:statistics, as: GoogleApi.BigQuery.V2.Model.JobStatistics) field(:status, as: GoogleApi.BigQuery.V2.Model.JobStatus) field(:user_email) end defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.JobListJobs do def decode(value, options) do GoogleApi.BigQuery.V2.Model.JobListJobs.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.JobListJobs do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
47.084507
187
0.703859
79584ca39d490edc1e26b5803fc7371192938590
2,033
exs
Elixir
config/prod.exs
antp/cxs_starter
349cbd61e561f276b552f95e88e24e01397b8519
[ "MIT" ]
null
null
null
config/prod.exs
antp/cxs_starter
349cbd61e561f276b552f95e88e24e01397b8519
[ "MIT" ]
null
null
null
config/prod.exs
antp/cxs_starter
349cbd61e561f276b552f95e88e24e01397b8519
[ "MIT" ]
null
null
null
use Mix.Config # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :cxs_starter, CxsStarterWeb.Endpoint, url: [host: "example.com", port: 80], cache_static_manifest: "priv/static/cache_manifest.json" # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :cxs_starter, CxsStarterWeb.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [ # port: 443, # cipher_suite: :strong, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH"), # transport_options: [socket_opts: [:inet6]] # ] # # The `cipher_suite` is set to `:strong` to support only the # latest and more secure SSL ciphers. This means old browsers # and clients may not be supported. You can set it to # `:compatible` for wider support. # # `:keyfile` and `:certfile` expect an absolute path to the key # and cert in disk or a relative path inside priv, for example # "priv/ssl/server.key". For all supported SSL configuration # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 # # We also recommend setting `force_ssl` in your endpoint, ensuring # no data is ever sent via http, always redirecting to https: # # config :cxs_starter, CxsStarterWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # Finally import the config/prod.secret.exs which loads secrets # and configuration from environment variables. import_config "prod.secret.exs"
36.303571
66
0.717659
79587409a056833aa0c8a79db12da1f11f519458
1,565
exs
Elixir
test/controllers/session_controller_test.exs
acloudiator/asciinema-server
f0afa4cb4312822f5dd56008b0c5ec9c7a410f85
[ "Apache-2.0" ]
null
null
null
test/controllers/session_controller_test.exs
acloudiator/asciinema-server
f0afa4cb4312822f5dd56008b0c5ec9c7a410f85
[ "Apache-2.0" ]
null
null
null
test/controllers/session_controller_test.exs
acloudiator/asciinema-server
f0afa4cb4312822f5dd56008b0c5ec9c7a410f85
[ "Apache-2.0" ]
null
null
null
defmodule Asciinema.SessionControllerTest do use AsciinemaWeb.ConnCase import Asciinema.Factory alias Asciinema.Repo alias Asciinema.Accounts setup %{conn: conn} do {:ok, conn: conn} end test "successful log-in", %{conn: conn} do user = insert(:user, email: "[email protected]", username: "blazko") conn = get conn, "/session/new", t: Accounts.login_token(user) assert redirected_to(conn, 302) == "/session/new" conn = get conn, "/session/new" assert html_response(conn, 200) conn = post conn, "/session" assert redirected_to(conn, 302) == "/~blazko" assert get_rails_flash(conn, :notice) =~ ~r/welcome/i end test "failed log-in due to invalid token", %{conn: conn} do conn = get conn, "/session/new", t: "nope" assert redirected_to(conn, 302) == "/session/new" conn = get conn, "/session/new" assert html_response(conn, 200) conn = post conn, "/session" assert redirected_to(conn, 302) == "/login/new" assert get_flash(conn, :error) =~ ~r/invalid/i end test "failed log-in due to account removed", %{conn: conn} do user = insert(:user, email: "[email protected]", username: "blazko") token = Accounts.login_token(user) Repo.delete!(user) conn = get conn, "/session/new", t: token assert redirected_to(conn, 302) == "/session/new" conn = get conn, "/session/new" assert html_response(conn, 200) conn = post conn, "/session" assert redirected_to(conn, 302) == "/login/new" assert get_flash(conn, :error) =~ ~r/removed/i end end
29.528302
71
0.65623
79587a8be5d4d7952f88e07703e59da05fff6796
29,292
ex
Elixir
lib/gen_state_machine.ex
jakeprem/gen_state_machine
9520790652bd73d2597dfd52e05b992226b2269a
[ "Apache-2.0" ]
null
null
null
lib/gen_state_machine.ex
jakeprem/gen_state_machine
9520790652bd73d2597dfd52e05b992226b2269a
[ "Apache-2.0" ]
null
null
null
lib/gen_state_machine.ex
jakeprem/gen_state_machine
9520790652bd73d2597dfd52e05b992226b2269a
[ "Apache-2.0" ]
null
null
null
defmodule GenStateMachine do @moduledoc """ A behaviour module for implementing a state machine. The advantage of using this module is that it will have a standard set of interface functions and include functionality for tracing and error reporting. It will also fit into a supervision tree. ## Example The `GenStateMachine` behaviour abstracts the state machine. Developers are only required to implement the callbacks and functionality they are interested in. Let's start with a code example and then explore the available callbacks. Imagine we want a `GenStateMachine` that works like a switch, allowing us to turn it on and off, as well as see how many times the switch has been turned on: defmodule Switch do use GenStateMachine # Callbacks def handle_event(:cast, :flip, :off, data) do {:next_state, :on, data + 1} end def handle_event(:cast, :flip, :on, data) do {:next_state, :off, data} end def handle_event({:call, from}, :get_count, state, data) do {:next_state, state, data, [{:reply, from, data}]} end end # Start the server {:ok, pid} = GenStateMachine.start_link(Switch, {:off, 0}) # This is the client GenStateMachine.cast(pid, :flip) #=> :ok GenStateMachine.call(pid, :get_count) #=> 1 We start our `Switch` by calling `start_link/3`, passing the module with the server implementation and its initial argument (a tuple where the first element is the initial state and the second is the initial data). We can primarily interact with the state machine by sending two types of messages. **call** messages expect a reply from the server (and are therefore synchronous) while **cast** messages do not. Every time you do a `call/3` or a `cast/2`, the message will be handled by `handle_event/4`. We can also use the `:state_functions` callback mode instead of the default, which is `:handle_event_function`: defmodule Switch do use GenStateMachine, callback_mode: :state_functions def off(:cast, :flip, data) do {:next_state, :on, data + 1} end def off(event_type, event_content, data) do handle_event(event_type, event_content, data) end def on(:cast, :flip, data) do {:next_state, :off, data} end def on(event_type, event_content, data) do handle_event(event_type, event_content, data) end def handle_event({:call, from}, :get_count, data) do {:keep_state_and_data, [{:reply, from, data}]} end end # Start the server {:ok, pid} = GenStateMachine.start_link(Switch, {:off, 0}) # This is the client GenStateMachine.cast(pid, :flip) #=> :ok GenStateMachine.call(pid, :get_count) #=> 1 Again, we start our `Switch` by calling `start_link/3`, passing the module with the server implementation and its initial argument, and interacting with it via **call** and **cast**. However, in `:state_functions` callback mode, every time you do a `call/3` or a `cast/2`, the message will be handled by the `state_name/3` function which is named the same as the current state. ## Callbacks In the default `:handle_event_function` callback mode, there are 4 callbacks required to be implemented. By adding `use GenStateMachine` to your module, Elixir will automatically define all 4 callbacks for you, leaving it up to you to implement the ones you want to customize. In the `:state_functions` callback mode, there are 3 callbacks required to be implemented. By adding `use GenStateMachine, callback_mode: :state_functions` to your module, Elixir will automatically define all 3 callbacks for you, leaving it up to you to implement the ones you want to customize, as well as `state_name/3` functions named the same as the states you wish to support. It is important to note that the default implementation of the `code_change/4` callback results in an `:undefined` error. This is because `code_change/4` is related to the quite difficult topic of hot upgrades, and if you need it, you should really be implementing it yourself. In normal use this callback will not be invoked. ## Name Registration Both `start_link/3` and `start/3` support registering the `GenStateMachine` under a given name on start via the `:name` option. Registered names are also automatically cleaned up on termination. The supported values are: * an atom - the `GenStateMachine` is registered locally with the given name using `Process.register/2`. * `{:global, term}`- the `GenStateMachine` is registered globally with the given term using the functions in the `:global` module. * `{:via, module, term}` - the `GenStateMachine` is registered with the given mechanism and name. The `:via` option expects a module that exports `register_name/2`, `unregister_name/1`, `whereis_name/1` and `send/2`. One such example is the `:global` module which uses these functions for keeping the list of names of processes and their associated pid's that are available globally for a network of Erlang nodes. For example, we could start and register our Switch server locally as follows: # Start the server and register it locally with name MySwitch {:ok, _} = GenStateMachine.start_link(Switch, {:off, 0}, name: MySwitch) # Now messages can be sent directly to MySwitch GenStateMachine.call(MySwitch, :get_count) #=> 0 Once the server is started, the remaining functions in this module (`call/3`, `cast/2`, and friends) will also accept an atom, or any `:global` or `:via` tuples. In general, the following formats are supported: * a `pid` * an `atom` if the server is locally registered * `{atom, node}` if the server is locally registered at another node * `{:global, term}` if the server is globally registered * `{:via, module, name}` if the server is registered through an alternative registry ## Client / Server APIs Although in the example above we have used `GenStateMachine.start_link/3` and friends to directly start and communicate with the server, most of the time we don't call the `GenStateMachine` functions directly. Instead, we wrap the calls in new functions representing the public API of the server. Here is a better implementation of our Switch module: defmodule Switch do use GenStateMachine # Client def start_link() do GenStateMachine.start_link(Switch, {:off, 0}) end def flip(pid) do GenStateMachine.cast(pid, :flip) end def get_count(pid) do GenStateMachine.call(pid, :get_count) end # Server (callbacks) def handle_event(:cast, :flip, :off, data) do {:next_state, :on, data + 1} end def handle_event(:cast, :flip, :on, data) do {:next_state, :off, data} end def handle_event({:call, from}, :get_count, state, data) do {:next_state, state, data, [{:reply, from, data}]} end def handle_event(event_type, event_content, state, data) do # Call the default implementation from GenStateMachine super(event_type, event_content, state, data) end end In practice, it is common to have both server and client functions in the same module. If the server and/or client implementations are growing complex, you may want to have them in different modules. ## Receiving custom messages The goal of a `GenStateMachine` is to abstract the "receive" loop for developers, automatically handling system messages, support code change, synchronous calls and more. Therefore, you should never call your own "receive" inside the `GenStateMachine` callbacks as doing so will cause the `GenStateMachine` to misbehave. If you want to receive custom messages, they will be delivered to the usual handler for your callback mode with event_type `:info`. ## Learn more If you wish to find out more about gen_statem, the documentation and links in Erlang can provide extra insight. * [`:gen_statem` module documentation](http://erlang.org/documentation/doc-8.0-rc1/lib/stdlib-3.0/doc/html/gen_statem.html) * [gen_statem Behaviour – OTP Design Principles](http://erlang.org/documentation/doc-8.0-rc1/doc/design_principles/statem.html) """ @typedoc """ The term representing the current state. In `:handle_event_function` callback mode, any term. In `:state_functions` callback mode, an atom. """ @type state :: state_name | term @typedoc """ The atom representing the current state in `:state_functions` callback mode. """ @type state_name :: atom @typedoc """ The persistent data (similar to a GenServer's `state`) for the GenStateMachine. """ @type data :: term @typedoc """ The source of the current event. `{:call, from}` will be received as a result of a call. `:cast` will be received as a result of a cast. `:info` will be received as a result of any regular process messages received. `:timeout` will be received as a result of a `:timeout` action. `:state_timeout` will be received as a result of a `:state_timeout` action. `:internal` will be received as a result of a `:next_event` action. See the erlang [documentation](http://erlang.org/documentation/doc-9.0/lib/stdlib-3.4/doc/html/gen_statem.html#type-event_type) for details. """ @type event_type :: :gen_statem.event_type() @typedoc """ The callback mode for the GenStateMachine. See the Example section above for more info. """ @type callback_mode :: :state_functions | :handle_event_function @typedoc """ The message content received as the result of an event. """ @type event_content :: term @typedoc """ State transition actions. They may be invoked by returning them from a state function or init/1. If present in a list of actions, they are executed in order, and any that set transition options (postpone, hibernate, and timeout) override any previously provided options of the same type. If the state changes, the queue of incoming events is reset to start with the oldest postponed. All events added as a result of a `:next_event` action are inserted in the queue to be processed before all other events. An event of type `:internal` should be used when you want to reliably distinguish an event inserted this way from an external event. See the erlang [documentation](http://erlang.org/documentation/doc-9.0/lib/stdlib-3.4/doc/html/gen_statem.html#type-action) for the possible values. """ @type action :: :gen_statem.action() @doc """ Invoked when the server is started. `start_link/3` (or `start/3`) will block until it returns. `args` is the argument term (second argument) passed to `start_link/3`. Returning `{:ok, state, data}` will cause `start_link/3` to return `{:ok, pid}` and the process to enter its loop. Returning `{:ok, state, data, actions}` is similar to `{:ok, state}` except the provided actions will be executed. Returning `:ignore` will cause `start_link/3` to return `:ignore` and the process will exit normally without entering the loop or calling `terminate/2`. If used when part of a supervision tree the parent supervisor will not fail to start nor immediately try to restart the `GenStateMachine`. The remainder of the supervision tree will be (re)started and so the `GenStateMachine` should not be required by other processes. It can be started later with `Supervisor.restart_child/2` as the child specification is saved in the parent supervisor. The main use cases for this are: * The `GenStateMachine` is disabled by configuration but might be enabled later. * An error occurred and it will be handled by a different mechanism than the `Supervisor`. Likely this approach involves calling `Supervisor.restart_child/2` after a delay to attempt a restart. Returning `{:stop, reason}` will cause `start_link/3` to return `{:error, reason}` and the process to exit with reason `reason` without entering the loop or calling `terminate/2`. This function can optionally throw a result to return it. """ @callback init(args :: term) :: :gen_statem.init_result(state) @doc """ Whenever a `GenStateMachine` in callback mode `:state_functions` receives a call, cast, or normal process message, a state function is called. This spec exists to document the callback, but in actual use the name of the function is probably not going to be state_name. Instead, there will be at least one state function named after each state you wish to handle. See the Examples section above for more info. These functions can optionally throw a result to return it. See the erlang [documentation](http://erlang.org/documentation/doc-9.0/lib/stdlib-3.4/doc/html/gen_statem.html#type-event_handler_result) for a complete reference. """ @callback state_name(event_type, event_content, data) :: :gen_statem.event_handler_result(state_name()) @doc """ Whenever a `GenStateMachine` in callback mode `:handle_event_function` (the default) receives a call, cast, or normal process messsage, this callback will be invoked. This function can optionally throw a result to return it. See the erlang [documentation](http://erlang.org/documentation/doc-9.0/lib/stdlib-3.4/doc/html/gen_statem.html#type-event_handler_result) for a complete reference. """ @callback handle_event(event_type, event_content, state, data) :: :gen_statem.event_handler_result(state()) @doc """ Invoked when the server is about to exit. It should do any cleanup required. `reason` is exit reason, `state` is the current state, and `data` is the current data of the `GenStateMachine`. The return value is ignored. `terminate/2` is called if a callback (except `init/1`) returns a `:stop` tuple, raises, calls `Kernel.exit/1` or returns an invalid value. It may also be called if the `GenStateMachine` traps exits using `Process.flag/2` *and* the parent process sends an exit signal. If part of a supervision tree a `GenStateMachine`'s `Supervisor` will send an exit signal when shutting it down. The exit signal is based on the shutdown strategy in the child's specification. If it is `:brutal_kill` the `GenStateMachine` is killed and so `terminate/2` is not called. However if it is a timeout the `Supervisor` will send the exit signal `:shutdown` and the `GenStateMachine` will have the duration of the timeout to call `terminate/2` - if the process is still alive after the timeout it is killed. If the `GenStateMachine` receives an exit signal (that is not `:normal`) from any process when it is not trapping exits it will exit abruptly with the same reason and so not call `terminate/2`. Note that a process does *NOT* trap exits by default and an exit signal is sent when a linked process exits or its node is disconnected. Therefore it is not guaranteed that `terminate/2` is called when a `GenStateMachine` exits. For such reasons, we usually recommend important clean-up rules to happen in separated processes either by use of monitoring or by links themselves. For example if the `GenStateMachine` controls a `port` (e.g. `:gen_tcp.socket`) or `File.io_device`, they will be closed on receiving a `GenStateMachine`'s exit signal and do not need to be closed in `terminate/2`. If `reason` is not `:normal`, `:shutdown` nor `{:shutdown, term}` an error is logged. This function can optionally throw a result, which is ignored. """ @callback terminate(reason :: term, state, data) :: any @doc """ Invoked to change the state of the `GenStateMachine` when a different version of a module is loaded (hot code swapping) and the state and/or data's term structure should be changed. `old_vsn` is the previous version of the module (defined by the `@vsn` attribute) when upgrading. When downgrading the previous version is wrapped in a 2-tuple with first element `:down`. `state` is the current state of the `GenStateMachine`, `data` is the current data, and `extra` is any extra data required to change the state. Returning `{:ok, new_state, new_data}` changes the state to `new_state`, the data to `new_data`, and the code change is successful. On OTP versions before 19.1, if you wish to change the callback mode as part of an upgrade/downgrade, you may return `{callback_mode, new_state, new_data}`. It is important to note however that for a downgrade you must use the argument `extra`, `{:down, vsn}` from the argument `old_vsn`, or some other data source to determine what the previous callback mode was. Returning `reason` fails the code change with reason `reason` and the state and data remains the same. If `code_change/4` raises the code change fails and the loop will continue with its previous state. Therefore this callback does not usually contain side effects. This function can optionally throw a result to return it. """ @callback code_change(old_vsn :: term | {:down, vsn :: term}, state, data, extra :: term) :: {:ok, state, data} | {callback_mode, state, data} | (reason :: term) @doc """ Invoked in some cases to retrieve a formatted version of the `GenStateMachine` status. This callback can be useful to control the *appearance* of the status of the `GenStateMachine`. For example, it can be used to return a compact representation of the `GenStateMachines`'s state/data to avoid having large terms printed. * one of `:sys.get_status/1` or `:sys.get_status/2` is invoked to get the status of the `GenStateMachine`; in such cases, `reason` is `:normal` * the `GenStateMachine` terminates abnormally and logs an error; in such cases, `reason` is `:terminate` `pdict_state_and_data` is a three-element list `[pdict, state, data]` where `pdict` is a list of `{key, value}` tuples representing the current process dictionary of the `GenStateMachine`, `state` is the current state of the `GenStateMachine`, and `data` is the current data. This function can optionally throw a result to return it. """ @callback format_status(reason :: :normal | :terminate, pdict_state_and_data :: list) :: term @optional_callbacks state_name: 3, handle_event: 4, format_status: 2 @gen_statem_callback_mode_callback Application.loaded_applications() |> Enum.find_value(fn {app, _, vsn} -> app == :stdlib and vsn end) |> to_string() |> String.split(".") |> (case do [major] -> "#{major}.0.0" [major, minor] -> "#{major}.#{minor}.0" [major, minor, patch | _] -> "#{major}.#{minor}.#{patch}" end) |> Version.parse() |> elem(1) |> Version.match?(">= 3.1.0") @doc false defmacro __using__(args) do {callback_mode, args} = Keyword.pop(args, :callback_mode, :handle_event_function) quote location: :keep do @behaviour GenStateMachine unless unquote(@gen_statem_callback_mode_callback) do @before_compile GenStateMachine end @gen_statem_callback_mode unquote(callback_mode) @doc false def init({state, data}) do {:ok, state, data} end if unquote(@gen_statem_callback_mode_callback) do def callback_mode do @gen_statem_callback_mode end end if @gen_statem_callback_mode == :handle_event_function do @doc false def handle_event(_event_type, _event_content, _state, _data) do {:stop, :bad_event} end end @doc false def terminate(_reason, _state, _data) do :ok end @doc false def code_change(_old_vsn, _state, _data, _extra) do :undefined end @doc """ Returns a specification to start this module under a supervisor. See `Supervisor` in Elixir v1.6+. """ def child_spec(arg) do default = %{id: __MODULE__, start: {__MODULE__, :start_link, [arg]}} Enum.reduce(unquote(args), default, fn {key, value}, acc when key in [:id, :start, :restart, :shutdown, :type, :modules] -> Map.put(acc, key, value) {key, _value}, _acc -> raise ArgumentError, "unknown key #{inspect(key)} in child specification override" end) end overridable_funcs = [init: 1, terminate: 3, code_change: 4, child_spec: 1] overridable_funcs = if @gen_statem_callback_mode == :handle_event_function do [handle_event: 4] ++ overridable_funcs else overridable_funcs end defoverridable overridable_funcs end end @doc false defmacro __before_compile__(_env) do quote location: :keep do defoverridable init: 1, code_change: 4 @doc false def init(args) do result = try do super(args) catch thrown -> thrown end case result do {:handle_event_function, _, _} = return -> {:stop, {:bad_return_value, return}} {:state_functions, _, _} = return -> {:stop, {:bad_return_value, return}} {:ok, state, data} -> {@gen_statem_callback_mode, state, data} {:ok, state, data, actions} -> {@gen_statem_callback_mode, state, data, actions} other -> other end end @doc false def code_change(old_vsn, state, data, extra) do result = try do super(old_vsn, state, data, extra) catch thrown -> thrown end case result do {:handle_event_function, state, data} -> {:handle_event_function, state, data} {:state_functions, state, data} -> {:state_functions, state, data} {:ok, state, data} -> {@gen_statem_callback_mode, state, data} other -> other end end end end @doc """ Starts a `GenStateMachine` process linked to the current process. This is often used to start the `GenStateMachine` as part of a supervision tree. Once the server is started, the `init/1` function of the given `module` is called with `args` as its arguments to initialize the server. To ensure a synchronized start-up procedure, this function does not return until `init/1` has returned. Note that a `GenStateMachine` started with `start_link/3` is linked to the parent process and will exit in case of crashes from the parent. The `GenStateMachine` will also exit due to the `:normal` reasons in case it is configured to trap exits in the `init/1` callback. ## Options * `:name` - used for name registration as described in the "Name registration" section of the module documentation * `:timeout` - if present, the server is allowed to spend the given amount of milliseconds initializing or it will be terminated and the start function will return `{:error, :timeout}` * `:debug` - if present, the corresponding function in the [`:sys` module](http://www.erlang.org/doc/man/sys.html) is invoked * `:spawn_opt` - if present, its value is passed as options to the underlying process as in `Process.spawn/4` ## Return values If the server is successfully created and initialized, this function returns `{:ok, pid}`, where `pid` is the pid of the server. If a process with the specified server name already exists, this function returns `{:error, {:already_started, pid}}` with the pid of that process. If the `init/1` callback fails with `reason`, this function returns `{:error, reason}`. Otherwise, if it returns `{:stop, reason}` or `:ignore`, the process is terminated and this function returns `{:error, reason}` or `:ignore`, respectively. """ @spec start_link(module, any, GenServer.options()) :: GenServer.on_start() def start_link(module, args, options \\ []) do {name, options} = Keyword.pop(options, :name) if name do name = if is_atom(name) do {:local, name} else name end :gen_statem.start_link(name, module, args, options) else :gen_statem.start_link(module, args, options) end end @doc """ Starts a `GenStateMachine` process without links (outside of a supervision tree). See `start_link/3` for more information. """ @spec start(module, any, GenServer.options()) :: GenServer.on_start() def start(module, args, options \\ []) do {name, options} = Keyword.pop(options, :name) if name do name = if is_atom(name) do {:local, name} else name end :gen_statem.start(name, module, args, options) else :gen_statem.start(module, args, options) end end @doc """ Stops the server with the given `reason`. The `terminate/2` callback of the given `server` will be invoked before exiting. This function returns `:ok` if the server terminates with the given reason; if it terminates with another reason, the call exits. This function keeps OTP semantics regarding error reporting. If the reason is any other than `:normal`, `:shutdown` or `{:shutdown, _}`, an error report is logged. """ @spec stop(GenServer.server(), reason :: term, timeout) :: :ok def stop(server, reason \\ :normal, timeout \\ :infinity) do :gen_statem.stop(server, reason, timeout) end @doc """ Makes a synchronous call to the `server` and waits for its reply. The client sends the given `request` to the server and waits until a reply arrives or a timeout occurs. The appropriate state function will be called on the server to handle the request. `server` can be any of the values described in the "Name registration" section of the documentation for this module. ## Timeouts `timeout` is an integer greater than zero which specifies how many milliseconds to wait for a reply, or the atom `:infinity` to wait indefinitely. The default value is `:infinity`. If no reply is received within the specified time, the function call fails and the caller exits. If the caller catches an exit, to avoid getting a late reply in the caller's inbox, this function spawns a proxy process that does the call. A late reply gets delivered to the dead proxy process, and hence gets discarded. This is less efficient than using `:infinity` as a timeout. """ @spec call(GenServer.server(), term, timeout) :: term def call(server, request, timeout \\ :infinity) do :gen_statem.call(server, request, timeout) end @doc """ Sends an asynchronous request to the `server`. This function always returns `:ok` regardless of whether the destination `server` (or node) exists. Therefore it is unknown whether the destination `server` successfully handled the message. The appropriate state function will be called on the server to handle the request. """ @spec cast(GenServer.server(), term) :: :ok def cast(server, request) do :gen_statem.cast(server, request) end @doc """ Sends replies to clients. Can be used to explicitly send replies to multiple clients. This function always returns `:ok`. See `reply/2` for more information. """ @spec reply([:gen_statem.reply_action()]) :: :ok def reply(replies) do :gen_statem.reply(replies) end @doc """ Replies to a client. This function can be used to explicitly send a reply to a client that called `call/3` when the reply cannot be specified in the return value of a state function. `client` must be the `from` element of the event type accepted by state functions. `reply` is an arbitrary term which will be given back to the client as the return value of the call. Note that `reply/2` can be called from any process, not just the one that originally received the call (as long as that process communicated the `from` argument somehow). This function always returns `:ok`. ## Examples def handle_event({:call, from}, :reply_in_one_second, state, data) do Process.send_after(self(), {:reply, from}, 1_000) :keep_state_and_data end def handle_event(:info, {:reply, from}, state, data) do GenStateMachine.reply(from, :one_second_has_passed) end """ @spec reply(GenServer.from(), term) :: :ok def reply(client, reply) do :gen_statem.reply(client, reply) end end
36.984848
139
0.678172
79588ec4db24837201051b8c137215f19e97ad0f
3,199
ex
Elixir
clients/you_tube/lib/google_api/you_tube/v3/model/playlist_snippet.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/playlist_snippet.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/playlist_snippet.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.YouTube.V3.Model.PlaylistSnippet do @moduledoc """ Basic details about a playlist, including title, description and thumbnails. ## Attributes - tags ([String.t]): Keyword tags associated with the playlist. Defaults to: `null`. - channelId (String.t): The ID that YouTube uses to uniquely identify the channel that published the playlist. Defaults to: `null`. - channelTitle (String.t): The channel title of the channel that the video belongs to. Defaults to: `null`. - defaultLanguage (String.t): The language of the playlist&#39;s default title and description. Defaults to: `null`. - description (String.t): The playlist&#39;s description. Defaults to: `null`. - localized (PlaylistLocalization): Localized title and description, read-only. Defaults to: `null`. - publishedAt (DateTime.t): The date and time that the playlist was created. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. Defaults to: `null`. - thumbnails (ThumbnailDetails): A map of thumbnail images associated with the playlist. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail. Defaults to: `null`. - title (String.t): The playlist&#39;s title. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :tags => list(any()), :channelId => any(), :channelTitle => any(), :defaultLanguage => any(), :description => any(), :localized => GoogleApi.YouTube.V3.Model.PlaylistLocalization.t(), :publishedAt => DateTime.t(), :thumbnails => GoogleApi.YouTube.V3.Model.ThumbnailDetails.t(), :title => any() } field(:tags, type: :list) field(:channelId) field(:channelTitle) field(:defaultLanguage) field(:description) field(:localized, as: GoogleApi.YouTube.V3.Model.PlaylistLocalization) field(:publishedAt, as: DateTime) field(:thumbnails, as: GoogleApi.YouTube.V3.Model.ThumbnailDetails) field(:title) end defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.PlaylistSnippet do def decode(value, options) do GoogleApi.YouTube.V3.Model.PlaylistSnippet.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.PlaylistSnippet do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
44.430556
263
0.723351
79589eb4ce146b1ee124a7efb2e871ee711ce132
3,259
ex
Elixir
lib/formatter.ex
dbernheisel/cldr_calendars_format
3777fc54fc21f9d942932927f2576bd1261c0831
[ "Apache-2.0" ]
null
null
null
lib/formatter.ex
dbernheisel/cldr_calendars_format
3777fc54fc21f9d942932927f2576bd1261c0831
[ "Apache-2.0" ]
null
null
null
lib/formatter.ex
dbernheisel/cldr_calendars_format
3777fc54fc21f9d942932927f2576bd1261c0831
[ "Apache-2.0" ]
null
null
null
defmodule Cldr.Calendar.Formatter do @moduledoc """ Calendar formatter behaviour. This behaviour defines a set of callbacks that are invoked during the formatting of a calendar. At each point in the formatting process the callbacks are invoked from the "inside out". That is, `format_day/4` is invoked for each day of the week, then `format_week/5` is called, then `format_month/4` and finally `format_year/3` is called if required. """ alias Cldr.Calendar.Format.Options @doc """ Returns the formatted calendar for a year ## Arguments * `formatted_months` is the result returned by `format_month/4` * `year` is the year for which the calendar is requested * `month` is the month for which the calendar is requested * `options` is a `Cldr.Calendar.Formatter.Options` struct ## Returns * An arbitrary result as required. """ @callback format_year( formatted_months :: String.t(), year :: Date.year(), options :: Keyword.t() | Options.t() ) :: any() @doc """ Returns the formatted calendar for a month ## Arguments * `formatted_weeks` is the result returned by `format_week/5` * `year` is the year for which the calendar is requested * `month` is the month for which the calendar is requested * `options` is a `Cldr.Calendar.Formatter.Options` struct ## Returns * An arbitrary result as required which is either returned if called by `Cldr.Calendar.Format.month/3` or passed to `format_year/3` if not. """ @callback format_month( formatted_weeks :: String.t(), year :: Date.year(), month :: Date.month(), options :: Keyword.t() | Options.t() ) :: any() @doc """ Returns the formatted calendar for a week ## Arguments * `formatted_days` is the result returned by `format_day/4` * `year` is the year for which the calendar is requested * `month` is the month for which the calendar is requested * `week_number` is a 2-tuple of the form `{year, week_number}` that represents the week of year for week to be formatted * `options` is a `Cldr.Calendar.Formatter.Options` struct ## Returns * An arbitrary result as required which is passed to `format_month/4` """ @callback format_week( formatted_days :: String.t(), year :: Date.year(), month :: Date.month(), week_number :: {Date.year(), pos_integer}, options :: Options.t() ) :: any() @doc """ Returns the formatted calendar for a day ## Arguments * `formatted_months` is the result returned by `format_month/4` * `year` is the year for which the calendar is requested * `month` is the month for which the calendar is requested * `options` is a `Cldr.Calendar.Formatter.Options` struct ## Returns * An arbitrary result as required which is passed to `format_week/5` """ @callback format_day( date :: Date.t(), year :: Date.year(), month :: Date.month(), options :: Options.t() ) :: any() end
22.170068
56
0.616447
7958b63c5383d42ad4a155683724663bafdc1e39
275
exs
Elixir
notebooks/modulo_4/parte_2/ecto_example/priv/university/migrations/20211110223638_create_students.exs
igorgbr/curso-alquimia-stone
c5e40b0efcb7eef282f0f13a421671580c2762c1
[ "MIT" ]
14
2021-11-19T00:22:09.000Z
2022-01-29T03:58:09.000Z
notebooks/modulo_4/parte_2/ecto_example/priv/university/migrations/20211110223638_create_students.exs
igorgbr/curso-alquimia-stone
c5e40b0efcb7eef282f0f13a421671580c2762c1
[ "MIT" ]
null
null
null
notebooks/modulo_4/parte_2/ecto_example/priv/university/migrations/20211110223638_create_students.exs
igorgbr/curso-alquimia-stone
c5e40b0efcb7eef282f0f13a421671580c2762c1
[ "MIT" ]
1
2022-03-01T00:49:50.000Z
2022-03-01T00:49:50.000Z
defmodule EctoExample.University.Repo.Migrations.CreateStudents do use Ecto.Migration def change do create table("students") do add(:student_name, :string) add(:grade, :decimal) add(:high_school_size, :integer) timestamps() end end end
21.153846
66
0.687273
7958d275f3bb7a6f0a0ddedaf0cc594f5b675554
1,155
exs
Elixir
config/config.exs
betrybe/markright
1b81a2d9931b70645f9eff70d2605f0e9a58f396
[ "MIT" ]
15
2017-01-12T19:24:35.000Z
2021-04-27T14:44:08.000Z
config/config.exs
betrybe/markright
1b81a2d9931b70645f9eff70d2605f0e9a58f396
[ "MIT" ]
8
2017-02-13T17:01:35.000Z
2021-07-27T16:20:52.000Z
config/config.exs
betrybe/markright
1b81a2d9931b70645f9eff70d2605f0e9a58f396
[ "MIT" ]
1
2021-04-24T18:40:11.000Z
2021-04-24T18:40:11.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :markright, key: :value # # And access this configuration in your application as: # # Application.get_env(:markright, :key) # # Or configure a 3rd-party app: # config :logger, :console, format: "[$level] $message\n", level: :debug # 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"
38.5
73
0.753247
7958d2ad7967ba8e99556e753f3abe4970a27593
360
ex
Elixir
lib/blitz/supervisor.ex
edraut/blitz
fa6b645e943f36ba40b7104ff4f8df6110aa7645
[ "MIT" ]
null
null
null
lib/blitz/supervisor.ex
edraut/blitz
fa6b645e943f36ba40b7104ff4f8df6110aa7645
[ "MIT" ]
null
null
null
lib/blitz/supervisor.ex
edraut/blitz
fa6b645e943f36ba40b7104ff4f8df6110aa7645
[ "MIT" ]
null
null
null
defmodule Blitz.Supervisor do use Supervisor def start_link(opts) do Supervisor.start_link(__MODULE__, :ok, opts) end @impl true def init(:ok) do children = [ # %{id: Blitz.Server, start: {Blitz.Server, :start_link, [[]]}, restart: :transient} Blitz.Server ] Supervisor.init(children, strategy: :one_for_one) end end
20
90
0.658333
7958f3200dcfe66edaeb775b654df08c207cd15f
4,088
ex
Elixir
lib/thrift/parser.ex
simplifi/elixir-thrift
3ce784e198fbdf77d7d2481e6fd0cc9fd9618630
[ "Apache-2.0" ]
209
2015-12-19T09:56:39.000Z
2022-03-22T04:43:16.000Z
lib/thrift/parser.ex
fakeNetflix/pinterest-repo-elixir-thrift
4e6cc130738b4f04fdbb06bd6f12985b9a9438d3
[ "Apache-2.0" ]
312
2016-01-05T04:04:58.000Z
2021-11-15T17:59:57.000Z
lib/thrift/parser.ex
thecodeboss/elixir-thrift
621a2039bcbcec62d1cedc85b01421813e0910e8
[ "Apache-2.0" ]
40
2015-12-21T19:46:03.000Z
2022-02-10T08:34:58.000Z
defmodule Thrift.Parser do @moduledoc """ This module provides functions for parsing [Thrift IDL][idl] (`.thrift`) files. [idl]: https://thrift.apache.org/docs/idl """ alias Thrift.Parser.FileGroup @typedoc "A Thrift IDL line number" @type line :: pos_integer | nil @typedoc "A map of Thrift annotation keys to values" @type annotations :: %{required(String.t()) => String.t()} @typedoc "Available parser options" @type opt :: {:include_paths, [Path.t()]} | {:namespace, module | String.t()} @type opts :: [opt] @typedoc "Parse error (path, line, message)" @type error :: {Path.t() | nil, line(), message :: String.t()} @doc """ Parses a Thrift IDL string into its AST representation. """ @spec parse_string(String.t()) :: {:ok, Thrift.AST.Schema.t()} | {:error, error} def parse_string(doc) do doc = String.to_charlist(doc) with {:ok, tokens, _} <- :thrift_lexer.string(doc), {:ok, _} = result <- :thrift_parser.parse(tokens) do result else {:error, {line, :thrift_lexer, error}, _} -> {:error, {nil, line, List.to_string(:thrift_lexer.format_error(error))}} {:error, {line, :thrift_parser, error}} -> {:error, {nil, line, List.to_string(:thrift_parser.format_error(error))}} end end @doc """ Parses a Thrift IDL file into its AST representation. """ @spec parse_file(Path.t()) :: {:ok, Thrift.AST.Schema.t()} | {:error, error} def parse_file(path) do with {:ok, contents} <- read_file(path), {:ok, _schema} = result <- parse_string(contents) do result else {:error, {nil, line, message}} -> {:error, {path, line, message}} {:error, message} -> {:error, {path, nil, message}} end end @doc """ Parses a Thrift IDL file and its included files into a file group. """ @spec parse_file_group(Path.t(), opts) :: {:ok, FileGroup.t()} | {:error, [error, ...]} def parse_file_group(path, opts \\ []) do group = FileGroup.new(path, normalize_opts(opts)) with {:ok, schema} <- parse_file(path), {group, [] = _errors} <- FileGroup.add(group, path, schema) do {:ok, FileGroup.set_current_module(group, module_name(path))} else {:error, error} -> {:error, [error]} {%FileGroup{}, errors} -> {:error, Enum.reverse(errors)} end end @doc """ Parses a Thrift IDL file and its included files into a file group. A `Thrift.FileParseError` will be raised if an error occurs. """ @spec parse_file_group!(Path.t(), opts) :: FileGroup.t() def parse_file_group!(path, opts \\ []) do case parse_file_group(path, opts) do {:ok, group} -> group {:error, [first_error | _errors]} -> raise Thrift.FileParseError, first_error end end defp read_file(path) do case File.read(path) do {:ok, contents} -> # We include the __file__ here to hack around the fact that leex and # yecc don't operate on files and lose the file info. This is relevant # because the filename is turned into the thrift module, and is # necessary for resolution. {:ok, contents <> "\n__file__ \"#{path}\""} {:error, reason} -> {:error, :file.format_error(reason)} end end defp module_name(path) do path |> Path.basename() |> Path.rootname() |> String.to_atom() end # normalize various type permutations that we could get options as defp normalize_opts(opts) do Keyword.update(opts, :namespace, nil, &namespace_string/1) end # namespace can be an atom or a binary # - convert an atom to a binary and remove the "Elixir." we get from atoms # like `Foo` # - make sure values are valid module names (CamelCase) defp namespace_string(""), do: nil defp namespace_string(nil), do: nil defp namespace_string(b) when is_binary(b), do: Macro.camelize(b) defp namespace_string(a) when is_atom(a) do a |> Atom.to_string() |> String.trim_leading("Elixir.") |> namespace_string end end
29.623188
89
0.620841
7958f66603d1b6a4ee0b32f83a978bfbe5692d3d
8,442
ex
Elixir
lib/Statux/tracker.ex
larshei/statex
7e76a820d5774887f08ac73eaf2ac8e1670cf1b2
[ "MIT" ]
1
2022-02-14T06:48:21.000Z
2022-02-14T06:48:21.000Z
lib/Statux/tracker.ex
larshei/statex
7e76a820d5774887f08ac73eaf2ac8e1670cf1b2
[ "MIT" ]
3
2022-02-12T11:32:31.000Z
2022-02-12T22:49:43.000Z
lib/Statux/tracker.ex
larshei/statex
7e76a820d5774887f08ac73eaf2ac8e1670cf1b2
[ "MIT" ]
null
null
null
defmodule Statux.Tracker do use GenServer require Logger alias Statux.Models.EntityStatus alias Statux.Models.Status alias Statux.Models.TrackingData def start_link(args) do GenServer.start_link( __MODULE__, args, name: args[:name] || __MODULE__ ) end def put(server \\ __MODULE__, id, status_name, value, rule_set) do GenServer.cast(server, {:put, id, status_name, value, rule_set}) end def get(server \\ __MODULE__, id) do GenServer.call(server, {:get, id}) end def set(server \\ __MODULE__, id, status_name, option) do GenServer.call(server, {:set, id, status_name, option}) end def reload_rule_set(server \\ __MODULE__) do GenServer.cast(server, :reload_default_rule_set) end # CALLBACKS @impl true def init(args) do name = args[:name] || __MODULE__ readable_name = case name do {:via, Registry, {_registry, name}} -> name {:global, name} -> name _ -> name end Logger.info("Starting #{__MODULE__} '#{inspect name}'") path = case args[:rule_set_file] || Application.get_env(:statux, :rule_set_file) do nil -> raise "Statux #{readable_name} - Missing configuration file for Statux. Configure as :statux, :rule_set_file or pass as argument :rule_set_file" path -> path |> Path.expand end rules = load_rule_set_file(path) pubsub = args[:pubsub] || Application.get_env(:statux, :pubsub) topic = if pubsub == nil do Logger.warn("Statux #{readable_name} - No PubSub configured for Statux. Configure as :statux, :pubsub or pass as argument :pubsub") nil else case args[:topic] || Application.get_env(:statux, :topic) do nil -> Logger.warn("Statux #{readable_name} - No PubSub topic configured for Statux. Configure as :statux, :topic or pass as argument :topic. Defaulting to topic 'Statux'") "Statux" topic -> topic end end persist? = args[:enable_persistence] || Application.get_env(:statux, :enable_persistence) folder = args[:persistence_folder] || Application.get_env(:statux, :persistence_folder) initial_states = case {persist?, folder} do {true, nil} -> raise "Statux #{readable_name}: You have enabled persistence, but did not provide a folder to persist data to. Configure as :statux, :persistence_folder or pass as argument :persistence_folder." {true, folder} -> Logger.info("Statux - Persistence is enabled, trying to read file for #{readable_name} from #{folder}") file_name = "#{folder}/#{readable_name}.dat" file_name |> String.replace("//", "/") |> File.exists?() |> case do false -> Logger.warn("Statux - Could not find existing state for #{readable_name} at #{folder}/#{readable_name}.dat. Creating empty state.") %{} true -> file_name |> File.read!() |> :erlang.binary_to_term() end _ -> %{} end Process.flag(:trap_exit, true) Logger.info("Statux - Successfully started for #{readable_name}") { :ok, %Statux.Models.TrackerState{ name: readable_name, persistence: %{ enabled: persist?, folder: folder, }, pubsub: %{module: pubsub, topic: topic}, rules: %{default: rules}, rule_set_file: path, states: initial_states, } } end @impl true def handle_cast({:put, id, status_name, value, rule_set} = _message, data) do {:noreply, data |> process_new_data(id, status_name, value, rule_set)} end @impl true def handle_cast(:reload_default_rule_set, data) do updated_data = try do new_rule_set = data.rule_set_file |> load_rule_set_file() data |> put_in([:rules, :default], new_rule_set) rescue _ -> Logger.error("Statux #{data.name} - Could not reload rule set file from #{data.rule_set_file}") data end {:noreply, updated_data} end @impl true def handle_cast(_message, data) do Logger.debug "#{__MODULE__} - handle_cast FALLBACK" {:noreply, data} end @impl true def handle_call({:get, id}, _from_pid, state) do {:reply, state.states[id][:current_status], state} end @impl true def handle_call({:set, id, status_name, option}, _from_pid, state) do {updated_status, updated_state} = set_status(state, id, status_name, option) {:reply, updated_status, updated_state} end @impl true # For reasons I don't understand, this seems to never be called. def handle_info({:EXIT, _from, reason}, state) do Logger.warn("Statux #{state.name} - Exited with reason #{inspect reason}") maybe_persist_state(state) {:stop, reason, state} end @impl true def terminate(reason, state) do Logger.warn("Statux #{state.name} - Terminated with reason #{inspect reason}") maybe_persist_state(state) reason end defp load_rule_set_file(path) do case path != nil and File.exists?(path) do true -> Statux.RuleSet.load_json!(path) false -> raise "Statux - Missing configuration file for Statux. Expected at '#{path}'. Configure as :statux, :rule_set_file or pass as argument :rule_set_file." end end defp maybe_persist_state(%{persistence: %{enabled: true, folder: folder}} = state) do path = "#{folder}/#{state.name}.dat" Logger.info("Statux #{state.name} - Persistence is enabled, persisting data under #{path}") File.mkdir_p!(Path.dirname(path)) File.write!(path, state.states |> :erlang.term_to_binary) end defp maybe_persist_state(state) do Logger.info("Statux #{state.name} - Persistence is disabled") end def set_status(state, id, status_name, option) do defined_options = state.rules[state.states[id][:rule_set_name] || :default][status_name][:status] |> Map.keys() valid_option? = option in defined_options case valid_option? do false -> {{:error, :invalid_option}, state} true -> updated_status = state.states[id][:current_status][status_name] |> Status.transition(option) updated_tracking = state.states[id][:tracking][status_name] |> Map.keys |> Enum.reduce(state.states[id][:tracking][status_name], fn option, tracking -> tracking |> update_in([option], fn option_tracking_data -> option_tracking_data |> TrackingData.reset() end) end) updated_state = state |> put_in([:states, id, :current_status, status_name], updated_status) |> put_in([:states, id, :tracking, status_name], updated_tracking) {updated_status, updated_state} end end # Data processing def process_new_data(data, id, status_name, value, rule_set_name \\ :default) do rule_set = data.rules[rule_set_name] || data.rules[:default] || %{} cond do # no status with this name rule_set[status_name] == nil -> data # value should be ignored Statux.ValueRules.should_be_ignored?(value, rule_set[status_name]) -> Logger.debug "Value #{inspect value} is to be ignored for rule set '#{inspect status_name}'" data # process the value true -> data |> evaluate_new_status(id, status_name, value, rule_set) end end defp evaluate_new_status(data, id, status_name, value, rule_set) do entity_status = data.states[id] || EntityStatus.new_from_rule_set(id, rule_set) status_options = rule_set[status_name][:status] case status_options do nil -> data _ -> valid_options_for_value = value |> Statux.ValueRules.find_possible_valid_status(status_options) updated_entity_status = entity_status |> Statux.Entities.update_tracking_data(status_name, status_options, valid_options_for_value) transitions = updated_entity_status |> Statux.Constraints.filter_valid_transition_options(status_name, status_options, valid_options_for_value) transitioned_entity_status = updated_entity_status |> Statux.Transitions.transition(status_name, transitions, data.pubsub) put_in(data, [:states, id], transitioned_entity_status) end end end
31.5
204
0.642739
7959b0958c23fb8ad0f979655e88dd286c55856a
751
exs
Elixir
mix.exs
seankay/curtail
1b9e1fcfe5305570e343c43a7f5831c046cb6563
[ "MIT" ]
27
2015-02-07T00:33:18.000Z
2021-01-17T20:22:09.000Z
mix.exs
seankay/curtail
1b9e1fcfe5305570e343c43a7f5831c046cb6563
[ "MIT" ]
5
2015-05-27T11:46:32.000Z
2020-08-21T00:43:32.000Z
mix.exs
seankay/curtail
1b9e1fcfe5305570e343c43a7f5831c046cb6563
[ "MIT" ]
4
2015-05-27T03:46:58.000Z
2020-08-20T22:06:15.000Z
defmodule Curtail.Mixfile do use Mix.Project @source_url "https://github.com/seankay/curtail" def project do [app: :curtail, version: "2.0.0", elixir: ">= 1.3.0", description: description(), package: package(), deps: deps(), name: "Curtail", source_url: @source_url ] end def application do [applications: [:logger]] end defp deps do [{:earmark, "~> 1.0", only: :dev}, {:ex_doc, "~> 0.19", only: :dev}] end defp description do "HTML-safe string truncation." end defp package do [ files: ["lib", "mix.exs", "README*", "LICENSE*"], contributors: ["Sean Kay"], licenses: ["Apache 2.0"], links: %{"GitHub" => @source_url} ] end end
18.775
55
0.563249
7959b7a01e4435cb43b00af029bbc050ef1058a3
1,509
ex
Elixir
apps/mishka_database/lib/schema/mishka_content/content_schema_enum.ex
mojtaba-naserei/mishka-cms
1f31f61347bab1aae6ba0d47c5515a61815db6c9
[ "Apache-2.0" ]
3
2021-06-27T10:26:51.000Z
2022-01-10T13:56:08.000Z
apps/mishka_database/lib/schema/mishka_content/content_schema_enum.ex
iArazar/mishka-cms
8b579101d607d91e80834527c1508fe5f4ceefef
[ "Apache-2.0" ]
null
null
null
apps/mishka_database/lib/schema/mishka_content/content_schema_enum.ex
iArazar/mishka-cms
8b579101d607d91e80834527c1508fe5f4ceefef
[ "Apache-2.0" ]
null
null
null
import EctoEnum defenum ContentStatusEnum, inactive: 0, active: 1, archived: 2, soft_delete: 3 defenum ContentPriorityEnum, none: 0, low: 1, medium: 2, high: 3, featured: 4 defenum ContentRobotsEnum, IndexFollow: 0, IndexNoFollow: 1, NoIndexFollow: 2, NoIndexNoFollow: 3 defenum CategoryVisibility, show: 0, invisibel: 1, test_show: 2, test_invisibel: 3 defenum PostVisibility, show: 0, invisibel: 1, test_show: 2, test_invisibel: 3 defenum CommentSection, blog_post: 0 defenum SubscriptionSection, blog_post: 0, blog_category: 1 defenum BlogLinkType, bottom: 0, inside: 1, featured: 2 defenum ActivitiesStatusEnum, error: 0, info: 1, warning: 2, report: 3, throw: 4, exit: 5 defenum ActivitiesTypeEnum, section: 0, email: 1, internal_api: 2, external_api: 3, html_router: 4, api_router: 5, db: 6 defenum ActivitiesSection, blog_post: 0, blog_category: 1, comment: 2, tag: 3, other: 4, blog_author: 5, blog_post_like: 6, blog_tag_mapper: 7, blog_link: 8, blog_tag: 9, activity: 10, bookmark: 11, comment_like: 12, notif: 13, subscription: 14, setting: 15, permission: 16, role: 17, user_role: 18, identity: 19, user: 20 defenum ActivitiesAction, add: 0, edit: 1, delete: 2, destroy: 3, read: 4, send_request: 5, receive_request: 6, other: 7, auth: 8 defenum BookmarkSection, blog_post: 0 defenum NotifSection, blog_post: 0, admin: 1, user_only: 3, public: 4 defenum NotifStatusType, read: 0, skipped: 1 defenum NotifType, client: 0, admin: 1 defenum NotifTarget, all: 0, mobile: 1, android: 2, ios: 3, cli: 4
79.421053
322
0.753479
7959c677967b36b76234cc4f3f81658b495730fe
1,847
ex
Elixir
clients/cloud_iot/lib/google_api/cloud_iot/v1/model/bind_device_to_gateway_request.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/cloud_iot/lib/google_api/cloud_iot/v1/model/bind_device_to_gateway_request.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/cloud_iot/lib/google_api/cloud_iot/v1/model/bind_device_to_gateway_request.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.CloudIot.V1.Model.BindDeviceToGatewayRequest do @moduledoc """ Request for &#x60;BindDeviceToGateway&#x60;. ## Attributes - deviceId (String.t): The device to associate with the specified gateway. The value of &#x60;device_id&#x60; can be either the device numeric ID or the user-defined device identifier. Defaults to: `null`. - gatewayId (String.t): The value of &#x60;gateway_id&#x60; can be either the device numeric ID or the user-defined device identifier. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :deviceId => any(), :gatewayId => any() } field(:deviceId) field(:gatewayId) end defimpl Poison.Decoder, for: GoogleApi.CloudIot.V1.Model.BindDeviceToGatewayRequest do def decode(value, options) do GoogleApi.CloudIot.V1.Model.BindDeviceToGatewayRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudIot.V1.Model.BindDeviceToGatewayRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.215686
207
0.745533
7959dd7ec5827245bec1b717a7d73cddd7cd619a
1,151
exs
Elixir
clients/web_security_scanner/config/config.exs
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/web_security_scanner/config/config.exs
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/web_security_scanner/config/config.exs
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :web_security_scanner_api, key: :value # # And access this configuration in your application as: # # Application.get_env(:web_security_scanner_api, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
37.129032
73
0.758471
795a085ac858f572eec3b90a706026fa4ecf4476
1,142
exs
Elixir
apps/user_manager/mix.exs
Alezrik/game_services_umbrella
9b9dd6707c200b10c5a73568913deb4d5d8320be
[ "MIT" ]
4
2018-11-09T16:57:06.000Z
2021-03-02T22:57:17.000Z
apps/user_manager/mix.exs
Alezrik/game_services_umbrella
9b9dd6707c200b10c5a73568913deb4d5d8320be
[ "MIT" ]
29
2018-10-26T08:29:37.000Z
2018-12-09T21:02:05.000Z
apps/user_manager/mix.exs
Alezrik/game_services_umbrella
9b9dd6707c200b10c5a73568913deb4d5d8320be
[ "MIT" ]
null
null
null
defmodule UserManager.MixProject do use Mix.Project def project do [ app: :user_manager, version: "0.1.0", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", lockfile: "../../mix.lock", elixir: "~> 1.7", start_permanent: Mix.env() == :prod, deps: deps(), test_coverage: [tool: ExCoveralls] ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger], mod: {UserManager.Application, []} ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:cluster_manager, in_umbrella: true}, {:ecto, "~> 3.0-rc", override: true}, {:game_services, in_umbrella: true}, {:libcluster, "~> 3.0"}, {:swarm, "~> 3.0"}, {:stream_data, "~> 0.1", only: :test}, {:logger_backend, in_umbrella: true} # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}, # {:sibling_app_in_umbrella, in_umbrella: true}, ] end end
26.55814
88
0.565674
795a10e5d97638066559823050c14ea71e433eaa
2,295
ex
Elixir
lib/firestorm_data/categories/categories.ex
dailydrip/firestorm_data
5c5e75271c43dc08d93a2492692b6601ef3682aa
[ "MIT" ]
null
null
null
lib/firestorm_data/categories/categories.ex
dailydrip/firestorm_data
5c5e75271c43dc08d93a2492692b6601ef3682aa
[ "MIT" ]
null
null
null
lib/firestorm_data/categories/categories.ex
dailydrip/firestorm_data
5c5e75271c43dc08d93a2492692b6601ef3682aa
[ "MIT" ]
null
null
null
defmodule FirestormData.Categories do @moduledoc """ Threads exist within categories. """ alias FirestormData.{ Repo, Categories.Category } @doc """ Finds a category by name ## Examples iex> find_category(%{title: "Elixir"}) {:ok, %Category{}} iex> find_category(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ @spec find_category(map()) :: {:ok, Category.t()} | {:error, :no_such_category} def find_category(attrs \\ %{}) do Category |> Repo.get_by(attrs) |> case do nil -> {:error, :no_such_category} category -> {:ok, category} end end @doc """ Creates a category. ## Examples iex> create_category(%{title: "Elixir"}) {:ok, %Category{}} iex> create_category(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ @spec create_category(map()) :: {:ok, Category.t()} | {:error, Ecto.Changeset.t()} def create_category(attrs \\ %{}) do %Category{} |> Category.changeset(attrs) |> Repo.insert() end @doc """ Gets a single category. ## Examples iex> get_category("123") {:ok, %Category{}} iex> get_category!("456") {:error, :no_such_category} """ @spec get_category(String.t()) :: {:ok, Category.t()} | {:error, :no_such_category} def get_category(id) do case Repo.get(Category, id) do nil -> {:error, :no_such_category} category -> {:ok, category} end end @doc """ Updates a category. ## Examples iex> update_category(category, %{field: new_value}) {:ok, %Category{}} iex> update_category(category, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ @spec update_category(Category.t(), map()) :: {:ok, Category.t()} | {:error, Ecto.Changeset.t()} def update_category(%Category{} = category, attrs) do category |> Category.changeset(attrs) |> Repo.update() end @doc """ Deletes a Category. ## Examples iex> delete_category(category) {:ok, %Category{}} iex> delete_category(category) {:error, %Ecto.Changeset{}} """ @spec delete_category(Category.t()) :: {:ok, Category.t()} | {:error, Ecto.Changeset.t()} def delete_category(%Category{} = category) do Repo.delete(category) end end
21.25
98
0.593464
795a2ca8c44c7b3abf7a3e4a21d1521a6e61cda4
900
exs
Elixir
mix.exs
trustcor/exqueue
b122d99080373eb802e0e5d9fa11c05975eabc7b
[ "MIT" ]
null
null
null
mix.exs
trustcor/exqueue
b122d99080373eb802e0e5d9fa11c05975eabc7b
[ "MIT" ]
null
null
null
mix.exs
trustcor/exqueue
b122d99080373eb802e0e5d9fa11c05975eabc7b
[ "MIT" ]
null
null
null
defmodule ExQueue.Mixfile do use Mix.Project def project do [app: :exqueue, version: "0.1.0", elixir: "~> 1.3", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, escript: [main_module: ExQueue], deps: deps()] end def application do [applications: [:logger, :yamerl, :yaml_elixir, :con_cache, :poison, :timex, :amqp, :ex_aws, :sweet_xml, :briefly], mod: {ExQueue, %{}} ] end defp deps do [ {:yaml_elixir, "~> 1.2.1"}, {:elmdb, "~> 0.4.1"}, {:con_cache, "~> 0.11.1"}, {:poison, "~> 2.2.0"}, {:timex, "~> 3.1.0"}, {:amqp_client, git: "https://github.com/dsrosario/amqp_client.git", branch: "erlang_otp_19", override: true}, {:amqp, "~> 0.1.4"}, {:ex_aws, "~> 1.0.0-beta5"}, {:sweet_xml, "~> 0.6.1"}, {:briefly, "~> 0.3.0"} ] end end
25
115
0.517778
795a3c98b951f0591b2f7d5ccf370f182963cc81
853
exs
Elixir
test/parallel_test.exs
eproxus/parallel
08337182573befc55f4aea835b0f68c686d57002
[ "MIT" ]
24
2015-02-20T09:05:22.000Z
2021-01-14T22:37:53.000Z
test/parallel_test.exs
eproxus/parallel
08337182573befc55f4aea835b0f68c686d57002
[ "MIT" ]
3
2016-03-23T10:49:44.000Z
2018-01-09T12:32:59.000Z
test/parallel_test.exs
eproxus/parallel
08337182573befc55f4aea835b0f68c686d57002
[ "MIT" ]
7
2015-01-08T19:17:49.000Z
2018-01-09T07:34:25.000Z
Code.require_file "test_helper.exs", __DIR__ defmodule ParallelTest do use ExUnit.Case doctest Parallel import EnumCompare import Parallel test :map do assert_enum :map, 1..10, &(&1 + 1), sort: true end test :random_map do :random.seed(:erlang.now()) Enum.each 1..50, fn _ -> list = Enum.map 1..50, &:random.uniform/1 assert_enum :map, list, &(&1 + 1), sort: true end end test :each do pid = self() collection = 1..10 each(collection, fn i -> send(pid, {:test, i}) end) Enum.each(collection, fn i -> receive do {:test, ^i} -> :ok after 100 -> assert false, "No result received" end end) end test :any? do assert_enum :any?, [false, true], fn b -> b end end test :all? do assert_enum :all?, [false, true], fn b -> b end end end
19.386364
55
0.584994
795a464bd5f4cd3d47495e8c7e3b21ff068500d4
3,226
ex
Elixir
clients/you_tube/lib/google_api/you_tube/v3/model/live_chat_message_list_response.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/live_chat_message_list_response.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/live_chat_message_list_response.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.YouTube.V3.Model.LiveChatMessageListResponse do @moduledoc """ ## Attributes * `etag` (*type:* `String.t`, *default:* `nil`) - Etag of this resource. * `eventId` (*type:* `String.t`, *default:* `nil`) - Serialized EventId of the request which produced this response. * `items` (*type:* `list(GoogleApi.YouTube.V3.Model.LiveChatMessage.t)`, *default:* `nil`) - * `kind` (*type:* `String.t`, *default:* `youtube#liveChatMessageListResponse`) - Identifies what kind of resource this is. Value: the fixed string "youtube#liveChatMessageListResponse". * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - * `offlineAt` (*type:* `DateTime.t`, *default:* `nil`) - The date and time when the underlying stream went offline. * `pageInfo` (*type:* `GoogleApi.YouTube.V3.Model.PageInfo.t`, *default:* `nil`) - General pagination information. * `pollingIntervalMillis` (*type:* `integer()`, *default:* `nil`) - The amount of time the client should wait before polling again. * `tokenPagination` (*type:* `GoogleApi.YouTube.V3.Model.TokenPagination.t`, *default:* `nil`) - * `visitorId` (*type:* `String.t`, *default:* `nil`) - The visitorId identifies the visitor. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :etag => String.t(), :eventId => String.t(), :items => list(GoogleApi.YouTube.V3.Model.LiveChatMessage.t()), :kind => String.t(), :nextPageToken => String.t(), :offlineAt => DateTime.t(), :pageInfo => GoogleApi.YouTube.V3.Model.PageInfo.t(), :pollingIntervalMillis => integer(), :tokenPagination => GoogleApi.YouTube.V3.Model.TokenPagination.t(), :visitorId => String.t() } field(:etag) field(:eventId) field(:items, as: GoogleApi.YouTube.V3.Model.LiveChatMessage, type: :list) field(:kind) field(:nextPageToken) field(:offlineAt, as: DateTime) field(:pageInfo, as: GoogleApi.YouTube.V3.Model.PageInfo) field(:pollingIntervalMillis) field(:tokenPagination, as: GoogleApi.YouTube.V3.Model.TokenPagination) field(:visitorId) end defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.LiveChatMessageListResponse do def decode(value, options) do GoogleApi.YouTube.V3.Model.LiveChatMessageListResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.LiveChatMessageListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
43.594595
190
0.695598
795a66b1ed5bcf691c0cd2238ddaead752bef349
2,631
ex
Elixir
apps/local_ledger_db/lib/local_ledger_db/token.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
322
2018-02-28T07:38:44.000Z
2020-05-27T23:09:55.000Z
apps/local_ledger_db/lib/local_ledger_db/token.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
643
2018-02-28T12:05:20.000Z
2020-05-22T08:34:38.000Z
apps/local_ledger_db/lib/local_ledger_db/token.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
63
2018-02-28T10:57:06.000Z
2020-05-27T23:10:38.000Z
# Copyright 2018-2019 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule LocalLedgerDB.Token do @moduledoc """ Ecto Schema representing tokens. Tokens are made up of an id (e.g. OMG) and the associated UUID in eWallet DB. """ use Ecto.Schema import Ecto.Changeset alias Ecto.UUID alias LocalLedgerDB.{Entry, Repo, Token} @primary_key {:uuid, UUID, autogenerate: true} @timestamps_opts [type: :naive_datetime_usec] schema "token" do field(:id, :string) field(:metadata, :map, default: %{}) field(:encrypted_metadata, LocalLedgerDB.Encrypted.Map, default: %{}) has_many( :entries, Entry, foreign_key: :token_id, references: :id ) timestamps() end @doc """ Validate the token attributes. """ def changeset(%Token{} = token, attrs) do token |> cast(attrs, [:id, :metadata, :encrypted_metadata]) |> validate_required([:id, :metadata, :encrypted_metadata]) |> unique_constraint(:id) end @doc """ Retrieve a token from the database using the specified id or insert a new one before returning it. """ def get_or_insert(%{"id" => id} = attrs) do case get(id) do nil -> insert(attrs) token -> {:ok, token} end end @doc """ Retrieve a token using the specified id. """ @spec get(String.t()) :: Ecto.Schema.t() | nil | no_return() def get(id) do Repo.get_by(Token, id: id) end @doc """ Create a new token with the passed attributes. With "on conflict: nothing", conflicts are ignored. No matter what, a fresh get query is made to get the current database record, be it the one inserted right before or one inserted by another concurrent process. """ @spec insert(map()) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} def insert(%{"id" => id} = attrs) do changeset = Token.changeset(%Token{}, attrs) opts = [on_conflict: :nothing, conflict_target: :id] case Repo.insert(changeset, opts) do {:ok, _token} -> {:ok, get(id)} {:error, changeset} -> {:error, changeset} end end end
27.694737
80
0.661345
795acd088847664467f811465b45628fa2defd0b
210
ex
Elixir
lib/exnn/nodes/loader.ex
zampino/exnn
2be888df107644daab1aca7614fecb4940fe3c84
[ "MIT" ]
104
2015-06-18T18:54:25.000Z
2021-11-04T15:07:02.000Z
lib/exnn/nodes/loader.ex
nelyj/exnn
2be888df107644daab1aca7614fecb4940fe3c84
[ "MIT" ]
3
2016-10-09T11:19:42.000Z
2018-09-17T16:36:32.000Z
lib/exnn/nodes/loader.ex
nelyj/exnn
2be888df107644daab1aca7614fecb4940fe3c84
[ "MIT" ]
17
2016-03-08T19:02:51.000Z
2019-04-27T16:40:52.000Z
defmodule EXNN.Nodes.Loader do def start_link do result = EXNN.Connectome.all |> Enum.each(&register/1) {result, self} end def register(genome) do EXNN.Nodes.register(genome) end end
15
32
0.67619
795ad1730e746c622f6a1411fdaa9057a179f229
3,265
ex
Elixir
lib/galnora/server.ex
kortirso/galnora
e10a4a9bacc1be0a68a1ac191b7fa9b335988cb6
[ "MIT" ]
null
null
null
lib/galnora/server.ex
kortirso/galnora
e10a4a9bacc1be0a68a1ac191b7fa9b335988cb6
[ "MIT" ]
null
null
null
lib/galnora/server.ex
kortirso/galnora
e10a4a9bacc1be0a68a1ac191b7fa9b335988cb6
[ "MIT" ]
null
null
null
defmodule Galnora.Server do @moduledoc false use GenServer alias Galnora.DB.Queries.{Job, Sentence} alias Galnora.JobServer # GenServer API @doc """ Inits server """ def init(_) do IO.puts "Galnora server is running" # pool = Job.get_active_jobs() |> Enum.map(fn job -> start_job_server(job) end) {:ok, %{pool: []}} end @doc """ Add job to state """ def handle_cast({:add_job, sentences, value}, state) do case Job.create(value) do {:error} -> {:noreply, state} job -> sentences |> Enum.each(fn sentence -> Sentence.create(sentence, job.id) end) {:noreply, %{pool: job |> start_job_server() |> place_value_to_pool(state.pool)}} end end @doc """ Deletes job by uid with sentences """ def handle_cast({:delete_job, uid}, state) do case Job.get_job_by_uid(uid) do nil -> nil job -> Job.delete(job) job.id |> Sentence.read_sentences() |> Enum.each(fn sentence -> Sentence.delete(sentence) end) end {:noreply, state} end @doc """ Returns job by uid """ def handle_call({:get_job, uid}, _, state), do: {:reply, Job.get_job_by_uid(uid), state} @doc """ Returns job by uid """ def handle_call({:get_job_with_sentences, uid}, _, state) do result = uid |> Sentence.read_sentences() |> Enum.map(fn sentence -> {sentence.uid, sentence.input, sentence.output} end) {:reply, result, state} end @doc """ Receives translation result """ def handle_info({:send_job_result, {{result, job}, job_server_pid}}, state) do IO.puts "Galnora server is receiving result for job #{job.id}" status = if result == :ok, do: :completed, else: :failed job |> Map.merge(%{status: status}) |> Job.update() stop_server(job_server_pid) {:noreply, %{pool: state.pool |> List.delete(job_server_pid)}} end @doc """ Handle terminating """ def terminate(_, state) do IO.puts "Galnora server is shutting down" cleanup(state) end # private functions defp start_job_server(job) do job_server_pid = JobServer.start caller = self() send(job_server_pid, {:send_job, caller, job}) job_server_pid end defp place_value_to_pool(addition, pool), do: [addition | pool] defp cleanup(%{pool: pool}) do pool |> Enum.each(fn server_pid -> stop_server(server_pid)end) IO.puts "All job servers are closed" end defp stop_server(server_pid), do: Process.exit(server_pid, :terminating) # Client API @doc """ Starts the Supervision Tree """ def start_link(state \\ []), do: GenServer.start_link(__MODULE__, state, name: __MODULE__) @doc """ Add job to the state """ def add_job(sentences, value) when is_list(sentences) and is_map(value), do: GenServer.cast(__MODULE__, {:add_job, sentences, value}) @doc """ Render job by uid """ def get_job(uid) when is_integer(uid), do: GenServer.call(__MODULE__, {:get_job, uid}) @doc """ Render job's sentences by job's uid """ def get_job_with_sentences(uid) when is_integer(uid), do: GenServer.call(__MODULE__, {:get_job_with_sentences, uid}) @doc """ Delete job by uid """ def delete_job(uid) when is_integer(uid), do: GenServer.cast(__MODULE__, {:delete_job, uid}) end
25.507813
135
0.652986
795ade3ab26b2c4dc373bcad17d86781f9a62d28
816
ex
Elixir
elixir/codes-from-books/little-elixir/cap5/ring/lib/ring.ex
trxeste/wrk
3e05e50ff621866f0361cc8494ce8f6bb4d97fae
[ "BSD-3-Clause" ]
1
2017-10-16T03:00:50.000Z
2017-10-16T03:00:50.000Z
elixir/codes-from-books/little-elixir/cap5/ring/lib/ring.ex
trxeste/wrk
3e05e50ff621866f0361cc8494ce8f6bb4d97fae
[ "BSD-3-Clause" ]
null
null
null
elixir/codes-from-books/little-elixir/cap5/ring/lib/ring.ex
trxeste/wrk
3e05e50ff621866f0361cc8494ce8f6bb4d97fae
[ "BSD-3-Clause" ]
null
null
null
defmodule Ring do @moduledoc """ Documentation for Ring. """ @doc """ Hello world. ## Examples iex> Ring.hello :world """ def create_processes(n) do 1..n |> Enum.map(fn _ -> spawn(fn -> loop end) end) def loop do receive do {:link, link_to} when is_pid(link_to) -> Process.link(link_to) loop :crash -> 1/0 end end def link_processes(procs) do link_processes(procs, []) end def link_processes([proc_1, proc_2 | rest], linked_processes) do send(proc_1, {:link, proc_2}) link_processes([proc_2|rest], [proc_1|linked_processes]) end def link_processes([proc|[]], linked_processes) do first_process = linked_processes |> List.last send(proc, {:link, first_process}) :ok end end
17.73913
68
0.599265
795ae5beeadfd02635f311ede039ca1b56583f9b
5,418
ex
Elixir
lib/firex.ex
msoedov/firex
03b70122c1ae34793c505557f81e44ed2d77cbde
[ "MIT" ]
26
2017-05-15T00:16:20.000Z
2019-06-17T13:21:24.000Z
lib/firex.ex
msoedov/firex
03b70122c1ae34793c505557f81e44ed2d77cbde
[ "MIT" ]
6
2017-06-20T15:58:40.000Z
2017-06-23T23:02:45.000Z
lib/firex.ex
msoedov/firex
03b70122c1ae34793c505557f81e44ed2d77cbde
[ "MIT" ]
2
2017-06-20T16:04:07.000Z
2018-02-16T19:01:33.000Z
defmodule Firex do @moduledoc """ Module with macro for generating `main` entrypoint and reflection of passed command line argument into functions. """ defmacro __using__(opts) do testing? = Keyword.get(opts, :testing, false) quote do import Firex @before_compile Firex @on_definition {Firex, :on_def} def main([]) do state = init([]) %{help_fn: help_fn} = state help_fn.(true) false |> sys_exit end def main(args) do state = init(args) commands = what_defined() |> Enum.map(&Firex.Options.params_for_option_parser/1) %{exausted: exausted, need_help: need_help, help_fn: help_fn, error_seen?: error_seen?} = Enum.reduce(commands, state, &traverse_commands/2) help_fn.(need_help) ok? = not need_help and not error_seen? ok? |> sys_exit end defp sys_exit(status) do case {status, unquote(testing?)} do {_, true} -> status {true, false} -> System.halt(0) {false, false} -> System.halt(1) end end defp init(args \\ []) do commands = what_defined() |> Enum.map(&Firex.Options.params_for_option_parser/1) commands_map = commands |> Enum.map(fn mp -> mp |> Enum.into(Keyword.new) end) |> Enum.reduce(Keyword.new, fn (map, acc) -> Keyword.merge(map, acc) end) help_info = what_defined() |> Enum.map(fn {name, _, doc, tspec} -> {name, {doc, tspec}} end) |> Enum.into(%{}) %{args: args, exausted: false, error_seen?: false, help_fn: fn need_help? -> help(commands_map, help_info, need_help?) end, need_help: false} end defp traverse_commands(pair, %{args: args, exausted: false, help_fn: help_fn} = state) do name = pair |> Map.keys() |> Enum.at(0) cmd = pair |> Map.values() |> Enum.at(0) parsed = OptionParser.parse(args, cmd) cmd_name = Atom.to_string(name) case parsed do {opts, [^cmd_name], _} -> fn_args = opts |> Enum.map(fn {k, v} -> v end) invoke(__MODULE__, name, fn_args, state) {_, _, [{"-h", nil}]} -> %{state | exausted: true, need_help: true} {[help: true], [], []} -> %{state | exausted: true, need_help: true} {_, ["help"], _} -> %{state | exausted: true, need_help: true} {_, [], []} -> %{state | exausted: true, need_help: true} {[], plain, []} when is_list(plain) -> [name|fn_args] = plain invoke(__MODULE__, name |> String.to_atom, fn_args, state) {_, _, _} -> state end end defp traverse_commands(_, %{exausted: true} = state) do state end defp invoke(module, fun, fn_args, %{help_fn: help_fn} = state) when is_atom(fun) do try do Kernel.apply(module, fun, fn_args) %{state | exausted: true} rescue e in UndefinedFunctionError -> [:red, "Invalid usage: #{module}:#{fun}"] |> Bunt.puts %{state | error_seen?: true, need_help: true} e in _ -> # %{message: msg} = e [:red, "Error: #{module}.#{fun}(#{fn_args})"] |> Bunt.puts # %{state | exausted: true, error_seen?: true} raise(e) end end defp command_help(name, params, help_info) do switches = Keyword.get(params, :switches, []) signature = params |> Keyword.get(:aliases, []) |> Enum.zip(switches) |> Enum.map(fn {{k, v}, {_, type}} -> "-#{k} --#{v} [#{v}:#{type}]" end) |> Enum.join(", ") meta = Map.get(help_info, name, {nil, nil}) {doc, _} = meta desc = case String.length(signature) do 0 -> "no args required" _ -> signature end """ #{name}: #{desc} #{doc} """ end defp help(_, _, false) do end defp help(command_map, help_info, true) do msg = command_map |> Enum.map(fn {name, params} -> command_help(name, params, help_info) end) |> Enum.join("\n") [:blue, "#{pub_moduledoc()}"] |> Bunt.puts [:blue, "Available commands:"] |> Bunt.puts IO.puts """ #{msg} """ end end end defmacro __before_compile__(_) do quote do def what_defined() do @commands end def pub_moduledoc() do @pub_moduledoc end end end @lint false def on_def(_env, _kind, :dispatch, _args, _guards, _body) do end def on_def(_env, _kind, :main, _args, _guards, _body) do end def on_def(env, :def, name, args, _guards, _body) do module = env.module defs = Module.get_attribute(module, :commands) || [] doc = case Module.get_attribute(module, :doc) do nil -> "" {_, doc} -> doc end fn_def = {name, args, doc, Module.get_attribute(module, :spec)} Module.put_attribute(module, :commands, [fn_def | defs]) moduledoc = case Module.get_attribute(module, :moduledoc) do nil -> "" {_line, moduledoc} -> moduledoc end Module.put_attribute(module, :pub_moduledoc, moduledoc) end def on_def(_env, _kind, _name, _args, _guards, _body) do end end
30.784091
97
0.538944
795afa8793d5d6380a490faa83744e80098885ed
4,505
exs
Elixir
config/.credo.exs
austinsmorris/compass
752108902a4d249579174abcf19fc1c944112c86
[ "MIT" ]
null
null
null
config/.credo.exs
austinsmorris/compass
752108902a4d249579174abcf19fc1c944112c86
[ "MIT" ]
null
null
null
config/.credo.exs
austinsmorris/compass
752108902a4d249579174abcf19fc1c944112c86
[ "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/", "web/", "apps/"], excluded: [~r"/_build/", ~r"/deps/"] }, # # 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: [], # # Credo automatically checks for updates, like e.g. Hex does. # You can disable this behaviour below: check_for_updates: 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: [ {Credo.Check.Consistency.ExceptionNames}, {Credo.Check.Consistency.LineEndings}, {Credo.Check.Consistency.SpaceAroundOperators}, {Credo.Check.Consistency.SpaceInParentheses}, {Credo.Check.Consistency.TabsOrSpaces}, # For some checks, like AliasUsage, you can only customize the priority # Priority values are: `low, normal, high, higher` {Credo.Check.Design.AliasUsage, priority: :low}, # For others you can set parameters # If you don't want the `setup` and `test` macro calls in ExUnit tests # or the `schema` macro in Ecto schemas to trigger DuplicatedCode, just # set the `excluded_macros` parameter to `[:schema, :setup, :test]`. {Credo.Check.Design.DuplicatedCode, excluded_macros: []}, # 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: 0}, {Credo.Check.Design.TagFIXME}, {Credo.Check.Readability.FunctionNames}, {Credo.Check.Readability.LargeNumbers}, {Credo.Check.Readability.MaxLineLength, ignore_definitions: false, priority: :low, max_length: 120}, {Credo.Check.Readability.ModuleAttributeNames}, {Credo.Check.Readability.ModuleDoc}, {Credo.Check.Readability.ModuleNames}, {Credo.Check.Readability.ParenthesesInCondition}, {Credo.Check.Readability.PredicateFunctionNames}, {Credo.Check.Readability.TrailingBlankLine}, {Credo.Check.Readability.TrailingWhiteSpace}, {Credo.Check.Readability.VariableNames}, {Credo.Check.Refactor.ABCSize}, # {Credo.Check.Refactor.CaseTrivialMatches}, # deprecated in 0.4.0 {Credo.Check.Refactor.CondStatements}, {Credo.Check.Refactor.FunctionArity}, {Credo.Check.Refactor.MatchInCondition}, {Credo.Check.Refactor.PipeChainStart}, {Credo.Check.Refactor.CyclomaticComplexity}, {Credo.Check.Refactor.NegatedConditionsInUnless}, {Credo.Check.Refactor.NegatedConditionsWithElse}, {Credo.Check.Refactor.Nesting}, {Credo.Check.Refactor.UnlessWithElse}, {Credo.Check.Warning.IExPry}, {Credo.Check.Warning.IoInspect}, {Credo.Check.Warning.NameRedeclarationByAssignment}, {Credo.Check.Warning.NameRedeclarationByCase}, {Credo.Check.Warning.NameRedeclarationByDef}, {Credo.Check.Warning.NameRedeclarationByFn}, {Credo.Check.Warning.OperationOnSameValues}, {Credo.Check.Warning.BoolOperationOnSameValues}, {Credo.Check.Warning.UnusedEnumOperation}, {Credo.Check.Warning.UnusedKeywordOperation}, {Credo.Check.Warning.UnusedListOperation}, {Credo.Check.Warning.UnusedStringOperation}, {Credo.Check.Warning.UnusedTupleOperation}, {Credo.Check.Warning.OperationWithConstantResult}, # Custom checks can be created using `mix credo.gen.check`. # ] } ] }
40.954545
108
0.65838
795b01648703cd0b81a3ee42747cc8e2c135be1d
920
exs
Elixir
test/clickhousex/table_storage_test.exs
julienmarie/clickhousex
7f79596b51da44737a84e1911b96852b86f1cd75
[ "Apache-2.0" ]
1
2021-11-26T16:43:09.000Z
2021-11-26T16:43:09.000Z
test/clickhousex/table_storage_test.exs
julienmarie/clickhousex
7f79596b51da44737a84e1911b96852b86f1cd75
[ "Apache-2.0" ]
1
2021-01-04T14:16:30.000Z
2021-01-04T14:16:30.000Z
test/clickhousex/table_storage_test.exs
julienmarie/clickhousex
7f79596b51da44737a84e1911b96852b86f1cd75
[ "Apache-2.0" ]
3
2020-02-25T05:31:08.000Z
2020-09-18T07:27:10.000Z
defmodule Clickhousex.TableStorageTest do use ClickhouseCase, async: true alias Clickhousex.Result test "can create and drop table", ctx do create_statement = """ CREATE TABLE {{table}} (id Int32) ENGINE = Memory """ assert {:ok, %Result{}} = schema(ctx, create_statement) assert {:ok, %Result{}} = schema(ctx, "DROP TABLE {{ table }}") end test "returns correct error when dropping table that doesn't exist", ctx do assert {:error, %{code: :base_table_or_view_not_found}} = schema(ctx, "DROP TABLE table_storage_test.not_exist") end test "returns correct error when creating a table that already exists", ctx do create_statement = """ CREATE TABLE {{ table }} (id Int32) ENGINE = Memory """ assert {:ok, %Result{}} = schema(ctx, create_statement) assert {:error, %{code: :table_already_exists}} = schema(ctx, create_statement) end end
29.677419
83
0.669565
795b05424c0718ad700df6e9d97ea63d079c922e
309
ex
Elixir
test/support/test/wait_until.ex
eahanson/corex
550020c5cbfc7dc828bc74e1edf0223c1cbffef1
[ "MIT" ]
null
null
null
test/support/test/wait_until.ex
eahanson/corex
550020c5cbfc7dc828bc74e1edf0223c1cbffef1
[ "MIT" ]
null
null
null
test/support/test/wait_until.ex
eahanson/corex
550020c5cbfc7dc828bc74e1edf0223c1cbffef1
[ "MIT" ]
null
null
null
defmodule Corex.Test.WaitUntil do def wait_until(fun), do: wait_until(1000, fun) def wait_until(0, fun), do: fun.() def wait_until(timeout, fun) do try do fun.() rescue ExUnit.AssertionError -> :timer.sleep(10) wait_until(max(0, timeout - 10), fun) end end end
22.071429
48
0.621359
795b12643eb9d744ae54c004e3938713376baa47
1,980
exs
Elixir
mix.exs
homesocial/dlex
d9df0d1a00f758930699f46d3ded124171473a4d
[ "Apache-2.0" ]
null
null
null
mix.exs
homesocial/dlex
d9df0d1a00f758930699f46d3ded124171473a4d
[ "Apache-2.0" ]
null
null
null
mix.exs
homesocial/dlex
d9df0d1a00f758930699f46d3ded124171473a4d
[ "Apache-2.0" ]
null
null
null
defmodule Dlex.MixProject do use Mix.Project def project do [ app: :dlex, version: "0.5.1", elixir: "~> 1.7", start_permanent: Mix.env() == :prod, deps: deps(), description: description(), package: package(), aliases: [ "test.all": ["test.http", "test"], "test.http": &test_http/1 ], preferred_cli_env: ["test.all": :test, "test.http": :test] ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:db_connection, "~> 2.3"}, {:jason, "~> 1.2"}, {:ecto, "~> 3.5"}, # GRPC {:grpc, github: "elixir-grpc/grpc"}, {:cowboy, github: "ninenines/cowboy", override: true}, {:cowlib, git: "https://github.com/ninenines/cowlib", ref: "master"}, # MINT {:mint, "~> 1.2"}, {:castore, "~> 0.1.9"}, # DEV {:earmark, "~> 1.4", only: :dev}, {:exrun, "~> 0.1", only: :dev}, {:ex_doc, "~> 0.23", only: :dev} ] end defp description do "Dlex is a gRPC based client for the Dgraph database." end defp package do [ maintainers: ["Dmitry Russ(Aleksandrov)", "Eric Hagman"], licenses: ["Apache 2.0"], links: %{"Github" => "https://github.com/liveforeverx/dlex"} ] end defp test_http(args) do env_run([{"DLEX_ADAPTER", "http"}], args) end defp env_run(envs, args) do args = if IO.ANSI.enabled?(), do: ["--color" | args], else: ["--no-color" | args] env_line = envs |> Enum.map(fn {key, value} -> "#{key}=#{value}" end) |> Enum.join(" ") IO.puts("==> Running tests with environments: #{env_line} mix test") {_, res} = System.cmd("mix", ["test" | args], into: IO.binstream(:stdio, :line), env: envs) if res > 0 do System.at_exit(fn _ -> exit({:shutdown, 1}) end) end end end
24.75
95
0.541919