hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
list
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
list
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
list
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
1c85b279047bd85a6f957386db64f896eebb4837
689
ex
Elixir
out/manticoresearch-elixir/lib/manticoresearch/model/percolate_request.ex
manticoresoftware/openapi
79bccede913291724c83ebcad5590f1f13ff7726
[ "MIT" ]
null
null
null
out/manticoresearch-elixir/lib/manticoresearch/model/percolate_request.ex
manticoresoftware/openapi
79bccede913291724c83ebcad5590f1f13ff7726
[ "MIT" ]
3
2021-12-21T08:18:48.000Z
2022-03-24T10:50:37.000Z
out/manticoresearch-elixir/lib/manticoresearch/model/percolate_request.ex
manticoresoftware/openapi
79bccede913291724c83ebcad5590f1f13ff7726
[ "MIT" ]
5
2021-12-11T06:10:14.000Z
2022-03-18T11:05:24.000Z
# Manticore Search Client # Copyright (c) 2020-2021, Manticore Software LTD (https://manticoresearch.com) # # All rights reserved # Do not edit the class manually. defmodule Manticoresearch.Model.PercolateRequest do @moduledoc """ Object with documents to percolate """ @derive [Poison.Encoder] defstruct [ :"query" ] @type t :: %__MODULE__{ :"query" => Manticoresearch.Model.PercolateRequestQuery.t } end defimpl Poison.Decoder, for: Manticoresearch.Model.PercolateRequest do import Manticoresearch.Deserializer def decode(value, options) do value |> deserialize(:"query", :struct, Manticoresearch.Model.PercolateRequestQuery, options) end end
22.225806
91
0.734398
1c85d1cb97296dd5877387918d45ba385bafcf08
1,967
ex
Elixir
clients/ad_experience_report/lib/google_api/ad_experience_report/v1/model/site_summary_response.ex
ericrwolfe/elixir-google-api
3dc0f17edd5e2d6843580c16ddae3bf84b664ffd
[ "Apache-2.0" ]
null
null
null
clients/ad_experience_report/lib/google_api/ad_experience_report/v1/model/site_summary_response.ex
ericrwolfe/elixir-google-api
3dc0f17edd5e2d6843580c16ddae3bf84b664ffd
[ "Apache-2.0" ]
null
null
null
clients/ad_experience_report/lib/google_api/ad_experience_report/v1/model/site_summary_response.ex
ericrwolfe/elixir-google-api
3dc0f17edd5e2d6843580c16ddae3bf84b664ffd
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AdExperienceReport.V1.Model.SiteSummaryResponse do @moduledoc """ Response message for GetSiteSummary. ## Attributes - desktopSummary (PlatformSummary): Summary for the desktop review of the site. Defaults to: `null`. - mobileSummary (PlatformSummary): Summary for the mobile review of the site. Defaults to: `null`. - reviewedSite (String): The name of the site reviewed. Defaults to: `null`. """ defstruct [ :desktopSummary, :mobileSummary, :reviewedSite ] end defimpl Poison.Decoder, for: GoogleApi.AdExperienceReport.V1.Model.SiteSummaryResponse do import GoogleApi.AdExperienceReport.V1.Deserializer def decode(value, options) do value |> deserialize( :desktopSummary, :struct, GoogleApi.AdExperienceReport.V1.Model.PlatformSummary, options ) |> deserialize( :mobileSummary, :struct, GoogleApi.AdExperienceReport.V1.Model.PlatformSummary, options ) end end defimpl Poison.Encoder, for: GoogleApi.AdExperienceReport.V1.Model.SiteSummaryResponse do def encode(value, options) do GoogleApi.AdExperienceReport.V1.Deserializer.serialize_non_nil(value, options) end end
31.725806
102
0.744789
1c85d2c47d4b8fa8c18c20c3a06946adf86297ca
606
ex
Elixir
lib/elasticsearch/application.ex
szajbus/elasticsearch-elixir
4ce751b4b5379ccc168a8930bca9c3ad99ffbc55
[ "MIT" ]
215
2019-01-28T23:31:14.000Z
2022-03-31T16:03:30.000Z
lib/elasticsearch/application.ex
szajbus/elasticsearch-elixir
4ce751b4b5379ccc168a8930bca9c3ad99ffbc55
[ "MIT" ]
56
2018-01-02T17:52:54.000Z
2019-01-19T16:05:47.000Z
lib/elasticsearch/application.ex
szajbus/elasticsearch-elixir
4ce751b4b5379ccc168a8930bca9c3ad99ffbc55
[ "MIT" ]
39
2019-03-12T20:35:03.000Z
2022-03-11T16:49:45.000Z
defmodule Elasticsearch.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do # List all child processes to be supervised children = [ # Starts a worker by calling: Elasticsearch.Worker.start_link(arg) # {Elasticsearch.Worker, arg}, ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Elasticsearch.Supervisor] Supervisor.start_link(children, opts) end end
28.857143
72
0.721122
1c85d65f751987b85779f9f04355ecce199bd705
1,416
ex
Elixir
clients/private_ca/lib/google_api/private_ca/v1/model/cert_chain.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/private_ca/lib/google_api/private_ca/v1/model/cert_chain.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/private_ca/lib/google_api/private_ca/v1/model/cert_chain.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.PrivateCA.V1.Model.CertChain do @moduledoc """ ## Attributes * `certificates` (*type:* `list(String.t)`, *default:* `nil`) - The certificates that form the CA chain, from leaf to root order. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :certificates => list(String.t()) | nil } field(:certificates, type: :list) end defimpl Poison.Decoder, for: GoogleApi.PrivateCA.V1.Model.CertChain do def decode(value, options) do GoogleApi.PrivateCA.V1.Model.CertChain.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.PrivateCA.V1.Model.CertChain do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
30.12766
133
0.730226
1c861894d5b34615a0ff881271efb6b231ea69fa
1,986
exs
Elixir
test/cleanser_test.exs
ivymarkwell/cleanser
06e7caffab282c5c63cf44c347b88258ebe7fef7
[ "MIT" ]
7
2018-04-21T02:25:05.000Z
2022-02-23T19:42:06.000Z
test/cleanser_test.exs
ivymarkwell/cleanser
06e7caffab282c5c63cf44c347b88258ebe7fef7
[ "MIT" ]
5
2018-04-28T23:50:49.000Z
2018-10-29T22:37:48.000Z
test/cleanser_test.exs
ivymarkwell/cleanser
06e7caffab282c5c63cf44c347b88258ebe7fef7
[ "MIT" ]
2
2018-04-28T23:48:54.000Z
2019-06-25T07:50:04.000Z
defmodule CleanserTest do use ExUnit.Case doctest Cleanser test "test email validation with default invalid domains" do assert Cleanser.validate_email("person@example.com") == :ok refute Cleanser.validate_email("person@spambox.me") == {:error, "person@spambox.me is an invalid email"} end test "test email validation with custom invalid domains" do assert Cleanser.validate_email("person@example.com", ["baddomain.com"]) == :ok refute Cleanser.validate_email("person@example.com", ["example.com"]) == {:error, "person@example.com is an invalid email"} end test "test bad language validation" do assert Cleanser.is_valid_language?("Arabic") == :ok assert Cleanser.is_valid_language?("japanese") == :ok assert Cleanser.is_valid_language?("meow") == {:error, "meow is either not a valid language or not available in this package"} assert Cleanser.contains_bad_words?("what the doodle", "tootielang") == {:error, "tootielang is either not a valid language or not available in this package"} assert Cleanser.contains_bad_words?("i have lots of butts ", "indo european") == {:error, "indo european is either not a valid language or not available in this package"} end test "test bad words filter" do assert Cleanser.contains_bad_words?("me and fils de pute okwhatthe", "german") == :ok assert Cleanser.contains_bad_words?("Puta pinche madre", "Spanish") == {:error, "This string contains bad words"} assert Cleanser.contains_bad_words?("me and fils de pute okwhatthe", "french") == {:error, "This string contains bad words"} assert Cleanser.contains_bad_words?("ดอกทอง ตอแหล ูด น้ําแตก", "Thai") == {:error, "This string contains bad words"} end test "test credit card validation with invalid card numbers" do assert Cleanser.is_valid_credit_card?(4532004657698632172) == :ok assert Cleanser.is_valid_credit_card?(370177727770444) == {:error, "370177727770444 is an invalid credit card number"} end end
56.742857
174
0.731621
1c86192d13197be9e0999f33d9f3b813e3df5090
2,214
ex
Elixir
clients/monitoring/lib/google_api/monitoring/v3/model/list_notification_channel_descriptors_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/monitoring/lib/google_api/monitoring/v3/model/list_notification_channel_descriptors_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/monitoring/lib/google_api/monitoring/v3/model/list_notification_channel_descriptors_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Monitoring.V3.Model.ListNotificationChannelDescriptorsResponse do @moduledoc """ The ListNotificationChannelDescriptors response. ## Attributes * `channelDescriptors` (*type:* `list(GoogleApi.Monitoring.V3.Model.NotificationChannelDescriptor.t)`, *default:* `nil`) - The monitored resource descriptors supported for the specified project, optionally filtered. * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - If not empty, indicates that there may be more results that match the request. Use the value in the page_token field in a subsequent request to fetch the next set of results. If empty, all results have been returned. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :channelDescriptors => list(GoogleApi.Monitoring.V3.Model.NotificationChannelDescriptor.t()) | nil, :nextPageToken => String.t() | nil } field(:channelDescriptors, as: GoogleApi.Monitoring.V3.Model.NotificationChannelDescriptor, type: :list ) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.Monitoring.V3.Model.ListNotificationChannelDescriptorsResponse do def decode(value, options) do GoogleApi.Monitoring.V3.Model.ListNotificationChannelDescriptorsResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Monitoring.V3.Model.ListNotificationChannelDescriptorsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.9
279
0.751581
1c86248de61909a81946afb22f9e2ea28ed67058
12,615
exs
Elixir
test/groupher_server/cms/article_community/works_test.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
240
2018-11-06T09:36:54.000Z
2022-02-20T07:12:36.000Z
test/groupher_server/cms/article_community/works_test.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
363
2018-07-11T03:38:14.000Z
2021-12-14T01:42:40.000Z
test/groupher_server/cms/article_community/works_test.exs
mydearxym/mastani_server
f24034a4a5449200165cf4a547964a0961793eab
[ "Apache-2.0" ]
22
2019-01-27T11:47:56.000Z
2021-02-28T13:17:52.000Z
defmodule GroupherServer.Test.CMS.ArticleCommunity.Works do use GroupherServer.TestTools alias Helper.ORM alias GroupherServer.CMS alias CMS.Model.Works setup do {:ok, user} = db_insert(:user) {:ok, user2} = db_insert(:user) {:ok, works} = db_insert(:works) {:ok, community} = db_insert(:community) {:ok, community2} = db_insert(:community) {:ok, community3} = db_insert(:community) works_attrs = mock_attrs(:works, %{community_id: community.id}) {:ok, ~m(user user2 community community2 community3 works works_attrs)a} end describe "[article mirror/move]" do test "created works has origial community info", ~m(user community works_attrs)a do {:ok, works} = CMS.create_article(community, :works, works_attrs, user) {:ok, works} = ORM.find(Works, works.id, preload: :original_community) assert works.original_community_id == community.id end test "works can be move to other community", ~m(user community community2 works_attrs)a do {:ok, works} = CMS.create_article(community, :works, works_attrs, user) assert works.original_community_id == community.id {:ok, _} = CMS.move_article(:works, works.id, community2.id) {:ok, works} = ORM.find(Works, works.id, preload: [:original_community, :communities]) assert works.original_community.id == community2.id assert exist_in?(community2, works.communities) end test "tags should be clean after works move to other community", ~m(user community community2 works_attrs)a do article_tag_attrs = mock_attrs(:article_tag) article_tag_attrs2 = mock_attrs(:article_tag) {:ok, works} = CMS.create_article(community, :works, works_attrs, user) {:ok, article_tag} = CMS.create_article_tag(community, :works, article_tag_attrs, user) {:ok, article_tag2} = CMS.create_article_tag(community, :works, article_tag_attrs2, user) {:ok, _works} = CMS.set_article_tag(:works, works.id, article_tag.id) {:ok, works} = CMS.set_article_tag(:works, works.id, article_tag2.id) assert works.article_tags |> length == 2 assert works.original_community_id == community.id {:ok, _} = CMS.move_article(:works, works.id, community2.id) {:ok, works} = ORM.find(Works, works.id, preload: [:original_community, :communities, :article_tags]) assert works.article_tags |> length == 0 assert works.original_community.id == community2.id assert exist_in?(community2, works.communities) end test "works move to other community with new tag", ~m(user community community2 works_attrs)a do article_tag_attrs0 = mock_attrs(:article_tag) article_tag_attrs = mock_attrs(:article_tag) article_tag_attrs2 = mock_attrs(:article_tag) {:ok, article_tag0} = CMS.create_article_tag(community, :works, article_tag_attrs0, user) {:ok, article_tag} = CMS.create_article_tag(community2, :works, article_tag_attrs, user) {:ok, article_tag2} = CMS.create_article_tag(community2, :works, article_tag_attrs2, user) {:ok, works} = CMS.create_article(community, :works, works_attrs, user) {:ok, _} = CMS.set_article_tag(:works, works.id, article_tag0.id) {:ok, _} = CMS.set_article_tag(:works, works.id, article_tag.id) {:ok, _} = CMS.set_article_tag(:works, works.id, article_tag2.id) {:ok, works} = ORM.find(Works, works.id, preload: [:article_tags]) assert works.article_tags |> length == 3 {:ok, _} = CMS.move_article(:works, works.id, community2.id, [article_tag.id, article_tag2.id]) {:ok, works} = ORM.find(Works, works.id, preload: [:original_community, :communities, :article_tags]) assert works.original_community.id == community2.id assert works.article_tags |> length == 2 assert not exist_in?(article_tag0, works.article_tags) assert exist_in?(article_tag, works.article_tags) assert exist_in?(article_tag2, works.article_tags) end test "works can be mirror to other community", ~m(user community community2 works_attrs)a do {:ok, works} = CMS.create_article(community, :works, works_attrs, user) {:ok, works} = ORM.find(Works, works.id, preload: :communities) assert works.communities |> length == 1 assert exist_in?(community, works.communities) {:ok, _} = CMS.mirror_article(:works, works.id, community2.id) {:ok, works} = ORM.find(Works, works.id, preload: :communities) assert works.communities |> length == 2 assert exist_in?(community, works.communities) assert exist_in?(community2, works.communities) end test "works can be mirror to other community with tags", ~m(user community community2 works_attrs)a do article_tag_attrs = mock_attrs(:article_tag) article_tag_attrs2 = mock_attrs(:article_tag) {:ok, article_tag} = CMS.create_article_tag(community2, :works, article_tag_attrs, user) {:ok, article_tag2} = CMS.create_article_tag(community2, :works, article_tag_attrs2, user) {:ok, works} = CMS.create_article(community, :works, works_attrs, user) {:ok, _} = CMS.mirror_article(:works, works.id, community2.id, [article_tag.id, article_tag2.id]) {:ok, works} = ORM.find(Works, works.id, preload: :article_tags) assert works.article_tags |> length == 2 assert exist_in?(article_tag, works.article_tags) assert exist_in?(article_tag2, works.article_tags) end test "works can be unmirror from community", ~m(user community community2 community3 works_attrs)a do {:ok, works} = CMS.create_article(community, :works, works_attrs, user) {:ok, _} = CMS.mirror_article(:works, works.id, community2.id) {:ok, _} = CMS.mirror_article(:works, works.id, community3.id) {:ok, works} = ORM.find(Works, works.id, preload: :communities) assert works.communities |> length == 3 {:ok, _} = CMS.unmirror_article(:works, works.id, community3.id) {:ok, works} = ORM.find(Works, works.id, preload: :communities) assert works.communities |> length == 2 assert not exist_in?(community3, works.communities) end test "works can be unmirror from community with tags", ~m(user community community2 community3 works_attrs)a do article_tag_attrs2 = mock_attrs(:article_tag) article_tag_attrs3 = mock_attrs(:article_tag) {:ok, article_tag2} = CMS.create_article_tag(community2, :works, article_tag_attrs2, user) {:ok, article_tag3} = CMS.create_article_tag(community3, :works, article_tag_attrs3, user) {:ok, works} = CMS.create_article(community, :works, works_attrs, user) {:ok, _} = CMS.mirror_article(:works, works.id, community2.id, [article_tag2.id]) {:ok, _} = CMS.mirror_article(:works, works.id, community3.id, [article_tag3.id]) {:ok, _} = CMS.unmirror_article(:works, works.id, community3.id) {:ok, works} = ORM.find(Works, works.id, preload: :article_tags) assert exist_in?(article_tag2, works.article_tags) assert not exist_in?(article_tag3, works.article_tags) end test "works can not unmirror from original community", ~m(user community community2 community3 works_attrs)a do {:ok, works} = CMS.create_article(community, :works, works_attrs, user) {:ok, _} = CMS.mirror_article(:works, works.id, community2.id) {:ok, _} = CMS.mirror_article(:works, works.id, community3.id) {:ok, works} = ORM.find(Works, works.id, preload: :communities) assert works.communities |> length == 3 {:error, reason} = CMS.unmirror_article(:works, works.id, community.id) assert reason |> is_error?(:mirror_article) end test "works can be mirror to home", ~m(community works_attrs user)a do {:ok, home_community} = db_insert(:community, %{raw: "home"}) {:ok, works} = CMS.create_article(community, :works, works_attrs, user) assert works.original_community_id == community.id {:ok, _} = CMS.mirror_to_home(:works, works.id) {:ok, works} = ORM.find(Works, works.id, preload: [:original_community, :communities]) assert works.original_community_id == community.id assert works.communities |> length == 2 assert exist_in?(community, works.communities) assert exist_in?(home_community, works.communities) filter = %{page: 1, size: 10, community: community.raw} {:ok, paged_articles} = CMS.paged_articles(:works, filter) assert exist_in?(works, paged_articles.entries) assert paged_articles.total_count === 1 filter = %{page: 1, size: 10, community: home_community.raw} {:ok, paged_articles} = CMS.paged_articles(:works, filter) assert exist_in?(works, paged_articles.entries) assert paged_articles.total_count === 1 end test "works can be mirror to home with tags", ~m(community works_attrs user)a do {:ok, home_community} = db_insert(:community, %{raw: "home"}) article_tag_attrs0 = mock_attrs(:article_tag) article_tag_attrs = mock_attrs(:article_tag) {:ok, article_tag0} = CMS.create_article_tag(home_community, :works, article_tag_attrs0, user) {:ok, article_tag} = CMS.create_article_tag(home_community, :works, article_tag_attrs, user) {:ok, works} = CMS.create_article(community, :works, works_attrs, user) assert works.original_community_id == community.id {:ok, _} = CMS.mirror_to_home(:works, works.id, [article_tag0.id, article_tag.id]) {:ok, works} = ORM.find(Works, works.id, preload: [:original_community, :communities, :article_tags]) assert works.original_community_id == community.id assert works.communities |> length == 2 assert exist_in?(community, works.communities) assert exist_in?(home_community, works.communities) assert works.article_tags |> length == 2 assert exist_in?(article_tag0, works.article_tags) assert exist_in?(article_tag, works.article_tags) filter = %{page: 1, size: 10, community: community.raw} {:ok, paged_articles} = CMS.paged_articles(:works, filter) assert exist_in?(works, paged_articles.entries) assert paged_articles.total_count === 1 filter = %{page: 1, size: 10, community: home_community.raw} {:ok, paged_articles} = CMS.paged_articles(:works, filter) assert exist_in?(works, paged_articles.entries) assert paged_articles.total_count === 1 end test "works can be move to blackhole", ~m(community works_attrs user)a do {:ok, blackhole_community} = db_insert(:community, %{raw: "blackhole"}) {:ok, works} = CMS.create_article(community, :works, works_attrs, user) assert works.original_community_id == community.id {:ok, _} = CMS.move_to_blackhole(:works, works.id) {:ok, works} = ORM.find(Works, works.id, preload: [:original_community, :communities]) assert works.original_community.id == blackhole_community.id assert works.communities |> length == 1 assert exist_in?(blackhole_community, works.communities) filter = %{page: 1, size: 10, community: blackhole_community.raw} {:ok, paged_articles} = CMS.paged_articles(:works, filter) assert exist_in?(works, paged_articles.entries) assert paged_articles.total_count === 1 end test "works can be move to blackhole with tags", ~m(community works_attrs user)a do {:ok, blackhole_community} = db_insert(:community, %{raw: "blackhole"}) article_tag_attrs0 = mock_attrs(:article_tag) article_tag_attrs = mock_attrs(:article_tag) {:ok, article_tag0} = CMS.create_article_tag(blackhole_community, :works, article_tag_attrs0, user) {:ok, article_tag} = CMS.create_article_tag(blackhole_community, :works, article_tag_attrs, user) {:ok, works} = CMS.create_article(community, :works, works_attrs, user) {:ok, _} = CMS.set_article_tag(:works, works.id, article_tag0.id) assert works.original_community_id == community.id {:ok, _} = CMS.move_to_blackhole(:works, works.id, [article_tag.id]) {:ok, works} = ORM.find(Works, works.id, preload: [:original_community, :communities, :article_tags]) assert works.original_community.id == blackhole_community.id assert works.communities |> length == 1 assert works.article_tags |> length == 1 assert exist_in?(blackhole_community, works.communities) assert exist_in?(article_tag, works.article_tags) end end end
41.771523
98
0.687119
1c864274d05e1ec5c532e6a34c4c10289ee73202
1,529
ex
Elixir
lib/my_app_web.ex
normanpatrick/elixir-python-task-api
84a12eff26ddf98a29526630e4ce9fa1076545cb
[ "MIT" ]
null
null
null
lib/my_app_web.ex
normanpatrick/elixir-python-task-api
84a12eff26ddf98a29526630e4ce9fa1076545cb
[ "MIT" ]
null
null
null
lib/my_app_web.ex
normanpatrick/elixir-python-task-api
84a12eff26ddf98a29526630e4ce9fa1076545cb
[ "MIT" ]
null
null
null
defmodule MyAppWeb do @moduledoc """ The entrypoint for defining your web interface, such as controllers, views, channels and so on. This can be used in your application as: use MyAppWeb, :controller use MyAppWeb, :view The definitions below will be executed for every view, controller, etc, so keep them short and clean, focused on imports, uses and aliases. Do NOT define functions inside the quoted expressions below. Instead, define any helper function in modules and import those modules here. """ def controller do quote do use Phoenix.Controller, namespace: MyAppWeb import Plug.Conn import MyAppWeb.Gettext alias MyAppWeb.Router.Helpers, as: Routes end end def view do quote do use Phoenix.View, root: "lib/my_app_web/templates", namespace: MyAppWeb # Import convenience functions from controllers import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1] import MyAppWeb.ErrorHelpers import MyAppWeb.Gettext alias MyAppWeb.Router.Helpers, as: Routes end end def router do quote do use Phoenix.Router import Plug.Conn import Phoenix.Controller end end def channel do quote do use Phoenix.Channel import MyAppWeb.Gettext end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
22.820896
83
0.687377
1c86608422bb5212d7d43047f5cd2509e5c13fd0
2,740
exs
Elixir
mix.exs
fremantle-industries/rube
ceb0c6d09e8b9c029a71115710265d8b6b31cc49
[ "MIT" ]
22
2021-06-23T06:25:41.000Z
2022-02-16T19:08:33.000Z
mix.exs
fremantle-industries/rube
ceb0c6d09e8b9c029a71115710265d8b6b31cc49
[ "MIT" ]
16
2021-06-21T17:02:13.000Z
2022-03-21T15:04:14.000Z
mix.exs
fremantle-industries/rube
ceb0c6d09e8b9c029a71115710265d8b6b31cc49
[ "MIT" ]
2
2021-06-23T13:40:52.000Z
2021-09-17T07:25:34.000Z
defmodule Rube.MixProject do use Mix.Project def project do [ app: :rube, version: "0.0.4", elixir: "~> 1.11", elixirc_paths: elixirc_paths(Mix.env()), compilers: [:phoenix, :gettext] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps(), description: description(), package: package(), preferred_cli_env: [ "test.docker": :test ] ] end def application do [ mod: {Rube.Application, []}, extra_applications: [:logger, :runtime_tools] ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] defp deps do [ {:accessible, "~> 0.3"}, {:deque, "~> 1.0"}, {:ecto_sql, "~> 3.4"}, {:gettext, "~> 0.11"}, {:jason, "~> 1.0"}, {:master_proxy, "~> 0.1"}, {:navigator, "~> 0.0.6"}, {:notified_phoenix, "~> 0.0.7"}, {:phoenix, "~> 1.6"}, {:phoenix_ecto, "~> 4.4"}, {:phoenix_html, "~> 3.0"}, {:phoenix_live_dashboard, "~> 0.5"}, {:phoenix_live_view, "~> 0.17"}, {:phoenix_live_react, "~> 0.4.1"}, {:plug_cowboy, "~> 2.0"}, {:postgrex, ">= 0.0.0"}, # {:slurp, github: "fremantle-industries/slurp", branch: "main", override: true}, {:slurp, "~> 0.0.11"}, # {:slurpee, github: "fremantle-industries/slurpee", branch: "main", override: true}, {:slurpee, "~> 0.0.14"}, # {:stylish, github: "fremantle-industries/stylish", branch: "main", override: true}, {:stylish, "~> 0.0.8"}, {:telemetry, "~> 1.0"}, {:telemetry_metrics, "~> 0.4"}, {:telemetry_poller, "~> 1.0"}, {:telemetry_metrics_prometheus, "~> 1.0"}, {:logger_file_backend, "~> 0.0.10", only: [:dev, :test]}, {:excoveralls, "~> 0.8", only: :test}, {:ex_unit_notifier, "~> 1.0", only: :test}, {:floki, ">= 0.27.0", only: :test}, {:phoenix_live_reload, "~> 1.2", only: :dev}, {:dialyxir, "~> 1.0", only: :dev, runtime: false}, {:mix_test_watch, "~> 1.0", only: :dev, runtime: false} ] end defp aliases do [ "setup.deps": ["deps.get", "cmd npm install --prefix assets"], setup: ["setup.deps", "ecto.setup"], "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"] ] end defp description do "A multi-chain DeFi development toolkit" end defp package do %{ licenses: ["MIT"], maintainers: ["Alex Kwiatkowski"], links: %{"GitHub" => "https://github.com/fremantle-industries/rube"} } end end
29.782609
91
0.529927
1c868763810b1b70cd2677969b6d10e2e257cb76
90
ex
Elixir
lib/banchan/mailer.ex
riamaria/banchan
c4f8bd9374acaf0a8bb2c501e2ae1eb78f96579f
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
lib/banchan/mailer.ex
riamaria/banchan
c4f8bd9374acaf0a8bb2c501e2ae1eb78f96579f
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
lib/banchan/mailer.ex
riamaria/banchan
c4f8bd9374acaf0a8bb2c501e2ae1eb78f96579f
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
defmodule Banchan.Mailer do @moduledoc false use Bamboo.Mailer, otp_app: :banchan end
18
38
0.777778
1c868ff3e375823ec98f14585b05a760d64e0d34
10,007
ex
Elixir
lib/vaporator/cloudfs/cloudfs.ex
dogwynn/vaporator
4aa48d3a0862af0b86849460401919ac8e3248d7
[ "MIT" ]
null
null
null
lib/vaporator/cloudfs/cloudfs.ex
dogwynn/vaporator
4aa48d3a0862af0b86849460401919ac8e3248d7
[ "MIT" ]
103
2019-01-13T20:39:00.000Z
2021-07-29T05:30:36.000Z
lib/vaporator/cloudfs/cloudfs.ex
dogwynn/vaporator
4aa48d3a0862af0b86849460401919ac8e3248d7
[ "MIT" ]
null
null
null
defprotocol Vaporator.CloudFs do @moduledoc """ Protocol for the most basic set of Cloud file-system operations Impls must implement the following functions: - list_folder - get_metadata - file_download - file_upload - ... """ @doc """ Need to be able to get the file's hash based on the destination CloudFs hashing method. This can be different for each cloud provider. Used when comparing ClientFs and CloudFs versions of a file. Args: - fs (Vaporator.CloudFs impl): Cloud file system - local_path (binary): Path of file on client file system Returns: cloudfs_hash (binary) """ def get_hash!(fs, local_path) @doc """ Need to be able to get the destination CloudFs path from a local_path Args: - fs (Vaporator.CloudFs impl): Cloud file system - local_root (binary): Path of root folder on client file system. That is, the given local_path should be within the given root, and it is this root that will be "replaced" with the cloudfs_root when transfering the file. - local_path (binary): Path of folder on client file system - cloudfs_root (binary): Path of root folder on cloud file system Returns: cloudfs_path (binary) """ def get_path(fs, local_root, local_path, cloudfs_root) @doc """ Need to be able to get the contents of a folder. Args: - fs (Vaporator.CloudFs impl): Cloud file system - path (binary): Path of folder on cloud file system to list - args (Map): File-system-specific arguments to pass to the underlying subsystem. In a perfect world, this would be unnecessary, but "let it fail..." and all that. Returns: {:ok, Vaporator.CloudFs.ResultsMeta} or {:error, {:cloud_path_not_found, path error (binary)} or {:error, {:bad_decode, decode error (any)} or {:error, {:bad_status, {:status_code, code (int)}, JSON (Map)}} or {:error, {:unhandled_status, {:status_code, code (int)}, body (binary)}} """ def list_folder(fs, path, args \\ %{}) @doc """ Need to be able to get the metadata of an object at a particular path. Args: - fs (Vaporator.CloudFs impl): Cloud file system - path (binary): Path of file/folder on cloud file system to get metadata for - args (Map): File-system-specific arguments to pass to the underlying subsystem. Returns: {:ok, Vaporator.CloudFS.Meta} or {:error, {:cloud_path_not_found, path error (binary)} or {:error, {:bad_decode, decode error (any)} or {:error, {:bad_status, {:status_code, code (int)}, JSON (Map)}} or {:error, {:unhandled_status, {:status_code, code (int)}, body (binary)}} """ def get_metadata(fs, path, args \\ %{}) @doc """ Need to be able to get the binary content of a file at a particular path. Args: - fs (Vaporator.CloudFs impl): Cloud file system - path (binary): Path of file on cloud file system to download - args (Map): File-system-specific arguments to pass to the underlying subsystem. Returns: {:ok, Vaporator.CloudFs.FileContent} or {:error, {:cloud_path_not_found, path error (binary)} or {:error, {:bad_decode, decode error (any)} or {:error, {:bad_status, {:status_code, code (int)}, JSON (Map)}} or {:error, {:unhandled_status, {:status_code, code (int)}, body (binary)}} """ def file_download(fs, path, args \\ %{}) @doc """ Need to be able to upload binary content of a file on the local file system to a particular path on the cloud file system. The file should always be transferred and should overwrite whatever is (might be) already there. Args: - fs (Vaporator.CloudFs impl): Cloud file system - local_path (binary): Path of file on local file system to upload - fs_path (binary): Path on cloud file system to place uploaded content. If this path ends with a "/" then it should be treated as a directory in which to place the local_path - args (Map): File-system-specific arguments to pass to the underlying subsystem. Returns: {:ok, Vaporator.CloudFs.Meta} or {:error, :local_path_not_found} or {:error, {:bad_decode, decode error (any)} or {:error, {:bad_status, {:status_code, code (int)}, JSON (Map)}} or {:error, {:unhandled_status, {:status_code, code (int)}, body (binary)}} """ def file_upload(fs, local_path, fs_path, args \\ %{}) @doc """ Need to be able to update binary content of a file on the cloud file system to the version on the local file system. In the case of file_upload, the file is always transferred. In the case of file_update, the file transfer only happens if the cloud content is different from the local content. Args: - fs (Vaporator.CloudFs impl): Cloud file system - local_path (binary): Path of file on local file system to upload - fs_path (binary): Path on cloud file system to place uploaded content. If this path ends with a "/" then it should be treated as a directory in which to place the local_path - args (Map): File-system-specific arguments to pass to the underlying subsystem. Returns: {:ok, Vaporator.CloudFs.Meta} or {:error, :local_path_not_found} or {:error, {:bad_decode, decode error (any)} or {:error, {:bad_status, {:status_code, code (int)}, JSON (Map)}} or {:error, {:unhandled_status, {:status_code, code (int)}, body (binary)}} """ def file_update(fs, local_path, fs_path, args \\ %{}) @doc """ Need to be able to remove a file or folder on the cloud file system. Args: - fs (Vaporator.CloudFs impl): Cloud file system - path (binary): Path on cloud file system to remove. - args (Map): File-system-specific arguments to pass to the underlying subsystem. Returns: {:ok, Vaporator.CloudFs.FileContent} or {:error, {:cloud_path_not_found, path error (binary)} or {:error, {:bad_decode, decode error (any)} or {:error, {:bad_status, {:status_code, code (int)}, JSON (Map)}} or {:error, {:unhandled_status, {:status_code, code (int)}, body (binary)}} """ def file_remove(fs, path, args \\ %{}) def folder_remove(fs, path, args \\ %{}) @doc """ Need to be able to copy one file in the cloud file system to another place in the cloud file system. Args: - fs (Vaporator.CloudFs impl): Cloud file system - from_path (binary): Path of file/folder on cloud file system to copy - to_path (binary): Path of file/folder on cloud file system to place the copied file. If this path ends in a "/", then it is treated as a directory into which the file should be copied. - args (Map): File-system-specific arguments to pass to the underlying subsystem. Returns: {:ok, Vaporator.CloudFS.Meta} or {:error, {:cloud_path_not_found, path error (binary)} or {:error, {:bad_decode, decode error (any)} or {:error, {:bad_status, {:status_code, code (int)}, JSON (Map)}} or {:error, {:unhandled_status, {:status_code, code (int)}, body (binary)}} """ def file_copy(dbx, from_path, to_path, args \\ %{}) @doc """ Need to be able to move one file in the cloud file system to another place in the cloud file system. Args: - fs (Vaporator.CloudFs impl): Cloud file system - from_path (binary): Path of file/folder on cloud file system to move - to_path (binary): Path of file/folder on cloud file system to place the moved file. If this path ends in a "/", then it is treated as a directory into which the file should be moved. - args (Map): File-system-specific arguments to pass to the underlying subsystem. Returns: {:ok, Vaporator.CloudFS.Meta} or {:error, {:cloud_path_not_found, path error (binary)} or {:error, {:bad_decode, decode error (any)} or {:error, {:bad_status, {:status_code, code (int)}, JSON (Map)}} or {:error, {:unhandled_status, {:status_code, code (int)}, body (binary)}} """ def file_move(dbx, from_path, to_path, args \\ %{}) end defmodule Vaporator.CloudFs.Meta do @moduledoc """ CloudFs file/folder (i.e. inode) metadata """ # Every file on any file-system (Dropbox, GDrive, S3, etc.) should # have at least these attributes @enforce_keys [:type, :path] defstruct [ # :file, :folder, or :none? :type, # file name (w/o path) :name, # path in file-system :path, # time of last modification (UTC) :modify_time, # time of creation (UTC) :create_time, # file-system-specific metadata term :meta # to be used internally by the # particular file-system (i.e. the # implementation of the CloudFs # protocol) ] end defmodule Vaporator.CloudFs.ResultsMeta do @moduledoc """ CloudFs result set/list metadata. Keeps track of a list of results that matter (usually file/folder metadata), but also keeps a reference to the original file-system-specific result meta object for use later by the particular cloud file system. E.g. Dropbox needs the list_folder metadata (specifically, the "cursor" and "has_more" values) for pagination. Some file systems might have results metadata, some might not. In the case of not, then the metadata field (meta:) has a default value of an empty map. """ @enforce_keys [:results] defstruct results: [], # List of CloudFs.Meta objects # File-system-specific metadata for this meta: %{} # result set end defmodule Vaporator.CloudFs.FileContent do @moduledoc """ CloudFs file content struct Basically a thin type wrapping the Map data returned by HTTPoison's HTTP methods (POST generally) """ defstruct content: "", # Binary data from the body # Header data returned by the HTTP headers: %{} # response end
30.602446
76
0.658039
1c869e00bc95f88f62e82083d47041639e8a94e7
565
ex
Elixir
lib/bankster/bic.ex
socialpaymentsbv/bankster
8ca4797f0d83968636fe4f01a8383a1b52f645b0
[ "MIT" ]
29
2016-02-21T20:29:02.000Z
2022-03-28T15:54:06.000Z
lib/bankster/bic.ex
socialpaymentsbv/bankster
8ca4797f0d83968636fe4f01a8383a1b52f645b0
[ "MIT" ]
6
2017-04-06T07:18:41.000Z
2019-07-23T14:49:16.000Z
lib/bankster/bic.ex
railsmechanic/bankster
8c81ad29aac2ff2ac2cfac0c2a07f64bb2b030d6
[ "MIT" ]
9
2017-04-05T15:37:50.000Z
2022-02-08T07:04:58.000Z
defmodule Bankster.Bic do @moduledoc """ Provides some SWIFT BIC related functions. """ @bic_validation_regex ~r/^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$/ @doc """ Validates a given string whether it's a valid SWIFT BIC ## Example iex> Bankster.Bic.valid?("INVALIDBIC") false """ @spec valid?(String.t()) :: boolean def valid?(bic), do: is_valid?(bic) defp is_valid?(bic) when is_binary(bic), do: Regex.match?(@bic_validation_regex, String.replace(bic, ~r/\s*/, "")) defp is_valid?(_), do: false end
25.681818
89
0.623009
1c86abec15b849586b553365c90bdcb13a7a2b72
2,727
exs
Elixir
test/exeration_test.exs
nerdslabs/exeration
99f297aadeb10b062dfb9aa614526d903a7474af
[ "Apache-2.0" ]
null
null
null
test/exeration_test.exs
nerdslabs/exeration
99f297aadeb10b062dfb9aa614526d903a7474af
[ "Apache-2.0" ]
null
null
null
test/exeration_test.exs
nerdslabs/exeration
99f297aadeb10b062dfb9aa614526d903a7474af
[ "Apache-2.0" ]
null
null
null
defmodule ExerationTest do use ExUnit.Case doctest Exeration defmodule Example do use Exeration.Operation, observers: [ExerationTest.Observer] defmodule Struct do defstruct [:name, :is_folder] end @argument name: :user, type: :string @argument name: :file, type: :string, required: true def test(user, file) when is_binary(user) do {:ok, {user, file}} end @argument name: :file, type: :struct, struct: Struct @authorize policy: &ExerationTest.Example.auth?/1, arguments: [:file] def get(file), do: {:ok, file} @argument name: :default, type: :string def default(default \\ "abc"), do: {:ok, default} @authorize policy: &ExerationTest.Example.auth?/0 def list(), do: {:ok, ["a", "b"]} @argument name: :string, type: :test def validator(string), do: {:ok, string} @argument name: :atom, type: :atom @observe modules: ExerationTest.Observer def observe(atom), do: {:ok, atom} def auth?(file) do file.is_folder end def auth?() do true end end defmodule Validator do @behaviour Exeration.Validator def check(_argument, value) do case String.length(value) do 1 -> :ok _ -> :error end end end defmodule Observer do use Exeration.Observer def handle({_name, _arity}, _result) do end end test "test non nil" do assert {:ok, {"main", "test.txt"}} == ExerationTest.Example.test("main", "test.txt") end test "test nil" do assert {:error, :file, :string} == ExerationTest.Example.test("main", nil) end test "get authenticated" do assert {:ok, %Example.Struct{name: "text.txt", is_folder: true}} == ExerationTest.Example.get(%Example.Struct{name: "text.txt", is_folder: true}) end test "get non authenticated" do assert {:error, :not_authorized} == ExerationTest.Example.get(%Example.Struct{name: "text.txt", is_folder: false}) end test "get non struct" do assert {:error, :file, :struct} == ExerationTest.Example.get(%{name: "text.txt", is_folder: true}) end test "test detault" do assert {:ok, "abc"} == ExerationTest.Example.default() end test "list authenticated" do assert {:ok, ["a", "b"]} == ExerationTest.Example.list() end test "custom validator positive" do assert {:ok, "a"} == ExerationTest.Example.validator("a") end test "custom validator negative" do assert {:error, :string, :test} == ExerationTest.Example.validator("ab") end test "observer" do ExerationTest.Example.observe(:observe) pid = GenServer.whereis(ExerationTest.Observer) assert {:ok, :observe} == :sys.get_state(pid) end end
25.018349
91
0.636964
1c86b3e63a05679c2eb15670bded604bfada6cfa
710
ex
Elixir
lesson_03/demo/a_demo_umbrella/apps/a_demo_web/lib/a_demo_web/gettext.ex
martijnmeeldijk/ip_major
867f09975aa8db0b308081216ace639c5677446b
[ "BSD-3-Clause" ]
1
2021-09-22T09:56:35.000Z
2021-09-22T09:56:35.000Z
lesson_03/demo/a_demo_umbrella/apps/a_demo_web/lib/a_demo_web/gettext.ex
martijnmeeldijk/ip_major
867f09975aa8db0b308081216ace639c5677446b
[ "BSD-3-Clause" ]
7
2020-03-14T19:30:29.000Z
2022-02-27T01:20:40.000Z
lesson_03/demo/a_demo_umbrella/apps/a_demo_web/lib/a_demo_web/gettext.ex
martijnmeeldijk/ip_major
867f09975aa8db0b308081216ace639c5677446b
[ "BSD-3-Clause" ]
11
2020-02-13T14:52:45.000Z
2020-08-03T12:18:56.000Z
defmodule ADemoWeb.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. By using [Gettext](https://hexdocs.pm/gettext), your module gains a set of macros for translations, for example: import ADemoWeb.Gettext # Simple translation gettext("Here is the string to translate") # Plural translation ngettext("Here is the string to translate", "Here are the strings to translate", 3) # Domain-based translation dgettext("errors", "Here is the error message to translate") See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. """ use Gettext, otp_app: :a_demo_web end
28.4
72
0.677465
1c86c350ca44f88f658a16925f683bdf92d8fc49
159
ex
Elixir
lib/xain/example.ex
carakan/xain
1d81400ea44449d498aeeb0e46c9af6f30553795
[ "MIT" ]
null
null
null
lib/xain/example.ex
carakan/xain
1d81400ea44449d498aeeb0e46c9af6f30553795
[ "MIT" ]
null
null
null
lib/xain/example.ex
carakan/xain
1d81400ea44449d498aeeb0e46c9af6f30553795
[ "MIT" ]
null
null
null
defmodule Xain.Example do use Xain def test do markup do div do span do end end div do end end end end
9.9375
25
0.503145
1c86d0f086c92d75a36d730220a879e4c1b98fd2
171
exs
Elixir
priv/repo/migrations/20210712024244_add_user_avatar.exs
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
6
2021-11-17T21:10:49.000Z
2022-02-16T19:45:28.000Z
priv/repo/migrations/20210712024244_add_user_avatar.exs
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
18
2021-11-25T04:31:06.000Z
2022-03-27T04:54:00.000Z
priv/repo/migrations/20210712024244_add_user_avatar.exs
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
null
null
null
defmodule Console.Repo.Migrations.AddUserAvatar do use Ecto.Migration def change do alter table(:watchman_users) do add :profile, :string end end end
17.1
50
0.719298
1c86e4cabc94f39e405571d097f3f7d717d1be6e
242
exs
Elixir
year_2020/test/day_10_test.exs
bschmeck/advent_of_code
cbec98019c6c00444e0f4c7e15e01b1ed9ae6145
[ "MIT" ]
null
null
null
year_2020/test/day_10_test.exs
bschmeck/advent_of_code
cbec98019c6c00444e0f4c7e15e01b1ed9ae6145
[ "MIT" ]
null
null
null
year_2020/test/day_10_test.exs
bschmeck/advent_of_code
cbec98019c6c00444e0f4c7e15e01b1ed9ae6145
[ "MIT" ]
null
null
null
defmodule Day10Test do use ExUnit.Case test "it computes the answer" do assert Day10.part_one(InputTestFile) == 22 * 10 end test "it computes distinct arrangements" do assert Day10.part_two(InputTestFile) == 19208 end end
20.166667
51
0.727273
1c86f404a479d795c4a17acaacb9282135b19224
242
ex
Elixir
lib/sakavault_web/views/auth_view.ex
Api2sem2021/5-ADS2020-2-equipe6-api
11484e0232c1edd7fc928aa68d5014f2e3a20d07
[ "MIT" ]
null
null
null
lib/sakavault_web/views/auth_view.ex
Api2sem2021/5-ADS2020-2-equipe6-api
11484e0232c1edd7fc928aa68d5014f2e3a20d07
[ "MIT" ]
3
2020-09-20T22:59:35.000Z
2020-09-20T23:00:47.000Z
lib/sakavault_web/views/auth_view.ex
SEGURANCA-DA-INFORMACAO-LGPD/sakavault_api
11484e0232c1edd7fc928aa68d5014f2e3a20d07
[ "MIT" ]
null
null
null
defmodule SakaVaultWeb.AuthView do use SakaVaultWeb, :view alias SakaVaultWeb.AccountView def render("auth.json", %{auth: auth}) do user = AccountView.render("account.json", %{user: auth.user}) %{auth | user: user} end end
20.166667
65
0.690083
1c86f49b7a1d72204482e5dbfd6bdd73921d4c14
4,931
ex
Elixir
lib/ja_serializer/relationship.ex
gamesrol/ja_serializer
c48d8fb0fb742bd96c30acd40e24f7395f25af2c
[ "Apache-2.0" ]
null
null
null
lib/ja_serializer/relationship.ex
gamesrol/ja_serializer
c48d8fb0fb742bd96c30acd40e24f7395f25af2c
[ "Apache-2.0" ]
null
null
null
lib/ja_serializer/relationship.ex
gamesrol/ja_serializer
c48d8fb0fb742bd96c30acd40e24f7395f25af2c
[ "Apache-2.0" ]
null
null
null
defmodule JaSerializer.AssociationNotLoadedError do defexception [:message] def exception(opts) do msg = """ The #{opts[:rel]} relationship returned %Ecto.Association.NotLoaded{}. Please pre-fetch the relationship before serialization or override the #{opts[:name]}/2 function in your serializer. Example: def #{opts[:name]}(struct, conn) do case struct.#{opts[:rel]} do %Ecto.Association.NotLoaded{} -> struct |> Ecto.assoc(:#{opts[:rel]}) |> Repo.all other -> other end end """ %JaSerializer.AssociationNotLoadedError{message: msg} end end defmodule JaSerializer.Relationship do @moduledoc false defmodule HasMany do @moduledoc """ Struct to represent a HasMany relationship. The fields are: * `serializer` - A Serializer (often a PhoenixView) implementing the JaSerializer.Serializer behaviour. * `include` - Should this relationship be included (sideloaded) by default. Overriden by `include` opt to JaSerializer.format/4 * `data` - A list of structs representing the data. * `identifiers` - Should "resource identifiers be included, options are `:when_included` and `:always`. Defaults to `:when_included` * `links` - A keyword list of links, `self` and `related` are most common. * `name` - Name of the relationship, automatically set. Used when defining relationships without the DSL using the JaSerializer.relationships/2 callback. For example: def relationships(article, _conn) do %{ comments: %HasMany{ serializer: MyApp.CommentView, include: true, data: article.comments, } } end See JaSerializer.DSL.has_many/2 for information on defining different types of relationships. """ defstruct [ links: [], type: nil, serializer: nil, include: false, data: nil, identifiers: :when_included, name: nil ] @doc false def from_dsl(name, dsl_opts) do %__MODULE__{ links: dsl_opts[:links] || [], type: dsl_opts[:type], serializer: dsl_opts[:serializer], include: dsl_opts[:include], data: dsl_opts[:data] || name, identifiers: dsl_opts[:identifiers] || :when_included, name: name } end end defmodule HasOne do @moduledoc """ Struct representing a HasOne (or belongs to) relationship. The fields are: * `serializer` - A Serializer (often a PhoenixView) implementing the JaSerializer.Serializer behaviour. * `include` - Should this relationship be included (sideloaded) by default. Overriden by `include` opt to JaSerializer.format/4 * `data` - A struct representing the data for serialization. * `identifiers` - Should "resource identifiers be included, options are `:when_included` and `:always`. Defaults to `:when_included` * `links` - A keyword list of links, `self` and `related` are most common. * `name` - Name of the relationship, automatically set. Used when defining relationships without the DSL using the JaSerializer.relationships/2 callback. For example: def relationships(article, _conn) do %{ comments: %HasOne{ serializer: MyApp.CommentView, include: true, data: article.comments, } } end See JaSerializer.DSL.has_many/2 for information on defining different types of relationships. """ defstruct [ links: [], type: nil, serializer: nil, include: false, data: nil, identifiers: :always, name: nil ] @doc false def from_dsl(name, dsl_opts) do %__MODULE__{ links: dsl_opts[:links] || [], type: dsl_opts[:type], serializer: dsl_opts[:serializer], include: dsl_opts[:include], data: dsl_opts[:data] || name, identifiers: dsl_opts[:identifiers] || :always, name: name } end end @doc false def default_function(name, opts) do quote bind_quoted: [name: name, opts: opts] do def unquote(name)(struct, _conn) do JaSerializer.Relationship.get_data(struct, unquote(name), unquote(opts)) end defoverridable [{name, 2}] end end @error JaSerializer.AssociationNotLoadedError def get_data(struct, name, opts) do rel = (opts[:field] || name) struct |> Map.get(rel) |> case do %{__struct__: Ecto.Association.NotLoaded} -> raise @error, rel: rel, name: name other -> other end end end
31.012579
138
0.596431
1c870eea7be5d2fb9f9e9eda2f1abb6edd9f9b2b
1,543
ex
Elixir
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/pretargeting_config_dimensions.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/pretargeting_config_dimensions.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/pretargeting_config_dimensions.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.AdExchangeBuyer.V14.Model.PretargetingConfigDimensions do @moduledoc """ ## Attributes * `height` (*type:* `String.t`, *default:* `nil`) - Height in pixels. * `width` (*type:* `String.t`, *default:* `nil`) - Width in pixels. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :height => String.t(), :width => String.t() } field(:height) field(:width) end defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V14.Model.PretargetingConfigDimensions do def decode(value, options) do GoogleApi.AdExchangeBuyer.V14.Model.PretargetingConfigDimensions.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V14.Model.PretargetingConfigDimensions do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
30.86
96
0.728451
1c87209ab5d3a80d4daa377dfb602e8d357c7b78
2,256
exs
Elixir
examples/apps/ecto_example/test/ecto_example_test.exs
marocchino/elixir_agent
3c63715b130cf5997868c3a59097da256bf65102
[ "Apache-2.0" ]
null
null
null
examples/apps/ecto_example/test/ecto_example_test.exs
marocchino/elixir_agent
3c63715b130cf5997868c3a59097da256bf65102
[ "Apache-2.0" ]
null
null
null
examples/apps/ecto_example/test/ecto_example_test.exs
marocchino/elixir_agent
3c63715b130cf5997868c3a59097da256bf65102
[ "Apache-2.0" ]
null
null
null
defmodule EctoExampleTest do use ExUnit.Case alias NewRelic.Harvest.Collector setup_all context, do: TestSupport.simulate_agent_enabled(context) test "Datastore metrics generated" do TestSupport.restart_harvest_cycle(Collector.Metric.HarvestCycle) {:ok, %{body: body}} = request() assert body =~ "world" metrics = TestSupport.gather_harvest(Collector.Metric.Harvester) assert TestSupport.find_metric( metrics, "Datastore/statement/Postgres/counts/insert", 3 ) assert TestSupport.find_metric( metrics, "Datastore/statement/MySQL/counts/insert", 3 ) assert TestSupport.find_metric( metrics, {"Datastore/statement/Postgres/counts/insert", "WebTransaction/Plug/GET//hello"}, 3 ) assert TestSupport.find_metric( metrics, {"Datastore/statement/MySQL/counts/insert", "WebTransaction/Plug/GET//hello"}, 3 ) assert TestSupport.find_metric( metrics, "Datastore/statement/Postgres/counts/select", 5 ) assert TestSupport.find_metric( metrics, "Datastore/statement/MySQL/counts/select", 5 ) assert TestSupport.find_metric( metrics, "Datastore/statement/Postgres/counts/delete" ) assert TestSupport.find_metric( metrics, "Datastore/statement/MySQL/counts/delete" ) assert TestSupport.find_metric( metrics, "Datastore/MySQL/allWeb", 12 ) assert TestSupport.find_metric( metrics, "Datastore/Postgres/allWeb", 12 ) assert TestSupport.find_metric( metrics, "Datastore/allWeb", 24 ) assert TestSupport.find_metric( metrics, "Datastore/all", 24 ) end defp request() do http_port = Application.get_env(:ecto_example, :http_port) NewRelic.Util.HTTP.get("http://localhost:#{http_port}/hello") end end
24.521739
94
0.562057
1c87262666fb0c6cdf9bfa7b962d288bf240f815
138
ex
Elixir
lib/external_config/interface.ex
mbta/realtime_signs
3fd8cbc26ce2b0820e608e60fe12135dab5def69
[ "MIT" ]
1
2022-01-24T12:39:05.000Z
2022-01-24T12:39:05.000Z
lib/external_config/interface.ex
mbta/realtime_signs
3fd8cbc26ce2b0820e608e60fe12135dab5def69
[ "MIT" ]
40
2021-05-05T10:14:25.000Z
2022-03-31T18:34:15.000Z
lib/external_config/interface.ex
mbta/realtime_signs
3fd8cbc26ce2b0820e608e60fe12135dab5def69
[ "MIT" ]
1
2022-03-20T21:08:12.000Z
2022-03-20T21:08:12.000Z
defmodule ExternalConfig.Interface do @callback get(Engine.Config.version_id()) :: {Engine.Config.version_id(), map()} | :unchanged end
34.5
95
0.753623
1c8740d9b3161ef1a40991f1b116de8263283aa0
966
ex
Elixir
elixir_advent/lib/day5.ex
bwbeach/advent-of-code-2020
572810c3adae5815543efde17a4bca9596d05a5b
[ "CC0-1.0" ]
null
null
null
elixir_advent/lib/day5.ex
bwbeach/advent-of-code-2020
572810c3adae5815543efde17a4bca9596d05a5b
[ "CC0-1.0" ]
null
null
null
elixir_advent/lib/day5.ex
bwbeach/advent-of-code-2020
572810c3adae5815543efde17a4bca9596d05a5b
[ "CC0-1.0" ]
null
null
null
defmodule Day5 do def run(lines) do with [p2] = part2(lines) do "part1: #{part1(lines)} part2: #{p2}" end end def part1(lines) do lines |> Enum.map(&parse_seat/1) |> Enum.max() end def part2(lines) do with seats = seat_set(lines) do for s <- seats, MapSet.member?(seats, s + 2), !MapSet.member?(seats, s + 1) do s + 1 end end end def seat_set(lines) do for code <- lines, into: MapSet.new() do parse_seat(code) end end @doc """ Parses one seat code and turns it into a seat id. ## Examples iex> Day5.parse_seat("BFFFBBFRRR") 567 iex> Day5.parse_seat("FFFBBBFRRR") 119 iex> Day5.parse_seat("BBFFBBFRLL") 820 """ def parse_seat(code) do code |> String.replace("B", "1") |> String.replace("F", "0") |> String.replace("R", "1") |> String.replace("L", "0") |> String.to_integer(2) end end
17.888889
51
0.549689
1c8761305b12e8fe411a65ece0e735117a7f5e1f
3,836
ex
Elixir
lib/nerves_network.ex
wasnotrice/nerves_network
e43da8c147c77ab6552015ee956579a3de6630ee
[ "Apache-2.0" ]
null
null
null
lib/nerves_network.ex
wasnotrice/nerves_network
e43da8c147c77ab6552015ee956579a3de6630ee
[ "Apache-2.0" ]
null
null
null
lib/nerves_network.ex
wasnotrice/nerves_network
e43da8c147c77ab6552015ee956579a3de6630ee
[ "Apache-2.0" ]
null
null
null
defmodule Nerves.Network do require Logger alias Nerves.Network.Types @moduledoc """ The Nerves.Network application handles the low level details of connecting to networks. To quickly get started, create a new Nerves project and add the following line someplace early on in your program: Nerves.Network.setup "wlan0", ssid: "myssid", key_mgmt: :"WPA-PSK", psk: "secretsecret" When you boot your Nerves image, Nerves.Network monitors for an interface called "wlan0" to be created. This occurs when you plug in a USB WiFi dongle. If you plug in more than one WiFi dongle, each one will be given a name like "wlan1", etc. Those may be setup as well. When not connected, Nerves.Network continually scans for the desired access point. Once found, it associates and runs DHCP to acquire an IP address. """ @typedoc "Settings to `setup/2`" @type setup_setting :: {:ipv4_address_method, :dhcp | :static | :linklocal} | {:ipv4_address, Types.ip_address()} | {:ipv4_subnet_mask, Types.ip_address()} | {:domain, String.t()} | {:nameservers, [Types.ip_address()]} | {atom, any()} @typedoc "Keyword List settings to `setup/2`" @type setup_settings :: [setup_setting] @doc """ Configure the specified interface. Settings contains one or more of the following: * `:ipv4_address_method` - `:dhcp`, `:static`, or `:linklocal` * `:ipv4_address` - e.g., "192.168.1.5" (specify when :ipv4_address_method = :static) * `:ipv4_subnet_mask` - e.g., "255.255.255.0" (specify when :ipv4_address_method = :static) * `:domain` - e.g., "mycompany.com" (specify when :ipv4_address_method = :static) * `:nameservers` - e.g., ["8.8.8.8", "8.8.4.4"] (specify when :ipv4_address_method = :static) * `:ssid` - "My WiFi AP" (specify if this is a wireless interface) * `:key_mgmt` - e.g., `:"WPA-PSK"` or `:NONE` * `:psk` - e.g., "my-secret-wlan-key" See `t(#{__MODULE__}.setup_setting)` for more info. """ @spec setup(Types.ifname(), setup_settings) :: :ok def setup(ifname, settings \\ []) do Logger.debug("#{__MODULE__} setup(#{ifname})") {:ok, {_new, _old}} = Nerves.Network.Config.put(ifname, settings) :ok end @doc """ Stop all control of `ifname` """ @spec teardown(Types.ifname()) :: :ok def teardown(ifname) do Logger.debug("#{__MODULE__} teardown(#{ifname})") {:ok, {_new, _old}} = Nerves.Network.Config.drop(ifname) :ok end @doc """ Convenience function for returning the current status of a network interface from SystemRegistry. """ @spec status(Types.ifname()) :: Nerves.NetworkInterface.Worker.status() | nil def status(ifname) do SystemRegistry.match(:_) |> get_in([:state, :network_interface, ifname]) end @doc """ If `ifname` is a wireless LAN, scan for access points. """ @spec scan(Types.ifname()) :: [String.t()] | {:error, any} def scan(ifname) do Nerves.Network.IFSupervisor.scan(ifname) end @doc """ Change the regulatory domain for wireless operations. This must be set to the two character `alpha2` code for the country where this device is operating. See [the kernel database](http://git.kernel.org/cgit/linux/kernel/git/sforshee/wireless-regdb.git/tree/db.txt) for the latest database and the frequencies allowed per country. The default is to use the world regulatory domain (00). You may also configure the regulatory domain in your app's `config/config.exs`: config :nerves_network, regulatory_domain: "US" """ @spec set_regulatory_domain(String.t()) :: :ok def set_regulatory_domain(country) do Logger.warn("Regulatory domain currently can only be updated on WiFi device addition.") Application.put_env(:nerves_network, :regulatory_domain, country) end end
37.242718
112
0.67805
1c8796461c5539a9e802f0ba16fe22748c9194de
205
exs
Elixir
elixir/elixir-sips/samples/digraph_maps/test/map_test.exs
afronski/playground-erlang
6ac4b58b2fd717260c22a33284547d44a9b5038e
[ "MIT" ]
2
2015-12-09T02:16:51.000Z
2021-07-26T22:53:43.000Z
elixir/elixir-sips/samples/digraph_maps/test/map_test.exs
afronski/playground-erlang
6ac4b58b2fd717260c22a33284547d44a9b5038e
[ "MIT" ]
null
null
null
elixir/elixir-sips/samples/digraph_maps/test/map_test.exs
afronski/playground-erlang
6ac4b58b2fd717260c22a33284547d44a9b5038e
[ "MIT" ]
1
2016-05-08T18:40:31.000Z
2016-05-08T18:40:31.000Z
defmodule DigraphMaps.MapsTest do use ExUnit.Case alias DigraphMaps.Map test "creating a map" do map = Map.new assert %Map{} = map assert {:digraph, _, _, _, _} = map.digraph end end
17.083333
47
0.653659
1c87ac2f10a991811f816e985b1dfe9ce5e24516
1,563
exs
Elixir
mix.exs
mfeckie/html5ever_elixir
f6743865c353aaebaec1959ae4025596f8344587
[ "Apache-2.0", "MIT" ]
null
null
null
mix.exs
mfeckie/html5ever_elixir
f6743865c353aaebaec1959ae4025596f8344587
[ "Apache-2.0", "MIT" ]
null
null
null
mix.exs
mfeckie/html5ever_elixir
f6743865c353aaebaec1959ae4025596f8344587
[ "Apache-2.0", "MIT" ]
null
null
null
defmodule Html5ever.Mixfile do use Mix.Project def project do [app: :html5ever, version: "0.7.0", elixir: "~> 1.4", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, compilers: [:rustler] ++ Mix.compilers(), rustler_crates: rustler_crates(), deps: deps(), description: description(), package: package()] end def rustler_crates do [ html5ever_nif: [ path: "native/html5ever_nif", cargo: :system, default_features: false, features: [], mode: :release, # mode: (if Mix.env == :prod, do: :release, else: :debug), ] ] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do # Specify extra applications you'll use from Erlang/Elixir [extra_applications: [:logger]] end # Dependencies can be Hex packages: # # {:my_dep, "~> 0.3.0"} # # Or git/path repositories: # # {:my_dep, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options defp deps do [{:rustler, "~> 0.21.0"}, {:ex_doc, ">= 0.0.0", only: :dev}] end defp description do """ NIF binding of html5ever using rustler. """ end defp package do [ files: ["lib", "native", "mix.exs", "README.md"], maintainers: ["hansihe"], licenses: ["MIT", "Apache-2.0"], links: %{"GitHub" => "https://github.com/hansihe/html5ever_elixir"}, ] end end
22.985294
79
0.582853
1c87e097e14978b38160aead91719f5d87a73f8f
781
ex
Elixir
lib/ex_minimatch/helper.ex
hez/ex_minimatch
f2a1505734faff6ebe414e31046dae109b5bb015
[ "MIT" ]
null
null
null
lib/ex_minimatch/helper.ex
hez/ex_minimatch
f2a1505734faff6ebe414e31046dae109b5bb015
[ "MIT" ]
null
null
null
lib/ex_minimatch/helper.ex
hez/ex_minimatch
f2a1505734faff6ebe414e31046dae109b5bb015
[ "MIT" ]
null
null
null
defmodule ExMinimatch.Helper do def debug(obj, options) do if options[:log] in [:debug], do: IO.inspect(obj) end def info(obj, options) do if options[:log] in [:info, :debug], do: IO.inspect(obj) end # preserves the state def minimatch_tap(state, sideback) do sideback.(state) state end def transform(state, callback) do callback.(state) end def len(a) when is_binary(a), do: String.length(a) def len(a), do: length(a) def at(a, i) when is_binary(a), do: String.at(a, i) def at(a, i), do: Enum.at(a, i) def slice(a, rng) when is_binary(a), do: String.slice(a, rng) def slice(a, rng), do: Enum.slice(a, rng) def slice(a, i, l) when is_binary(a), do: String.slice(a, i, l) def slice(a, i, l), do: Enum.slice(a, i, l) end
23.666667
65
0.635083
1c87fe97166e5911fa398b0d77952bb3ad160729
138
ex
Elixir
lib/ucx_ucc_web/controllers/page_controller.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
lib/ucx_ucc_web/controllers/page_controller.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
lib/ucx_ucc_web/controllers/page_controller.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
defmodule UcxUccWeb.PageController do use UcxUccWeb, :controller def index(conn, _params) do render conn, "index.html" end end
17.25
37
0.73913
1c88013246e683d0a4d8e41258707aaa349f8d04
17,745
ex
Elixir
lib/codes/codes_m14.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_m14.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_m14.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_M14 do alias IcdCode.ICDCode def _M1460 do %ICDCode{full_code: "M1460", category_code: "M14", short_code: "60", full_name: "Charcot's joint, unspecified site", short_name: "Charcot's joint, unspecified site", category_name: "Charcot's joint, unspecified site" } end def _M14611 do %ICDCode{full_code: "M14611", category_code: "M14", short_code: "611", full_name: "Charcot's joint, right shoulder", short_name: "Charcot's joint, right shoulder", category_name: "Charcot's joint, right shoulder" } end def _M14612 do %ICDCode{full_code: "M14612", category_code: "M14", short_code: "612", full_name: "Charcot's joint, left shoulder", short_name: "Charcot's joint, left shoulder", category_name: "Charcot's joint, left shoulder" } end def _M14619 do %ICDCode{full_code: "M14619", category_code: "M14", short_code: "619", full_name: "Charcot's joint, unspecified shoulder", short_name: "Charcot's joint, unspecified shoulder", category_name: "Charcot's joint, unspecified shoulder" } end def _M14621 do %ICDCode{full_code: "M14621", category_code: "M14", short_code: "621", full_name: "Charcot's joint, right elbow", short_name: "Charcot's joint, right elbow", category_name: "Charcot's joint, right elbow" } end def _M14622 do %ICDCode{full_code: "M14622", category_code: "M14", short_code: "622", full_name: "Charcot's joint, left elbow", short_name: "Charcot's joint, left elbow", category_name: "Charcot's joint, left elbow" } end def _M14629 do %ICDCode{full_code: "M14629", category_code: "M14", short_code: "629", full_name: "Charcot's joint, unspecified elbow", short_name: "Charcot's joint, unspecified elbow", category_name: "Charcot's joint, unspecified elbow" } end def _M14631 do %ICDCode{full_code: "M14631", category_code: "M14", short_code: "631", full_name: "Charcot's joint, right wrist", short_name: "Charcot's joint, right wrist", category_name: "Charcot's joint, right wrist" } end def _M14632 do %ICDCode{full_code: "M14632", category_code: "M14", short_code: "632", full_name: "Charcot's joint, left wrist", short_name: "Charcot's joint, left wrist", category_name: "Charcot's joint, left wrist" } end def _M14639 do %ICDCode{full_code: "M14639", category_code: "M14", short_code: "639", full_name: "Charcot's joint, unspecified wrist", short_name: "Charcot's joint, unspecified wrist", category_name: "Charcot's joint, unspecified wrist" } end def _M14641 do %ICDCode{full_code: "M14641", category_code: "M14", short_code: "641", full_name: "Charcot's joint, right hand", short_name: "Charcot's joint, right hand", category_name: "Charcot's joint, right hand" } end def _M14642 do %ICDCode{full_code: "M14642", category_code: "M14", short_code: "642", full_name: "Charcot's joint, left hand", short_name: "Charcot's joint, left hand", category_name: "Charcot's joint, left hand" } end def _M14649 do %ICDCode{full_code: "M14649", category_code: "M14", short_code: "649", full_name: "Charcot's joint, unspecified hand", short_name: "Charcot's joint, unspecified hand", category_name: "Charcot's joint, unspecified hand" } end def _M14651 do %ICDCode{full_code: "M14651", category_code: "M14", short_code: "651", full_name: "Charcot's joint, right hip", short_name: "Charcot's joint, right hip", category_name: "Charcot's joint, right hip" } end def _M14652 do %ICDCode{full_code: "M14652", category_code: "M14", short_code: "652", full_name: "Charcot's joint, left hip", short_name: "Charcot's joint, left hip", category_name: "Charcot's joint, left hip" } end def _M14659 do %ICDCode{full_code: "M14659", category_code: "M14", short_code: "659", full_name: "Charcot's joint, unspecified hip", short_name: "Charcot's joint, unspecified hip", category_name: "Charcot's joint, unspecified hip" } end def _M14661 do %ICDCode{full_code: "M14661", category_code: "M14", short_code: "661", full_name: "Charcot's joint, right knee", short_name: "Charcot's joint, right knee", category_name: "Charcot's joint, right knee" } end def _M14662 do %ICDCode{full_code: "M14662", category_code: "M14", short_code: "662", full_name: "Charcot's joint, left knee", short_name: "Charcot's joint, left knee", category_name: "Charcot's joint, left knee" } end def _M14669 do %ICDCode{full_code: "M14669", category_code: "M14", short_code: "669", full_name: "Charcot's joint, unspecified knee", short_name: "Charcot's joint, unspecified knee", category_name: "Charcot's joint, unspecified knee" } end def _M14671 do %ICDCode{full_code: "M14671", category_code: "M14", short_code: "671", full_name: "Charcot's joint, right ankle and foot", short_name: "Charcot's joint, right ankle and foot", category_name: "Charcot's joint, right ankle and foot" } end def _M14672 do %ICDCode{full_code: "M14672", category_code: "M14", short_code: "672", full_name: "Charcot's joint, left ankle and foot", short_name: "Charcot's joint, left ankle and foot", category_name: "Charcot's joint, left ankle and foot" } end def _M14679 do %ICDCode{full_code: "M14679", category_code: "M14", short_code: "679", full_name: "Charcot's joint, unspecified ankle and foot", short_name: "Charcot's joint, unspecified ankle and foot", category_name: "Charcot's joint, unspecified ankle and foot" } end def _M1468 do %ICDCode{full_code: "M1468", category_code: "M14", short_code: "68", full_name: "Charcot's joint, vertebrae", short_name: "Charcot's joint, vertebrae", category_name: "Charcot's joint, vertebrae" } end def _M1469 do %ICDCode{full_code: "M1469", category_code: "M14", short_code: "69", full_name: "Charcot's joint, multiple sites", short_name: "Charcot's joint, multiple sites", category_name: "Charcot's joint, multiple sites" } end def _M1480 do %ICDCode{full_code: "M1480", category_code: "M14", short_code: "80", full_name: "Arthropathies in other specified diseases classified elsewhere, unspecified site", short_name: "Arthropathies in other specified diseases classified elsewhere, unspecified site", category_name: "Arthropathies in other specified diseases classified elsewhere, unspecified site" } end def _M14811 do %ICDCode{full_code: "M14811", category_code: "M14", short_code: "811", full_name: "Arthropathies in other specified diseases classified elsewhere, right shoulder", short_name: "Arthropathies in other specified diseases classified elsewhere, right shoulder", category_name: "Arthropathies in other specified diseases classified elsewhere, right shoulder" } end def _M14812 do %ICDCode{full_code: "M14812", category_code: "M14", short_code: "812", full_name: "Arthropathies in other specified diseases classified elsewhere, left shoulder", short_name: "Arthropathies in other specified diseases classified elsewhere, left shoulder", category_name: "Arthropathies in other specified diseases classified elsewhere, left shoulder" } end def _M14819 do %ICDCode{full_code: "M14819", category_code: "M14", short_code: "819", full_name: "Arthropathies in other specified diseases classified elsewhere, unspecified shoulder", short_name: "Arthropathies in other specified diseases classified elsewhere, unspecified shoulder", category_name: "Arthropathies in other specified diseases classified elsewhere, unspecified shoulder" } end def _M14821 do %ICDCode{full_code: "M14821", category_code: "M14", short_code: "821", full_name: "Arthropathies in other specified diseases classified elsewhere, right elbow", short_name: "Arthropathies in other specified diseases classified elsewhere, right elbow", category_name: "Arthropathies in other specified diseases classified elsewhere, right elbow" } end def _M14822 do %ICDCode{full_code: "M14822", category_code: "M14", short_code: "822", full_name: "Arthropathies in other specified diseases classified elsewhere, left elbow", short_name: "Arthropathies in other specified diseases classified elsewhere, left elbow", category_name: "Arthropathies in other specified diseases classified elsewhere, left elbow" } end def _M14829 do %ICDCode{full_code: "M14829", category_code: "M14", short_code: "829", full_name: "Arthropathies in other specified diseases classified elsewhere, unspecified elbow", short_name: "Arthropathies in other specified diseases classified elsewhere, unspecified elbow", category_name: "Arthropathies in other specified diseases classified elsewhere, unspecified elbow" } end def _M14831 do %ICDCode{full_code: "M14831", category_code: "M14", short_code: "831", full_name: "Arthropathies in other specified diseases classified elsewhere, right wrist", short_name: "Arthropathies in other specified diseases classified elsewhere, right wrist", category_name: "Arthropathies in other specified diseases classified elsewhere, right wrist" } end def _M14832 do %ICDCode{full_code: "M14832", category_code: "M14", short_code: "832", full_name: "Arthropathies in other specified diseases classified elsewhere, left wrist", short_name: "Arthropathies in other specified diseases classified elsewhere, left wrist", category_name: "Arthropathies in other specified diseases classified elsewhere, left wrist" } end def _M14839 do %ICDCode{full_code: "M14839", category_code: "M14", short_code: "839", full_name: "Arthropathies in other specified diseases classified elsewhere, unspecified wrist", short_name: "Arthropathies in other specified diseases classified elsewhere, unspecified wrist", category_name: "Arthropathies in other specified diseases classified elsewhere, unspecified wrist" } end def _M14841 do %ICDCode{full_code: "M14841", category_code: "M14", short_code: "841", full_name: "Arthropathies in other specified diseases classified elsewhere, right hand", short_name: "Arthropathies in other specified diseases classified elsewhere, right hand", category_name: "Arthropathies in other specified diseases classified elsewhere, right hand" } end def _M14842 do %ICDCode{full_code: "M14842", category_code: "M14", short_code: "842", full_name: "Arthropathies in other specified diseases classified elsewhere, left hand", short_name: "Arthropathies in other specified diseases classified elsewhere, left hand", category_name: "Arthropathies in other specified diseases classified elsewhere, left hand" } end def _M14849 do %ICDCode{full_code: "M14849", category_code: "M14", short_code: "849", full_name: "Arthropathies in other specified diseases classified elsewhere, unspecified hand", short_name: "Arthropathies in other specified diseases classified elsewhere, unspecified hand", category_name: "Arthropathies in other specified diseases classified elsewhere, unspecified hand" } end def _M14851 do %ICDCode{full_code: "M14851", category_code: "M14", short_code: "851", full_name: "Arthropathies in other specified diseases classified elsewhere, right hip", short_name: "Arthropathies in other specified diseases classified elsewhere, right hip", category_name: "Arthropathies in other specified diseases classified elsewhere, right hip" } end def _M14852 do %ICDCode{full_code: "M14852", category_code: "M14", short_code: "852", full_name: "Arthropathies in other specified diseases classified elsewhere, left hip", short_name: "Arthropathies in other specified diseases classified elsewhere, left hip", category_name: "Arthropathies in other specified diseases classified elsewhere, left hip" } end def _M14859 do %ICDCode{full_code: "M14859", category_code: "M14", short_code: "859", full_name: "Arthropathies in other specified diseases classified elsewhere, unspecified hip", short_name: "Arthropathies in other specified diseases classified elsewhere, unspecified hip", category_name: "Arthropathies in other specified diseases classified elsewhere, unspecified hip" } end def _M14861 do %ICDCode{full_code: "M14861", category_code: "M14", short_code: "861", full_name: "Arthropathies in other specified diseases classified elsewhere, right knee", short_name: "Arthropathies in other specified diseases classified elsewhere, right knee", category_name: "Arthropathies in other specified diseases classified elsewhere, right knee" } end def _M14862 do %ICDCode{full_code: "M14862", category_code: "M14", short_code: "862", full_name: "Arthropathies in other specified diseases classified elsewhere, left knee", short_name: "Arthropathies in other specified diseases classified elsewhere, left knee", category_name: "Arthropathies in other specified diseases classified elsewhere, left knee" } end def _M14869 do %ICDCode{full_code: "M14869", category_code: "M14", short_code: "869", full_name: "Arthropathies in other specified diseases classified elsewhere, unspecified knee", short_name: "Arthropathies in other specified diseases classified elsewhere, unspecified knee", category_name: "Arthropathies in other specified diseases classified elsewhere, unspecified knee" } end def _M14871 do %ICDCode{full_code: "M14871", category_code: "M14", short_code: "871", full_name: "Arthropathies in other specified diseases classified elsewhere, right ankle and foot", short_name: "Arthropathies in other specified diseases classified elsewhere, right ankle and foot", category_name: "Arthropathies in other specified diseases classified elsewhere, right ankle and foot" } end def _M14872 do %ICDCode{full_code: "M14872", category_code: "M14", short_code: "872", full_name: "Arthropathies in other specified diseases classified elsewhere, left ankle and foot", short_name: "Arthropathies in other specified diseases classified elsewhere, left ankle and foot", category_name: "Arthropathies in other specified diseases classified elsewhere, left ankle and foot" } end def _M14879 do %ICDCode{full_code: "M14879", category_code: "M14", short_code: "879", full_name: "Arthropathies in other specified diseases classified elsewhere, unspecified ankle and foot", short_name: "Arthropathies in other specified diseases classified elsewhere, unspecified ankle and foot", category_name: "Arthropathies in other specified diseases classified elsewhere, unspecified ankle and foot" } end def _M1488 do %ICDCode{full_code: "M1488", category_code: "M14", short_code: "88", full_name: "Arthropathies in other specified diseases classified elsewhere, vertebrae", short_name: "Arthropathies in other specified diseases classified elsewhere, vertebrae", category_name: "Arthropathies in other specified diseases classified elsewhere, vertebrae" } end def _M1489 do %ICDCode{full_code: "M1489", category_code: "M14", short_code: "89", full_name: "Arthropathies in other specified diseases classified elsewhere, multiple sites", short_name: "Arthropathies in other specified diseases classified elsewhere, multiple sites", category_name: "Arthropathies in other specified diseases classified elsewhere, multiple sites" } end end
40.421412
117
0.648633
1c888613486fb1658093f7e2e1addc5c29a76bd8
1,793
ex
Elixir
clients/books/lib/google_api/books/v1/model/geolayerdata_geo_viewport.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/books/lib/google_api/books/v1/model/geolayerdata_geo_viewport.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/books/lib/google_api/books/v1/model/geolayerdata_geo_viewport.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.Books.V1.Model.GeolayerdataGeoViewport do @moduledoc """ The viewport for showing this location. This is a latitude, longitude rectangle. ## Attributes - hi (GeolayerdataGeoViewportHi): Defaults to: `null`. - lo (GeolayerdataGeoViewportHi): Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :hi => GoogleApi.Books.V1.Model.GeolayerdataGeoViewportHi.t(), :lo => GoogleApi.Books.V1.Model.GeolayerdataGeoViewportHi.t() } field(:hi, as: GoogleApi.Books.V1.Model.GeolayerdataGeoViewportHi) field(:lo, as: GoogleApi.Books.V1.Model.GeolayerdataGeoViewportHi) end defimpl Poison.Decoder, for: GoogleApi.Books.V1.Model.GeolayerdataGeoViewport do def decode(value, options) do GoogleApi.Books.V1.Model.GeolayerdataGeoViewport.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Books.V1.Model.GeolayerdataGeoViewport do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.156863
82
0.75237
1c8887a33be64b16333000d05aa976bb835e4e30
140
exs
Elixir
templates/elchemy_test.exs
wende/elchemy-library
442ecdf740678df7ef17ae57ac14eecbe6221fed
[ "MIT" ]
969
2017-07-07T18:44:36.000Z
2022-03-27T07:52:39.000Z
templates/elchemy_test.exs
wende/elmchemist
21650416e634bb3c75300fb2bede74c4768d979a
[ "MIT" ]
158
2017-07-07T18:14:01.000Z
2020-03-17T13:16:00.000Z
templates/elchemy_test.exs
wende/elmchemist
21650416e634bb3c75300fb2bede74c4768d979a
[ "MIT" ]
23
2017-10-04T15:47:13.000Z
2021-10-02T10:05:52.000Z
defmodule ElchemyTest do use ExUnit.Case use Elchemy doctest Hello test "Hello" do assert Hello.hello() == "world!" end end
12.727273
36
0.678571
1c888ecec10bbe252d99204df2cd76eeb60b0414
55
ex
Elixir
lib/vega_web/views/auth_view.ex
Fudoshiki/vega
0577024afc734933048645976705784512fbc1f4
[ "MIT" ]
4
2020-03-22T22:12:29.000Z
2020-07-01T22:32:01.000Z
lib/vega_web/views/auth_view.ex
Fudoshiki/vega
0577024afc734933048645976705784512fbc1f4
[ "MIT" ]
3
2021-03-10T11:53:41.000Z
2021-10-17T11:18:54.000Z
lib/vega_web/views/auth_view.ex
Fudoshiki/vega
0577024afc734933048645976705784512fbc1f4
[ "MIT" ]
3
2020-03-30T19:03:23.000Z
2022-01-17T20:21:42.000Z
defmodule VegaWeb.AuthView do use VegaWeb, :view end
13.75
29
0.781818
1c88c39cb3acde53815a34dba7079388b4c88523
1,688
ex
Elixir
clients/content/lib/google_api/content/v2/model/product_destination.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/product_destination.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/product_destination.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.Content.V2.Model.ProductDestination do @moduledoc """ ## Attributes * `destinationName` (*type:* `String.t`, *default:* `nil`) - The name of the destination. * `intention` (*type:* `String.t`, *default:* `nil`) - Whether the destination is required, excluded or should be validated. Acceptable values are: - "`default`" - "`excluded`" - "`optional`" - "`required`" """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :destinationName => String.t(), :intention => String.t() } field(:destinationName) field(:intention) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.ProductDestination do def decode(value, options) do GoogleApi.Content.V2.Model.ProductDestination.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.ProductDestination do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
30.142857
128
0.705569
1c88e3e2440e816c7656637ed2e47bc2d67bb87a
1,946
exs
Elixir
clients/web_security_scanner/mix.exs
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/web_security_scanner/mix.exs
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/web_security_scanner/mix.exs
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "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.WebSecurityScanner.Mixfile do use Mix.Project @version "0.13.0" def project() do [ app: :google_api_web_security_scanner, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/web_security_scanner" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.2"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Web Security Scanner API client library. Scans your Compute and App Engine apps for common web vulnerabilities. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/web_security_scanner", "Homepage" => "https://cloud.google.com/security-command-center/docs/concepts-web-security-scanner-overview/" } ] end end
29.044776
117
0.669579
1c88ee561c4d298b94901fd1714700fd8593c009
2,012
ex
Elixir
lib/edgedb/result.ex
f0lio/edgedb-elixir
b285bd8037b0b951aabfa1d1733889880f8bfd66
[ "MIT" ]
null
null
null
lib/edgedb/result.ex
f0lio/edgedb-elixir
b285bd8037b0b951aabfa1d1733889880f8bfd66
[ "MIT" ]
null
null
null
lib/edgedb/result.ex
f0lio/edgedb-elixir
b285bd8037b0b951aabfa1d1733889880f8bfd66
[ "MIT" ]
null
null
null
defmodule EdgeDB.Result do @moduledoc """ A structure that contains information related to the query result. It's mostly used in driver internally, but user can retrive it along with `EdgeDB.Query` struct from succeed query execution using `:raw` option for `EdgeDB.query*/4` functions. See `t:EdgeDB.query_option/0`. """ alias EdgeDB.Protocol.Enums defstruct [ :cardinality, :required, set: [], statement: nil ] @typedoc """ A structure that contains information related to the query result. Fields: * `:statement` - EdgeQL statement that was executed. * `:required` - flag specifying that the result should not be empty. * `:set` - query result. * `:cardinality` - the expected number of elements in the returned set as a result of the query. """ @type t() :: %__MODULE__{ statement: String.t() | nil, required: boolean(), set: EdgeDB.Set.t() | list(binary()), cardinality: Enums.Cardinality.t() } @doc """ Process the result and extract the data. """ @spec extract(t()) :: {:ok, EdgeDB.Set.t() | term() | :done} | {:error, Exception.t()} def extract(%__MODULE__{set: data}) when is_list(data) do {:error, EdgeDB.Error.interface_error("result hasn't been decoded yet")} end def extract(%__MODULE__{cardinality: :at_most_one, required: required, set: set}) do if EdgeDB.Set.empty?(set) and required do {:error, EdgeDB.Error.no_data_error("expected result, but query did not return any data")} else value = set |> Enum.take(1) |> List.first() {:ok, value} end end def extract(%__MODULE__{cardinality: :many, set: %EdgeDB.Set{} = set}) do {:ok, set} end def extract(%__MODULE__{cardinality: :no_result, required: true}) do {:error, EdgeDB.Error.interface_error("query does not return data")} end def extract(%__MODULE__{cardinality: :no_result}) do {:ok, :executed} end end
28.338028
116
0.640159
1c88f7a295aeb55fb391496193833e867f202d65
7,412
ex
Elixir
lib/sanbase/clickhouse/github/sql_query.ex
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
81
2017-11-20T01:20:22.000Z
2022-03-05T12:04:25.000Z
lib/sanbase/clickhouse/github/sql_query.ex
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
359
2017-10-15T14:40:53.000Z
2022-01-25T13:34:20.000Z
lib/sanbase/clickhouse/github/sql_query.ex
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
16
2017-11-19T13:57:40.000Z
2022-02-07T08:13:02.000Z
defmodule Sanbase.Clickhouse.Github.SqlQuery do @non_dev_events [ "IssueCommentEvent", "IssuesEvent", "ForkEvent", "CommitCommentEvent", "FollowEvent", "ForkEvent", "DownloadEvent", "WatchEvent", "ProjectCardEvent", "ProjectColumnEvent", "ProjectEvent" ] @table "github_v2" def non_dev_events(), do: @non_dev_events def first_datetime_query(organization) when is_binary(organization) do query = """ SELECT toUnixTimestamp(min(dt)) FROM #{@table} PREWHERE owner = ?1 """ args = [organization] {query, args} end def last_datetime_computed_at_query(organization) when is_binary(organization) do query = """ SELECT toUnixTimestamp(max(dt)) FROM #{@table} PREWHERE owner = ?1 """ args = [organization] {query, args} end def dev_activity_contributors_count_query(organizations, from, to, interval) do to = Enum.min_by([to, Timex.now()], &DateTime.to_unix/1) from_unix = DateTime.to_unix(from) to_unix = Enum.min([DateTime.utc_now(), to], DateTime) |> DateTime.to_unix() interval = Sanbase.DateTimeUtils.str_to_sec(interval) span = div(to_unix - from_unix, interval) |> max(1) query = """ SELECT time, toUInt32(SUM(uniq_contributors)) AS value FROM ( SELECT toUnixTimestamp(intDiv(toUInt32(dt), ?1) * ?1) AS time, uniqExact(actor) AS uniq_contributors FROM #{@table} PREWHERE owner IN (?2) AND dt >= toDateTime(?3) AND dt < toDateTime(?4) AND event NOT IN (?5) GROUP BY time ) GROUP BY time """ |> wrap_timeseries_in_gap_filling_query(interval_pos: 1, from_datetime_pos: 3, span_pos: 6) args = [ interval, organizations |> Enum.map(&String.downcase/1), from_unix, to_unix, @non_dev_events, span ] {query, args} end def github_activity_contributors_count_query(organizations, from, to, interval) do to = Enum.min_by([to, Timex.now()], &DateTime.to_unix/1) from_unix = DateTime.to_unix(from) to_unix = Enum.min([DateTime.utc_now(), to], DateTime) |> DateTime.to_unix() interval = Sanbase.DateTimeUtils.str_to_sec(interval) span = div(to_unix - from_unix, interval) |> max(1) query = """ SELECT time, toUInt32(SUM(uniq_contributors)) AS value FROM ( SELECT toUnixTimestamp(intDiv(toUInt32(dt), ?1) * ?1) AS time, uniqExact(actor) AS uniq_contributors FROM #{@table} PREWHERE owner IN (?2) AND dt >= toDateTime(?3) AND dt < toDateTime(?4) GROUP BY time ) GROUP BY time """ |> wrap_timeseries_in_gap_filling_query(interval_pos: 1, from_datetime_pos: 3, span_pos: 5) args = [ interval, organizations |> Enum.map(&String.downcase/1), from_unix, to_unix, span ] {query, args} end def dev_activity_query(organizations, from, to, interval) do to = Enum.min_by([to, Timex.now()], &DateTime.to_unix/1) from_unix = DateTime.to_unix(from) to_unix = Enum.min([DateTime.utc_now(), to], DateTime) |> DateTime.to_unix() interval = Sanbase.DateTimeUtils.str_to_sec(interval) span = div(to_unix - from_unix, interval) |> max(1) query = """ SELECT time, SUM(events) AS value FROM ( SELECT toUnixTimestamp(intDiv(toUInt32(dt), ?1) * ?1) AS time, count(events) AS events FROM ( SELECT any(event) AS events, dt FROM #{@table} PREWHERE owner IN (?2) AND dt >= toDateTime(?3) AND dt < toDateTime(?4) AND event NOT IN (?5) GROUP BY owner, repo, dt, event ) GROUP BY time ) GROUP BY time """ |> wrap_timeseries_in_gap_filling_query(interval_pos: 1, from_datetime_pos: 3, span_pos: 6) args = [ interval, organizations |> Enum.map(&String.downcase/1), from_unix, to_unix, @non_dev_events, span ] {query, args} end def github_activity_query(organizations, from, to, interval) do to = Enum.min_by([to, Timex.now()], &DateTime.to_unix/1) from_unix = DateTime.to_unix(from) to_unix = Enum.min([DateTime.utc_now(), to], DateTime) |> DateTime.to_unix() interval = Sanbase.DateTimeUtils.str_to_sec(interval) span = div(to_unix - from_unix, interval) |> max(1) query = """ SELECT time, SUM(events) AS value FROM ( SELECT toUnixTimestamp(intDiv(toUInt32(dt), ?1) * ?1) AS time, count(events) AS events FROM ( SELECT any(event) AS events, dt FROM #{@table} PREWHERE owner IN (?2) AND dt >= toDateTime(?3) AND dt < toDateTime(?4) GROUP BY owner, repo, dt, event ) GROUP BY time ) GROUP BY time """ |> wrap_timeseries_in_gap_filling_query(interval_pos: 1, from_datetime_pos: 3, span_pos: 5) args = [ interval, organizations |> Enum.map(&String.downcase/1), from_unix, to_unix, span ] {query, args} end def total_github_activity_query(organizations, from, to) do query = """ SELECT owner, toUInt64(COUNT(*)) AS value FROM( SELECT owner, COUNT(*) FROM #{@table} PREWHERE owner IN (?1) AND dt >= toDateTime(?2) AND dt <= toDateTime(?3) GROUP BY owner, repo, dt, event ) GROUP BY owner """ |> wrap_aggregated_in_zero_filling_query(organizations_pos: 1) args = [ organizations |> Enum.map(&String.downcase/1), DateTime.to_unix(from), DateTime.to_unix(to) ] {query, args} end def total_dev_activity_query(organizations, from, to) do query = """ SELECT owner, toUInt64(COUNT(*)) AS value FROM( SELECT owner, COUNT(*) FROM #{@table} PREWHERE owner IN (?1) AND dt >= toDateTime(?2) AND dt <= toDateTime(?3) AND event NOT IN (?4) GROUP BY owner, repo, dt, event ) GROUP BY owner """ |> wrap_aggregated_in_zero_filling_query(organizations_pos: 1) args = [ organizations |> Enum.map(&String.downcase/1), DateTime.to_unix(from), DateTime.to_unix(to), @non_dev_events ] {query, args} end defp wrap_aggregated_in_zero_filling_query(query, opts) do o_pos = Keyword.fetch!(opts, :organizations_pos) """ SELECT owner, SUM(value) FROM ( SELECT arrayJoin([?#{o_pos}]) AS owner, toUInt64(0) AS value UNION ALL #{query} ) GROUP BY owner """ end defp wrap_timeseries_in_gap_filling_query(query, opts) do i_pos = Keyword.fetch!(opts, :interval_pos) f_pos = Keyword.fetch!(opts, :from_datetime_pos) s_pos = Keyword.fetch!(opts, :span_pos) """ SELECT time, SUM(value) FROM ( SELECT toUnixTimestamp(intDiv(toUInt32(?#{f_pos} + number * ?#{i_pos}), ?#{i_pos}) * ?#{i_pos}) AS time, toUInt32(0) AS value FROM numbers(?#{s_pos}) UNION ALL #{query} ) GROUP BY time ORDER BY time """ end end
25.296928
105
0.587426
1c89034ede495ee74c15ffbc70c2e3b8920bebc4
1,150
exs
Elixir
clients/datastore/mix.exs
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/datastore/mix.exs
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/datastore/mix.exs
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
defmodule GoogleApi.Datastore.V1.Mixfile do use Mix.Project @version "0.3.0" def project do [app: :google_api_datastore, version: @version, elixir: "~> 1.4", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/datastore" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.1.0"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Accesses the schemaless NoSQL database to provide fully managed, robust, scalable storage for your application. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/datastore", "Homepage" => "https://cloud.google.com/datastore/" } ] end end
23.958333
115
0.608696
1c89331c439955e7079ad38a15c40eb01998c73d
1,094
ex
Elixir
lib/invenger_web/channels/user_socket.ex
manoel-lopes/invenger
19f76964c95cd4e038c78cf743fe28069b73b9b2
[ "MIT" ]
null
null
null
lib/invenger_web/channels/user_socket.ex
manoel-lopes/invenger
19f76964c95cd4e038c78cf743fe28069b73b9b2
[ "MIT" ]
null
null
null
lib/invenger_web/channels/user_socket.ex
manoel-lopes/invenger
19f76964c95cd4e038c78cf743fe28069b73b9b2
[ "MIT" ]
null
null
null
defmodule InvengerWeb.UserSocket do use Phoenix.Socket ## Channels # channel "room:*", InvengerWeb.RoomChannel # Socket params are passed from the client and can # be used to verify and authenticate a user. After # verification, you can put default assigns into # the socket that will be set for all channels, ie # # {:ok, assign(socket, :user_id, verified_user_id)} # # To deny connection, return `:error`. # # See `Phoenix.Token` documentation for examples in # performing token verification on connect. @impl true def connect(_params, socket, _connect_info) do {:ok, socket} end # Socket id's are topics that allow you to identify all sockets for a given user: # # def id(socket), do: "user_socket:#{socket.assigns.user_id}" # # Would allow you to broadcast a "disconnect" event and terminate # all active sockets and channels for a given user: # # InvengerWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. @impl true def id(_socket), do: nil end
30.388889
83
0.695612
1c8964f5f8bc955315ed8f4f6206ab0cd835846b
1,214
ex
Elixir
lib/scenario/enum_check_empty.ex
unnawut/ex_benchmark
d6f946bd60da57722434cecc53eda7701b3c7423
[ "MIT" ]
null
null
null
lib/scenario/enum_check_empty.ex
unnawut/ex_benchmark
d6f946bd60da57722434cecc53eda7701b3c7423
[ "MIT" ]
null
null
null
lib/scenario/enum_check_empty.ex
unnawut/ex_benchmark
d6f946bd60da57722434cecc53eda7701b3c7423
[ "MIT" ]
null
null
null
defmodule ExBenchmark.Scenario.EnumCheckEmpty do @moduledoc """ The module containing scenarios to benchmark checking enum for emptiness. """ use ExBenchmark.Scenario, time: 10, print: [fast_warning: false] @list_empty [] @list_large Enum.to_list(1..10_000) @map_empty %{} @map_large Map.new(for i <- 1..10_000, do: {i, i}) # List operations def benchmark_enum_empty_on_empty_list, do: Enum.empty?(@list_empty) def benchmark_enum_empty_on_large_list, do: Enum.empty?(@list_large) def benchmark_enum_count_on_empty_list, do: Enum.count(@list_empty) == 0 def benchmark_enum_count_on_large_list, do: Enum.count(@list_large) == 0 def benchmark_equality_on_empty_list, do: @list_empty == [] def benchmark_equality_on_large_list, do: @list_large == [] # Map operations def benchmark_enum_empty_on_empty_map, do: Enum.empty?(@map_empty) def benchmark_enum_empty_on_large_map, do: Enum.empty?(@map_large) def benchmark_enum_count_on_empty_map, do: Enum.count(@map_empty) == 0 def benchmark_enum_count_on_large_map, do: Enum.count(@map_large) == 0 def benchmark_equality_on_empty_map, do: @map_empty == %{} def benchmark_equality_on_large_map, do: @map_large == %{} end
36.787879
75
0.755354
1c89677237758df0700779b9e6ecb3d814e82830
279,734
ex
Elixir
clients/gmail/lib/google_api/gmail/v1/api/users.ex
Contractbook/elixir-google-api
342751041aaf8c2e7f76f9922cf24b9c5895802b
[ "Apache-2.0" ]
1
2021-10-01T09:20:41.000Z
2021-10-01T09:20:41.000Z
clients/gmail/lib/google_api/gmail/v1/api/users.ex
Contractbook/elixir-google-api
342751041aaf8c2e7f76f9922cf24b9c5895802b
[ "Apache-2.0" ]
null
null
null
clients/gmail/lib/google_api/gmail/v1/api/users.ex
Contractbook/elixir-google-api
342751041aaf8c2e7f76f9922cf24b9c5895802b
[ "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.Gmail.V1.Api.Users do @moduledoc """ API calls for all endpoints tagged `Users`. """ alias GoogleApi.Gmail.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Gets the current user's Gmail profile. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Profile{}}` on success * `{:error, info}` on failure """ @spec gmail_users_get_profile(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Profile.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_get_profile(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/profile", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.Profile{}]) end @doc """ Stop receiving push notifications for the given user mailbox. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_stop(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_stop(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/stop", %{ "userId" => URI.encode(user_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 ++ [decode: false]) end @doc """ Set up or update a push notification watch on the given user mailbox. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.WatchRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.WatchResponse{}}` on success * `{:error, info}` on failure """ @spec gmail_users_watch(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.WatchResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_watch(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/watch", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.WatchResponse{}]) end @doc """ Creates a new draft with the `DRAFT` label. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Draft.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Draft{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_create(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Draft.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_create(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/drafts", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.Draft{}]) end @doc """ Creates a new draft with the `DRAFT` label. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "multipart". * `metadata` (*type:* `GoogleApi.Gmail.V1.Model.Draft.t`) - object metadata * `data` (*type:* `iodata`) - Content to upload, as a string or iolist * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Draft{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_create_iodata( Tesla.Env.client(), String.t(), String.t(), GoogleApi.Gmail.V1.Model.Draft.t(), iodata, keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Draft.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_create_iodata( connection, user_id, upload_type, metadata, data, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/upload/gmail/v1/users/{userId}/drafts", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_param(:body, :metadata, metadata) |> Request.add_param(:body, :data, data) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Draft{}]) end @doc """ Creates a new draft with the `DRAFT` label. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "resumable". * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Draft.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_create_resumable( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_create_resumable( connection, user_id, upload_type, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/resumable/upload/gmail/v1/users/{userId}/drafts", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Creates a new draft with the `DRAFT` label. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "multipart". * `metadata` (*type:* `GoogleApi.Gmail.V1.Model.Draft.t`) - object metadata * `data` (*type:* `String.t`) - Path to file containing content to upload * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Draft{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_create_simple( Tesla.Env.client(), String.t(), String.t(), GoogleApi.Gmail.V1.Model.Draft.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Draft.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_create_simple( connection, user_id, upload_type, metadata, data, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/upload/gmail/v1/users/{userId}/drafts", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_param(:body, :metadata, metadata) |> Request.add_param(:file, :data, data) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Draft{}]) end @doc """ Immediately and permanently deletes the specified draft. Does not simply trash it. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the draft to delete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_delete( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_delete(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/gmail/v1/users/{userId}/drafts/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Gets the specified draft. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the draft to retrieve. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:format` (*type:* `String.t`) - The format to return the draft in. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Draft{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Draft.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_get(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :format => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/drafts/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Draft{}]) end @doc """ Lists the drafts in the user's mailbox. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:includeSpamTrash` (*type:* `boolean()`) - Include drafts from `SPAM` and `TRASH` in the results. * `:maxResults` (*type:* `integer()`) - Maximum number of drafts to return. This field defaults to 100. The maximum allowed value for this field is 500. * `:pageToken` (*type:* `String.t`) - Page token to retrieve a specific page of results in the list. * `:q` (*type:* `String.t`) - Only return draft messages matching the specified query. Supports the same query format as the Gmail search box. For example, `"from:someuser@example.com rfc822msgid: is:unread"`. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ListDraftsResponse{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.ListDraftsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_list(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :includeSpamTrash => :query, :maxResults => :query, :pageToken => :query, :q => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/drafts", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.ListDraftsResponse{}]) end @doc """ Sends the specified, existing draft to the recipients in the `To`, `Cc`, and `Bcc` headers. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Draft.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_send(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_send(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/drafts/send", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.Message{}]) end @doc """ Sends the specified, existing draft to the recipients in the `To`, `Cc`, and `Bcc` headers. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "multipart". * `metadata` (*type:* `GoogleApi.Gmail.V1.Model.Draft.t`) - object metadata * `data` (*type:* `iodata`) - Content to upload, as a string or iolist * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_send_iodata( Tesla.Env.client(), String.t(), String.t(), GoogleApi.Gmail.V1.Model.Draft.t(), iodata, keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_send_iodata( connection, user_id, upload_type, metadata, data, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/upload/gmail/v1/users/{userId}/drafts/send", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_param(:body, :metadata, metadata) |> Request.add_param(:body, :data, data) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Message{}]) end @doc """ Sends the specified, existing draft to the recipients in the `To`, `Cc`, and `Bcc` headers. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "resumable". * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Draft.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_send_resumable( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_send_resumable( connection, user_id, upload_type, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/resumable/upload/gmail/v1/users/{userId}/drafts/send", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Sends the specified, existing draft to the recipients in the `To`, `Cc`, and `Bcc` headers. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "multipart". * `metadata` (*type:* `GoogleApi.Gmail.V1.Model.Draft.t`) - object metadata * `data` (*type:* `String.t`) - Path to file containing content to upload * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_send_simple( Tesla.Env.client(), String.t(), String.t(), GoogleApi.Gmail.V1.Model.Draft.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_send_simple( connection, user_id, upload_type, metadata, data, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/upload/gmail/v1/users/{userId}/drafts/send", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_param(:body, :metadata, metadata) |> Request.add_param(:file, :data, data) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Message{}]) end @doc """ Replaces a draft's content. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the draft to update. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Draft.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Draft{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_update( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Draft.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_update(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/gmail/v1/users/{userId}/drafts/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Draft{}]) end @doc """ Replaces a draft's content. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the draft to update. * `upload_type` (*type:* `String.t`) - Upload type. Must be "multipart". * `metadata` (*type:* `GoogleApi.Gmail.V1.Model.Draft.t`) - object metadata * `data` (*type:* `iodata`) - Content to upload, as a string or iolist * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Draft{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_update_iodata( Tesla.Env.client(), String.t(), String.t(), String.t(), GoogleApi.Gmail.V1.Model.Draft.t(), iodata, keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Draft.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_update_iodata( connection, user_id, id, upload_type, metadata, data, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:put) |> Request.url("/upload/gmail/v1/users/{userId}/drafts/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_param(:body, :metadata, metadata) |> Request.add_param(:body, :data, data) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Draft{}]) end @doc """ Replaces a draft's content. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the draft to update. * `upload_type` (*type:* `String.t`) - Upload type. Must be "resumable". * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Draft.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_update_resumable( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_update_resumable( connection, user_id, id, upload_type, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/resumable/upload/gmail/v1/users/{userId}/drafts/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Replaces a draft's content. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the draft to update. * `upload_type` (*type:* `String.t`) - Upload type. Must be "multipart". * `metadata` (*type:* `GoogleApi.Gmail.V1.Model.Draft.t`) - object metadata * `data` (*type:* `String.t`) - Path to file containing content to upload * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Draft{}}` on success * `{:error, info}` on failure """ @spec gmail_users_drafts_update_simple( Tesla.Env.client(), String.t(), String.t(), String.t(), GoogleApi.Gmail.V1.Model.Draft.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Draft.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_drafts_update_simple( connection, user_id, id, upload_type, metadata, data, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:put) |> Request.url("/upload/gmail/v1/users/{userId}/drafts/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_param(:body, :metadata, metadata) |> Request.add_param(:file, :data, data) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Draft{}]) end @doc """ Lists the history of all changes to the given mailbox. History results are returned in chronological order (increasing `historyId`). ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:historyTypes` (*type:* `list(String.t)`) - History types to be returned by the function * `:labelId` (*type:* `String.t`) - Only return messages with a label matching the ID. * `:maxResults` (*type:* `integer()`) - Maximum number of history records to return. This field defaults to 100. The maximum allowed value for this field is 500. * `:pageToken` (*type:* `String.t`) - Page token to retrieve a specific page of results in the list. * `:startHistoryId` (*type:* `String.t`) - Required. Returns history records after the specified `startHistoryId`. The supplied `startHistoryId` should be obtained from the `historyId` of a message, thread, or previous `list` response. History IDs increase chronologically but are not contiguous with random gaps in between valid IDs. Supplying an invalid or out of date `startHistoryId` typically returns an `HTTP 404` error code. A `historyId` is typically valid for at least a week, but in some rare circumstances may be valid for only a few hours. If you receive an `HTTP 404` error response, your application should perform a full sync. If you receive no `nextPageToken` in the response, there are no updates to retrieve and you can store the returned `historyId` for a future request. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ListHistoryResponse{}}` on success * `{:error, info}` on failure """ @spec gmail_users_history_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.ListHistoryResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_history_list(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :historyTypes => :query, :labelId => :query, :maxResults => :query, :pageToken => :query, :startHistoryId => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/history", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.ListHistoryResponse{}]) end @doc """ Creates a new label. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Label.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Label{}}` on success * `{:error, info}` on failure """ @spec gmail_users_labels_create(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Label.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_labels_create(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/labels", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.Label{}]) end @doc """ Immediately and permanently deletes the specified label and removes it from any messages and threads that it is applied to. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the label to delete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_labels_delete( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_labels_delete(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/gmail/v1/users/{userId}/labels/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Gets the specified label. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the label to retrieve. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Label{}}` on success * `{:error, info}` on failure """ @spec gmail_users_labels_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Label.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_labels_get(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/labels/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Label{}]) end @doc """ Lists all labels in the user's mailbox. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ListLabelsResponse{}}` on success * `{:error, info}` on failure """ @spec gmail_users_labels_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.ListLabelsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_labels_list(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/labels", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.ListLabelsResponse{}]) end @doc """ Patch the specified label. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the label to update. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Label.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Label{}}` on success * `{:error, info}` on failure """ @spec gmail_users_labels_patch(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Label.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_labels_patch(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/gmail/v1/users/{userId}/labels/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Label{}]) end @doc """ Updates the specified label. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the label to update. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Label.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Label{}}` on success * `{:error, info}` on failure """ @spec gmail_users_labels_update( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Label.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_labels_update(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/gmail/v1/users/{userId}/labels/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Label{}]) end @doc """ Deletes many messages by message ID. Provides no guarantees that messages were not already deleted or even existed at all. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.BatchDeleteMessagesRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_batch_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_batch_delete(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/messages/batchDelete", %{ "userId" => URI.encode(user_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 ++ [decode: false]) end @doc """ Modifies the labels on the specified messages. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.BatchModifyMessagesRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_batch_modify(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_batch_modify(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/messages/batchModify", %{ "userId" => URI.encode(user_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 ++ [decode: false]) end @doc """ Immediately and permanently deletes the specified message. This operation cannot be undone. Prefer `messages.trash` instead. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the message to delete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_delete( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_delete(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/gmail/v1/users/{userId}/messages/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Gets the specified message. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the message to retrieve. This ID is usually retrieved using `messages.list`. The ID is also contained in the result when a message is inserted (`messages.insert`) or imported (`messages.import`). * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:format` (*type:* `String.t`) - The format to return the message in. * `:metadataHeaders` (*type:* `list(String.t)`) - When given and format is `METADATA`, only include headers specified. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_get(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :format => :query, :metadataHeaders => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/messages/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Message{}]) end @doc """ Imports a message into only this user's mailbox, with standard email delivery scanning and classification similar to receiving via SMTP. Does not send a message. Note: This function doesn't trigger forwarding rules or filters set up by the user. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:deleted` (*type:* `boolean()`) - Mark the email as permanently deleted (not TRASH) and only visible in Google Vault to a Vault administrator. Only used for G Suite accounts. * `:internalDateSource` (*type:* `String.t`) - Source for Gmail's internal date of the message. * `:neverMarkSpam` (*type:* `boolean()`) - Ignore the Gmail spam classifier decision and never mark this email as SPAM in the mailbox. * `:processForCalendar` (*type:* `boolean()`) - Process calendar invites in the email and add any extracted meetings to the Google Calendar for this user. * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Message.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_import(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_import(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :deleted => :query, :internalDateSource => :query, :neverMarkSpam => :query, :processForCalendar => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/messages/import", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.Message{}]) end @doc """ Imports a message into only this user's mailbox, with standard email delivery scanning and classification similar to receiving via SMTP. Does not send a message. Note: This function doesn't trigger forwarding rules or filters set up by the user. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "multipart". * `metadata` (*type:* `GoogleApi.Gmail.V1.Model.Message.t`) - object metadata * `data` (*type:* `iodata`) - Content to upload, as a string or iolist * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:deleted` (*type:* `boolean()`) - Mark the email as permanently deleted (not TRASH) and only visible in Google Vault to a Vault administrator. Only used for G Suite accounts. * `:internalDateSource` (*type:* `String.t`) - Source for Gmail's internal date of the message. * `:neverMarkSpam` (*type:* `boolean()`) - Ignore the Gmail spam classifier decision and never mark this email as SPAM in the mailbox. * `:processForCalendar` (*type:* `boolean()`) - Process calendar invites in the email and add any extracted meetings to the Google Calendar for this user. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_import_iodata( Tesla.Env.client(), String.t(), String.t(), GoogleApi.Gmail.V1.Model.Message.t(), iodata, keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_import_iodata( connection, user_id, upload_type, metadata, data, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :deleted => :query, :internalDateSource => :query, :neverMarkSpam => :query, :processForCalendar => :query } request = Request.new() |> Request.method(:post) |> Request.url("/upload/gmail/v1/users/{userId}/messages/import", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_param(:body, :metadata, metadata) |> Request.add_param(:body, :data, data) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Message{}]) end @doc """ Imports a message into only this user's mailbox, with standard email delivery scanning and classification similar to receiving via SMTP. Does not send a message. Note: This function doesn't trigger forwarding rules or filters set up by the user. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "resumable". * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:deleted` (*type:* `boolean()`) - Mark the email as permanently deleted (not TRASH) and only visible in Google Vault to a Vault administrator. Only used for G Suite accounts. * `:internalDateSource` (*type:* `String.t`) - Source for Gmail's internal date of the message. * `:neverMarkSpam` (*type:* `boolean()`) - Ignore the Gmail spam classifier decision and never mark this email as SPAM in the mailbox. * `:processForCalendar` (*type:* `boolean()`) - Process calendar invites in the email and add any extracted meetings to the Google Calendar for this user. * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Message.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_import_resumable( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_import_resumable( connection, user_id, upload_type, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :deleted => :query, :internalDateSource => :query, :neverMarkSpam => :query, :processForCalendar => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/resumable/upload/gmail/v1/users/{userId}/messages/import", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Imports a message into only this user's mailbox, with standard email delivery scanning and classification similar to receiving via SMTP. Does not send a message. Note: This function doesn't trigger forwarding rules or filters set up by the user. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "multipart". * `metadata` (*type:* `GoogleApi.Gmail.V1.Model.Message.t`) - object metadata * `data` (*type:* `String.t`) - Path to file containing content to upload * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:deleted` (*type:* `boolean()`) - Mark the email as permanently deleted (not TRASH) and only visible in Google Vault to a Vault administrator. Only used for G Suite accounts. * `:internalDateSource` (*type:* `String.t`) - Source for Gmail's internal date of the message. * `:neverMarkSpam` (*type:* `boolean()`) - Ignore the Gmail spam classifier decision and never mark this email as SPAM in the mailbox. * `:processForCalendar` (*type:* `boolean()`) - Process calendar invites in the email and add any extracted meetings to the Google Calendar for this user. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_import_simple( Tesla.Env.client(), String.t(), String.t(), GoogleApi.Gmail.V1.Model.Message.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_import_simple( connection, user_id, upload_type, metadata, data, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :deleted => :query, :internalDateSource => :query, :neverMarkSpam => :query, :processForCalendar => :query } request = Request.new() |> Request.method(:post) |> Request.url("/upload/gmail/v1/users/{userId}/messages/import", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_param(:body, :metadata, metadata) |> Request.add_param(:file, :data, data) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Message{}]) end @doc """ Directly inserts a message into only this user's mailbox similar to `IMAP APPEND`, bypassing most scanning and classification. Does not send a message. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:deleted` (*type:* `boolean()`) - Mark the email as permanently deleted (not TRASH) and only visible in Google Vault to a Vault administrator. Only used for G Suite accounts. * `:internalDateSource` (*type:* `String.t`) - Source for Gmail's internal date of the message. * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Message.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_insert(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_insert(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :deleted => :query, :internalDateSource => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/messages", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.Message{}]) end @doc """ Directly inserts a message into only this user's mailbox similar to `IMAP APPEND`, bypassing most scanning and classification. Does not send a message. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "multipart". * `metadata` (*type:* `GoogleApi.Gmail.V1.Model.Message.t`) - object metadata * `data` (*type:* `iodata`) - Content to upload, as a string or iolist * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:deleted` (*type:* `boolean()`) - Mark the email as permanently deleted (not TRASH) and only visible in Google Vault to a Vault administrator. Only used for G Suite accounts. * `:internalDateSource` (*type:* `String.t`) - Source for Gmail's internal date of the message. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_insert_iodata( Tesla.Env.client(), String.t(), String.t(), GoogleApi.Gmail.V1.Model.Message.t(), iodata, keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_insert_iodata( connection, user_id, upload_type, metadata, data, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :deleted => :query, :internalDateSource => :query } request = Request.new() |> Request.method(:post) |> Request.url("/upload/gmail/v1/users/{userId}/messages", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_param(:body, :metadata, metadata) |> Request.add_param(:body, :data, data) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Message{}]) end @doc """ Directly inserts a message into only this user's mailbox similar to `IMAP APPEND`, bypassing most scanning and classification. Does not send a message. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "resumable". * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:deleted` (*type:* `boolean()`) - Mark the email as permanently deleted (not TRASH) and only visible in Google Vault to a Vault administrator. Only used for G Suite accounts. * `:internalDateSource` (*type:* `String.t`) - Source for Gmail's internal date of the message. * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Message.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_insert_resumable( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_insert_resumable( connection, user_id, upload_type, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :deleted => :query, :internalDateSource => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/resumable/upload/gmail/v1/users/{userId}/messages", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Directly inserts a message into only this user's mailbox similar to `IMAP APPEND`, bypassing most scanning and classification. Does not send a message. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "multipart". * `metadata` (*type:* `GoogleApi.Gmail.V1.Model.Message.t`) - object metadata * `data` (*type:* `String.t`) - Path to file containing content to upload * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:deleted` (*type:* `boolean()`) - Mark the email as permanently deleted (not TRASH) and only visible in Google Vault to a Vault administrator. Only used for G Suite accounts. * `:internalDateSource` (*type:* `String.t`) - Source for Gmail's internal date of the message. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_insert_simple( Tesla.Env.client(), String.t(), String.t(), GoogleApi.Gmail.V1.Model.Message.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_insert_simple( connection, user_id, upload_type, metadata, data, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :deleted => :query, :internalDateSource => :query } request = Request.new() |> Request.method(:post) |> Request.url("/upload/gmail/v1/users/{userId}/messages", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_param(:body, :metadata, metadata) |> Request.add_param(:file, :data, data) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Message{}]) end @doc """ Lists the messages in the user's mailbox. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:includeSpamTrash` (*type:* `boolean()`) - Include messages from `SPAM` and `TRASH` in the results. * `:labelIds` (*type:* `list(String.t)`) - Only return messages with labels that match all of the specified label IDs. * `:maxResults` (*type:* `integer()`) - Maximum number of messages to return. This field defaults to 100. The maximum allowed value for this field is 500. * `:pageToken` (*type:* `String.t`) - Page token to retrieve a specific page of results in the list. * `:q` (*type:* `String.t`) - Only return messages matching the specified query. Supports the same query format as the Gmail search box. For example, `"from:someuser@example.com rfc822msgid: is:unread"`. Parameter cannot be used when accessing the api using the gmail.metadata scope. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ListMessagesResponse{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.ListMessagesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_list(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :includeSpamTrash => :query, :labelIds => :query, :maxResults => :query, :pageToken => :query, :q => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/messages", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.ListMessagesResponse{}]) end @doc """ Modifies the labels on the specified message. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the message to modify. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.ModifyMessageRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_modify( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_modify(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/messages/{id}/modify", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(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.Gmail.V1.Model.Message{}]) end @doc """ Sends the specified message to the recipients in the `To`, `Cc`, and `Bcc` headers. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Message.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_send(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_send(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/messages/send", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.Message{}]) end @doc """ Sends the specified message to the recipients in the `To`, `Cc`, and `Bcc` headers. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "multipart". * `metadata` (*type:* `GoogleApi.Gmail.V1.Model.Message.t`) - object metadata * `data` (*type:* `iodata`) - Content to upload, as a string or iolist * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_send_iodata( Tesla.Env.client(), String.t(), String.t(), GoogleApi.Gmail.V1.Model.Message.t(), iodata, keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_send_iodata( connection, user_id, upload_type, metadata, data, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/upload/gmail/v1/users/{userId}/messages/send", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_param(:body, :metadata, metadata) |> Request.add_param(:body, :data, data) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Message{}]) end @doc """ Sends the specified message to the recipients in the `To`, `Cc`, and `Bcc` headers. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "resumable". * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Message.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_send_resumable( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_send_resumable( connection, user_id, upload_type, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/resumable/upload/gmail/v1/users/{userId}/messages/send", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Sends the specified message to the recipients in the `To`, `Cc`, and `Bcc` headers. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `upload_type` (*type:* `String.t`) - Upload type. Must be "multipart". * `metadata` (*type:* `GoogleApi.Gmail.V1.Model.Message.t`) - object metadata * `data` (*type:* `String.t`) - Path to file containing content to upload * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_send_simple( Tesla.Env.client(), String.t(), String.t(), GoogleApi.Gmail.V1.Model.Message.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_send_simple( connection, user_id, upload_type, metadata, data, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/upload/gmail/v1/users/{userId}/messages/send", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :uploadType, upload_type) |> Request.add_param(:body, :metadata, metadata) |> Request.add_param(:file, :data, data) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Message{}]) end @doc """ Moves the specified message to the trash. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the message to Trash. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_trash( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_trash(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/messages/{id}/trash", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(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.Gmail.V1.Model.Message{}]) end @doc """ Removes the specified message from the trash. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the message to remove from Trash. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Message{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_untrash( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_untrash(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/messages/{id}/untrash", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(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.Gmail.V1.Model.Message{}]) end @doc """ Gets the specified message attachment. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `message_id` (*type:* `String.t`) - The ID of the message containing the attachment. * `id` (*type:* `String.t`) - The ID of the attachment. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.MessagePartBody{}}` on success * `{:error, info}` on failure """ @spec gmail_users_messages_attachments_get( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.MessagePartBody.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_messages_attachments_get( connection, user_id, message_id, id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/messages/{messageId}/attachments/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "messageId" => URI.encode(message_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.MessagePartBody{}]) end @doc """ Gets the auto-forwarding setting for the specified account. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.AutoForwarding{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_get_auto_forwarding( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.AutoForwarding.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_get_auto_forwarding( connection, user_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/autoForwarding", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.AutoForwarding{}]) end @doc """ Gets IMAP settings. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ImapSettings{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_get_imap(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.ImapSettings.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_get_imap(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/imap", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.ImapSettings{}]) end @doc """ Gets language settings. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.LanguageSettings{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_get_language(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.LanguageSettings.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_get_language(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/language", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.LanguageSettings{}]) end @doc """ Gets POP settings. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.PopSettings{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_get_pop(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.PopSettings.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_get_pop(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/pop", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.PopSettings{}]) end @doc """ Gets vacation responder settings. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.VacationSettings{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_get_vacation(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.VacationSettings.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_get_vacation(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/vacation", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.VacationSettings{}]) end @doc """ Updates the auto-forwarding setting for the specified account. A verified forwarding address must be specified when auto-forwarding is enabled. This method is only available to service account clients that have been delegated domain-wide authority. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.AutoForwarding.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.AutoForwarding{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_update_auto_forwarding( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.AutoForwarding.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_update_auto_forwarding( connection, user_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/gmail/v1/users/{userId}/settings/autoForwarding", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.AutoForwarding{}]) end @doc """ Updates IMAP settings. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.ImapSettings.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ImapSettings{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_update_imap(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.ImapSettings.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_update_imap(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/gmail/v1/users/{userId}/settings/imap", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.ImapSettings{}]) end @doc """ Updates language settings. If successful, the return object contains the `displayLanguage` that was saved for the user, which may differ from the value passed into the request. This is because the requested `displayLanguage` may not be directly supported by Gmail but have a close variant that is, and so the variant may be chosen and saved instead. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.LanguageSettings.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.LanguageSettings{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_update_language(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.LanguageSettings.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_update_language(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/gmail/v1/users/{userId}/settings/language", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.LanguageSettings{}]) end @doc """ Updates POP settings. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.PopSettings.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.PopSettings{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_update_pop(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.PopSettings.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_update_pop(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/gmail/v1/users/{userId}/settings/pop", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.PopSettings{}]) end @doc """ Updates vacation responder settings. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.VacationSettings.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.VacationSettings{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_update_vacation(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.VacationSettings.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_update_vacation(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/gmail/v1/users/{userId}/settings/vacation", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.VacationSettings{}]) end @doc """ Adds a delegate with its verification status set directly to `accepted`, without sending any verification email. The delegate user must be a member of the same G Suite organization as the delegator user. Gmail imposes limitations on the number of delegates and delegators each user in a G Suite organization can have. These limits depend on your organization, but in general each user can have up to 25 delegates and up to 10 delegators. Note that a delegate user must be referred to by their primary email address, and not an email alias. Also note that when a new delegate is created, there may be up to a one minute delay before the new delegate is available for use. This method is only available to service account clients that have been delegated domain-wide authority. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Delegate.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Delegate{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_delegates_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Delegate.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_delegates_create( connection, user_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/settings/delegates", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.Delegate{}]) end @doc """ Removes the specified delegate (which can be of any verification status), and revokes any verification that may have been required for using it. Note that a delegate user must be referred to by their primary email address, and not an email alias. This method is only available to service account clients that have been delegated domain-wide authority. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `delegate_email` (*type:* `String.t`) - The email address of the user to be removed as a delegate. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_delegates_delete( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_delegates_delete( connection, user_id, delegate_email, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/gmail/v1/users/{userId}/settings/delegates/{delegateEmail}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "delegateEmail" => URI.encode(delegate_email, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Gets the specified delegate. Note that a delegate user must be referred to by their primary email address, and not an email alias. This method is only available to service account clients that have been delegated domain-wide authority. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `delegate_email` (*type:* `String.t`) - The email address of the user whose delegate relationship is to be retrieved. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Delegate{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_delegates_get( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Delegate.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_delegates_get( connection, user_id, delegate_email, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/delegates/{delegateEmail}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "delegateEmail" => URI.encode(delegate_email, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Delegate{}]) end @doc """ Lists the delegates for the specified account. This method is only available to service account clients that have been delegated domain-wide authority. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ListDelegatesResponse{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_delegates_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.ListDelegatesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_delegates_list(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/delegates", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.ListDelegatesResponse{}]) end @doc """ Creates a filter. Note: you can only create a maximum of 1,000 filters. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.Filter.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Filter{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_filters_create(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Filter.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_filters_create(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/settings/filters", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.Filter{}]) end @doc """ Deletes a filter. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the filter to be deleted. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_filters_delete( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_filters_delete( connection, user_id, id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/gmail/v1/users/{userId}/settings/filters/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Gets a filter. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the filter to be fetched. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Filter{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_filters_get( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Filter.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_filters_get(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/filters/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Filter{}]) end @doc """ Lists the message filters of a Gmail user. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ListFiltersResponse{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_filters_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.ListFiltersResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_filters_list(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/filters", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.ListFiltersResponse{}]) end @doc """ Creates a forwarding address. If ownership verification is required, a message will be sent to the recipient and the resource's verification status will be set to `pending`; otherwise, the resource will be created with verification status set to `accepted`. This method is only available to service account clients that have been delegated domain-wide authority. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.ForwardingAddress.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ForwardingAddress{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_forwarding_addresses_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.ForwardingAddress.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_forwarding_addresses_create( connection, user_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/settings/forwardingAddresses", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.ForwardingAddress{}]) end @doc """ Deletes the specified forwarding address and revokes any verification that may have been required. This method is only available to service account clients that have been delegated domain-wide authority. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `forwarding_email` (*type:* `String.t`) - The forwarding address to be deleted. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_forwarding_addresses_delete( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_forwarding_addresses_delete( connection, user_id, forwarding_email, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/gmail/v1/users/{userId}/settings/forwardingAddresses/{forwardingEmail}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "forwardingEmail" => URI.encode(forwarding_email, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Gets the specified forwarding address. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `forwarding_email` (*type:* `String.t`) - The forwarding address to be retrieved. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ForwardingAddress{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_forwarding_addresses_get( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.ForwardingAddress.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_forwarding_addresses_get( connection, user_id, forwarding_email, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/forwardingAddresses/{forwardingEmail}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "forwardingEmail" => URI.encode(forwarding_email, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.ForwardingAddress{}]) end @doc """ Lists the forwarding addresses for the specified account. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ListForwardingAddressesResponse{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_forwarding_addresses_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.ListForwardingAddressesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_forwarding_addresses_list( connection, user_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/forwardingAddresses", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.ListForwardingAddressesResponse{}] ) end @doc """ Creates a custom "from" send-as alias. If an SMTP MSA is specified, Gmail will attempt to connect to the SMTP service to validate the configuration before creating the alias. If ownership verification is required for the alias, a message will be sent to the email address and the resource's verification status will be set to `pending`; otherwise, the resource will be created with verification status set to `accepted`. If a signature is provided, Gmail will sanitize the HTML before saving it with the alias. This method is only available to service account clients that have been delegated domain-wide authority. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.SendAs.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.SendAs{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_send_as_create(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.SendAs.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_send_as_create(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/settings/sendAs", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.SendAs{}]) end @doc """ Deletes the specified send-as alias. Revokes any verification that may have been required for using it. This method is only available to service account clients that have been delegated domain-wide authority. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `send_as_email` (*type:* `String.t`) - The send-as alias to be deleted. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_send_as_delete( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_send_as_delete( connection, user_id, send_as_email, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "sendAsEmail" => URI.encode(send_as_email, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Gets the specified send-as alias. Fails with an HTTP 404 error if the specified address is not a member of the collection. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `send_as_email` (*type:* `String.t`) - The send-as alias to be retrieved. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.SendAs{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_send_as_get( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.SendAs.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_send_as_get( connection, user_id, send_as_email, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "sendAsEmail" => URI.encode(send_as_email, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.SendAs{}]) end @doc """ Lists the send-as aliases for the specified account. The result includes the primary send-as address associated with the account as well as any custom "from" aliases. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ListSendAsResponse{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_send_as_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.ListSendAsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_send_as_list(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/sendAs", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.ListSendAsResponse{}]) end @doc """ Patch the specified send-as alias. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `send_as_email` (*type:* `String.t`) - The send-as alias to be updated. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.SendAs.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.SendAs{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_send_as_patch( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.SendAs.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_send_as_patch( connection, user_id, send_as_email, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "sendAsEmail" => URI.encode(send_as_email, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.SendAs{}]) end @doc """ Updates a send-as alias. If a signature is provided, Gmail will sanitize the HTML before saving it with the alias. Addresses other than the primary address for the account can only be updated by service account clients that have been delegated domain-wide authority. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `send_as_email` (*type:* `String.t`) - The send-as alias to be updated. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.SendAs.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.SendAs{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_send_as_update( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.SendAs.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_send_as_update( connection, user_id, send_as_email, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "sendAsEmail" => URI.encode(send_as_email, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.SendAs{}]) end @doc """ Sends a verification email to the specified send-as alias address. The verification status must be `pending`. This method is only available to service account clients that have been delegated domain-wide authority. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - User's email address. The special value "me" can be used to indicate the authenticated user. * `send_as_email` (*type:* `String.t`) - The send-as alias to be verified. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_send_as_verify( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_send_as_verify( connection, user_id, send_as_email, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/verify", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "sendAsEmail" => URI.encode(send_as_email, &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 ++ [decode: false]) end @doc """ Deletes the specified S/MIME config for the specified send-as alias. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `send_as_email` (*type:* `String.t`) - The email address that appears in the "From:" header for mail sent using this alias. * `id` (*type:* `String.t`) - The immutable ID for the SmimeInfo. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_send_as_smime_info_delete( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_send_as_smime_info_delete( connection, user_id, send_as_email, id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "sendAsEmail" => URI.encode(send_as_email, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Gets the specified S/MIME config for the specified send-as alias. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `send_as_email` (*type:* `String.t`) - The email address that appears in the "From:" header for mail sent using this alias. * `id` (*type:* `String.t`) - The immutable ID for the SmimeInfo. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.SmimeInfo{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_send_as_smime_info_get( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.SmimeInfo.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_send_as_smime_info_get( connection, user_id, send_as_email, id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "sendAsEmail" => URI.encode(send_as_email, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.SmimeInfo{}]) end @doc """ Insert (upload) the given S/MIME config for the specified send-as alias. Note that pkcs12 format is required for the key. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `send_as_email` (*type:* `String.t`) - The email address that appears in the "From:" header for mail sent using this alias. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.SmimeInfo.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.SmimeInfo{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_send_as_smime_info_insert( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.SmimeInfo.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_send_as_smime_info_insert( connection, user_id, send_as_email, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "sendAsEmail" => URI.encode(send_as_email, &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.Gmail.V1.Model.SmimeInfo{}]) end @doc """ Lists S/MIME configs for the specified send-as alias. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `send_as_email` (*type:* `String.t`) - The email address that appears in the "From:" header for mail sent using this alias. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ListSmimeInfoResponse{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_send_as_smime_info_list( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.ListSmimeInfoResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_send_as_smime_info_list( connection, user_id, send_as_email, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "sendAsEmail" => URI.encode(send_as_email, &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.Gmail.V1.Model.ListSmimeInfoResponse{}]) end @doc """ Sets the default S/MIME config for the specified send-as alias. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `send_as_email` (*type:* `String.t`) - The email address that appears in the "From:" header for mail sent using this alias. * `id` (*type:* `String.t`) - The immutable ID for the SmimeInfo. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_settings_send_as_smime_info_set_default( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_settings_send_as_smime_info_set_default( connection, user_id, send_as_email, id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url( "/gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo/{id}/setDefault", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "sendAsEmail" => URI.encode(send_as_email, &URI.char_unreserved?/1), "id" => URI.encode(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 ++ [decode: false]) end @doc """ Immediately and permanently deletes the specified thread. This operation cannot be undone. Prefer `threads.trash` instead. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - ID of the Thread to delete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec gmail_users_threads_delete( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_threads_delete(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/gmail/v1/users/{userId}/threads/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Gets the specified thread. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the thread to retrieve. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:format` (*type:* `String.t`) - The format to return the messages in. * `:metadataHeaders` (*type:* `list(String.t)`) - When given and format is METADATA, only include headers specified. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Thread{}}` on success * `{:error, info}` on failure """ @spec gmail_users_threads_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.Thread.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_threads_get(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :format => :query, :metadataHeaders => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/threads/{id}", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Gmail.V1.Model.Thread{}]) end @doc """ Lists the threads in the user's mailbox. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:includeSpamTrash` (*type:* `boolean()`) - Include threads from `SPAM` and `TRASH` in the results. * `:labelIds` (*type:* `list(String.t)`) - Only return threads with labels that match all of the specified label IDs. * `:maxResults` (*type:* `integer()`) - Maximum number of threads to return. This field defaults to 100. The maximum allowed value for this field is 500. * `:pageToken` (*type:* `String.t`) - Page token to retrieve a specific page of results in the list. * `:q` (*type:* `String.t`) - Only return threads matching the specified query. Supports the same query format as the Gmail search box. For example, `"from:someuser@example.com rfc822msgid: is:unread"`. Parameter cannot be used when accessing the api using the gmail.metadata scope. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.ListThreadsResponse{}}` on success * `{:error, info}` on failure """ @spec gmail_users_threads_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Gmail.V1.Model.ListThreadsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_threads_list(connection, user_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :includeSpamTrash => :query, :labelIds => :query, :maxResults => :query, :pageToken => :query, :q => :query } request = Request.new() |> Request.method(:get) |> Request.url("/gmail/v1/users/{userId}/threads", %{ "userId" => URI.encode(user_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.Gmail.V1.Model.ListThreadsResponse{}]) end @doc """ Modifies the labels applied to the thread. This applies to all messages in the thread. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the thread to modify. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Gmail.V1.Model.ModifyThreadRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Thread{}}` on success * `{:error, info}` on failure """ @spec gmail_users_threads_modify( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Thread.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_threads_modify(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/threads/{id}/modify", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(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.Gmail.V1.Model.Thread{}]) end @doc """ Moves the specified thread to the trash. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the thread to Trash. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Thread{}}` on success * `{:error, info}` on failure """ @spec gmail_users_threads_trash( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Thread.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_threads_trash(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/threads/{id}/trash", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(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.Gmail.V1.Model.Thread{}]) end @doc """ Removes the specified thread from the trash. ## Parameters * `connection` (*type:* `GoogleApi.Gmail.V1.Connection.t`) - Connection to server * `user_id` (*type:* `String.t`) - The user's email address. The special value `me` can be used to indicate the authenticated user. * `id` (*type:* `String.t`) - The ID of the thread to remove from Trash. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Gmail.V1.Model.Thread{}}` on success * `{:error, info}` on failure """ @spec gmail_users_threads_untrash( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Gmail.V1.Model.Thread.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def gmail_users_threads_untrash(connection, user_id, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/gmail/v1/users/{userId}/threads/{id}/untrash", %{ "userId" => URI.encode(user_id, &URI.char_unreserved?/1), "id" => URI.encode(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.Gmail.V1.Model.Thread{}]) end end
46.313576
798
0.606133
1c89a1043976bb59f541c7c9f74f3d0e3fd125e8
2,298
ex
Elixir
clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_numerical_stats_result.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_numerical_stats_result.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_numerical_stats_result.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.DLP.V2.Model.GooglePrivacyDlpV2NumericalStatsResult do @moduledoc """ Result of the numerical stats computation. ## Attributes * `maxValue` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Value.t`, *default:* `nil`) - Maximum value appearing in the column. * `minValue` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Value.t`, *default:* `nil`) - Minimum value appearing in the column. * `quantileValues` (*type:* `list(GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Value.t)`, *default:* `nil`) - List of 99 values that partition the set of field values into 100 equal sized buckets. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :maxValue => GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Value.t(), :minValue => GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Value.t(), :quantileValues => list(GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Value.t()) } field(:maxValue, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Value) field(:minValue, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Value) field(:quantileValues, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Value, type: :list) end defimpl Poison.Decoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2NumericalStatsResult do def decode(value, options) do GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2NumericalStatsResult.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2NumericalStatsResult do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.555556
181
0.751088
1c89a3654b06245280a8d516785e33abcca78fc4
5,112
exs
Elixir
mix.exs
kaikuchn/eventstore
cfe77cb22860526ef3591ba43649ceffc3175259
[ "MIT" ]
null
null
null
mix.exs
kaikuchn/eventstore
cfe77cb22860526ef3591ba43649ceffc3175259
[ "MIT" ]
null
null
null
mix.exs
kaikuchn/eventstore
cfe77cb22860526ef3591ba43649ceffc3175259
[ "MIT" ]
null
null
null
defmodule EventStore.Mixfile do use Mix.Project @version "1.1.0" def project do [ app: :eventstore, version: @version, elixir: "~> 1.6", elixirc_paths: elixirc_paths(Mix.env()), deps: deps(), description: description(), package: package(), docs: docs(), build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, consolidate_protocols: Mix.env() == :prod, aliases: aliases(), preferred_cli_env: preferred_cli_env(), dialyzer: dialyzer(), name: "EventStore", source_url: "https://github.com/commanded/eventstore" ] end def application do [ extra_applications: [:logger, :ssl] ] end defp elixirc_paths(env) when env in [:bench, :distributed, :jsonb, :migration, :test], do: ["lib", "test/support", "test/subscriptions/support"] defp elixirc_paths(_env), do: ["lib"] defp deps do [ {:elixir_uuid, "~> 1.2"}, {:fsm, "~> 0.3"}, {:gen_stage, "~> 1.0"}, {:postgrex, "~> 0.15"}, {:highlander, "~> 0.2"}, # Optional dependencies {:jason, "~> 1.2", optional: true}, {:poolboy, "~> 1.5", optional: true}, # Development and test tooling {:benchfella, "~> 0.3", only: :bench}, {:dialyxir, "~> 1.0", only: :dev, runtime: false}, {:ex_doc, "~> 0.22", only: :dev}, {:local_cluster, "~> 1.1", only: [:distributed]}, {:mix_test_watch, "~> 1.0", only: :dev} ] end defp description do """ Event store using PostgreSQL for persistence. """ end defp docs do [ main: "EventStore", canonical: "http://hexdocs.pm/eventstore", source_ref: "v#{@version}", extra_section: "GUIDES", extras: [ "CHANGELOG.md", "guides/Getting Started.md", "guides/Usage.md", "guides/Subscriptions.md", "guides/Cluster.md", "guides/Event Serialization.md", "guides/Upgrades.md", "guides/upgrades/0.17-1.0.md": [ filename: "0.17-1.0", title: "Upgrade guide v0.17.x to 1.0" ] ], groups_for_extras: [ Introduction: [ "guides/Getting Started.md", "guides/Usage.md", "guides/Subscriptions.md" ], Serialization: [ "guides/Event Serialization.md" ], Deployment: [ "guides/Cluster.md" ], Upgrades: [ "guides/Upgrades.md", "guides/upgrades/0.17-1.0.md" ] ], groups_for_modules: [ "Data types": [ EventStore.EventData, EventStore.RecordedEvent, EventStore.Snapshots.SnapshotData ], Serialization: [ EventStore.JsonSerializer, EventStore.JsonbSerializer, EventStore.Serializer, EventStore.TermSerializer ], Registration: [ EventStore.Registration, EventStore.Registration.DistributedRegistry, EventStore.Registration.LocalRegistry ], Tasks: [ EventStore.Tasks.Create, EventStore.Tasks.Drop, EventStore.Tasks.Init, EventStore.Tasks.Migrate ] ] ] end defp package do [ files: ["lib", "priv/event_store", "guides", "mix.exs", "README*", "LICENSE*"], maintainers: ["Ben Smith"], licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/commanded/eventstore" } ] end defp aliases do [ benchmark: ["es.reset", "app.start", "bench"], "event_store.reset": ["event_store.drop", "event_store.setup"], "event_store.setup": ["event_store.create", "event_store.init"], "es.reset": ["event_store.reset"], "es.setup": ["event_store.setup"], "test.all": ["test", "test.jsonb", "test.distributed", "test.migration", "test --only slow"], "test.distributed": &test_distributed/1, "test.jsonb": &test_jsonb/1, "test.migration": &test_migration/1 ] end defp preferred_cli_env do [ "test.all": :test, "test.distributed": :test, "test.jsonb": :test, "test.migration": :test ] end defp dialyzer do [ plt_add_apps: [:ex_unit, :jason, :mix], plt_add_deps: :app_tree, plt_file: {:no_warn, "priv/plts/eventstore.plt"} ] end defp test_distributed(args), do: test_env(:distributed, ["--only", "distributed"] ++ args) defp test_migration(args), do: test_env(:migration, ["--include", "migration"] ++ args) defp test_jsonb(args), do: test_env(:jsonb, args) defp test_env(env, args) do test_args = if IO.ANSI.enabled?(), do: ["--color" | args], else: ["--no-color" | args] IO.puts("==> Running tests for MIX_ENV=#{env} mix test #{Enum.join(args, " ")}") {_, res} = System.cmd( "mix", ["test" | test_args], into: IO.binstream(:stdio, :line), env: [{"MIX_ENV", to_string(env)}] ) if res > 0 do System.at_exit(fn _ -> exit({:shutdown, 1}) end) end end end
26.625
99
0.553208
1c89c219028c6f235712cd309dd0338e056c4356
2,314
exs
Elixir
test/ecto/query/builder/distinct_test.exs
Anber/ecto
2b903c8c6acb924f87746fe4d40cb4b42a7f0491
[ "Apache-2.0" ]
null
null
null
test/ecto/query/builder/distinct_test.exs
Anber/ecto
2b903c8c6acb924f87746fe4d40cb4b42a7f0491
[ "Apache-2.0" ]
null
null
null
test/ecto/query/builder/distinct_test.exs
Anber/ecto
2b903c8c6acb924f87746fe4d40cb4b42a7f0491
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.Query.Builder.DistinctTest do use ExUnit.Case, async: true import Ecto.Query.Builder.Distinct doctest Ecto.Query.Builder.Distinct import Ecto.Query describe "escape" do test "handles expressions and params" do assert {true, {%{}, :acc}} == escape(true, {%{}, :acc}, [x: 0], __ENV__) assert {Macro.escape(quote do [asc: &0.y] end), {%{}, :acc}} == escape(quote do x.y end, {%{}, :acc}, [x: 0], __ENV__) assert {Macro.escape(quote do [asc: &0.x, asc: &1.y] end), {%{}, :acc}} == escape(quote do [x.x, y.y] end, {%{}, :acc}, [x: 0, y: 1], __ENV__) assert {Macro.escape(quote do [asc: &0.x, desc: &1.y] end), {%{}, :acc}} == escape(quote do [x.x, desc: y.y] end, {%{}, :acc}, [x: 0, y: 1], __ENV__) import Kernel, except: [>: 2] assert {Macro.escape(quote do [asc: 1 > 2] end), {%{}, :acc}} == escape(quote do 1 > 2 end, {%{}, :acc}, [], __ENV__) end test "raises on unbound variables" do assert_raise Ecto.Query.CompileError, ~r"unbound variable `x` in query", fn -> escape(quote do x.y end, {%{}, :acc}, [], __ENV__) end end end describe "at runtime" do test "accepts fields" do key = :title assert distinct("q", [q], ^key).distinct == distinct("q", [q], [q.title]).distinct assert distinct("q", [q], [^key]).distinct == distinct("q", [q], [q.title]).distinct end test "accepts keyword lists" do kw = [desc: :title] assert distinct("q", [q], ^kw).distinct == distinct("q", [q], [desc: q.title]).distinct end test "accepts the boolean true" do bool = true assert distinct("q", [q], ^bool).distinct == distinct("q", [q], true).distinct end test "raises on non-atoms" do message = "expected a field as an atom, a list or keyword list in `distinct`, got: `\"temp\"`" assert_raise ArgumentError, message, fn -> temp = "temp" distinct("posts", [p], [^temp]) end end test "raises non-lists" do message = "expected a field as an atom, a list or keyword list in `distinct`, got: `\"temp\"`" assert_raise ArgumentError, message, fn -> temp = "temp" distinct("posts", [p], ^temp) end end end end
33.536232
100
0.557476
1c89cf468e570c03320b83cc0e5bb0d15bbecc27
374
ex
Elixir
lib/oli/interop/custom_activities/record_context.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
1
2022-03-17T20:35:47.000Z
2022-03-17T20:35:47.000Z
lib/oli/interop/custom_activities/record_context.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
9
2021-11-02T16:52:09.000Z
2022-03-25T15:14:01.000Z
lib/oli/interop/custom_activities/record_context.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
null
null
null
defmodule Oli.Interop.CustomActivities.RecordContext do import XmlBuilder def setup( %{ context: context } ) do element( :record_context, %{ activity_guid: context.activity_attempt.attempt_guid, attempt: context.activity_attempt.attempt_number, user_guid: context.user.id } ) end end
18.7
61
0.617647
1c89f5be472b521cc823ce1ef587ebd4978a3df9
1,123
exs
Elixir
elixir-class/basic/5-control-structure/testif/config/config.exs
ikhlas-firlana/learning-class
58c2db1e8121eaec47190105dffa47d6db84bb55
[ "Apache-2.0" ]
null
null
null
elixir-class/basic/5-control-structure/testif/config/config.exs
ikhlas-firlana/learning-class
58c2db1e8121eaec47190105dffa47d6db84bb55
[ "Apache-2.0" ]
null
null
null
elixir-class/basic/5-control-structure/testif/config/config.exs
ikhlas-firlana/learning-class
58c2db1e8121eaec47190105dffa47d6db84bb55
[ "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 your application as: # # config :testif, key: :value # # and access this configuration in your application as: # # Application.get_env(:testif, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env()}.exs"
36.225806
73
0.749777
1c8a5469aa4210dce0dbe7bb562fab7b0642be24
1,120
exs
Elixir
test/absinthe/phase/document/validation/variables_are_input_types_test.exs
TheRealReal/absinthe
6eae5bc36283e58f42d032b8afd90de3ad64f97b
[ "MIT" ]
1
2019-10-10T02:57:52.000Z
2019-10-10T02:57:52.000Z
test/absinthe/phase/document/validation/variables_are_input_types_test.exs
TheRealReal/absinthe
6eae5bc36283e58f42d032b8afd90de3ad64f97b
[ "MIT" ]
2
2018-08-02T13:35:38.000Z
2018-08-02T13:36:42.000Z
test/absinthe/phase/document/validation/variables_are_input_types_test.exs
TheRealReal/absinthe
6eae5bc36283e58f42d032b8afd90de3ad64f97b
[ "MIT" ]
1
2018-11-16T02:34:40.000Z
2018-11-16T02:34:40.000Z
defmodule Absinthe.Phase.Document.Validation.VariablesAreInputTypesTest do @phase Absinthe.Phase.Document.Validation.VariablesAreInputTypes use Absinthe.ValidationPhaseCase, phase: @phase, async: true alias Absinthe.Blueprint defp non_input_type(name, type_rep, line) do bad_value( Blueprint.Document.VariableDefinition, @phase.error_message(name, type_rep), line, name: name ) end describe "Validate: Variables are input types" do test "input types are valid" do assert_passes_validation( """ query Foo($a: String, $b: [Boolean!]!, $c: ComplexInput) { field(a: $a, b: $b, c: $c) } """, [] ) end test "output types are invalid" do assert_fails_validation( """ query Foo($a: Dog, $b: [[CatOrDog!]]!, $c: Pet) { field(a: $a, b: $b, c: $c) } """, [], [ non_input_type("a", "Dog", 1), non_input_type("b", "[[CatOrDog!]]!", 1), non_input_type("c", "Pet", 1) ] ) end end end
23.333333
74
0.550893
1c8a5c19301126118bd42a91affbdc30bb14985a
1,214
exs
Elixir
mix.exs
jnylen/pkg_deb
61186a4231e546fa433a0ecd68c3586abaffce4d
[ "MIT" ]
null
null
null
mix.exs
jnylen/pkg_deb
61186a4231e546fa433a0ecd68c3586abaffce4d
[ "MIT" ]
12
2020-07-18T10:38:53.000Z
2022-03-24T04:04:12.000Z
mix.exs
jnylen/pkg_deb
61186a4231e546fa433a0ecd68c3586abaffce4d
[ "MIT" ]
1
2020-11-28T21:08:54.000Z
2020-11-28T21:08:54.000Z
defmodule PkgDeb.MixProject do use Mix.Project @name :pkg_deb @version "0.4.0" @description """ Elixir lib for creating Debian packages with Mix Release. """ @deps [ {:pkg_core, "~> 0.1"}, {:vex, "~> 0.8"}, {:ex_doc, ">= 0.0.0", only: :dev, runtime: false} ] @hex_package [ name: @name, files: ["lib", "mix.exs", "README*", "LICENSE*", "templates"], maintainers: ["Joakim Nylen <hexpm@joakim.nylen.nu>"], licenses: ["MIT"], links: %{ "Github" => "https://github.com/jnylen/pkg_deb", "Docs" => "https://hexdocs.pm/pkg_deb/" } ] def project do [ app: @name, version: @version, elixir: ">= 1.9.0", start_permanent: Mix.env() == :prod, deps: @deps, package: @hex_package, description: @description, docs: docs() ] end defp docs do [ source_ref: "master", main: "PkgDeb", canonical: "http://hexdocs.pm/pkg_deb", source_url: "https://github.com/jnylen/pkg_deb", extras: [ "README.md" ] ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end end
20.931034
66
0.552718
1c8a71fab739a1784baa8b35f1800bafc2df625a
928
ex
Elixir
lib/ex_changerate/fluctuation.ex
81dr/ex_changerate
b5df0d1aeac755d2826d000b08e23077ca7a0c62
[ "0BSD" ]
2
2020-06-07T09:29:23.000Z
2020-11-16T01:59:40.000Z
lib/ex_changerate/fluctuation.ex
81dr/ex_changerate
b5df0d1aeac755d2826d000b08e23077ca7a0c62
[ "0BSD" ]
null
null
null
lib/ex_changerate/fluctuation.ex
81dr/ex_changerate
b5df0d1aeac755d2826d000b08e23077ca7a0c62
[ "0BSD" ]
null
null
null
defmodule ExChangerate.Fluctuation do @moduledoc """ Enables the use of Fluctuation Endpoint *Note from documentation: Using the fluctuation endpoint you will be able to retrieve information about how currencies fluctuate on a day-to-day basis. To use this feature, simply append a start_date and end_date and choose which currencies (symbols) you would like to query the API for. Please note that the maximum allowed timeframe is 365 days.* """ @endpoint "/fluctuation" alias ExChangerate.Handler def get(options, params), do: fetch(options, params) def get(options), do: fetch(options) def get, do: {:error, "Missing required parameters: start_date, end_date"} defp fetch(options, params), do: Handler.handle(@endpoint, options, params, keywords()) defp fetch(options), do: Handler.handle(@endpoint, options) defp keywords, do: [:base, :symbols, :amount, :callback, :places, :format, :source] end
46.4
350
0.751078
1c8a91914194f78d7522a13d9d4ecfbcce7a09c6
2,295
ex
Elixir
clients/games_configuration/lib/google_api/games_configuration/v1configuration/model/achievement_configuration_list_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/games_configuration/lib/google_api/games_configuration/v1configuration/model/achievement_configuration_list_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/games_configuration/lib/google_api/games_configuration/v1configuration/model/achievement_configuration_list_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfigurationListResponse do @moduledoc """ A ListConfigurations response. ## Attributes * `items` (*type:* `list(GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfiguration.t)`, *default:* `nil`) - The achievement configurations. * `kind` (*type:* `String.t`, *default:* `nil`) - Uniquely identifies the type of this resource. Value is always the fixed string `gamesConfiguration#achievementConfigurationListResponse`. * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - The pagination token for the next page of results. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :items => list(GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfiguration.t()) | nil, :kind => String.t() | nil, :nextPageToken => String.t() | nil } field(:items, as: GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfiguration, type: :list ) field(:kind) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfigurationListResponse do def decode(value, options) do GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfigurationListResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfigurationListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.859375
192
0.740305
1c8aaebab9f6d75b76bf6d28939540356a3583f9
2,186
exs
Elixir
config/prod.exs
teaearlgraycold/HippoGuesser
f47fb0636c841ce9b579c07e423c980b17cb9965
[ "MIT" ]
null
null
null
config/prod.exs
teaearlgraycold/HippoGuesser
f47fb0636c841ce9b579c07e423c980b17cb9965
[ "MIT" ]
null
null
null
config/prod.exs
teaearlgraycold/HippoGuesser
f47fb0636c841ce9b579c07e423c980b17cb9965
[ "MIT" ]
null
null
null
use Mix.Config # For production, we often load configuration from external # sources, such as your system environment. For this reason, # you won't find the :http configuration below, but set inside # MtpoWeb.Endpoint.init/2 when load_from_system_env is # true. Any dynamic configuration should be done there. # # Don't forget to configure the url host to something meaningful, # Phoenix uses this information when generating URLs. # # Finally, 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 typically run after static files are built. config :mtpo, MtpoWeb.Endpoint, load_from_system_env: true, url: [host: "mtpo.teaearlgraycold.me", port: 1337], cache_static_manifest: "priv/static/cache_manifest.json" # Do not print debug messages in production config :logger, level: :debug # ## 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 :mtpo, MtpoWeb.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [:inet6, # port: 443, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH")] # # Where those two env variables return an absolute path to # the key and cert in disk or a relative path inside priv, # for example "priv/ssl/server.key". # # We also recommend setting `force_ssl`, ensuring no data is # ever sent via http, always redirecting to https: # # config :mtpo, MtpoWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # ## Using releases # # If you are doing OTP releases, you need to instruct Phoenix # to start the server for all endpoints: # config :phoenix, :serve_endpoints, true # # Alternatively, you can configure exactly which server to # start per endpoint: # # config :mtpo, MtpoWeb.Endpoint, server: true # config :mtpo, run_bot: true # Finally import the config/prod.secret.exs # which should be versioned separately. import_config "prod.secret.exs"
32.147059
67
0.720952
1c8aef40a16df8a60ec2eb2114db53c1b8cc270d
5,263
ex
Elixir
lib/erl2ex/source.ex
axelson/erl2ex
382d87ab5fe4a3a3bdb03001226c9c514b889eb0
[ "BSD-3-Clause" ]
77
2015-12-28T10:54:32.000Z
2021-11-17T16:14:41.000Z
lib/erl2ex/source.ex
axelson/erl2ex
382d87ab5fe4a3a3bdb03001226c9c514b889eb0
[ "BSD-3-Clause" ]
5
2016-02-13T09:36:59.000Z
2022-02-23T16:57:58.000Z
lib/erl2ex/source.ex
axelson/erl2ex
382d87ab5fe4a3a3bdb03001226c9c514b889eb0
[ "BSD-3-Clause" ]
13
2016-06-04T06:49:19.000Z
2021-10-14T03:00:54.000Z
defmodule Erl2ex.Source do @moduledoc """ Erl2ex.Source is a process that produces Erlang source, normally reading files from the file system. """ @typedoc """ The ProcessID of a source process. """ @type t :: pid() @doc """ Starts a source and returns its PID. """ @spec start_link(list) :: t def start_link(opts) do {:ok, pid} = GenServer.start_link(__MODULE__, opts) pid end @doc """ Reads the source file at the given path or symbolic location, and returns a tuple comprising the data in the file and the full path to it. """ @spec read_source(t, Erl2ex.file_id) :: {String.t, Erl2ex.file_id} def read_source(source, path) do source |> GenServer.call({:read_source, path}) |> handle_result end @doc """ Reads the include file at the given path, given a context directory, and returns a tuple comprising the data in the file and the full path to it. """ @spec read_include(t, Path.t, Path.t | nil) :: {String.t, Path.t} def read_include(source, path, cur_dir) do source |> GenServer.call({:read_include, path, cur_dir}) |> handle_result end @doc """ Reads the include file at the given path, given a context library, and returns a tuple comprising the data in the file and the full path to it. """ @spec read_lib_include(t, atom, Path.t) :: {String.t, Path.t} def read_lib_include(source, lib, path) do source |> GenServer.call({:read_lib_include, lib, path}) |> handle_result end @doc """ Stops the source process. """ @spec stop(t) :: :ok def stop(source) do GenServer.cast(source, {:stop}) end defp handle_result({:ok, data, path}), do: {data, path} defp handle_result({:error, code, path}) do raise CompileError, file: path, line: :unknown, description: "Error #{code} while reading source file" end use GenServer defmodule State do @moduledoc false defstruct( source_dir: nil, source_data: %{}, include_dirs: [], include_data: %{}, lib_dirs: %{}, lib_data: %{} ) end def init(opts) do source_dir = Keyword.get(opts, :source_dir, nil) source_data = opts |> Keyword.get_values(:source_data) |> Enum.reduce(%{}, &(add_to_map(&2, &1))) include_dirs = opts |> Keyword.get_values(:include_dir) |> Enum.reduce([], &([&1 | &2])) include_data = opts |> Keyword.get_values(:include_data) |> Enum.reduce(%{}, &(add_to_map(&2, &1))) lib_dirs = opts |> Keyword.get_values(:lib_dir) |> Enum.reduce(%{}, &(add_to_map(&2, &1))) lib_data = opts |> Keyword.get_values(:lib_data) |> Enum.reduce(%{}, &(add_to_map(&2, &1))) {:ok, %State{ source_dir: source_dir, source_data: source_data, include_dirs: include_dirs, include_data: include_data, lib_dirs: lib_dirs, lib_data: lib_data, } } end def handle_call( {:read_source, path}, _from, %State{source_dir: source_dir, source_data: source_data} = state) do dirs = if source_dir == nil, do: [], else: [source_dir] result = read_impl(path, source_data, dirs) {:reply, result, state} end def handle_call( {:read_include, path, cur_dir}, _from, %State{include_dirs: include_dirs, include_data: include_data} = state) do dirs = if cur_dir == nil do include_dirs else [cur_dir | include_dirs] end dirs = [File.cwd! | dirs] result = read_impl(path, include_data, dirs) {:reply, result, state} end def handle_call( {:read_lib_include, lib, path}, _from, %State{lib_data: lib_data, lib_dirs: lib_dirs} = state) do case get_lib_dir(lib_dirs, lib) do {:error, code} -> {:reply, {:error, code, path}, state} {:ok, lib_dir} -> result = read_impl(path, lib_data, [lib_dir]) {:reply, result, state} end end def handle_cast({:stop}, state) do {:stop, :normal, state} end defp read_impl(path, data_map, search_dirs) do case Map.fetch(data_map, path) do {:ok, data} when is_binary(data) -> {:ok, data, path} {:ok, io} when is_pid(io) -> data = io |> IO.read(:all) |> IO.chardata_to_string {:ok, data, path} :error -> Enum.find_value(search_dirs, {:error, :not_found, path}, fn dir -> actual_path = Path.expand(path, dir) if File.exists?(actual_path) do case File.read(actual_path) do {:ok, data} -> {:ok, data, actual_path} {:error, code} -> {:error, code, path} end else false end end) end end defp get_lib_dir(lib_dirs, lib) do case Map.fetch(lib_dirs, lib) do {:ok, dir} -> {:ok, dir} :error -> case :code.lib_dir(lib) do {:error, code} -> {:error, code} dir -> {:ok, dir} end end end defp add_to_map(map, value) when is_map(value), do: Map.merge(map, value) defp add_to_map(map, {key, value}), do: Map.put(map, key, value) defp add_to_map(map, value), do: Map.put(map, nil, value) end
23.185022
77
0.593578
1c8af4dd49ed97b16a65dfd78c5568fdc072c761
1,250
ex
Elixir
lib/ex_clubhouse/model/milestone.ex
pootsbook/exclubhouse
3b93cded0124e4e5df489db4f9262a560595bb8e
[ "MIT" ]
4
2020-03-17T00:42:10.000Z
2021-04-11T16:39:52.000Z
lib/ex_clubhouse/model/milestone.ex
pootsbook/exclubhouse
3b93cded0124e4e5df489db4f9262a560595bb8e
[ "MIT" ]
7
2020-03-21T20:22:13.000Z
2021-12-30T16:32:07.000Z
lib/ex_clubhouse/model/milestone.ex
pootsbook/exclubhouse
3b93cded0124e4e5df489db4f9262a560595bb8e
[ "MIT" ]
4
2020-03-25T18:34:49.000Z
2021-09-13T16:44:00.000Z
defmodule ExClubhouse.Model.Milestone do @moduledoc """ Milestone response model """ alias ExClubhouse.Model @type t :: %__MODULE__{ app_url: binary(), categories: list(Model.Category.t()), completed: boolean(), completed_at: binary() | nil, completed_at_override: binary() | nil, created_at: binary() | nil, description: binary(), entity_type: binary(), id: integer(), name: binary(), position: integer(), started: boolean(), started_at: binary() | nil, started_at_override: binary() | nil, state: binary(), stats: Model.MilestoneStats.t(), updated_at: binary() | nil } defstruct app_url: nil, categories: [], completed: true, completed_at: nil, completed_at_override: nil, created_at: nil, description: nil, entity_type: nil, id: nil, name: nil, position: nil, started: true, started_at: nil, started_at_override: nil, state: nil, stats: nil, updated_at: nil end
27.173913
48
0.5096
1c8b1587d6ea3bde5bbe87da0a1e00719ee52b4a
1,654
ex
Elixir
apps/snitch_api/lib/snitch_api_web/views/product_view.ex
saurabharch/avia
74a82a95cf8bfe8143d1fce8136a3bb7ffc9467c
[ "MIT" ]
null
null
null
apps/snitch_api/lib/snitch_api_web/views/product_view.ex
saurabharch/avia
74a82a95cf8bfe8143d1fce8136a3bb7ffc9467c
[ "MIT" ]
null
null
null
apps/snitch_api/lib/snitch_api_web/views/product_view.ex
saurabharch/avia
74a82a95cf8bfe8143d1fce8136a3bb7ffc9467c
[ "MIT" ]
null
null
null
defmodule SnitchApiWeb.ProductView do use SnitchApiWeb, :view use JaSerializer.PhoenixView alias Snitch.Data.Model.{Product, ProductReview} alias Snitch.Core.Tools.MultiTenancy.Repo location("/products/:slug") attributes([ :name, :description, :available_on, :deleted_at, :discontinue_on, :slug, :meta_description, :meta_keywords, :meta_title, :promotionable, :selling_price, :max_retail_price, :images, :rating_summary, :is_orderable ]) def selling_price(product) do Money.round(product.selling_price, currency_digits: :cash) end def max_retail_price(product) do Money.round(product.max_retail_price, currency_digits: :cash) end def images(product, _conn) do product = product |> Repo.preload(:images) product.images |> Enum.map(fn image -> %{"product_url" => Product.image_url(image.name, product)} end) end def rating_summary(product, _conn) do ProductReview.review_aggregate(product) end def is_orderable(product, _conn) do Product.is_orderable?(product) end has_one( :theme, serializer: SnitchApiWeb.VariationThemeView, include: false ) has_many( :variants, serializer: SnitchApiWeb.ProductView, include: false ) has_many( :options, serializer: SnitchApiWeb.ProductOptionValueView, include: false ) has_many( :reviews, serializer: SnitchApiWeb.ReviewView, include: false ) def render("rating_summary.json-api", %{data: data, id: id}) do %{ links: %{ self: "products/#{id}/rating-summary" }, data: data } end end
19.927711
91
0.674728
1c8b273c10878f24fa838be3e02fcf57ae5efe37
57
ex
Elixir
web/views/page_view.ex
matthewphilyaw/basic_auth_test
9bd6b62c8680ec603314adab940b8840e50b240c
[ "MIT" ]
null
null
null
web/views/page_view.ex
matthewphilyaw/basic_auth_test
9bd6b62c8680ec603314adab940b8840e50b240c
[ "MIT" ]
null
null
null
web/views/page_view.ex
matthewphilyaw/basic_auth_test
9bd6b62c8680ec603314adab940b8840e50b240c
[ "MIT" ]
null
null
null
defmodule FooApi.PageView do use FooApi.Web, :view end
14.25
28
0.77193
1c8b950e654a7e55fa62f1068e9aa32dbda4aa16
1,168
exs
Elixir
test/lib/tilex/rate_limiter_test.exs
plicjo/tilex
f3d9cba7f2ca99c75622cd1a9992508614dd455f
[ "MIT" ]
1
2021-05-27T16:46:34.000Z
2021-05-27T16:46:34.000Z
test/lib/tilex/rate_limiter_test.exs
plicjo/tilex
f3d9cba7f2ca99c75622cd1a9992508614dd455f
[ "MIT" ]
null
null
null
test/lib/tilex/rate_limiter_test.exs
plicjo/tilex
f3d9cba7f2ca99c75622cd1a9992508614dd455f
[ "MIT" ]
null
null
null
defmodule Tilex.RateLimiterTest do use ExUnit.Case, async: false alias Tilex.RateLimiter alias Tilex.DateTimeMock setup do RateLimiter.start_link() :ok end test "it responds to valid calls with true" do DateTimeMock.start_link([]) assert RateLimiter.check(ip: "abc.def.ghi.123") end test "it responds to invalid calls with false" do ip = "1.1.1.1" now = DateTime.utc_now() times = [25, 20, 15, 10, 5, 1] |> Enum.map(fn seconds -> Timex.subtract(now, Timex.Duration.from_seconds(seconds)) end) DateTimeMock.start_link(times) 1..5 |> Enum.each(fn _ -> assert RateLimiter.check(ip: ip) end) assert RateLimiter.check(ip: ip) == false end test "it responds with true if requests are spread over more than 1 minute" do ip = "1.1.1.1" now = DateTime.utc_now() times = [62, 20, 15, 10, 5, 1] |> Enum.map(fn seconds -> Timex.subtract(now, Timex.Duration.from_seconds(seconds)) end) DateTimeMock.start_link(times) 1..5 |> Enum.each(fn _ -> assert RateLimiter.check(ip: ip) end) assert RateLimiter.check(ip: ip) == true end end
22.037736
94
0.640411
1c8ba586acc949afafdaa5734fb1b94ef12aa516
3,428
exs
Elixir
us_address/test/us_address_test.exs
reidmorrison/us_address_service
988bcfbb57fc4cb8a51ffe850527fdbfe1ea4b92
[ "Apache-2.0" ]
2
2021-05-03T20:04:11.000Z
2021-07-12T09:23:20.000Z
us_address/test/us_address_test.exs
reidmorrison/us_address_service
988bcfbb57fc4cb8a51ffe850527fdbfe1ea4b92
[ "Apache-2.0" ]
null
null
null
us_address/test/us_address_test.exs
reidmorrison/us_address_service
988bcfbb57fc4cb8a51ffe850527fdbfe1ea4b92
[ "Apache-2.0" ]
null
null
null
defmodule PostalAddressTest do use ExUnit.Case doctest USAddress test "verify" do address = %{"address" => "2811 Safe Harbor Drive", "city" => "Tampa", "state" => "FL", "zip" => "33618"} verified = USAddress.verify(address) assert verified[:address] == "2811 Safe Harbor Dr" assert verified[:city] == "Tampa" assert verified[:state] == "FL" assert verified[:zip] == "33618" end test "verify with utf-8" do address = %{"address" => "2811 Sëbastián Drîve", "city" => "Tâmpá", "state" => "FĹ", "zip" => "33618"} verified = USAddress.verify(address) assert verified[:address] == "2811 Sebastian Drive" assert verified[:city] == "Tampa" assert verified[:state] == "FL" assert verified[:zip] == "33618" end test "verify non utf-8" do address = %{"address" => "2811 Safe Harbor Drive", "city" => "Tampa", "state" => "FL", "zip" => "33618"} verified = USAddress.verify(address) assert verified[:address] == "2811 Safe Harbor Dr" assert verified[:city] == "Tampa" assert verified[:state] == "FL" assert verified[:zip] == "33618" end test "verify with empty strings" do address = %{"address" => "2811 Safe Harbor Drive", "city" => "Tampa", "state" => "FL", "zip" => ""} verified = USAddress.verify(address) assert verified[:address] == "2811 Safe Harbor Dr" assert verified[:city] == "Tampa" assert verified[:state] == "FL" assert verified[:zip] == "33618" assert verified[:delivery_point] == "33618453411" end test "verify with nil values" do address = %{"address" => "2811 Safe Harbor Drive", "city" => "Tampa", "state" => "FL", "zip" => nil} verified = USAddress.verify(address) assert verified[:address] == "2811 Safe Harbor Dr" assert verified[:city] == "Tampa" assert verified[:state] == "FL" assert verified[:zip] == "33618" assert verified[:delivery_point] == "33618453411" end test "verify with utf8 values" do address = %{"address" => "2004 SAN SEBASTIáN CT", "city" => "HOUSTON", "state" => "TX", "zip" => "77058"} verified = USAddress.verify(address) assert verified[:address] == "2004 San Sebastian Ct" assert verified[:city] == "Houston" assert verified[:state] == "TX" assert verified[:zip] == "77058" assert verified[:delivery_point] == "77058368599" end test "verify with more utf8 values" do address = %{"address" => "6729 àVE E", "city" => "HOUSTON", "state" => "TX", "suite" => nil, "zip" => "77011"} verified = USAddress.verify(address) assert verified[:address] == "6729 Avenue E" assert verified[:city] == "Houston" assert verified[:state] == "TX" assert verified[:zip] == "77011" assert verified[:delivery_point] == "77011353529" end test "verify with no keys" do address = %{} verified = USAddress.verify(address) assert verified[:address] == "" assert verified[:city] == "" assert verified[:state] == "" assert verified[:zip] == "" assert verified[:delivery_point] == "" end test "version" do result = USAddress.version() assert result[:build_number] assert result[:database_date] assert result[:expiration_date] assert result[:initialize_status] assert result[:license_expiration_date] end test "not using a demo license" do version = USAddress.version() refute version[:build_number] =~ " DEMO" end end
32.961538
115
0.626021
1c8bab1a991d1ac8a1201621b781e098252fcf9d
408
ex
Elixir
lib/markdown_server.ex
knewter/markdown_server
0b852d23247589ad23557bf1a205e9d1b9af7dda
[ "Unlicense" ]
null
null
null
lib/markdown_server.ex
knewter/markdown_server
0b852d23247589ad23557bf1a205e9d1b9af7dda
[ "Unlicense" ]
1
2015-12-13T19:55:09.000Z
2015-12-13T19:55:09.000Z
lib/markdown_server.ex
knewter/markdown_server
0b852d23247589ad23557bf1a205e9d1b9af7dda
[ "Unlicense" ]
null
null
null
defmodule MarkdownServer do use Application.Behaviour # See http://elixir-lang.org/docs/stable/Application.Behaviour.html # for more information on OTP Applications def start(_type, _args) do MarkdownServer.Supervisor.start_link end def base_dir do System.get_env("MARKDOWN_SERVER_DIR") || default_base_dir end defp default_base_dir do "./test/support/sample_files/" end end
22.666667
69
0.757353
1c8bb5d296482757ae76cc1e9cc197c5dabf3a74
208
exs
Elixir
test/nanocrawler_web/controllers/page_controller_test.exs
meltingice/nanocrawler-phoenix
2477e8cb63a04d89eeda676c474e9b89c29da0e5
[ "MIT" ]
1
2020-04-19T07:48:46.000Z
2020-04-19T07:48:46.000Z
test/nanocrawler_web/controllers/page_controller_test.exs
meltingice/nanocrawler-phoenix
2477e8cb63a04d89eeda676c474e9b89c29da0e5
[ "MIT" ]
2
2021-03-09T20:27:19.000Z
2021-05-10T17:32:50.000Z
test/nanocrawler_web/controllers/page_controller_test.exs
meltingice/nanocrawler-phoenix
2477e8cb63a04d89eeda676c474e9b89c29da0e5
[ "MIT" ]
null
null
null
defmodule NanocrawlerWeb.PageControllerTest do use NanocrawlerWeb.ConnCase test "GET /", %{conn: conn} do conn = get(conn, "/") assert html_response(conn, 200) =~ "Welcome to Phoenix!" end end
23.111111
60
0.692308
1c8bc774a558ca1755ed33b22cf46d206e74a567
588
ex
Elixir
lib/real_world_web/components/editor/editor_page.ex
razuf/elixir-phoenix-liveview-realworld
182eb845b2b56f146468d9a095a8d5d72fc44f17
[ "MIT" ]
10
2020-09-21T23:24:53.000Z
2022-03-08T02:12:32.000Z
lib/real_world_web/components/editor/editor_page.ex
razuf/elixir-phoenix-liveview-realworld
182eb845b2b56f146468d9a095a8d5d72fc44f17
[ "MIT" ]
null
null
null
lib/real_world_web/components/editor/editor_page.ex
razuf/elixir-phoenix-liveview-realworld
182eb845b2b56f146468d9a095a8d5d72fc44f17
[ "MIT" ]
1
2021-06-26T19:46:09.000Z
2021-06-26T19:46:09.000Z
defmodule RealWorldWeb.EditorPage do use RealWorldWeb, :live_component alias RealWorldWeb.FormErrorList alias RealWorldWeb.EditorForm @impl true def render(assigns) do ~L""" <div class="editor-page"> <div class="container page"> <div class="row"> <div class="col-md-10 offset-md-1 col-xs-12"> <%= live_component @socket, FormErrorList, changeset: @changeset %> <%= live_component @socket, EditorForm, changeset: @changeset, submit: @submit %> </div> </div> </div> </div> """ end end
22.615385
93
0.605442
1c8c004a416d0d50218230b5d652ca0dfd0130b4
774
exs
Elixir
test/commands/user/list_handles_test.exs
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
1,003
2016-02-23T17:21:12.000Z
2022-02-20T14:39:35.000Z
test/commands/user/list_handles_test.exs
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
906
2016-02-22T22:54:19.000Z
2022-03-11T15:19:43.000Z
test/commands/user/list_handles_test.exs
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
95
2016-02-23T13:42:31.000Z
2021-11-30T14:39:55.000Z
defmodule Cog.Test.Commands.User.ListHandlesTest do use Cog.CommandCase, command_module: Cog.Commands.User.ListHandles import Cog.Support.ModelUtilities, only: [user: 1, with_chat_handle_for: 2] setup :with_users test "listing chat handles works", %{users: users} do Enum.each(users, &(with_chat_handle_for(&1, "test"))) payload = new_req() |> send_req() |> unwrap() |> Enum.sort_by(fn(h) -> h[:username] end) assert [%{username: "admin", handle: "admin"}, %{username: "tester", handle: "tester"}] = payload end #### Setup Functions #### defp with_users(_) do [users: [user("admin"), user("tester")]] end end
26.689655
68
0.562016
1c8c1af7c6c36f8b08accf52f994f4af9c3dd383
3,086
ex
Elixir
lib/koans/13_functions.ex
eugenioLopezRamos/elixir-koans-solutions
ac183528275c1b271e66c4cd3a644784b6965335
[ "MIT" ]
1
2020-02-19T12:30:13.000Z
2020-02-19T12:30:13.000Z
lib/koans/13_functions.ex
eugenioLopezRamos/elixir-koans-solutions
ac183528275c1b271e66c4cd3a644784b6965335
[ "MIT" ]
null
null
null
lib/koans/13_functions.ex
eugenioLopezRamos/elixir-koans-solutions
ac183528275c1b271e66c4cd3a644784b6965335
[ "MIT" ]
null
null
null
defmodule Functions do use Koans @intro "Functions" def greet(name) do "Hello, #{name}!" end koan "Functions map arguments to outputs" do assert greet("World") == "Hello, World!" end def multiply(a, b), do: a * b koan "Single line functions are cool, but mind the comma and the colon!" do assert 6 == multiply(2, 3) end def first(foo, bar), do: "#{foo} and #{bar}" def first(foo), do: "Only #{foo}" koan "Functions with the same name are distinguished by the number of arguments they take" do assert first("One", "Two") == "One and Two" assert first("One") == "Only One" end def repeat_again(message, times \\ 5) do String.duplicate(message, times) end koan "Functions can have default argument values" do assert repeat_again("Hello ") == "Hello Hello Hello Hello Hello " assert repeat_again("Hello ", 2) == "Hello Hello " end def sum_up(thing) when is_list(thing), do: :entire_list def sum_up(_thing), do: :single_thing koan "Functions can have guard expressions" do assert sum_up([1, 2, 3]) == :entire_list assert sum_up(1) == :single_thing end def bigger(a,b) when a > b, do: "#{a} is bigger than #{b}" def bigger(a,b) when a <= b, do: "#{a} is not bigger than #{b}" koan "Intricate guards are possible, but be mindful of the reader" do assert bigger(10, 5) == "10 is bigger than 5" assert bigger(4, 27) == "4 is not bigger than 27" end def get_number(0), do: "The number was zero" def get_number(number), do: "The number was #{number}" koan "For simpler cases, pattern matching is effective" do assert get_number(0) == "The number was zero" assert get_number(5) == "The number was 5" end koan "Little anonymous functions are common, and called with a dot" do multiply = fn (a,b) -> a * b end assert multiply.(2,3) == 6 end koan "You can even go shorter, by using capture syntax `&()` and positional arguments" do multiply = &(&1 * &2) assert multiply.(2,3) == 6 end koan "Prefix a string with & to build a simple anonymous greet function" do greet = &"Hi, #{&1}!" assert greet.("Foo") == "Hi, Foo!" end koan "You can build anonymous functions out of any elixir expression by prefixing it with &" do three_times = &[&1, &1, &1] assert three_times.("foo") == ["foo", "foo", "foo"] end def times_five_and_then(number, fun), do: fun.(number*5) def square(number), do: number * number koan "You can pass functions around as arguments. Place an '&' before the name and state the arity" do assert times_five_and_then(2, &square/1) == 100 end koan "The '&' operation is not needed for anonymous functions" do cube = fn number -> number * number * number end assert times_five_and_then(2, cube) == 1000 end koan "The result of a function can be piped into another function as its first argument" do result = "full-name" |> String.split("-") |> Enum.map(&(String.capitalize(&1))) |> Enum.join(" ") assert result == "Full Name" end end
30.554455
104
0.645172
1c8c37141d91e960b6fbff9d1cabdb776775157d
53,482
ex
Elixir
lib/ex_admin/form.ex
spunkedy/ex_admin
a576bead2a030f3dfe7abec0ff610809eb0db06f
[ "MIT" ]
1
2019-11-25T17:53:57.000Z
2019-11-25T17:53:57.000Z
lib/ex_admin/form.ex
leonardzhou/ex_admin
c241e956503c548a472e3ee89751e64a16477638
[ "MIT" ]
null
null
null
lib/ex_admin/form.ex
leonardzhou/ex_admin
c241e956503c548a472e3ee89751e64a16477638
[ "MIT" ]
null
null
null
defmodule ExAdmin.Form do @moduledoc """ Override the default new and edit form pages for an ExAdmin resource. By default, ExAdmin renders the form page without any additional configuration. It renders each column in the model, except the id, inserted_at, and updated_at columns in an attributes table. To customize the new and edit pages, use the `form` macro. For example, the following will show on the id an name fields, as well place a selection column and batch actions row on the page: defmodule MyProject.ExAdmin.Contact do use ExAdmin.Register register_resource MyProject.Contact do form contact do inputs do input contact, :first_name input contact, :last_name input contact, :email input contact, :register_date, type: Date input contact, :category, collection: MyProject.Category.all end inputs "Groups" do inputs :groups, as: :check_boxes, collection: MyProject.Group.all end end end end ## The form command Call form with a name for your resource and a do block. ## The inputs command Calling inputs with a do block displays a field set with the specified inputs from the block. Adding a label to inputs, labels the field set. ## The input command The first argument is input is alway the resource name give to the form command. The second argument is the the field name expressed as an atom. Optionally, a third argument can be a keyword list. ### Override the default label input resource, :name, label: "Customer Name" ### Specify a collection input resource, :category, collection: Repo.all(Category) ### Specify the field names for a collection input resource, :user, fields: [:first_name, :email] ### Specifying type of control input user, :password, type: :password # If you use :naive_datetime or :utc_datetime in your schema instead of Ecto.DateTime input user, :register_datetime, type: DateTime ### Array field support # default tag style input user, :nicknames # multi select restricted to the provided collection input user, :groups, select2: [collection: ~w(Sales Marketing Dev)] # tags style with the extra collection options input user, :groups, select2: [collection: ~w(Sales Marketing Dev)] ### Customizing DateTime fields input user, :start_at, options: [sec: []] Most of the options from the `datetime_select` control from `phoenix_html` should work. ### Map field support Since maps don't have a defined schema, you can define the schema as an option to the input macro. For example: form user do inputs "User Details" do input user, :name end inputs "Statistics" do input user, :stats, schema: [age: :integer, height: :string, birthday: :string] end end ### Array of maps field support Like maps, you must provided the schema for an array of maps. For example: form user do inputs "User Details" do input user, :name end inputs "Addresses" do input user, :addresses, schema: [street: :string, city: :string] end end ## Rendering a has_many :through (many-to-many) relationship The example at the beginning of the chapter illustrates how to add a list of groups, displaying them as check boxes. inputs "Groups" do inputs :groups, as: :check_boxes, collection: MyProject.Group.all end ## Nested attributes ExAdmin supports in-line creation of a has_many, through: (many-to-many) relationship. The example below allows the user to add/delete phone numbers on the contact form using the has_many command. form contact do inputs do input contact, :first_name input contact, :last_name input contact, :email input contact, :category, collection: UcxNotifier.Category.all end inputs "Phone Numbers" do has_many contact, :phone_numbers, fn(p) -> input p, :label, collection: PhoneNumber.labels input p, :number end end end Note: has_many does not yet work with simple one-to-many relationships. # Adding conditional fields The following complicated example illustrates a number of concepts possible in a form definition. The example allows management of an authentication token for a user while on the edit page. First, the `if params[:id] do` condition ensures that the code block only executes for an edit form, and not a new form. Next, the actions command adds in-line content to an inputs block. form user do inputs "User Details" do input user, :name # ... end if params[:id] do inputs "Authentication Token" do actions do user = Repo.get User, params[:id] if user.authentication_token do content content_tag(:li, user.authentication_token, style: "padding: 5px 10px") content content_tag(:li, token_link("Reset Token", :reset, params[:id]), class: "cancel") content content_tag(:li, token_link("Delete Token", :delete, params[:id]), class: "cancel") else content content_tag(:li, token_link("Create Token", :create, params[:id]), class: "cancel", style: "padding-left: 20px") end end end end end ## The javascript command Use the javascript command to add javascript to the form page. For example, the following adds a change handler to get a list of assets using an ajax call: javascript do \""" $(document).ready(function() { $('#asset_assetable_type_id').change(function() { $.get('/assets/'+$(this).val()+'/assetables?format=js'); }); }); \""" end """ use ExAdmin.Adminlog import ExAdmin.Utils import ExAdmin.Helpers import ExAdmin.DslUtils import ExAdmin.Form.Fields import ExAdmin.ViewHelpers, only: [escape_javascript: 1] require IEx import ExAdmin.Theme.Helpers alias ExAdmin.Schema import Kernel, except: [div: 2] use Xain import Xain, except: [input: 2, input: 1] defmacro __using__(_) do quote do import unquote(__MODULE__) import Xain, except: [input: 1] end end ################ # DSL Macros @doc """ Customize the form page. Use the form command to customize the new and edit page forms. Pass a name for the resource to be created or modified. """ defmacro form(resource, do: contents) do quote location: :keep, bind_quoted: [resource: escape(resource), contents: escape(contents)] do import ExAdmin.Index, only: [index: 1] def form_view(var!(conn), unquote(resource) = var!(resource), var!(params) = params) do import ExAdmin.Register, except: [actions: 1] var!(input_blocks, ExAdmin.Form) = [] var!(script_block, ExAdmin.Form) = nil unquote(contents) items = var!(input_blocks, ExAdmin.Form) |> Enum.reverse() script_block = var!(script_block, ExAdmin.Form) Module.concat(var!(conn).assigns.theme, Form).build_form( var!(conn), var!(resource), items, var!(params), script_block, ExAdmin.Form.global_script() ) end def get_blocks(var!(conn), unquote(resource) = var!(resource), var!(params) = _params) do # TODO: do we need the passed params? they are not used. _ = {var!(conn), var!(resource), var!(params)} import ExAdmin.Register, except: [actions: 1] var!(input_blocks, ExAdmin.Form) = [] var!(script_block, ExAdmin.Form) = nil unquote(contents) var!(input_blocks, ExAdmin.Form) |> Enum.reverse() end def ajax_view(conn, params, resource, resources, block) do defn = conn.assigns.defn field_name = String.to_atom(params[:field_name]) model_name = model_name(resource) ext_name = ext_name(model_name, field_name) view = markup safe: true do ExAdmin.Form.Fields.ajax_input_collection( resource, resources, model_name, field_name, params[:id1], params[:nested2], block, conn.params ) end ~s/$('##{ext_name}_input').html("#{escape_javascript(view)}");/ end end end @doc """ Add an fieldset to the form """ defmacro inputs(opts) do quote(do: inputs("", unquote(opts))) end @doc """ Add a has_many field to a form. """ defmacro inputs(name, opts, do: block) do quote location: :keep do import Xain, except: [input: 1] # inputs_save = var!(inputs, ExAdmin.Form) var!(inputs, ExAdmin.Form) = [] unquote(block) items = var!(inputs, ExAdmin.Form) |> Enum.reverse() # var!(inputs, ExAdmin.Form) = inputs_save input_block = %{type: :inputs, name: unquote(name), inputs: items, opts: unquote(opts)} var!(input_blocks, ExAdmin.Form) = [input_block | var!(input_blocks, ExAdmin.Form)] end end @doc """ Add a named fieldset to a form. Works the same as inputs/1, but labels the fieldset with name """ defmacro inputs(name, do: block) do quote location: :keep do import Xain, except: [input: 1] # inputs_save = var!(inputs, ExAdmin.Form) var!(inputs, ExAdmin.Form) = [] unquote(block) items = var!(inputs, ExAdmin.Form) |> Enum.reverse() # var!(inputs, ExAdmin.Form) = inputs_save input_block = %{type: :inputs, name: unquote(name), inputs: items, opts: []} var!(input_blocks, ExAdmin.Form) = [input_block | var!(input_blocks, ExAdmin.Form)] end end @doc """ Add a has_many field to a form. """ defmacro inputs(name, opts) do quote location: :keep do import Xain, except: [input: 1] opts = Enum.into(unquote(opts), %{}) item = %{type: :inputs, name: unquote(name), opts: opts} var!(inputs, ExAdmin.Form) = [item | var!(inputs, ExAdmin.Form)] end end @doc """ Display an input field on the form. Display all types of form inputs. ## Options * `:type` - Sets the type of the control (`:password`, `:hidden`, etc) * `:label` - Sets a custom label * `:collection` - Sets the collection to render for a `belongs_to` relationship * `:fields` - Sets a list of fields to be used in a select control. For example `input post :user, fields: [:first_name, :last_name]` would render a control like: <select> <option id="1">José Valim</option> <option id="2">Chris McCord</option> </select> * `:prompt` - Sets a HTML placeholder * `:change` - Sets change handler to a control. When set to a string, the string is assumed to be javascript and added with the control. When a keyword list, the list is used to define what should happen when the input changes. See the section below on valid keywords. * `:ajax` - Used for ajax controls. See ajax below * `:display` - When set to false, the control and its label are hidden with `style="display: none"`. Use this to hide inputs that will later be displayed with javascript or an ajax request * `:as` - Sets the type of collection. Valid options are: * `:check_boxes` - Use check boxes * `:radio` - Use radio buttons ## Ajax controls Use the ajax: true, change: [...] do allow dynamic updating of nested collection inputs. For example, assume a page for purchasing a product, where the product has a number of options and each option has different possible color selections. When option 1 is selected, they have the choice of red or black. If option 2 is selected, they have the choice of red or green. So, based on the option selected, the color select needs to be dynamically reloaded. TBD: Complete this """ defmacro input(resource, name, opts \\ []) do quote do opts = Enum.into(unquote(opts), %{}) item = %{type: :input, resource: unquote(resource), name: unquote(name), opts: opts} var!(inputs, ExAdmin.Form) = [item | var!(inputs, ExAdmin.Form)] end end @doc """ Display a nested resource on the form. Adds management of a has_many resource to the page, allowing in-line addition, editing, and deletion of the nested resource. """ defmacro has_many(resource, name, opts \\ [], fun \\ nil) do quote do opts = ExAdmin.DslUtils.fun_to_opts(unquote(opts), unquote(fun)) item = %{type: :has_many, resource: unquote(resource), name: unquote(name), opts: opts} var!(inputs, ExAdmin.Form) = [item | var!(inputs, ExAdmin.Form)] end end @doc """ Add an action block to a form TBD: Add more description here """ defmacro actions(do: block) do quote do var!(inputs, ExAdmin.Form) = [] var!(items, ExAdmin.Form) = [] unquote(block) items = var!(items, ExAdmin.Form) |> Enum.reverse() item = %{type: :actions, name: "", items: items} var!(inputs, ExAdmin.Form) = [item | var!(inputs, ExAdmin.Form)] end end @doc """ Add a HTML content block to a form For example: content do \""" <div>Something here</div> <div>More stuff here</div> \""" end """ defmacro content(do: block) do quote do contents = unquote(block) item = %{type: :content, name: "", content: unquote(block), opts: []} var!(inputs, ExAdmin.Form) = [item | var!(inputs, ExAdmin.Form)] end end @doc """ Add HTML content to a form. Can be called multiple times to append HTML content for a page For example: content content_tag(:li, user.authentication_token, style: "padding: 5px 10px") content content_tag(:li, token_link("Reset Token", :reset, params[:id]), class: "cancel") content content_tag(:li, token_link("Delete Token", :delete, params[:id]), class: "cancel") """ defmacro content(items, opts \\ quote(do: [])) do quote do item = %{type: :content, content: unquote(items), opts: unquote(opts)} var!(items, ExAdmin.Form) = [item | var!(items, ExAdmin.Form)] end end @doc """ Add javascript to the form Adds a block of javascript code to the form. Typically used to add change or click handlers to elements on the page """ defmacro javascript(do: block) do quote do var!(script_block, ExAdmin.Form) = unquote(block) end end ################# # Functions defp build_item(resource, defn, name) do Adminlog.debug("build_item 1 ....") case translate_field(defn, name) do field when field == name -> %{type: :input, resource: resource, name: name, opts: %{}} {:map, _field} -> %{type: :input, resource: resource, name: name, opts: %{map: true}} {:maps, _field} -> %{type: :input, resource: resource, name: name, opts: %{maps: true}} field -> case resource.__struct__.__schema__(:association, field) do %Ecto.Association.BelongsTo{cardinality: :one, queryable: assoc} -> collection = Application.get_env(:ex_admin, :repo).all(assoc) %{type: :input, resource: resource, name: field, opts: %{collection: collection}} _ -> nil end end end def setup_resource(resource, params, model_name) do model_name = String.to_atom(model_name) case params[model_name] do nil -> resource model_params -> struct(resource, Map.to_list(model_params)) end end def put_script_block(script_block) do if script_block do Xain.script type: "text/javascript" do text("\n" <> script_block <> "\n") end end end def build_scripts(list) do head = "$(function() {\n" script = for i <- list, is_tuple(i), into: head, do: build_script(i) script <> "});" end def build_script({:change, %{id: id, script: script}}) do """ $(document).on('change','##{id}', function() { #{script} }); """ end def build_script(_other), do: "" def get_action(resource, mode) do case mode do :new -> admin_resource_path(resource, :create) :edit -> admin_resource_path(resource, :update) end end defp get_put_fields(:edit) do Xain.input(name: "_method", value: "put", type: "hidden") end defp get_put_fields(_), do: nil def build_hidden_block(_conn, mode) do csrf = Plug.CSRFProtection.get_csrf_token() div style: "margin:0;padding:0;display:inline" do Xain.input(name: "utf8", type: :hidden, value: "✓") Xain.input(type: :hidden, name: "_csrf_token", value: csrf) get_put_fields(mode) end end def build_main_block(conn, resource, model_name, schema) do errors = Phoenix.Controller.get_flash(conn, :inline_error) for item <- schema do item = put_in(item, [:required], conn.assigns[:ea_required] || []) build_item(conn, item, resource, model_name, errors) end |> flatten end defp flatten(list) when is_list(list), do: List.flatten(list) defp flatten(other), do: [other] @hidden_style [style: "display: none"] defp check_display(opts) do if Map.get(opts, :display, true), do: [], else: @hidden_style end defp check_params(display_style, resource, params, model_name, field_name, _ajax) do cond do params["id"] -> [] params[model_name][params_name(resource, field_name, params)] -> [] true -> display_style end end defp field_type(resource, field_name) do field_type_matching = Application.get_env(:ex_admin, :field_type_matching) || %{} original_ft = resource.__struct__.__schema__(:type, field_name) Map.get(field_type_matching, original_ft, original_ft) end defp params_name(resource, field_name, _params) do case resource.__struct__.__schema__(:association, field_name) do %{cardinality: :one, owner_key: owner_key} -> Atom.to_string(owner_key) %{cardinality: :many, owner_key: owner_key, through: [_, name]} -> Atom.to_string(name) <> "_" <> Inflex.pluralize(Atom.to_string(owner_key)) _ -> Atom.to_string(field_name) end end @doc false def wrap_item(resource, field_name, model_name, label, error, opts, params, required, contents) do as = Map.get(opts, :as) ajax = Map.get(opts, :ajax) ext_name = ext_name(model_name, field_name) display_style = check_display(opts) |> check_params(resource, params, model_name, field_name, ajax) {label, hidden} = case label do {:hidden, l} -> {l, @hidden_style} l when l in [:none, false] -> {"", @hidden_style} l -> {l, display_style} end {error, hidden} = if error in [nil, [], false] do {"", hidden} else {"error ", []} end { theme_module(Form).theme_wrap_item( field_type(resource, field_name), ext_name, label, hidden, ajax, error, contents, as, required ), ext_name } end def wrap_item_type(type, label, ext_name, contents, error, required) do ExAdmin.theme().wrap_item_type(type, label, ext_name, contents, error, required) end defp build_select_binary_tuple_list( collection, item, field_name, resource, model_name, ext_name ) do html_opts = item[:opts][:html_opts] || [] html_opts = Keyword.merge([name: "#{model_name}[#{field_name}]"], html_opts) select "##{ext_name}_id.form-control", html_opts do handle_prompt(field_name, item) for item <- collection do {value, name} = case item do {value, name} -> {value, name} other -> {other, other} end selected = if Map.get(resource, field_name) == value, do: [selected: :selected], else: [] option(name, [value: value] ++ selected) end end end @doc false def build_item(_conn, %{type: :script, contents: contents}, _resource, _model_name, _errors) do Adminlog.debug("build_item 2:") script type: "javascript" do text("\n" <> contents <> "\n") end end def build_item( conn, %{type: :input, field_type: :map, name: field_name, resource: _resource} = item, resource, model_name, _error ) do Adminlog.debug("build_item 11: #{inspect(field_name)}") schema = get_schema(item, field_name) data = Map.get(resource, field_name, model_name) || %{} for {field, type} <- schema do build_input(conn, type, field, field_name, data, model_name) end |> Enum.join("\n") end def build_item( conn, %{type: :input, field_type: {:array, :map}, name: field_name, resource: _resource} = item, resource, model_name, error ) do Adminlog.debug("build_item 12: #{inspect(field_name)}") schema = get_schema(item, field_name) human_label = "#{humanize(field_name) |> Inflex.singularize()}" new_record_name_var = new_record_name(field_name) div ".has_many.#{field_name}" do {contents, html} = theme_module(conn, Form).build_inputs_has_many(field_name, human_label, fn -> resource_contents = (Map.get(resource, field_name) || []) |> Enum.with_index() |> Enum.map(fn {res, inx} -> errors = map_array_errors(error, field_name, inx) html = theme_module(conn, Form).theme_map_field_set( conn, res, schema, inx, field_name, model_name, errors ) html end) fieldset_contents = theme_module(conn, Form).theme_map_field_set( conn, nil, schema, new_record_name(field_name), field_name, model_name, nil ) {fieldset_contents, resource_contents} end) {_, onclick} = Phoenix.HTML.html_escape( theme_module(conn, Form).has_many_insert_item(contents, new_record_name_var) ) markup do html theme_module(conn, Form).theme_button( "Add New #{human_label}", href: "#", onclick: onclick, type: ".btn-primary" ) end end end @doc """ Private: Build a belongs_to control. Generate a select box for a belongs_to control. """ def build_item( conn, %{type: :input, name: field_name, resource: _resource, opts: %{collection: collection}} = item, resource, model_name, error ) do Adminlog.debug("build_item 3: #{inspect(field_name)}") # IO.puts "build_item 3: #{inspect field_name}" collection = if is_function(collection), do: collection.(conn, resource), else: collection module = resource.__struct__ errors_field_name = if field_name in module.__schema__(:associations) do Map.get(module.__schema__(:association, field_name), :owner_key) else field_name end required = if errors_field_name in (conn.assigns[:ea_required] || []), do: true, else: false errors = get_errors(error, errors_field_name) label = Map.get(item[:opts], :label, field_name) onchange = Map.get(item[:opts], :change) binary_tuple = binary_tuple?(collection) {html, _id} = wrap_item( resource, field_name, model_name, label, errors, item[:opts], conn.params, required, fn ext_name -> item = update_in(item[:opts], &(Map.delete(&1, :change) |> Map.delete(:ajax))) markup do if binary_tuple do build_select_binary_tuple_list( collection, item, field_name, resource, model_name, ext_name ) else input_collection( resource, collection, model_name, field_name, nil, nil, item, conn.params, error ) end build_errors(errors, item[:opts][:hint]) end end ) id = ext_name(model_name, field_name) value = case onchange do script when is_binary(script) -> {:change, %{id: id <> "_id", script: onchange}} list when is_list(list) -> update = Keyword.get(list, :update) params = Keyword.get(list, :params) if update do route_path = admin_resource_path(resource.__struct__, :index) target = pluralize(field_name) nested = pluralize(update) {extra, param_str} = case params do atom when is_atom(atom) -> extra_javascript(model_name, atom, atom) [{param, attr}] -> extra_javascript(model_name, param, attr) _ -> {"", ""} end control_id = "#{model_name}_#{update}_input" get_cmd = if resource.id do "$.get('#{route_path}/#{resource.id}/#{target}/'+$(this).val()+'/#{nested}" else "$.get('#{route_path}/#{target}/'+$(this).val()+'/#{nested}" end script = "$('##{control_id}').show();\n" <> extra <> "console.log('show #{control_id}');\n" <> get_cmd <> "/?field_name=#{update}#{param_str}&format=js');\n" {:change, %{id: id <> "_id", script: script}} end _ -> nil end if onchange do {html, value} else html end end def build_item(conn, %{type: :actions, items: items}, resource, model_name, errors) do Adminlog.debug("build_item 4: #{inspect(model_name)}") fieldset ".actions" do for i <- items do build_item(conn, i, resource, model_name, errors) end end end def build_item(_conn, %{type: :content, content: content}, _resource, _model_name, _errors) when is_binary(content) do Adminlog.debug("build_item 5.") text(content) end def build_item(_conn, %{type: :content, content: content}, _resource, _model_name, _errors) do Adminlog.debug("build_item 6.") text(elem(content, 1)) end def build_item( conn, %{type: :input, resource: _resource, name: field_name, opts: opts}, resource, model_name, errors ) do Adminlog.debug("build_item 7: #{inspect(field_name)}") errors = get_errors(errors, field_name) label = get_label(field_name, opts) required = if field_name in (conn.assigns[:ea_required] || []), do: true, else: false {html, _id} = wrap_item( resource, field_name, model_name, label, errors, opts, conn.params, required, fn ext_name -> field_type = opts[:type] || field_type(resource, field_name) [ build_control(field_type, resource, opts, model_name, field_name, ext_name), build_errors(errors, opts[:hint]) ] end ) html end def build_item( conn, %{type: :has_many, resource: _resource, name: field_name, opts: %{fun: fun}}, resource, model_name, errors ) do Adminlog.debug("build_item 8: #{inspect(field_name)}") field_field_name = "#{field_name}_attributes" human_label = "#{humanize(field_name) |> Inflex.singularize()}" new_record_name_var = new_record_name(field_name) div ".has_many.#{field_name}" do {contents, html} = theme_module(conn, Form).build_inputs_has_many(field_name, human_label, fn -> resource_content = get_resource_field2(resource, field_name) |> Enum.with_index() |> Enum.map(fn {res, inx} -> fields = fun.(res) |> Enum.reverse() ext_name = "#{model_name}_#{field_field_name}_#{inx}" res = cond do is_tuple(res) -> elem(res, 1) true -> res end {new_inx, html} = build_has_many_fieldset( conn, res, fields, inx, ext_name, field_name, field_field_name, model_name, errors ) res_id = ExAdmin.Schema.get_id(res) markup do html Xain.input( id: "#{ext_name}_id", name: "#{model_name}[#{field_field_name}][#{new_inx}][id]", value: "#{res_id}", type: :hidden ) end end) ext_name = "#{model_name}_#{field_field_name}_#{new_record_name_var}" {assoc_model, _} = assoc_model_tuple = ExAdmin.Repo.get_assoc_model(resource, field_name) fields = fun.(assoc_model_tuple) |> Enum.reverse() {_, fieldset_contents} = build_has_many_fieldset( conn, assoc_model.__struct__, fields, new_record_name_var, ext_name, field_name, field_field_name, model_name, errors ) {fieldset_contents, resource_content} end) html {_, onclick} = Phoenix.HTML.html_escape( theme_module(conn, Form).has_many_insert_item(contents, new_record_name_var) ) theme_module(conn, Form).theme_button( "Add New #{human_label}", href: "#", onclick: onclick, type: ".btn-primary" ) end end @doc """ Handle building an inputs :name, as: ... """ def build_item( conn, %{type: :inputs, name: name, opts: %{collection: collection} = opts}, resource, model_name, errors ) when is_atom(name) do Adminlog.debug("build_item 9: #{inspect(name)}") collection = if is_function(collection), do: collection.(conn, resource), else: collection errors = get_errors(errors, name) name_ids = "#{Atom.to_string(name) |> Inflex.singularize()}_ids" name_str = "#{model_name}[#{name_ids}][]" required = get_required(name, opts) theme_module(conn, Form).build_inputs_collection(model_name, name, name_ids, required, fn -> markup do Xain.input(name: name_str, type: "hidden", value: "") if opts[:as] == :check_boxes do build_checkboxes(conn, name, collection, opts, resource, model_name, errors, name_ids) else assoc_ids = get_resource_field2(resource, name) |> Enum.map(&Schema.get_id(&1)) select id: "#{model_name}_#{name_ids}", class: "form-control", multiple: "multiple", name: name_str do for opt <- collection do opt_id = Schema.get_id(opt) selected = if opt_id in assoc_ids, do: [selected: "selected"], else: [] display_name = display_name(opt) option("#{display_name}", [value: "#{opt_id}"] ++ selected) end end end build_errors(errors, opts[:hint]) end end) end @doc """ Setups the default collection on a inputs dsl request and then calls build_item again with the collection added """ def build_item( conn, %{type: :inputs, name: name, opts: %{as: _type}} = options, resource, model_name, errors ) when is_atom(name) do # Get the model from the atom name mod = name |> Atom.to_string() |> String.capitalize() |> Inflex.singularize() |> String.to_atom() module = Application.get_env(:ex_admin, :module) |> Module.concat(mod) opts = put_in(options, [:opts, :collection], apply(module, :all, [])) # call the build item with the default collection build_item(conn, opts, resource, model_name, errors) end @doc """ Handle building the items for an input block. This is where each of the fields will be build """ def build_item(conn, %{type: :inputs, name: _field_name} = item, resource, model_name, errors) do opts = Map.get(item, :opts, []) Adminlog.debug("build_item 10: #{inspect(_field_name)}") theme_module(conn, Form).form_box(item, opts, fn -> theme_module(conn, Form).theme_build_inputs(item, opts, fn -> for inpt <- item[:inputs] do type = resource.__struct__.__schema__(:type, inpt[:name]) item = put_in(inpt, [:field_type], type) build_item(conn, item, resource, model_name, errors) end end) end) end defp build_checkboxes(conn, name, collection, _opts, resource, model_name, errors, name_ids) do theme_module(conn, Form).wrap_collection_check_boxes(fn -> for opt <- collection do opt_id = Schema.get_id(opt) name_str = "#{model_name}[#{name_ids}][#{opt_id}]" selected = cond do errors != nil -> # error and selected in params request_params = Map.get(conn, :body_params, nil) ids = Map.get(request_params, model_name, %{}) |> Map.get(name_ids, []) |> ExAdmin.EctoFormMappers.checkboxes_to_ids() Integer.to_string(opt_id) in ids true -> assoc_ids = Enum.map(get_resource_field2(resource, name), &Schema.get_id(&1)) # select and no error opt_id in assoc_ids end display_name = display_name(opt) theme_module(conn, Form).collection_check_box(display_name, name_str, opt_id, selected) end end) end defp get_schema(item, field_name) do schema = item[:opts][:schema] unless schema, do: raise("Can't render map without schema #{inspect(field_name)}") schema end def build_input(conn, type, field, field_name, data, model_name, errors \\ nil, index \\ nil) do field = to_string(field) error = if errors in [nil, [], false], do: "", else: ".has-error" {inx, id} = if is_nil(index) do {"", "#{model_name}_#{field_name}_#{field}"} else {"[#{index}]", "#{model_name}_#{field_name}_#{index}_#{field}"} end name = "#{model_name}[#{field_name}]#{inx}[#{field}]" label = humanize(field) theme_module(conn, Form).build_map(id, label, index, error, fn class -> markup do [] |> Keyword.put(:type, input_type(type)) |> Keyword.put(:class, class) |> Keyword.put(:id, id) |> Keyword.put(:name, name) |> Keyword.put(:value, data[field]) |> Xain.input() build_errors(errors, nil) end end) end defp input_type(:string), do: "text" defp input_type(:integer), do: "number" defp input_type(_), do: "text" @doc false def build_control(:boolean, resource, opts, model_name, field_name, ext_name) do opts = unless Map.get(resource, field_name) in [false, nil, "false"] do Map.put_new(opts, :checked, "checked") else opts end opts = opts |> Map.put_new(:type, :checkbox) |> Map.put_new(:value, "true") |> Map.put_new(:name, "#{model_name}[#{field_name}]") |> Map.put_new(:id, ext_name) |> Map.to_list() markup do Xain.input(type: :hidden, value: "false", name: "#{model_name}[#{field_name}]") Xain.input(opts) end end # def build_control(Ecto.DateTime, resource, opts, model_name, field_name, _ext_name) do # %{name: model_name, model: resource, id: model_name, class: "form-control"} # |> datetime_select(field_name, Map.get(opts, :options, [])) # end def build_control(DateTime, resource, opts, model_name, field_name, _ext_name) do %{name: model_name, model: resource, id: model_name, class: "form-control"} |> datetime_select(field_name, Map.get(opts, :options, [])) end def build_control(NaiveDateTime, resource, opts, model_name, field_name, _ext_name) do %{name: model_name, model: resource, id: model_name, class: "form-control"} |> datetime_select(field_name, Map.get(opts, :options, [])) end # def build_control(Ecto.Date, resource, opts, model_name, field_name, _ext_name) do # %{name: model_name, model: resource, id: model_name, class: "form-control"} # |> date_select(field_name, Map.get(opts, :options, [])) # end def build_control(Ecto.Time, resource, opts, model_name, field_name, _ext_name) do %{name: model_name, model: resource, id: model_name, class: "form-control"} |> time_select(field_name, Map.get(opts, :options, [])) end def build_control(Elixir.Date, resource, opts, model_name, field_name, _ext_name) do %{name: model_name, model: resource, id: model_name, class: "form-control"} |> date_select(field_name, Map.get(opts, :options, [])) end def build_control(Elixir.Time, resource, opts, model_name, field_name, _ext_name) do %{name: model_name, model: resource, id: model_name, class: "form-control"} |> time_select(field_name, Map.get(opts, :options, [])) end def build_control(:text, resource, opts, model_name, field_name, ext_name) do value = Map.get(resource, field_name, "") |> escape_value options = opts |> Map.put(:class, "form-control") |> Map.put_new(:name, "#{model_name}[#{field_name}]") |> Map.put_new(:id, ext_name) |> Map.delete(:display) |> Map.to_list() Xain.textarea(value, options) end def build_control({:array, type}, resource, opts, model_name, field_name, ext_name) when type in ~w(string integer)a do name = "#{model_name}-#{field_name}" # currently we only support select 2 opts = Map.put_new(opts, :select2, tags: true) ctrl_opts = opts |> Map.put(:class, "form-control #{name}") |> Map.put(:multiple, true) |> Map.put_new(:name, "#{model_name}[#{field_name}][]") |> Map.put_new(:id, ext_name) |> Map.delete(:display) |> Map.delete(:select2) |> Map.to_list() options = case Map.get(resource, field_name, []) do nil -> [] list when is_list(list) -> list string when is_binary(string) -> String.split(string, " ") end build_array_control_select2(opts[:select2], name) |> build_array_control_control(ctrl_opts, options) |> build_array_control_block end def build_control({:embed, e}, resource, _opts, model_name, field_name, ext_name) do embed_content = Map.get(resource, field_name) || e.related.__struct__ embed_module = e.related embed_module.__schema__(:fields) |> Enum.map(&{&1, embed_module.__schema__(:type, &1)}) |> Enum.map(fn {field, type} -> [ label(Atom.to_string(field)), build_control( type, embed_content, %{}, "#{model_name}[#{field_name}]", field, "#{ext_name}_#{field}" ) ] end) end def build_control(type, resource, opts, model_name, field_name, ext_name) do {field_type, value} = cond do type == :file || type |> Kernel.to_string() |> String.ends_with?(".Type") -> val = Map.get(resource, field_name, %{}) || %{} {:file, Map.get(val, :filename, "")} true -> {:text, Map.get(resource, field_name, "")} end value = ExAdmin.Render.to_string(value) Map.put_new(opts, :type, field_type) |> Map.put(:class, "form-control") |> Map.put_new(:maxlength, "255") |> Map.put_new(:name, "#{model_name}[#{field_name}]") |> Map.put_new(:id, ext_name) |> Map.put_new(:value, value |> escape_value) |> Map.delete(:display) |> Map.to_list() |> Xain.input() end defp build_array_control_control({collection, script}, ctrl_opts, options) do select = Xain.select ctrl_opts do Enum.map(options, fn opt -> Xain.option(opt, value: opt, selected: "selected", style: "color: #333") end) ++ Enum.map(collection, fn opt -> Xain.option(opt, value: opt) end) end {select, script} end defp build_array_control_block({select, nil}), do: select defp build_array_control_block({select, script}), do: [select, script] defp build_array_control_select2(nil, _), do: {nil, []} defp build_array_control_select2(select2, name) do Keyword.pop(select2, :collection, []) |> build_array_control_select2_script_opts |> build_array_control_select2_script(name) end def build_array_control_select2_script_opts({collection, true}) do {collection, "{}"} end def build_array_control_select2_script_opts({collection, list}) when is_list(list) do args = Enum.reduce(list, [], fn {k, v}, acc -> ["#{k}: #{v}" | acc] end) |> Enum.reverse() |> Enum.join(", ") {collection, "{#{args}}"} end def build_array_control_select2_script({collection, options}, name) do script = Xain.script do """ $(document).ready(function() { $(".#{name}").select2(#{options}); }) """ end {collection, script} end def datetime_select(form, field_name, opts \\ []) do value = value_from(form, field_name) builder = Keyword.get(opts, :builder) || fn b -> markup do date_builder(b, opts) span(".date-time-separator") time_builder(b, opts) end end builder.(datetime_builder(form, field_name, date_value(value), time_value(value), opts)) end def date_select(form, field_name, opts \\ []) do value = Keyword.get(opts, :value, value_from(form, field_name) || Keyword.get(opts, :default)) builder = Keyword.get(opts, :builder) || (&date_builder(&1, opts)) builder.(datetime_builder(form, field_name, date_value(value), nil, opts)) end defp date_builder(b, _opts) do markup do b.(:year, []) span(".date-separator") b.(:month, []) span(".date-separator") b.(:day, []) end end defp date_value(%{"year" => year, "month" => month, "day" => day}), do: %{year: year, month: month, day: day} defp date_value(%{year: year, month: month, day: day}), do: %{year: year, month: month, day: day} defp date_value({{year, month, day}, _}), do: %{year: year, month: month, day: day} defp date_value({year, month, day}), do: %{year: year, month: month, day: day} defp date_value(nil), do: %{year: nil, month: nil, day: nil} defp date_value(other), do: raise(ArgumentError, "unrecognized date #{inspect(other)}") def time_select(form, field, opts \\ []) do value = Keyword.get(opts, :value, value_from(form, field) || Keyword.get(opts, :default)) builder = Keyword.get(opts, :builder) || (&time_builder(&1, opts)) builder.(datetime_builder(form, field, nil, time_value(value), opts)) end defp time_builder(b, opts) do markup do b.(:hour, []) span(".time-separator") b.(:min, []) if Keyword.get(opts, :sec) do markup do span(".time-separator") b.(:sec, []) end end if Keyword.get(opts, :usec) do markup do span(".time-separator") b.(:usec, []) end end end end defp time_value(%{"hour" => hour, "min" => min} = map), do: %{hour: hour, min: min, sec: Map.get(map, "sec", 0), usec: Map.get(map, "usec", 0)} defp time_value(%{hour: hour, min: min} = map), do: %{hour: hour, min: min, sec: Map.get(map, :sec, 0), usec: Map.get(map, :usec, 0)} defp time_value(%{hour: hour, minute: min} = map), do: %{ hour: hour, min: min, sec: Map.get(map, :second, 0), usec: elem(Map.get(map, :microsecond, {0, 0}), 0) } defp time_value({_, {hour, min, sec, usec}}), do: %{hour: hour, min: min, sec: sec, usec: usec} defp time_value({hour, min, sec, usec}), do: %{hour: hour, min: min, sec: sec, usec: usec} defp time_value({_, {hour, min, sec}}), do: %{hour: hour, min: min, sec: sec, usec: nil} defp time_value({hour, min, sec}), do: %{hour: hour, min: min, sec: sec, usec: nil} defp time_value(nil), do: %{hour: nil, min: nil, sec: nil, usec: nil} defp time_value(other), do: raise(ArgumentError, "unrecognized time #{inspect(other)}") @months [ {"January", "1"}, {"February", "2"}, {"March", "3"}, {"April", "4"}, {"May", "5"}, {"June", "6"}, {"July", "7"}, {"August", "8"}, {"September", "9"}, {"October", "10"}, {"November", "11"}, {"December", "12"} ] map = &Enum.map(&1, fn i -> i = Integer.to_string(i) {String.pad_leading(i, 2, "0"), i} end) @days map.(1..31) @hours map.(0..23) @minsec map.(0..59) @usec map.(0..999) defp datetime_builder(form, field, date, time, parent) do id = Keyword.get(parent, :id, id_from(form, field)) name = Keyword.get(parent, :name, name_from(form, field)) fn :year, opts when date != nil -> {year, _, _} = :erlang.date() {value, opts} = datetime_options(:year, (year - 5)..(year + 5), id, name, parent, date, opts) build_select(:datetime, :year, value, opts) :month, opts when date != nil -> {value, opts} = datetime_options(:month, @months, id, name, parent, date, opts) build_select(:datetime, :month, value, opts) :day, opts when date != nil -> {value, opts} = datetime_options(:day, @days, id, name, parent, date, opts) build_select(:datetime, :day, value, opts) :hour, opts when time != nil -> {value, opts} = datetime_options(:hour, @hours, id, name, parent, time, opts) build_select(:datetime, :hour, value, opts) :min, opts when time != nil -> {value, opts} = datetime_options(:min, @minsec, id, name, parent, time, opts) build_select(:datetime, :min, value, opts) :sec, opts when time != nil -> {value, opts} = datetime_options(:sec, @minsec, id, name, parent, time, opts) build_select(:datetime, :sec, value, opts) :usec, opts when time != nil -> {value, opts} = datetime_options(:usec, @usec, id, name, parent, time, opts) build_select(:datetime, :usec, value, opts) end end defp build_select(_name, type, value, opts) do value = case value do _first.._last -> Enum.map(value, fn x -> val = Integer.to_string(x) {val, val} end) _ -> value end select "", [{:class, "form-control date-time"} | opts] do if opts[:prompt], do: handle_prompt(type, opts: %{prompt: opts[:prompt]}) current_value = "#{opts[:value]}" Enum.map(value, fn {k, v} -> selected = if v == current_value, do: [selected: "selected"], else: [] option(k, [{:value, v} | selected]) end) end end defp datetime_options(type, values, id, name, parent, datetime, opts) do opts = Keyword.merge(Keyword.get(parent, type, []), opts) suff = Atom.to_string(type) {value, opts} = Keyword.pop(opts, :options, values) { value, opts |> Keyword.put_new(:id, id <> "_" <> suff) |> Keyword.put_new(:name, name <> "[" <> suff <> "]") |> Keyword.put_new(:value, Map.get(datetime, type)) } end defp value_from(%{model: resource}, field_name) do Map.get(resource, field_name, "") end defp id_from(%{id: id}, field), do: "#{id}_#{field}" defp id_from(name, field) when is_atom(name), do: "#{name}_#{field}" defp name_from(%{name: name}, field), do: "#{name}[#{field}]" defp name_from(name, field) when is_atom(name), do: "#{name}[#{field}]" @doc false def build_has_many_fieldset( conn, res, fields, orig_inx, ext_name, field_name, field_field_name, model_name, errors ) do theme_module(conn, Form).theme_build_has_many_fieldset( conn, res, fields, orig_inx, ext_name, field_name, field_field_name, model_name, errors ) end @doc false def get_label(field_name, opts) do cond do Map.get(opts, :type) in ["hidden", :hidden] -> :none Map.get(opts, :display) -> {:hidden, Map.get(opts, :label, field_name)} Map.get(opts, :ajax) -> {:ajax, Map.get(opts, :label, field_name)} true -> Map.get(opts, :label, field_name) end end defp new_record_name(field_name) do name = field_name |> Atom.to_string() |> Inflex.singularize() |> String.replace(" ", "_") |> String.upcase() "NEW_#{name}_RECORD" end def escape_value(nil), do: nil def escape_value(value) when is_map(value), do: value def escape_value(value) do to_string(Phoenix.HTML.html_escape(value) |> elem(1)) end @doc false def build_field_errors(conn, field_name) do conn.private |> Map.get(:phoenix_flash, %{}) |> Map.get("inline_error", []) |> get_errors(field_name) |> Enum.reduce("", fn error, acc -> acc <> """ <p class="inline-errors">#{error_messages(error)}</p> """ end) end @doc false def default_form_view(conn, resource, params) do case conn.assigns.defn do nil -> throw(:invalid_route) %{__struct__: _} = defn -> columns = defn.resource_model.__schema__(:fields) |> Enum.filter(&(&1 not in [:id, :inserted_at, :updated_at])) |> Enum.map(&build_item(resource, defn, &1)) |> Enum.filter(&(not is_nil(&1))) items = [%{type: :inputs, name: "", inputs: columns, opts: []}] Module.concat(var!(conn).assigns.theme, Form).build_form( conn, resource, items, params, false, ExAdmin.Form.global_script() ) end end defp binary_tuple?([]), do: false defp binary_tuple?(collection) do Enum.all?(collection, &(is_binary(&1) or (is_tuple(&1) and tuple_size(&1) == 2))) end def required_abbr(true) do abbr(".required *", title: "required") end def required_abbr(_), do: "" def get_required(field_name, %{required: required}) do if field_name in required, do: true, else: false end def get_required(_, _), do: false @doc false def extra_javascript(model_name, param, attr) do {"var extra = $('##{model_name}_#{attr}').val();\n", "&#{param}='+extra+'"} end @doc false defp map_array_errors(nil, _, _), do: nil defp map_array_errors(errors, field_name, inx) do errors = errors || [] errors |> Enum.filter(fn {k, {_err, opts}} -> k == field_name and opts[:index] == inx end) |> Enum.map(fn {_k, {err, opts}} -> {opts[:field], err} end) end @doc false def get_errors(nil, _field_name), do: nil def get_errors(errors, field_name) do Enum.reduce(errors, [], fn {k, v}, acc -> if k == field_name, do: [v | acc], else: acc end) end @doc false def build_errors(nil, nil), do: nil def build_errors(nil, hint) do theme_module(Form).build_hint(hint) end def build_errors(errors, _) do for error <- errors do theme_module(Form).build_form_error(error) end end @doc false def error_messages(:unique), do: "has already been taken" def error_messages(:invalid), do: "has to be valid" def error_messages({:too_short, min}), do: "must be longer than #{min - 1}" def error_messages({:must_match, field}), do: "must match #{humanize(field)}" def error_messages(:format), do: "has incorrect format" def error_messages("empty"), do: "can't be blank" def error_messages({msg, opts}) when is_binary(msg) do count = if is_integer(opts[:count]), do: opts[:count], else: 0 String.replace(msg, "%{count}", Integer.to_string(count)) end def error_messages(other) when is_binary(other), do: other def error_messages(other), do: "error: #{inspect(other)}" def global_script, do: """ $(function() { $(document).on('click', '.remove_has_many_maps', function() { console.log('remove has many maps'); $(this).closest(".has_many_fields").remove(); return false; }); }); """ end
29.177305
107
0.590535
1c8c543832493275783abd83e5da2b68e2715b3f
1,280
ex
Elixir
lib/crudimentary/absinthe/plugs/cache.ex
CRUDimentary/crudimentary_absinthe
af903e9e87b4e0931d1f3a0a220f5114ae8de460
[ "MIT" ]
null
null
null
lib/crudimentary/absinthe/plugs/cache.ex
CRUDimentary/crudimentary_absinthe
af903e9e87b4e0931d1f3a0a220f5114ae8de460
[ "MIT" ]
1
2019-01-21T18:00:00.000Z
2019-01-21T18:00:00.000Z
lib/crudimentary/absinthe/plugs/cache.ex
CRUDimentary/crudimentary_absinthe
af903e9e87b4e0931d1f3a0a220f5114ae8de460
[ "MIT" ]
null
null
null
defmodule CRUDimentary.Absinthe.Plugs.Cache do @moduledoc """ Plug for issuing cache during response creation. This plug creates temporary cache storage uppon incoming request, cache (GenServer) pid is stored in Absinthe Resolution Context. Also it creates hook which destorys created and populated cache before sending a response. """ @behaviour Plug import Plug.Conn @spec init(opts :: keyword) :: keyword def init(opts), do: opts @doc """ Creates Cache Agent and stores PID in Absinthe Resolution Context. Before sending the response, Agent dies. """ @spec call(conn :: Conn.t(), params :: keyword) :: Conn.t() def call(conn, _) do cache = case CRUDimentary.Cache.InMemory.start_link() do {:ok, pid} -> pid _ -> nil end context = if conn.private[:absinthe] do Map.merge(conn.private.absinthe.context, %{cache: cache}) else %{cache: cache} end conn = put_private( conn, :absinthe, %{ context: context } ) Plug.Conn.register_before_send( conn, fn conn -> if cache = conn.private[:absinthe][:context][:cache] do Agent.stop(cache) end conn end ) end end
23.703704
131
0.614844
1c8c629da2bdb03f1099c1d7847e70e37f4e3429
1,388
ex
Elixir
home_page_local/test/support/data_case.ex
tlk-emb/CMS_koji
40a93073128bfad7fdfa987c69d4a8759752064f
[ "Apache-2.0" ]
8
2019-06-02T05:02:36.000Z
2021-08-11T04:23:10.000Z
home_page_local/test/support/data_case.ex
tlk-emb/CMS_koji
40a93073128bfad7fdfa987c69d4a8759752064f
[ "Apache-2.0" ]
7
2019-05-15T08:32:51.000Z
2020-06-10T07:46:43.000Z
home_page_local/test/support/data_case.ex
tlk-emb/CMS_koji
40a93073128bfad7fdfa987c69d4a8759752064f
[ "Apache-2.0" ]
1
2019-06-02T05:02:47.000Z
2019-06-02T05:02:47.000Z
defmodule HomePage.DataCase do @moduledoc """ This module defines the setup for tests requiring access to the application's data layer. You may define functions here to be used as helpers in your tests. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do alias HomePage.Repo import Ecto import Ecto.Changeset import Ecto.Query import HomePage.DataCase end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(HomePage.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(HomePage.Repo, {:shared, self()}) end :ok end @doc """ A helper that transform changeset errors to a map of messages. assert {:error, changeset} = Accounts.create_user(%{password: "short"}) assert "password is too short" in errors_on(changeset).password assert %{password: ["password is too short"]} = errors_on(changeset) """ def errors_on(changeset) do Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> Enum.reduce(opts, message, fn {key, value}, acc -> String.replace(acc, "%{#{key}}", to_string(value)) end) end) end end
25.703704
77
0.680836
1c8c62cd9344c6affac5ea51f286b38a95f74241
871
ex
Elixir
lib/rocketpay_web/controllers/accounts_controller.ex
nnmuniz/rocketpay
3174bcb6bed1578a1cd96e3be90499cc87382b21
[ "MIT" ]
2
2021-03-09T22:58:09.000Z
2021-03-28T12:22:11.000Z
lib/rocketpay_web/controllers/accounts_controller.ex
nnmuniz/rocketpay
3174bcb6bed1578a1cd96e3be90499cc87382b21
[ "MIT" ]
9
2021-02-28T20:29:58.000Z
2021-03-26T01:28:01.000Z
lib/rocketpay_web/controllers/accounts_controller.ex
nnmuniz/rocketpay
3174bcb6bed1578a1cd96e3be90499cc87382b21
[ "MIT" ]
1
2021-03-28T11:56:37.000Z
2021-03-28T11:56:37.000Z
defmodule RocketpayWeb.AccountsController do use RocketpayWeb, :controller alias Rocketpay.Account alias Rocketpay.Account.Transaction.Response, as: TransactionResponse action_fallback RocketpayWeb.FallbackController def deposit(conn, params) do with {:ok, %Account{} = account} <- Rocketpay.deposit(params) do conn |> put_status(:ok) |> render("update.json", account: account) end end def withdraw(conn, params) do with {:ok, %Account{} = account} <- Rocketpay.withdraw(params) do conn |> put_status(:ok) |> render("update.json", account: account) end end def transaction(conn, params) do with {:ok, %TransactionResponse{}= transaction} <- Rocketpay.transaction(params) do conn |> put_status(:ok) |> render("transaction.json", transaction: transaction) end end end
26.393939
87
0.676234
1c8c941b9044fff8da61b242bd35b159681ab400
969
ex
Elixir
lib/demo/accounts/user.ex
jefk/phoenix_live_view
5ef754b4246d3ba5aeeceb3875eda116bddfa834
[ "MIT" ]
null
null
null
lib/demo/accounts/user.ex
jefk/phoenix_live_view
5ef754b4246d3ba5aeeceb3875eda116bddfa834
[ "MIT" ]
null
null
null
lib/demo/accounts/user.ex
jefk/phoenix_live_view
5ef754b4246d3ba5aeeceb3875eda116bddfa834
[ "MIT" ]
null
null
null
defmodule Demo.Accounts.User do use Ecto.Schema import Ecto.Changeset schema "users" do field :username, :string field :email, :string field :phone_number, :string field :password, :string, virtual: true field :password_confirmation, :string, virtual: true timestamps() end @phone ~r/^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/ @doc false def changeset(user, attrs) do user |> cast(attrs, [:username, :email, :phone_number, :password]) |> validate_required([:username, :email, :phone_number]) |> validate_confirmation(:password) |> validate_format(:username, ~r/^[a-zA-Z0-9_]*$/, message: "only letters, numbers, and underscores please" ) |> validate_length(:username, max: 12) |> validate_format(:email, ~r/.+@.+/, message: "must be a valid email address") |> validate_format(:phone_number, @phone, message: "must be a valid number") |> unique_constraint(:email) end end
30.28125
83
0.642931
1c8c99c9418262001e118731ae6c68d287c8af4c
933
ex
Elixir
test/support/channel_case.ex
sb8244/okr_app_pub
933872107bd13390a0a5ea119d7997d4cb5ea7db
[ "MIT" ]
12
2019-05-10T21:48:06.000Z
2021-11-07T14:04:30.000Z
test/support/channel_case.ex
sb8244/okr_app_pub
933872107bd13390a0a5ea119d7997d4cb5ea7db
[ "MIT" ]
2
2019-05-14T19:07:10.000Z
2019-05-20T21:06:27.000Z
test/support/channel_case.ex
sb8244/okr_app_pub
933872107bd13390a0a5ea119d7997d4cb5ea7db
[ "MIT" ]
3
2019-05-19T18:24:20.000Z
2019-10-31T20:29:12.000Z
defmodule OkrAppWeb.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 OkrAppWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(OkrApp.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(OkrApp.Repo, {:shared, self()}) end :ok end end
24.552632
68
0.714898
1c8cc543b97baa6df3764ad859547edcb1818d18
901
exs
Elixir
test/bitstring_test.exs
Cantido/int_set
9418200e5c15326bee04e4a272a0ff0b5caca9b5
[ "MIT" ]
5
2019-11-11T17:43:40.000Z
2021-10-20T05:59:31.000Z
test/bitstring_test.exs
Cantido/int_set
9418200e5c15326bee04e4a272a0ff0b5caca9b5
[ "MIT" ]
6
2020-11-07T22:55:39.000Z
2022-02-28T11:05:39.000Z
test/bitstring_test.exs
Cantido/int_set
9418200e5c15326bee04e4a272a0ff0b5caca9b5
[ "MIT" ]
null
null
null
# SPDX-FileCopyrightText: 2021 Rosa Richter # # SPDX-License-Identifier: MIT defmodule IntSetBitstringTest do use ExUnit.Case, async: true use ExUnitProperties describe "IntSet.bitstring/1" do property "returns an equal bitstring to that which created it" do check all int <- positive_integer() do bitstr = IntSet.new(int) |> IntSet.bitstring() assert bit_size(bitstr) >= int + 1 end end property "returns a bitstring big enough to contain all its members" do check all bitstr <- bitstring() do assert IntSet.new(bitstr) |> IntSet.bitstring() == bitstr end end property "returns a bitstring that can re-create the set" do check all list <- list_of(positive_integer()) do set = IntSet.new(list) reset = set |> IntSet.bitstring() |> IntSet.new() assert set == reset end end end end
27.30303
75
0.657048
1c8ccb60f1c0ed1b64e3906f16d44a2343d21082
9,149
ex
Elixir
lib/broadway_cloud_pub_sub/producer.ex
kianmeng/broadway_cloud_pub_sub
0d59845c16864aa336e8399b12b33ace7a772cd5
[ "Apache-2.0" ]
null
null
null
lib/broadway_cloud_pub_sub/producer.ex
kianmeng/broadway_cloud_pub_sub
0d59845c16864aa336e8399b12b33ace7a772cd5
[ "Apache-2.0" ]
null
null
null
lib/broadway_cloud_pub_sub/producer.ex
kianmeng/broadway_cloud_pub_sub
0d59845c16864aa336e8399b12b33ace7a772cd5
[ "Apache-2.0" ]
null
null
null
defmodule BroadwayCloudPubSub.Producer do @moduledoc """ A GenStage producer that continuously receives messages from a Google Cloud Pub/Sub topic and acknowledges them after being successfully processed. By default this producer uses `BroadwayCloudPubSub.PullClient` to talk to Cloud Pub/Sub, but you can provide your client by implementing the `BroadwayCloudPubSub.Client` behaviour. ## Options using `BroadwayCloudPubSub.PullClient` * `:subscription` - Required. The name of the subscription. Example: "projects/my-project/subscriptions/my-subscription" * `:max_number_of_messages` - Optional. The maximum number of messages to be fetched per request. Default is `10`. * `:scope` - Optional. A string representing the scope or scopes to use when fetching an access token. Default is `"https://www.googleapis.com/auth/pubsub"`. Note: The `:scope` option only applies to the default token generator. * `:token_generator` - Optional. An MFArgs tuple that will be called before each request to fetch an authentication token. It should return `{:ok, String.t()} | {:error, any()}`. Default generator uses `Goth.Token.for_scope/1` with `"https://www.googleapis.com/auth/pubsub"`. See "Custom token generator" section below for more information. * `:base_url` - Optional. The base URL for the Cloud PubSub services. Default is "https://pubsub.googleapis.com". * `:finch_name` - Optional. The used name to launch the `Finch` client in the supervision tree. Useful if you are reusing the same module for many `Broadway` pipelines. Defaults to `YourModule.PullClient` ### Custom token generator A custom token generator can be given as a MFArgs tuple. For example, define a `MyApp.fetch_token/0` function: defmodule MyApp do @scope "https://www.googleapis.com/auth/pubsub" def fetch_token() do with {:ok, token} <- Goth.Token.for_scope(@scope) {:ok, token.token} end end end and configure the producer to use it: token_generator: {MyApp, :fetch_token, []} ## Acknowledger options These options apply to `BroadwayCloudPubSub.PullClient` acknowledgement API: * `:on_success` - Optional. Configures the behaviour for successful messages. See the "Acknowledgements" section below for all the possible values. This option can also be changed for each message through `Broadway.Message.configure_ack/2`. Default is `:ack`. * `:on_failure` - Optional. Configures the behaviour for failed messages. See the "Acknowledgements" section below for all the possible values. This option can also be changed for each message through `Broadway.Message.configure_ack/2`. Default is `:noop`. ## Additional options These options apply to all producers, regardless of client implementation: * `:client` - Optional. A module that implements the `BroadwayCloudPubSub.Client` behaviour. This module is responsible for fetching and acknowledging the messages. Pay attention that all options passed to the producer will be forwarded to the client. It's up to the client to normalize the options it needs. Default is `BroadwayCloudPubSub.PullClient`. * `:pool_size` - Optional. The size of the connection pool. Default is twice the producer concurrency. * `:receive_interval` - Optional. The duration (in milliseconds) for which the producer waits before making a request for more messages. Default is 5000. ## Acknowledgements You can use the `:on_success` and `:on_failure` options to control how messages are acknowledged with the Pub/Sub system. By default successful messages are acknowledged and failed messages are ignored. You can set `:on_success` and `:on_failure` when starting this producer, or change them for each message through `Broadway.Message.configure_ack/2`. The following values are supported by both `:on_success` and `:on_failure`: * `:ack` - Acknowledge the message. Pub/Sub can remove the message from the subscription. * `:noop` - Do nothing. No requests will be made to Pub/Sub, and the message will be rescheduled according to the subscription-level `ackDeadlineSeconds`. * `:nack` - Make a request to Pub/Sub to set `ackDeadlineSeconds` to `0`, which may cause the message to be immediately redelivered to another connected consumer. Note that this does not modify the subscription-level `ackDeadlineSeconds` used for subsequent messages. * `{:nack, integer}` - Modifies the `ackDeadlineSeconds` for a particular message. Note that this does not modify the subscription-level `ackDeadlineSeconds` used for subsequent messages. ### Batching Even if you are not interested in working with Broadway batches via the `handle_batch/3` callback, we recommend all Broadway pipelines with Pub/Sub producers to define a default batcher with `batch_size` set to 10, so messages can be acknowledged in batches, which improves the performance and reduces the cost of integrating with Google Cloud Pub/Sub. In addition, you should ensure that `batch_timeout` is set to a value less than the acknowledgement deadline on the subscription. Otherwise you could potentially have messages that remain in the subscription and are never acknowledged successfully. ### Example Broadway.start_link(MyBroadway, name: MyBroadway, producer: [ module: {BroadwayCloudPubSub.Producer, subscription: "projects/my-project/subscriptions/my_subscription" } ], processors: [ default: [] ], batchers: [ default: [ batch_size: 10, batch_timeout: 2_000 ] ] ) The above configuration will set up a producer that continuously receives messages from `"projects/my-project/subscriptions/my_subscription"` and sends them downstream. """ use GenStage alias Broadway.Producer alias BroadwayCloudPubSub.Acknowledger @behaviour Producer @default_base_url "https://pubsub.googleapis.com" @default_client BroadwayCloudPubSub.PullClient @default_receive_interval 5000 @impl Producer def prepare_for_start(module, opts) do {me, my_opts} = opts[:producer][:module] client = Keyword.get(my_opts, :client, @default_client) my_opts = Keyword.put_new_lazy(my_opts, :pool_size, fn -> 2 * opts[:producer][:concurrency] end) {specs, my_opts} = prepare_to_connect(module, client, my_opts) {specs, put_in(opts, [:producer, :module], {me, my_opts})} end defp prepare_to_connect(module, client, producer_opts) do if Code.ensure_loaded?(client) and function_exported?(client, :prepare_to_connect, 2) do client.prepare_to_connect(module, producer_opts) else {[], producer_opts} end end @impl true def init(opts) do client = opts[:client] || @default_client receive_interval = opts[:receive_interval] || @default_receive_interval opts = Keyword.put_new(opts, :base_url, @default_base_url) with {:ok, config} <- client.init(opts), {:ok, ack_ref} <- Acknowledger.init(client, config, opts) do {:producer, %{ demand: 0, receive_timer: nil, receive_interval: receive_interval, client: {client, config}, ack_ref: ack_ref }} else {:error, message} -> raise ArgumentError, message end end @impl true def handle_demand(incoming_demand, %{demand: demand} = state) do handle_receive_messages(%{state | demand: demand + incoming_demand}) end @impl true def handle_info(:receive_messages, %{receive_timer: nil} = state) do {:noreply, [], state} end def handle_info(:receive_messages, state) do handle_receive_messages(%{state | receive_timer: nil}) end @impl true def handle_info(_, state) do {:noreply, [], state} end @impl Producer def prepare_for_draining(%{receive_timer: receive_timer} = state) do receive_timer && Process.cancel_timer(receive_timer) {:noreply, [], %{state | receive_timer: nil}} end defp handle_receive_messages(%{receive_timer: nil, demand: demand} = state) when demand > 0 do messages = receive_messages_from_pubsub(state, demand) new_demand = demand - length(messages) receive_timer = case {messages, new_demand} do {[], _} -> schedule_receive_messages(state.receive_interval) {_, 0} -> nil _ -> schedule_receive_messages(0) end {:noreply, messages, %{state | demand: new_demand, receive_timer: receive_timer}} end defp handle_receive_messages(state) do {:noreply, [], state} end defp receive_messages_from_pubsub(state, total_demand) do %{client: {client, opts}, ack_ref: ack_ref} = state client.receive_messages(total_demand, Acknowledger.builder(ack_ref), opts) end defp schedule_receive_messages(interval) do Process.send_after(self(), :receive_messages, interval) end end
36.019685
102
0.704886
1c8cf329b1c10290c07a2e8f484e255ba994e207
954
ex
Elixir
lib/glimesh_web/uploaders/stream_thumbnail.ex
mja00/glimesh.tv
1f543bfdf68de269d0984041ed8394b78fb2158d
[ "MIT" ]
1
2020-08-02T00:12:28.000Z
2020-08-02T00:12:28.000Z
lib/glimesh_web/uploaders/stream_thumbnail.ex
mja00/glimesh.tv
1f543bfdf68de269d0984041ed8394b78fb2158d
[ "MIT" ]
null
null
null
lib/glimesh_web/uploaders/stream_thumbnail.ex
mja00/glimesh.tv
1f543bfdf68de269d0984041ed8394b78fb2158d
[ "MIT" ]
null
null
null
defmodule Glimesh.StreamThumbnail do @moduledoc false use Waffle.Definition use Waffle.Ecto.Definition @versions [:original] def acl(:original, _), do: :public_read # Whitelist file extensions: def validate({file, _}) do ~w(.jpg .jpeg .png) |> Enum.member?(Path.extname(file.file_name)) end # Define a thumbnail transformation: def transform(:original, _) do {:convert, "-strip -thumbnail 832x468^ -gravity center -extent 832x468 -interlace Plane -gaussian-blur 0.05 -quality 85% -format jpg", :jpg} end # Override the persisted filenames: def filename(_version, {_file, %Glimesh.Streams.Stream{} = stream}) do stream.id end # Override the storage directory: def storage_dir(_version, {_file, _scope}) do "uploads/stream-thumbnails" end # Provide a default URL if there hasn't been a file uploaded def default_url(_version, _scope) do "/images/stream-not-started.jpg" end end
25.105263
128
0.702306
1c8d0c9fd17eb090c0f50a85554189e980ee996c
1,319
ex
Elixir
lib/game_of_life/board.ex
potto007/elixir-game_of_life
28402f57f63e16c2c4c0d52b1130f52a2373e1bd
[ "MIT" ]
57
2016-04-28T09:02:27.000Z
2021-12-16T20:03:05.000Z
lib/game_of_life/board.ex
potto007/elixir-game_of_life
28402f57f63e16c2c4c0d52b1130f52a2373e1bd
[ "MIT" ]
1
2016-05-30T05:51:10.000Z
2016-05-31T21:32:44.000Z
lib/game_of_life/board.ex
potto007/elixir-game_of_life
28402f57f63e16c2c4c0d52b1130f52a2373e1bd
[ "MIT" ]
4
2016-05-27T18:38:23.000Z
2019-05-30T11:03:45.000Z
defmodule GameOfLife.Board do def add_cells(alive_cells, new_cells) do alive_cells ++ new_cells |> Enum.uniq end def remove_cells(alive_cells, kill_cells) do alive_cells -- kill_cells end @doc "Returns cells that should still live on the next generation" def keep_alive_tick(alive_cells) do alive_cells |> Enum.map(&(Task.Supervisor.async({GameOfLife.TaskSupervisor, GameOfLife.NodeManager.random_node}, GameOfLife.Board, :keep_alive_or_nilify, [alive_cells, &1]))) |> Enum.map(&Task.await/1) |> remove_nil_cells end @doc "Returns new born cells on the next generation" def become_alive_tick(alive_cells) do GameOfLife.Cell.dead_neighbours(alive_cells) |> Enum.map(&(Task.Supervisor.async({GameOfLife.TaskSupervisor, GameOfLife.NodeManager.random_node}, GameOfLife.Board, :become_alive_or_nilify, [alive_cells, &1]))) |> Enum.map(&Task.await/1) |> remove_nil_cells end def keep_alive_or_nilify(alive_cells, cell) do if GameOfLife.Cell.keep_alive?(alive_cells, cell), do: cell, else: nil end def become_alive_or_nilify(alive_cells, dead_cell) do if GameOfLife.Cell.become_alive?(alive_cells, dead_cell), do: dead_cell, else: nil end defp remove_nil_cells(cells) do cells |> Enum.filter(fn cell -> cell != nil end) end end
32.975
168
0.736164
1c8d17ba5625d3e8f4b735361a050dbd3dddd96e
45,107
ex
Elixir
lib/phoenix_live_view.ex
Ian-GL/phoenix_live_view
52bf9a4a929a499aa7280f2d914cd36412f7ee6f
[ "MIT" ]
1
2021-04-22T16:40:32.000Z
2021-04-22T16:40:32.000Z
lib/phoenix_live_view.ex
msaraiva/phoenix_live_view
5eae7ed93e29fa00b695b7e063f2426d63861f29
[ "MIT" ]
null
null
null
lib/phoenix_live_view.ex
msaraiva/phoenix_live_view
5eae7ed93e29fa00b695b7e063f2426d63861f29
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveView do @moduledoc ~S''' LiveView provides rich, real-time user experiences with server-rendered HTML. The LiveView programming model is declarative: instead of saying "once event X happens, change Y on the page", events in LiveView are regular messages which may cause changes to its state. Once the state changes, LiveView will re-render the relevant parts of its HTML template and push it to the browser, which updates itself in the most efficient manner. This means developers write LiveView templates as any other server-rendered HTML and LiveView does the hard work of tracking changes and sending the relevant diffs to the browser. At the end of the day, a LiveView is nothing more than a process that receives events as messages and updates its state. The state itself is nothing more than functional and immutable Elixir data structures. The events are either internal application messages (usually emitted by `Phoenix.PubSub`) or sent by the client/browser. LiveView is first rendered statically as part of regular HTTP requests, which provides quick times for "First Meaningful Paint", in addition to helping search and indexing engines. Then a persistent connection is established between client and server. This allows LiveView applications to react faster to user events as there is less work to be done and less data to be sent compared to stateless requests that have to authenticate, decode, load, and encode data on every request. The flipside is that LiveView uses more memory on the server compared to stateless requests. ## Use cases There are many use cases where LiveView is an excellent fit right now: * Handling of user interaction and inputs, buttons, and forms - such as input validation, dynamic forms, autocomplete, etc; * Events and updates pushed by server - such as notifications, dashboards, etc; * Page and data navigation - such as navigating between pages, pagination, etc can be built with LiveView using the excellent live navigation feature set. This reduces the amount of data sent over the wire, gives developers full control over the LiveView life-cycle, while controlling how the browser tracks those changes in state; There are also use cases which are a bad fit for LiveView: * Animations - animations, menus, and general UI events that do not need the server in the first place are a bad fit for LiveView. Those can be achieved without LiveView in multiple ways, such as with CSS and CSS transitions, using LiveView hooks, or even integrating with UI toolkits designed for this purpose, such as Bootstrap, Alpine.JS, and similar. ## Life-cycle A LiveView begins as a regular HTTP request and HTML response, and then upgrades to a stateful view on client connect, guaranteeing a regular HTML page even if JavaScript is disabled. Any time a stateful view changes or updates its socket assigns, it is automatically re-rendered and the updates are pushed to the client. You begin by rendering a LiveView typically from your router. When LiveView is first rendered, the `c:mount/3` callback is invoked with the current params, the current session and the LiveView socket. As in a regular request, `params` contains public data that can be modified by the user. The `session` always contains private data set by the application itself. The `c:mount/3` callback wires up socket assigns necessary for rendering the view. After mounting, `c:render/1` is invoked and the HTML is sent as a regular HTML response to the client. After rendering the static page, LiveView connects from the client to the server where stateful views are spawned to push rendered updates to the browser, and receive client events via `phx-` bindings. Just like the first rendering, `c:mount/3` is invoked with params, session, and socket state, where mount assigns values for rendering. However in the connected client case, a LiveView process is spawned on the server, pushes the result of `c:render/1` to the client and continues on for the duration of the connection. If at any point during the stateful life-cycle a crash is encountered, or the client connection drops, the client gracefully reconnects to the server, calling `c:mount/3` once again. ## Example Before writing your first example, make sure that Phoenix LiveView is properly installed. If you are just getting started, this can be easily done by running `mix phx.new my_app --live`. The `phx.new` command with the `--live` flag will create a new project with LiveView installed and configured. Otherwise, please follow the steps in the [installation guide](installation.md) before continuing. A LiveView is a simple module that requires two callbacks: `c:mount/3` and `c:render/1`: defmodule MyAppWeb.ThermostatLive do # If you generated an app with mix phx.new --live, # the line below would be: use MyAppWeb, :live_view use Phoenix.LiveView def render(assigns) do ~L""" Current temperature: <%= @temperature %> """ end def mount(_params, %{"current_user_id" => user_id}, socket) do temperature = Thermostat.get_user_reading(user_id) {:ok, assign(socket, :temperature, temperature)} end end The `c:render/1` callback receives the `socket.assigns` and is responsible for returning rendered content. You can use `Phoenix.LiveView.Helpers.sigil_L/2` to inline LiveView templates. Next, decide where you want to use your LiveView. You can serve the LiveView directly from your router (recommended): defmodule MyAppWeb.Router do use Phoenix.Router import Phoenix.LiveView.Router scope "/", MyAppWeb do live "/thermostat", ThermostatLive end end *Note:* the above assumes there is `plug :put_root_layout` call in your router that configures the LiveView layout. This call is automatically included by `mix phx.new --live` and described in the installation guide. If you don't want to configure a root layout, you must pass `layout: {MyAppWeb.LayoutView, "app.html"}` as an option to the `live` macro above. Alternatively, you can `live_render` from any template: <h1>Temperature Control</h1> <%= live_render(@conn, MyAppWeb.ThermostatLive) %> Or you can `live_render` your view from any controller: defmodule MyAppWeb.ThermostatController do ... import Phoenix.LiveView.Controller def show(conn, %{"id" => id}) do live_render(conn, MyAppWeb.ThermostatLive) end end When a LiveView is rendered, all of the data currently stored in the connection session (see `Plug.Conn.get_session/1`) will be given to the LiveView. It is also possible to pass additional session information to the LiveView through a session parameter: # In the router live "/thermostat", ThermostatLive, session: %{"extra_token" => "foo"} # In a view <%= live_render(@conn, MyAppWeb.ThermostatLive, session: %{"extra_token" => "foo"}) %> Notice the `:session` uses string keys as a reminder that session data is serialized and sent to the client. So you should always keep the data in the session to a minimum. For example, instead of storing a User struct, you should store the "user_id" and load the User when the LiveView mounts. Once the LiveView is rendered, a regular HTML response is sent. In your app.js file, you should find the following: import {Socket} from "phoenix" import LiveSocket from "phoenix_live_view" let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}}) liveSocket.connect() After the client connects, `c:mount/3` will be invoked inside a spawned LiveView process. At this point, you can use `connected?/1` to conditionally perform stateful work, such as subscribing to pubsub topics, sending messages, etc. For example, you can periodically update a LiveView with a timer: defmodule DemoWeb.ThermostatLive do use Phoenix.LiveView ... def mount(_params, %{"current_user_id" => user_id}, socket) do if connected?(socket), do: Process.send_after(self(), :update, 30000) case Thermostat.get_user_reading(user_id) do {:ok, temperature} -> {:ok, assign(socket, temperature: temperature, user_id: user_id)} {:error, _reason} -> {:ok, redirect(socket, to: "/error")} end end def handle_info(:update, socket) do Process.send_after(self(), :update, 30000) {:ok, temperature} = Thermostat.get_reading(socket.assigns.user_id) {:noreply, assign(socket, :temperature, temperature)} end end We used `connected?(socket)` on mount to send our view a message every 30s if the socket is in a connected state. We receive the `:update` message in the `handle_info/2` callback, just like in an Elixir `GenServer`, and update our socket assigns. Whenever a socket's assigns change, `c:render/1` is automatically invoked, and the updates are sent to the client. ## Colocating templates In the examples above, we have placed the template directly inside the LiveView: defmodule MyAppWeb.ThermostatLive do use Phoenix.LiveView def render(assigns) do ~L""" Current temperature: <%= @temperature %> """ end For larger templates, you can place them in a file in the same directory and same name as the LiveView. For example, if the file above is placed at `lib/my_app_web/live/thermostat_live.ex`, you can also remove the `c:render/1` definition above and instead put the template code at `lib/my_app_web/live/thermostat_live.html.leex`. Alternatively, you can keep the `c:render/1` callback but delegate to an existing `Phoenix.View` module in your application. For example: defmodule MyAppWeb.ThermostatLive do use Phoenix.LiveView def render(assigns) do Phoenix.View.render(MyAppWeb.PageView, "page.html", assigns) end end In all cases, each assign in the template will be accessible as `@assign`. You can learn more about [assigns and LiveEEx templates in their own guide](assigns-eex.md). ## Bindings Phoenix supports DOM element bindings for client-server interaction. For example, to react to a click on a button, you would render the element: <button phx-click="inc_temperature">+</button> Then on the server, all LiveView bindings are handled with the `handle_event` callback, for example: def handle_event("inc_temperature", _value, socket) do {:ok, new_temp} = Thermostat.inc_temperature(socket.assigns.id) {:noreply, assign(socket, :temperature, new_temp)} end | Binding | Attributes | |------------------------|------------| | [Params](bindings.md#click-events) | `phx-value-*` | | [Click Events](bindings.md#click-events) | `phx-click`, `phx-capture-click` | | [Focus/Blur Events](bindings.md#focus-and-blur-events) | `phx-blur`, `phx-focus`, `phx-window-blur`, `phx-window-focus` | | [Key Events](bindings.md#key-events) | `phx-keydown`, `phx-keyup`, `phx-window-keydown`, `phx-window-keyup` | | [Form Events](form-bindings.md) | `phx-change`, `phx-submit`, `phx-feedback-for`, `phx-disable-with`, `phx-trigger-action`, `phx-auto-recover` | | [Rate Limiting](bindings.md#rate-limiting-events-with-debounce-and-throttle) | `phx-debounce`, `phx-throttle` | | [DOM Patching](dom-patching.md) | `phx-update` | | [JS Interop](js-interop.md#client-hooks) | `phx-hook` | ## Compartmentalizing markup and events with `render`, `live_render`, and `live_component` We can render another template directly from a LiveView template by simply calling `render`: render SomeView, "child_template.html", assigns Where `SomeView` is a regular `Phoenix.View`, typically defined in `lib/my_app_web/views/some_view.ex` and "child_template.html" is defined at `lib/my_app_web/templates/some_view/child_template.html.leex`. As long as the template has the `.leex` extension and all assigns are passed, LiveView change tracking will also work across templates. When rendering a child template, any of the `phx-*` events in the child template will be sent to the LiveView. In other words, similar to regular Phoenix templates, a regular `render` call does not start another LiveView. This means `render` is useful for sharing markup between views. If you want to start a separate LiveView from within a LiveView, then you can call `live_render/3` instead of `render/3`. This child LiveView runs in a separate process than the parent, with its own `mount` and `handle_event` callbacks. If a child LiveView crashes, it won't affect the parent. If the parent crashes, all children are terminated. When rendering a child LiveView, the `:id` option is required to uniquely identify the child. A child LiveView will only ever be rendered and mounted a single time, provided its ID remains unchanged. Updates to a child session will be merged on the client, but not passed back up until either a crash and re-mount or a connection drop and recovery. To force a child to re-mount with new session data, a new ID must be provided. Given that a LiveView runs on its own process, it is an excellent tool for creating completely isolated UI elements, but it is a slightly expensive abstraction if all you want is to compartmentalize markup and events. For example, if you are showing a table with all users in the system, and you want to compartmentalize this logic, rendering a separate `LiveView` for each user, then using a process per user would likely be too expensive. For these cases, LiveView provides `Phoenix.LiveComponent`, which are rendered using `live_component/3`: <%= live_component(@socket, UserComponent, id: user.id, user: user) %> Components have their own `mount` and `handle_event` callbacks, as well as their own state with change tracking support. Components are also lightweight as they "run" in the same process as the parent `LiveView`. However, this means an error in a component would cause the whole view to fail to render. See `Phoenix.LiveComponent` for a complete rundown on components. To sum it up: * `render` - compartmentalizes markup * `live_component` - compartmentalizes state, markup, and events * `live_render` - compartmentalizes state, markup, events, and error isolation ## Endpoint configuration LiveView accepts the following configuration in your endpoint under the `:live_view` key: * `:signing_salt` (required) - the salt used to sign data sent to the client * `:hibernate_after` (optional) - the idle time in milliseconds allowed in the LiveView before compressing its own memory and state. Defaults to 15000ms (15 seconds) ## Guides LiveView has many guides to help you on your journey. ## Server-side These guides focus on server-side functionality: * [Assigns and LiveEEx](assigns-eex.md) * [Error and exception handling](error-handling.md) * [Live Layouts](live-layouts.md) * [Live Navigation](live-navigation.md) * [Security considerations of the LiveView model](security-model.md) * [Telemetry](telemetry.md) * [Uploads](uploads.md) * [Using Gettext for internationalization](using-gettext.md) ## Client-side These guides focus on LiveView bindings and client-side integration: * [Bindings](bindings.md) * [Form bindings](form-bindings.md) * [DOM patching and temporary assigns](dom-patching.md) * [JavaScript interoperability](js-interop.md) * [Uploads (External)](uploads-external.md) ''' alias Phoenix.LiveView.Socket @type unsigned_params :: map @doc """ The LiveView entry-point. For each LiveView in the root of a template, `c:mount/3` is invoked twice: once to do the initial page load and again to establish the live socket. It expects three parameters: * `params` - a map of string keys which contain public information that can be set by the user. The map contains the query params as well as any router path parameter. If the LiveView was not mounted at the router, this argument is the atom `:not_mounted_at_router` * `session` - the connection session * `socket` - the LiveView socket It must return either `{:ok, socket}` or `{:ok, socket, options}`, where `options` is one of: * `:temporary_assigns` - a keyword list of assigns that are temporary and must be reset to their value after every render. Note that once the value is reset, it won't be re-rendered again until it is explicitly assigned * `:layout` - the optional layout to be used by the LiveView """ @callback mount( unsigned_params() | :not_mounted_at_router, session :: map, socket :: Socket.t() ) :: {:ok, Socket.t()} | {:ok, Socket.t(), keyword()} @callback render(assigns :: Socket.assigns()) :: Phoenix.LiveView.Rendered.t() @callback terminate(reason, socket :: Socket.t()) :: term when reason: :normal | :shutdown | {:shutdown, :left | :closed | term} @callback handle_params(unsigned_params(), uri :: String.t(), socket :: Socket.t()) :: {:noreply, Socket.t()} @callback handle_event(event :: binary, unsigned_params(), socket :: Socket.t()) :: {:noreply, Socket.t()} | {:reply, map, Socket.t()} @callback handle_call(msg :: term, {pid, reference}, socket :: Socket.t()) :: {:noreply, Socket.t()} | {:reply, term, Socket.t()} @callback handle_info(msg :: term, socket :: Socket.t()) :: {:noreply, Socket.t()} @callback handle_cast(msg :: term, socket :: Socket.t()) :: {:noreply, Socket.t()} @optional_callbacks mount: 3, terminate: 2, handle_params: 3, handle_event: 3, handle_call: 3, handle_info: 2, handle_cast: 2 @doc """ Uses LiveView in the current module to mark it a LiveView. use Phoenix.LiveView, namespace: MyAppWeb, container: {:tr, class: "colorized"}, layout: {MyAppWeb.LayoutView, "live.html"} ## Options * `:namespace` - configures the namespace the `LiveView` is in * `:container` - configures the container the `LiveView` will be wrapped in * `:layout` - configures the layout the `LiveView` will be rendered in """ defmacro __using__(opts) do # Expand layout if possible to avoid compile-time dependencies opts = with true <- Keyword.keyword?(opts), {layout, template} <- Keyword.get(opts, :layout) do layout = Macro.expand(layout, %{__CALLER__ | function: {:__live__, 0}}) Keyword.replace!(opts, :layout, {layout, template}) else _ -> opts end quote bind_quoted: [opts: opts] do import Phoenix.LiveView import Phoenix.LiveView.Helpers @behaviour Phoenix.LiveView require Phoenix.LiveView.Renderer @before_compile Phoenix.LiveView.Renderer @doc false def __live__, do: unquote(Macro.escape(Phoenix.LiveView.__live__(__MODULE__, opts))) end end @doc false def __live__(module, opts) do container = opts[:container] || {:div, []} namespace = opts[:namespace] || module |> Module.split() |> Enum.take(1) |> Module.concat() name = module |> Atom.to_string() |> String.replace_prefix("#{namespace}.", "") layout = case opts[:layout] do {mod, template} when is_atom(mod) and is_binary(template) -> {mod, template} nil -> nil other -> raise ArgumentError, ":layout expects a tuple of the form {MyLayoutView, \"my_template.html\"}, " <> "got: #{inspect(other)}" end %{container: container, name: name, kind: :view, module: module, layout: layout} end @doc """ Returns true if the socket is connected. Useful for checking the connectivity status when mounting the view. For example, on initial page render, the view is mounted statically, rendered, and the HTML is sent to the client. Once the client connects to the server, a LiveView is then spawned and mounted statefully within a process. Use `connected?/1` to conditionally perform stateful work, such as subscribing to pubsub topics, sending messages, etc. ## Examples defmodule DemoWeb.ClockLive do use Phoenix.LiveView ... def mount(_params, _session, socket) do if connected?(socket), do: :timer.send_interval(1000, self(), :tick) {:ok, assign(socket, date: :calendar.local_time())} end def handle_info(:tick, socket) do {:noreply, assign(socket, date: :calendar.local_time())} end end """ def connected?(%Socket{connected?: connected?}), do: connected? @doc """ Assigns a value into the socket only if it does not exist. Useful for lazily assigning values and referencing parent assigns. ## Referencing parent assigns When a LiveView is mounted in a disconnected state, the `Plug.Conn` assigns will be available for reference via `assign_new/3`, allowing assigns to be shared for the initial HTTP request. The `Plug.Conn` assigns will not be available during the connected mount. Likewise, nested LiveView children have access to their parent's assigns on mount using `assign_new`, which allows assigns to be shared down the nested LiveView tree. ## Examples # controller conn |> assign(:current_user, user) |> LiveView.Controller.live_render(MyLive, session: %{"user_id" => user.id}) # LiveView mount def mount(_params, %{"user_id" => user_id}, socket) do {:ok, assign_new(socket, :current_user, fn -> Accounts.get_user!(user_id) end)} end """ def assign_new(%Socket{} = socket, key, func) when is_function(func, 0) do validate_assign_key!(key) case socket do %{assigns: %{^key => _}} -> socket %{private: %{assign_new: {assigns, keys}}} -> # It is important to store the keys even if they are not in assigns # because maybe the controller doesn't have it but the view does. socket = put_in(socket.private.assign_new, {assigns, [key | keys]}) Phoenix.LiveView.Utils.force_assign(socket, key, Map.get_lazy(assigns, key, func)) %{} -> Phoenix.LiveView.Utils.force_assign(socket, key, func.()) end end @doc """ Adds key value pairs to socket assigns. A single key value pair may be passed, or a keyword list or a map of assigns may be provided to be merged into existing socket assigns. ## Examples iex> assign(socket, :name, "Elixir") iex> assign(socket, name: "Elixir", logo: "💧") iex> assign(socket, %{name: "Elixir"}) """ def assign(%Socket{} = socket, key, value) do validate_assign_key!(key) Phoenix.LiveView.Utils.assign(socket, key, value) end @doc """ See `assign/3`. """ def assign(%Socket{} = socket, attrs) when is_map(attrs) or is_list(attrs) do Enum.reduce(attrs, socket, fn {key, value}, acc -> validate_assign_key!(key) Phoenix.LiveView.Utils.assign(acc, key, value) end) end defp validate_assign_key!(:flash) do raise ArgumentError, ":flash is a reserved assign by LiveView and it cannot be set directly. " <> "Use the appropriate flash functions instead." end defp validate_assign_key!(_key), do: :ok @doc """ Updates an existing key in the socket assigns. The update function receives the current key's value and returns the updated value. Raises if the key does not exist. ## Examples iex> update(socket, :count, fn count -> count + 1 end) iex> update(socket, :count, &(&1 + 1)) """ def update(%Socket{assigns: assigns} = socket, key, func) do case Map.fetch(assigns, key) do {:ok, val} -> assign(socket, [{key, func.(val)}]) :error -> raise KeyError, key: key, term: assigns end end @doc """ Adds a flash message to the socket to be displayed. *Note*: While you can use `put_flash/3` inside a `Phoenix.LiveComponent`, components have their own `@flash` assigns. The `@flash` assign in a component is only copied to its parent LiveView if the component calls `push_redirect/2` or `push_patch/2`. *Note*: You must also place the `Phoenix.LiveView.Router.fetch_live_flash/2` plug in your browser's pipeline in place of `fetch_flash` to be supported, for example: import Phoenix.LiveView.Router pipeline :browser do ... plug :fetch_live_flash end ## Examples iex> put_flash(socket, :info, "It worked!") iex> put_flash(socket, :error, "You can't access that page") """ defdelegate put_flash(socket, kind, msg), to: Phoenix.LiveView.Utils @doc """ Clears the flash. ## Examples iex> clear_flash(socket) """ defdelegate clear_flash(socket), to: Phoenix.LiveView.Utils @doc """ Clears a key from the flash. ## Examples iex> clear_flash(socket, :info) """ defdelegate clear_flash(socket, key), to: Phoenix.LiveView.Utils @doc """ Pushes an event to the client to be consumed by hooks. *Note*: events will be dispatched to all active hooks on the client who are handling the given `event`. Scoped events can be achieved by namespacing your event names. ## Examples {:noreply, push_event(socket, "scores", %{points: 100, user: "josé"})} """ defdelegate push_event(socket, event, payload), to: Phoenix.LiveView.Utils @doc ~S""" Allows an upload for the provided name. ## Options * `:accept` - Required. A list of unique file type specifiers or the atom :any to allow any kind of file. For example, `[".jpeg"]`, `:any`, etc. * `:max_entries` - The maximum number of selected files to allow per file input. Defaults to 1. * `:max_file_size` - The maximum file size in bytes to allow to be uploaded. Defaults 8MB. For example, `12_000_000`. * `:chunk_size` - The chunk size in bytes to send when uploading. Defaults `64_000`. * `:chunk_timeout` - The time in milliseconds to wait before closing the upload channel when a new chunk has not been received. Defaults `10_000`. * `:external` - The 2-arity function for generating metadata for external client uploaders. See the Uploads section for example usage. * `:progress` - The optional 3-arity function for receiving progress events * `:auto_upload` - Instructs the client to upload the file automatically on file selection instead of waiting for form submits. Default false. Raises when a previously allowed upload under the same name is still active. ## Examples allow_upload(socket, :avatar, accept: ~w(.jpg .jpeg), max_entries: 2) allow_upload(socket, :avatar, accept: :any) For consuming files automatically as they are uploaded, you can pair `auto_upload: true` with a custom progress function to consume the entries as they are completed. For example: allow_upload(socket, :avatar, accept: :any, progress: &handle_progress/3, auto_upload: true) defp handle_progress(:avatar, entry, socket) do if entry.done? do uploaded_file = consume_uploaded_entry(socket, entry, fn %{} = meta -> ... end) {:noreply, put_flash(socket, :info, "file #{uploaded_file.name} uploaded")} else {:noreply, socket} end end """ defdelegate allow_upload(socket, name, options), to: Phoenix.LiveView.Upload @doc """ Revokes a previously allowed upload from `allow_upload/3`. ## Examples disallow_upload(socket, :avatar) """ defdelegate disallow_upload(socket, name), to: Phoenix.LiveView.Upload @doc """ Cancels an upload for the given entry. ## Examples <%= for entry <- @uploads.avatar.entries do %> ... <button phx-click="cancel-upload" phx-value-ref="<%= entry.ref %>">cancel</button> <% end %> def handle_event("cancel-upload", %{"ref" => ref}, socket) do {:noreply, cancel_upload(socket, :avatar, ref)} end """ defdelegate cancel_upload(socket, name, entry_ref), to: Phoenix.LiveView.Upload @doc """ Returns the completed and in progress entries for the upload. ## Examples case uploaded_entries(socket, :photos) do {[_ | _] = completed, []} -> # all entries are completed {[], [_ | _] = in_progress} -> # all entries are still in progress end """ defdelegate uploaded_entries(socket, name), to: Phoenix.LiveView.Upload @doc ~S""" Consumes the uploaded entries. Raises when there are still entries in progress. Typically called when submitting a form to handle the uploaded entries alongside the form data. For form submissions, it is guaranteed that all entries have completed before the submit event is invoked. Once entries are consumed, they are removed from the upload. ## Examples def handle_event("save", _params, socket) do uploaded_files = consume_uploaded_entries(socket, :avatar, fn %{path: path}, _entry -> dest = Path.join("priv/static/uploads", Path.basename(path)) File.cp!(path, dest) Routes.static_path(socket, "/uploads/#{Path.basename(dest)}") end) {:noreply, update(socket, :uploaded_files, &(&1 ++ uploaded_files))} end """ defdelegate consume_uploaded_entries(socket, name, func), to: Phoenix.LiveView.Upload @doc ~S""" Consumes an individual uploaded entry. Raises when the entry is still in progress. Typically called when submitting a form to handle the uploaded entries alongside the form data. Once entries are consumed, they are removed from the upload. This is a lower-level feature than `consume_uploaded_entries/3` and useful for scenarios where you want to consume entries as they are individually completed. ## Examples def handle_event("save", _params, socket) do case uploaded_entries(socket, :avatar) do {[_|_] = entries, []} -> uploaded_files = for entry <- entries do consume_uploaded_entry(socket, entry, fn %{path: path} -> dest = Path.join("priv/static/uploads", Path.basename(path)) File.cp!(path, dest) Routes.static_path(socket, "/uploads/#{Path.basename(dest)}") end) end {:noreply, update(socket, :uploaded_files, &(&1 ++ uploaded_files))} _ -> {:noreply, socket} end end """ defdelegate consume_uploaded_entry(socket, entry, func), to: Phoenix.LiveView.Upload @doc """ Annotates the socket for redirect to a destination path. *Note*: LiveView redirects rely on instructing client to perform a `window.location` update on the provided redirect location. The whole page will be reloaded and all state will be discarded. ## Options * `:to` - the path to redirect to. It must always be a local path * `:external` - an external path to redirect to """ def redirect(%Socket{} = socket, to: url) do validate_local_url!(url, "redirect/2") put_redirect(socket, {:redirect, %{to: url}}) end def redirect(%Socket{} = socket, external: url) do put_redirect(socket, {:redirect, %{external: url}}) end def redirect(%Socket{}, _) do raise ArgumentError, "expected :to or :external option in redirect/2" end @doc """ Annotates the socket for navigation within the current LiveView. When navigating to the current LiveView, `c:handle_params/3` is immediately invoked to handle the change of params and URL state. Then the new state is pushed to the client, without reloading the whole page while also maintaining the current scroll position. For live redirects to another LiveView, use `push_redirect/2`. ## Options * `:to` - the required path to link to. It must always be a local path * `:replace` - the flag to replace the current history or push a new state. Defaults `false`. ## Examples {:noreply, push_patch(socket, to: "/")} {:noreply, push_patch(socket, to: "/", replace: true)} """ def push_patch(%Socket{} = socket, opts) do %{to: to} = opts = push_opts!(opts, "push_patch/2") case Phoenix.LiveView.Utils.live_link_info!(socket, socket.root_view, to) do {:internal, params, action, _parsed_uri} -> put_redirect(socket, {:live, {params, action}, opts}) {:external, _uri} -> raise ArgumentError, "cannot push_patch/2 to #{inspect(to)} because the given path " <> "does not point to the current root view #{inspect(socket.root_view)}" end end @doc """ Annotates the socket for navigation to another LiveView. The current LiveView will be shutdown and a new one will be mounted in its place, without reloading the whole page. This can also be used to remount the same LiveView, in case you want to start fresh. If you want to navigate to the same LiveView without remounting it, use `push_patch/2` instead. ## Options * `:to` - the required path to link to. It must always be a local path * `:replace` - the flag to replace the current history or push a new state. Defaults `false`. ## Examples {:noreply, push_redirect(socket, to: "/")} {:noreply, push_redirect(socket, to: "/", replace: true)} """ def push_redirect(%Socket{} = socket, opts) do opts = push_opts!(opts, "push_redirect/2") put_redirect(socket, {:live, :redirect, opts}) end defp push_opts!(opts, context) do to = Keyword.fetch!(opts, :to) validate_local_url!(to, context) kind = if opts[:replace], do: :replace, else: :push %{to: to, kind: kind} end defp put_redirect(%Socket{redirected: nil} = socket, command) do %Socket{socket | redirected: command} end defp put_redirect(%Socket{redirected: to} = _socket, _command) do raise ArgumentError, "socket already prepared to redirect with #{inspect(to)}" end @invalid_local_url_chars ["\\"] defp validate_local_url!("//" <> _ = to, where) do raise_invalid_local_url!(to, where) end defp validate_local_url!("/" <> _ = to, where) do if String.contains?(to, @invalid_local_url_chars) do raise ArgumentError, "unsafe characters detected for #{where} in URL #{inspect(to)}" else to end end defp validate_local_url!(to, where) do raise_invalid_local_url!(to, where) end defp raise_invalid_local_url!(to, where) do raise ArgumentError, "the :to option in #{where} expects a path but was #{inspect(to)}" end @doc """ Accesses the connect params sent by the client for use on connected mount. Connect params are only sent when the client connects to the server and only remain available during mount. `nil` is returned when called in a disconnected state and a `RuntimeError` is raised if called after mount. ## Reserved params The following params have special meaning in LiveView: * "_csrf_token" - the CSRF Token which must be explicitly set by the user when connecting * "_mounts" - the number of times the current LiveView is mounted. It is 0 on first mount, then increases on each reconnect. It resets when navigating away from the current LiveView or on errors * "_track_static" - set automatically with a list of all href/src from tags with the "phx-track-static" annotation in them. If there are no such tags, nothing is sent ## Examples def mount(_params, _session, socket) do {:ok, assign(socket, width: get_connect_params(socket)["width"] || @width)} end """ def get_connect_params(%Socket{private: private} = socket) do if connect_params = private[:connect_params] do if connected?(socket), do: connect_params, else: nil else raise_connect_only!(socket, "connect_params") end end @doc """ Accesses the connect info from the socket to use on connected mount. Connect info are only sent when the client connects to the server and only remain available during mount. `nil` is returned when called in a disconnected state and a `RuntimeError` is raised if called after mount. ## Examples First, when invoking the LiveView socket, you need to declare the `connect_info` you want to receive. Typically, it includes at least the session but it may include other keys, such as `:peer_data`. See `Phoenix.Endpoint.socket/3`: socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [:peer_data, session: @session_options]] Those values can now be accessed on the connected mount as `get_connect_info/1`: def mount(_params, _session, socket) do if info = get_connect_info(socket) do {:ok, assign(socket, ip: info.peer_data.address)} else {:ok, assign(socket, ip: nil)} end end """ def get_connect_info(%Socket{private: private} = socket) do if connect_info = private[:connect_info] do if connected?(socket), do: connect_info, else: nil else raise_connect_only!(socket, "connect_info") end end @doc """ Returns true if the socket is connected and the tracked static assets have changed. This function is useful to detect if the client is running on an outdated version of the marked static files. It works by comparing the static paths sent by the client with the one on the server. **Note:** this functionality requires Phoenix v1.5.2 or later. To use this functionality, the first step is to annotate which static files you want to be tracked by LiveView, with the `phx-track-static`. For example: <link phx-track-static rel="stylesheet" href="<%= Routes.static_path(@conn, "/css/app.css") %>"/> <script defer phx-track-static type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script> Now, whenever LiveView connects to the server, it will send a copy `src` or `href` attributes of all tracked statics and compare those values with the latest entries computed by `mix phx.digest` in the server. The tracked statics on the client will match the ones on the server the huge majority of times. However, if there is a new deployment, those values may differ. You can use this function to detect those cases and show a banner to the user, asking them to reload the page. To do so, first set the assign on mount: def mount(params, session, socket) do {:ok, assign(socket, static_changed?: static_changed?(socket))} end And then in your views: <%= if @static_changed? do %> <div id="reload-static"> The app has been updated. Click here to <a href="#" onclick="window.location.reload()">reload</a>. </div> <% end %> If you prefer, you can also send a JavaScript script that immediately reloads the page. **Note:** only set `phx-track-static` on your own assets. For example, do not set it in external JavaScript files: <script defer phx-track-static type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> Because you don't actually serve the file above, LiveView will interpret the static above as missing, and this function will return true. """ def static_changed?(%Socket{private: private, endpoint: endpoint} = socket) do if connect_params = private[:connect_params] do connected?(socket) and static_changed?( connect_params["_track_static"], endpoint.config(:cache_static_manifest_latest) ) else raise_connect_only!(socket, "static_changed?") end end defp static_changed?([_ | _] = statics, %{} = latest) do latest = Map.to_list(latest) not Enum.all?(statics, fn static -> [static | _] = :binary.split(static, "?") Enum.any?(latest, fn {non_digested, digested} -> String.ends_with?(static, non_digested) or String.ends_with?(static, digested) end) end) end defp static_changed?(_, _), do: false defp raise_connect_only!(socket, fun) do if child?(socket) do raise RuntimeError, """ attempted to read #{fun} from a nested child LiveView #{inspect(socket.view)}. Only the root LiveView has access to #{fun}. """ else raise RuntimeError, """ attempted to read #{fun} outside of #{inspect(socket.view)}.mount/3. #{fun} only exists while mounting. If you require access to this information after mount, store the state in socket assigns. """ end end @doc """ Asynchronously updates a `Phoenix.LiveComponent` with new assigns. The component that is updated must be stateful (the `:id` in the assigns must match the `:id` associated with the component) and the component must be mounted within the current LiveView. If this call is executed from a process which is not a LiveView nor a LiveComponent, the `pid` parameter has to be specified. When the component receives the update, the optional [`preload/1`](`c:Phoenix.LiveComponent.preload/1`) callback is invoked, then the updated values are merged with the component's assigns and [`update/2`](`c:Phoenix.LiveComponent.update/2`) is called for the updated component(s). While a component may always be updated from the parent by updating some parent assigns which will re-render the child, thus invoking [`update/3`](`c:Phoenix.LiveComponent.update/3`) on the child component, `send_update/3` is useful for updating a component that entirely manages its own state, as well as messaging between components mounted in the same LiveView. **Note:** `send_update/3` cannot update a LiveComponent that is mounted in a different LiveView. To update a component in a different LiveView you must send a message to the LiveView process that the LiveComponent is mounted within (often via `Phoenix.PubSub`). ## Examples def handle_event("cancel-order", _, socket) do ... send_update(Cart, id: "cart", status: "cancelled") {:noreply, socket} end def handle_event("cancel-order-asynchronously", _, socket) do ... pid = self() Task.async(fn -> # Do domething asynchronously send_update(pid, Cart, id: "cart", status: "cancelled") end) {:noreply, socket} end """ def send_update(pid \\ self(), module, assigns) when is_atom(module) and is_pid(pid) do assigns = Enum.into(assigns, %{}) id = assigns[:id] || raise ArgumentError, "missing required :id in send_update. Got: #{inspect(assigns)}" Phoenix.LiveView.Channel.send_update(pid, module, id, assigns) end @doc """ Similar to `send_update/3` but the update will be delayed according to the given `time_in_milliseconds`. ## Examples def handle_event("cancel-order", _, socket) do ... send_update_after(Cart, [id: "cart", status: "cancelled"], 3000) {:noreply, socket} end def handle_event("cancel-order-asynchronously", _, socket) do ... pid = self() Task.async(fn -> # Do domething asynchronously send_update_after(pid, Cart, [id: "cart", status: "cancelled"], 3000) end) {:noreply, socket} end """ def send_update_after(pid \\ self(), module, assigns, time_in_milliseconds) when is_atom(module) and is_integer(time_in_milliseconds) and is_pid(pid) do assigns = Enum.into(assigns, %{}) id = assigns[:id] || raise ArgumentError, "missing required :id in send_update_after. Got: #{inspect(assigns)}" Phoenix.LiveView.Channel.send_update_after(pid, module, id, assigns, time_in_milliseconds) end @doc """ Returns the transport pid of the socket. Raises `ArgumentError` if the socket is not connected. ## Examples iex> transport_pid(socket) #PID<0.107.0> """ def transport_pid(%Socket{}) do case Process.get(:"$callers") do [transport_pid | _] -> transport_pid _ -> raise ArgumentError, "transport_pid/1 may only be called when the socket is connected." end end defp child?(%Socket{parent_pid: pid}), do: is_pid(pid) end
36.494337
148
0.682023
1c8d2533849d2d4b8b6874fcf1cfbb976f7b9bc5
146
ex
Elixir
code examples/example-15-12.ex
kujua/erlang-elixir-imperative-bookcompanion
7bc9f033bacd0f8744ec6bcee3932794d594fe69
[ "Apache-2.0" ]
8
2016-08-14T12:35:16.000Z
2021-01-26T04:05:31.000Z
code examples/example-15-12.ex
kujua/erlang-elixir-imperative-bookcompanion
7bc9f033bacd0f8744ec6bcee3932794d594fe69
[ "Apache-2.0" ]
null
null
null
code examples/example-15-12.ex
kujua/erlang-elixir-imperative-bookcompanion
7bc9f033bacd0f8744ec6bcee3932794d594fe69
[ "Apache-2.0" ]
5
2016-08-18T22:12:19.000Z
2020-02-17T18:52:41.000Z
iex(1)> VegetableStew.cook %{{:carot, :piece} => 3, {:onion, :piece} => 2, {:tomato, :piece} => 2} iex(2)> BeefStew.cook How much beef? 250 grams
29.2
71
0.616438
1c8d2ebb7f67ed843b9d3bc5b32085da40a12e77
1,464
ex
Elixir
geo3x3.ex
yrm006/Geo3x3
269124682b307e0e8b100d179e3bf21d931df722
[ "CC0-1.0" ]
23
2021-02-20T12:53:34.000Z
2021-12-07T02:56:21.000Z
geo3x3.ex
yrm006/Geo3x3
269124682b307e0e8b100d179e3bf21d931df722
[ "CC0-1.0" ]
22
2021-02-21T03:44:34.000Z
2022-03-27T13:32:24.000Z
geo3x3.ex
yrm006/Geo3x3
269124682b307e0e8b100d179e3bf21d931df722
[ "CC0-1.0" ]
14
2021-02-20T23:51:46.000Z
2021-08-17T13:20:41.000Z
defmodule Geo3x3 do def encode(_lat, _lng, level) when level < 1, do: "" def encode(lat, lng, level) do {res, lng} = if lng >= 0, do: {"E", lng}, else: {"W", lng + 180} lat = lat + 90 # 180:the North Pole, 0:the South Pole unit = 180.0 {_, _, _, res} = 1..level-1 |> Enum.reduce({unit, lng, lat, res}, fn _lv, {unit, lng, lat, res} -> unit = unit / 3 x = floor(lng / unit) y = floor(lat / unit) res = "#{res}#{x + y * 3 + 1}" lng = lng - x * unit lat = lat - y * unit {unit, lng, lat, res} end) res end def decode(code) do {flg, code} = case code do "-" <> rest -> {true, rest} "W" <> rest -> {true, rest} "+" <> rest -> {false, rest} "E" <> rest -> {false, rest} _ -> {false, code} end {lat, lng, level, unit} = code |> String.codepoints() |> Enum.reduce_while({0.0, 0.0, 1, 180.0}, fn c, {lat, lng, level, unit} = acc -> with {n, _} <- Integer.parse(c), true <- n > 0 do n = n - 1 unit = unit / 3 lat = lat + div(n, 3) * unit lng = lng + rem(n, 3) * unit {:cont, {lat, lng, level + 1, unit}} else _ -> {:halt, acc} end end) lat = lat + (unit / 2) lat = lat - 90 lng = lng + (unit / 2) lng = if flg, do: lng - 180.0, else: lng [lat, lng, level, unit] end end
24
87
0.443306
1c8d465b14282c8deb3af4679a4c49bb773a95a3
44,877
ex
Elixir
lib/aws/storage_gateway.ex
tylerpearson/aws-elixir
09b7d3a3b9da1d775249cca291ab42ec5a081ff2
[ "Apache-2.0" ]
null
null
null
lib/aws/storage_gateway.ex
tylerpearson/aws-elixir
09b7d3a3b9da1d775249cca291ab42ec5a081ff2
[ "Apache-2.0" ]
null
null
null
lib/aws/storage_gateway.ex
tylerpearson/aws-elixir
09b7d3a3b9da1d775249cca291ab42ec5a081ff2
[ "Apache-2.0" ]
null
null
null
# WARNING: DO NOT EDIT, AUTO-GENERATED CODE! # See https://github.com/jkakar/aws-codegen for more details. defmodule AWS.StorageGateway do @moduledoc """ AWS Storage Gateway Service AWS Storage Gateway is the service that connects an on-premises software appliance with cloud-based storage to provide seamless and secure integration between an organization's on-premises IT environment and AWS's storage infrastructure. The service enables you to securely upload data to the AWS cloud for cost effective backup and rapid disaster recovery. Use the following links to get started using the *AWS Storage Gateway Service API Reference*: <ul> <li> [AWS Storage Gateway Required Request Headers](http://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#AWSStorageGatewayHTTPRequestsHeaders): Describes the required headers that you must send with every POST request to AWS Storage Gateway. </li> <li> [Signing Requests](http://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#AWSStorageGatewaySigningRequests): AWS Storage Gateway requires that you authenticate every request you send; this topic describes how sign such a request. </li> <li> [Error Responses](http://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#APIErrorResponses): Provides reference information about AWS Storage Gateway errors. </li> <li> [Operations in AWS Storage Gateway](http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_Operations.html): Contains detailed descriptions of all AWS Storage Gateway operations, their request parameters, response elements, possible errors, and examples of requests and responses. </li> <li> [AWS Storage Gateway Regions and Endpoints:](http://docs.aws.amazon.com/general/latest/gr/rande.html#sg_region) Provides a list of each region and endpoints available for use with AWS Storage Gateway. </li> </ul> <note> AWS Storage Gateway resource IDs are in uppercase. When you use these resource IDs with the Amazon EC2 API, EC2 expects resource IDs in lowercase. You must change your resource ID to lowercase to use it with the EC2 API. For example, in Storage Gateway the ID for a volume might be `vol-AA22BB012345DAF670`. When you use this ID with the EC2 API, you must change it to `vol-aa22bb012345daf670`. Otherwise, the EC2 API might not behave as expected. </note> <important> IDs for Storage Gateway volumes and Amazon EBS snapshots created from gateway volumes are changing to a longer format. Starting in December 2016, all new volumes and snapshots will be created with a 17-character string. Starting in April 2016, you will be able to use these longer IDs so you can test your systems with the new format. For more information, see [Longer EC2 and EBS Resource IDs](https://aws.amazon.com/ec2/faqs/#longer-ids). For example, a volume Amazon Resource Name (ARN) with the longer volume ID format looks like the following: `arn:aws:storagegateway:us-west-2:111122223333:gateway/sgw-12A3456B/volume/vol-1122AABBCCDDEEFFG`. A snapshot ID with the longer ID format looks like the following: `snap-78e226633445566ee`. For more information, see [Announcement: Heads-up – Longer AWS Storage Gateway volume and snapshot IDs coming in 2016](https://forums.aws.amazon.com/ann.jspa?annID=3557). </important> """ @doc """ Activates the gateway you previously deployed on your host. In the activation process, you specify information such as the region you want to use for storing snapshots or tapes, the time zone for scheduled snapshots the gateway snapshot schedule window, an activation key, and a name for your gateway. The activation process also associates your gateway with your account; for more information, see `UpdateGatewayInformation`. <note> You must turn on the gateway VM before you can activate your gateway. </note> """ def activate_gateway(client, input, options \\ []) do request(client, "ActivateGateway", input, options) end @doc """ Configures one or more gateway local disks as cache for a gateway. This operation is only supported in the cached volume, tape and file gateway type (see [Storage Gateway Concepts](http://docs.aws.amazon.com/storagegateway/latest/userguide/StorageGatewayConcepts.html)). In the request, you specify the gateway Amazon Resource Name (ARN) to which you want to add cache, and one or more disk IDs that you want to configure as cache. """ def add_cache(client, input, options \\ []) do request(client, "AddCache", input, options) end @doc """ Adds one or more tags to the specified resource. You use tags to add metadata to resources, which you can use to categorize these resources. For example, you can categorize resources by purpose, owner, environment, or team. Each tag consists of a key and a value, which you define. You can add tags to the following AWS Storage Gateway resources: <ul> <li> Storage gateways of all types </li> </ul> <ul> <li> Storage Volumes </li> </ul> <ul> <li> Virtual Tapes </li> </ul> You can create a maximum of 10 tags for each resource. Virtual tapes and storage volumes that are recovered to a new gateway maintain their tags. """ def add_tags_to_resource(client, input, options \\ []) do request(client, "AddTagsToResource", input, options) end @doc """ Configures one or more gateway local disks as upload buffer for a specified gateway. This operation is supported for the stored volume, cached volume and tape gateway types. In the request, you specify the gateway Amazon Resource Name (ARN) to which you want to add upload buffer, and one or more disk IDs that you want to configure as upload buffer. """ def add_upload_buffer(client, input, options \\ []) do request(client, "AddUploadBuffer", input, options) end @doc """ Configures one or more gateway local disks as working storage for a gateway. This operation is only supported in the stored volume gateway type. This operation is deprecated in cached volume API version 20120630. Use `AddUploadBuffer` instead. <note> Working storage is also referred to as upload buffer. You can also use the `AddUploadBuffer` operation to add upload buffer to a stored volume gateway. </note> In the request, you specify the gateway Amazon Resource Name (ARN) to which you want to add working storage, and one or more disk IDs that you want to configure as working storage. """ def add_working_storage(client, input, options \\ []) do request(client, "AddWorkingStorage", input, options) end @doc """ Cancels archiving of a virtual tape to the virtual tape shelf (VTS) after the archiving process is initiated. This operation is only supported in the tape gateway type. """ def cancel_archival(client, input, options \\ []) do request(client, "CancelArchival", input, options) end @doc """ Cancels retrieval of a virtual tape from the virtual tape shelf (VTS) to a gateway after the retrieval process is initiated. The virtual tape is returned to the VTS. This operation is only supported in the tape gateway type. """ def cancel_retrieval(client, input, options \\ []) do request(client, "CancelRetrieval", input, options) end @doc """ Creates a cached volume on a specified cached volume gateway. This operation is only supported in the cached volume gateway type. <note> Cache storage must be allocated to the gateway before you can create a cached volume. Use the `AddCache` operation to add cache storage to a gateway. </note> In the request, you must specify the gateway, size of the volume in bytes, the iSCSI target name, an IP address on which to expose the target, and a unique client token. In response, the gateway creates the volume and returns information about it. This information includes the volume Amazon Resource Name (ARN), its size, and the iSCSI target ARN that initiators can use to connect to the volume target. Optionally, you can provide the ARN for an existing volume as the `SourceVolumeARN` for this cached volume, which creates an exact copy of the existing volume’s latest recovery point. The `VolumeSizeInBytes` value must be equal to or larger than the size of the copied volume, in bytes. """ def create_cached_iscsi_volume(client, input, options \\ []) do request(client, "CreateCachediSCSIVolume", input, options) end @doc """ Creates a file share on an existing file gateway. In Storage Gateway, a file share is a file system mount point backed by Amazon S3 cloud storage. Storage Gateway exposes file shares using a Network File System (NFS) interface. This operation is only supported in the file gateway type. <important> File gateway requires AWS Security Token Service (AWS STS) to be activated to enable you create a file share. Make sure AWS STS is activated in the region you are creating your file gateway in. If AWS STS is not activated in the region, activate it. For information about how to activate AWS STS, see Activating and Deactivating AWS STS in an AWS Region in the AWS Identity and Access Management User Guide. File gateway does not support creating hard or symbolic links on a file share. </important> """ def create_nfs_file_share(client, input, options \\ []) do request(client, "CreateNFSFileShare", input, options) end @doc """ Initiates a snapshot of a volume. AWS Storage Gateway provides the ability to back up point-in-time snapshots of your data to Amazon Simple Storage (S3) for durable off-site recovery, as well as import the data to an Amazon Elastic Block Store (EBS) volume in Amazon Elastic Compute Cloud (EC2). You can take snapshots of your gateway volume on a scheduled or ad-hoc basis. This API enables you to take ad-hoc snapshot. For more information, see [Editing a Snapshot Schedule](http://docs.aws.amazon.com/storagegateway/latest/userguide/managing-volumes.html#SchedulingSnapshot). In the CreateSnapshot request you identify the volume by providing its Amazon Resource Name (ARN). You must also provide description for the snapshot. When AWS Storage Gateway takes the snapshot of specified volume, the snapshot and description appears in the AWS Storage Gateway Console. In response, AWS Storage Gateway returns you a snapshot ID. You can use this snapshot ID to check the snapshot progress or later use it when you want to create a volume from a snapshot. This operation is only supported in stored and cached volume gateway type. <note> To list or delete a snapshot, you must use the Amazon EC2 API. For more information, see DescribeSnapshots or DeleteSnapshot in the [EC2 API reference](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Operations.html). </note> <important> Volume and snapshot IDs are changing to a longer length ID format. For more information, see the important note on the [Welcome](http://docs.aws.amazon.com/storagegateway/latest/APIReference/Welcome.html) page. </important> """ def create_snapshot(client, input, options \\ []) do request(client, "CreateSnapshot", input, options) end @doc """ Initiates a snapshot of a gateway from a volume recovery point. This operation is only supported in the cached volume gateway type. A volume recovery point is a point in time at which all data of the volume is consistent and from which you can create a snapshot. To get a list of volume recovery point for cached volume gateway, use `ListVolumeRecoveryPoints`. In the `CreateSnapshotFromVolumeRecoveryPoint` request, you identify the volume by providing its Amazon Resource Name (ARN). You must also provide a description for the snapshot. When the gateway takes a snapshot of the specified volume, the snapshot and its description appear in the AWS Storage Gateway console. In response, the gateway returns you a snapshot ID. You can use this snapshot ID to check the snapshot progress or later use it when you want to create a volume from a snapshot. <note> To list or delete a snapshot, you must use the Amazon EC2 API. For more information, in *Amazon Elastic Compute Cloud API Reference*. </note> """ def create_snapshot_from_volume_recovery_point(client, input, options \\ []) do request(client, "CreateSnapshotFromVolumeRecoveryPoint", input, options) end @doc """ Creates a volume on a specified gateway. This operation is only supported in the stored volume gateway type. The size of the volume to create is inferred from the disk size. You can choose to preserve existing data on the disk, create volume from an existing snapshot, or create an empty volume. If you choose to create an empty gateway volume, then any existing data on the disk is erased. In the request you must specify the gateway and the disk information on which you are creating the volume. In response, the gateway creates the volume and returns volume information such as the volume Amazon Resource Name (ARN), its size, and the iSCSI target ARN that initiators can use to connect to the volume target. """ def create_stored_iscsi_volume(client, input, options \\ []) do request(client, "CreateStorediSCSIVolume", input, options) end @doc """ Creates a virtual tape by using your own barcode. You write data to the virtual tape and then archive the tape. A barcode is unique and can not be reused if it has already been used on a tape . This applies to barcodes used on deleted tapes. This operation is only supported in the tape gateway type. <note> Cache storage must be allocated to the gateway before you can create a virtual tape. Use the `AddCache` operation to add cache storage to a gateway. </note> """ def create_tape_with_barcode(client, input, options \\ []) do request(client, "CreateTapeWithBarcode", input, options) end @doc """ Creates one or more virtual tapes. You write data to the virtual tapes and then archive the tapes. This operation is only supported in the tape gateway type. <note> Cache storage must be allocated to the gateway before you can create virtual tapes. Use the `AddCache` operation to add cache storage to a gateway. </note> """ def create_tapes(client, input, options \\ []) do request(client, "CreateTapes", input, options) end @doc """ Deletes the bandwidth rate limits of a gateway. You can delete either the upload and download bandwidth rate limit, or you can delete both. If you delete only one of the limits, the other limit remains unchanged. To specify which gateway to work with, use the Amazon Resource Name (ARN) of the gateway in your request. """ def delete_bandwidth_rate_limit(client, input, options \\ []) do request(client, "DeleteBandwidthRateLimit", input, options) end @doc """ Deletes Challenge-Handshake Authentication Protocol (CHAP) credentials for a specified iSCSI target and initiator pair. """ def delete_chap_credentials(client, input, options \\ []) do request(client, "DeleteChapCredentials", input, options) end @doc """ Deletes a file share from a file gateway. This operation is only supported in the file gateway type. """ def delete_file_share(client, input, options \\ []) do request(client, "DeleteFileShare", input, options) end @doc """ Deletes a gateway. To specify which gateway to delete, use the Amazon Resource Name (ARN) of the gateway in your request. The operation deletes the gateway; however, it does not delete the gateway virtual machine (VM) from your host computer. After you delete a gateway, you cannot reactivate it. Completed snapshots of the gateway volumes are not deleted upon deleting the gateway, however, pending snapshots will not complete. After you delete a gateway, your next step is to remove it from your environment. <important> You no longer pay software charges after the gateway is deleted; however, your existing Amazon EBS snapshots persist and you will continue to be billed for these snapshots. You can choose to remove all remaining Amazon EBS snapshots by canceling your Amazon EC2 subscription. If you prefer not to cancel your Amazon EC2 subscription, you can delete your snapshots using the Amazon EC2 console. For more information, see the [ AWS Storage Gateway Detail Page](http://aws.amazon.com/storagegateway). </important> """ def delete_gateway(client, input, options \\ []) do request(client, "DeleteGateway", input, options) end @doc """ Deletes a snapshot of a volume. You can take snapshots of your gateway volumes on a scheduled or ad hoc basis. This API action enables you to delete a snapshot schedule for a volume. For more information, see [Working with Snapshots](http://docs.aws.amazon.com/storagegateway/latest/userguide/WorkingWithSnapshots.html). In the `DeleteSnapshotSchedule` request, you identify the volume by providing its Amazon Resource Name (ARN). This operation is only supported in stored and cached volume gateway types. <note> To list or delete a snapshot, you must use the Amazon EC2 API. in *Amazon Elastic Compute Cloud API Reference*. </note> """ def delete_snapshot_schedule(client, input, options \\ []) do request(client, "DeleteSnapshotSchedule", input, options) end @doc """ Deletes the specified virtual tape. This operation is only supported in the tape gateway type. """ def delete_tape(client, input, options \\ []) do request(client, "DeleteTape", input, options) end @doc """ Deletes the specified virtual tape from the virtual tape shelf (VTS). This operation is only supported in the tape gateway type. """ def delete_tape_archive(client, input, options \\ []) do request(client, "DeleteTapeArchive", input, options) end @doc """ Deletes the specified storage volume that you previously created using the `CreateCachediSCSIVolume` or `CreateStorediSCSIVolume` API. This operation is only supported in the cached volume and stored volume types. For stored volume gateways, the local disk that was configured as the storage volume is not deleted. You can reuse the local disk to create another storage volume. Before you delete a volume, make sure there are no iSCSI connections to the volume you are deleting. You should also make sure there is no snapshot in progress. You can use the Amazon Elastic Compute Cloud (Amazon EC2) API to query snapshots on the volume you are deleting and check the snapshot status. For more information, go to [DescribeSnapshots](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshots.html) in the *Amazon Elastic Compute Cloud API Reference*. In the request, you must provide the Amazon Resource Name (ARN) of the storage volume you want to delete. """ def delete_volume(client, input, options \\ []) do request(client, "DeleteVolume", input, options) end @doc """ Returns the bandwidth rate limits of a gateway. By default, these limits are not set, which means no bandwidth rate limiting is in effect. This operation only returns a value for a bandwidth rate limit only if the limit is set. If no limits are set for the gateway, then this operation returns only the gateway ARN in the response body. To specify which gateway to describe, use the Amazon Resource Name (ARN) of the gateway in your request. """ def describe_bandwidth_rate_limit(client, input, options \\ []) do request(client, "DescribeBandwidthRateLimit", input, options) end @doc """ Returns information about the cache of a gateway. This operation is only supported in the cached volume, tape and file gateway types. The response includes disk IDs that are configured as cache, and it includes the amount of cache allocated and used. """ def describe_cache(client, input, options \\ []) do request(client, "DescribeCache", input, options) end @doc """ Returns a description of the gateway volumes specified in the request. This operation is only supported in the cached volume gateway types. The list of gateway volumes in the request must be from one gateway. In the response Amazon Storage Gateway returns volume information sorted by volume Amazon Resource Name (ARN). """ def describe_cached_iscsi_volumes(client, input, options \\ []) do request(client, "DescribeCachediSCSIVolumes", input, options) end @doc """ Returns an array of Challenge-Handshake Authentication Protocol (CHAP) credentials information for a specified iSCSI target, one for each target-initiator pair. """ def describe_chap_credentials(client, input, options \\ []) do request(client, "DescribeChapCredentials", input, options) end @doc """ Returns metadata about a gateway such as its name, network interfaces, configured time zone, and the state (whether the gateway is running or not). To specify which gateway to describe, use the Amazon Resource Name (ARN) of the gateway in your request. """ def describe_gateway_information(client, input, options \\ []) do request(client, "DescribeGatewayInformation", input, options) end @doc """ Returns your gateway's weekly maintenance start time including the day and time of the week. Note that values are in terms of the gateway's time zone. """ def describe_maintenance_start_time(client, input, options \\ []) do request(client, "DescribeMaintenanceStartTime", input, options) end @doc """ Gets a description for one or more file shares from a file gateway. This operation is only supported in the file gateway type. """ def describe_nfs_file_shares(client, input, options \\ []) do request(client, "DescribeNFSFileShares", input, options) end @doc """ Describes the snapshot schedule for the specified gateway volume. The snapshot schedule information includes intervals at which snapshots are automatically initiated on the volume. This operation is only supported in the cached volume and stored volume types. """ def describe_snapshot_schedule(client, input, options \\ []) do request(client, "DescribeSnapshotSchedule", input, options) end @doc """ Returns the description of the gateway volumes specified in the request. The list of gateway volumes in the request must be from one gateway. In the response Amazon Storage Gateway returns volume information sorted by volume ARNs. This operation is only supported in stored volume gateway type. """ def describe_stored_iscsi_volumes(client, input, options \\ []) do request(client, "DescribeStorediSCSIVolumes", input, options) end @doc """ Returns a description of specified virtual tapes in the virtual tape shelf (VTS). This operation is only supported in the tape gateway type. If a specific `TapeARN` is not specified, AWS Storage Gateway returns a description of all virtual tapes found in the VTS associated with your account. """ def describe_tape_archives(client, input, options \\ []) do request(client, "DescribeTapeArchives", input, options) end @doc """ Returns a list of virtual tape recovery points that are available for the specified tape gateway. A recovery point is a point-in-time view of a virtual tape at which all the data on the virtual tape is consistent. If your gateway crashes, virtual tapes that have recovery points can be recovered to a new gateway. This operation is only supported in the tape gateway type. """ def describe_tape_recovery_points(client, input, options \\ []) do request(client, "DescribeTapeRecoveryPoints", input, options) end @doc """ Returns a description of the specified Amazon Resource Name (ARN) of virtual tapes. If a `TapeARN` is not specified, returns a description of all virtual tapes associated with the specified gateway. This operation is only supported in the tape gateway type. """ def describe_tapes(client, input, options \\ []) do request(client, "DescribeTapes", input, options) end @doc """ Returns information about the upload buffer of a gateway. This operation is supported for the stored volume, cached volume and tape gateway types. The response includes disk IDs that are configured as upload buffer space, and it includes the amount of upload buffer space allocated and used. """ def describe_upload_buffer(client, input, options \\ []) do request(client, "DescribeUploadBuffer", input, options) end @doc """ Returns a description of virtual tape library (VTL) devices for the specified tape gateway. In the response, AWS Storage Gateway returns VTL device information. This operation is only supported in the tape gateway type. """ def describe_vtl_devices(client, input, options \\ []) do request(client, "DescribeVTLDevices", input, options) end @doc """ Returns information about the working storage of a gateway. This operation is only supported in the stored volumes gateway type. This operation is deprecated in cached volumes API version (20120630). Use DescribeUploadBuffer instead. <note> Working storage is also referred to as upload buffer. You can also use the DescribeUploadBuffer operation to add upload buffer to a stored volume gateway. </note> The response includes disk IDs that are configured as working storage, and it includes the amount of working storage allocated and used. """ def describe_working_storage(client, input, options \\ []) do request(client, "DescribeWorkingStorage", input, options) end @doc """ Disables a tape gateway when the gateway is no longer functioning. For example, if your gateway VM is damaged, you can disable the gateway so you can recover virtual tapes. Use this operation for a tape gateway that is not reachable or not functioning. This operation is only supported in the tape gateway type. <important> Once a gateway is disabled it cannot be enabled. </important> """ def disable_gateway(client, input, options \\ []) do request(client, "DisableGateway", input, options) end @doc """ Gets a list of the file shares for a specific file gateway, or the list of file shares that belong to the calling user account. This operation is only supported in the file gateway type. """ def list_file_shares(client, input, options \\ []) do request(client, "ListFileShares", input, options) end @doc """ Lists gateways owned by an AWS account in a region specified in the request. The returned list is ordered by gateway Amazon Resource Name (ARN). By default, the operation returns a maximum of 100 gateways. This operation supports pagination that allows you to optionally reduce the number of gateways returned in a response. If you have more gateways than are returned in a response (that is, the response returns only a truncated list of your gateways), the response contains a marker that you can specify in your next request to fetch the next page of gateways. """ def list_gateways(client, input, options \\ []) do request(client, "ListGateways", input, options) end @doc """ Returns a list of the gateway's local disks. To specify which gateway to describe, you use the Amazon Resource Name (ARN) of the gateway in the body of the request. The request returns a list of all disks, specifying which are configured as working storage, cache storage, or stored volume or not configured at all. The response includes a `DiskStatus` field. This field can have a value of present (the disk is available to use), missing (the disk is no longer connected to the gateway), or mismatch (the disk node is occupied by a disk that has incorrect metadata or the disk content is corrupted). """ def list_local_disks(client, input, options \\ []) do request(client, "ListLocalDisks", input, options) end @doc """ Lists the tags that have been added to the specified resource. This operation is only supported in the cached volume, stored volume and tape gateway type. """ def list_tags_for_resource(client, input, options \\ []) do request(client, "ListTagsForResource", input, options) end @doc """ Lists virtual tapes in your virtual tape library (VTL) and your virtual tape shelf (VTS). You specify the tapes to list by specifying one or more tape Amazon Resource Names (ARNs). If you don't specify a tape ARN, the operation lists all virtual tapes in both your VTL and VTS. This operation supports pagination. By default, the operation returns a maximum of up to 100 tapes. You can optionally specify the `Limit` parameter in the body to limit the number of tapes in the response. If the number of tapes returned in the response is truncated, the response includes a `Marker` element that you can use in your subsequent request to retrieve the next set of tapes. This operation is only supported in the tape gateway type. """ def list_tapes(client, input, options \\ []) do request(client, "ListTapes", input, options) end @doc """ Lists iSCSI initiators that are connected to a volume. You can use this operation to determine whether a volume is being used or not. This operation is only supported in the cached volume and stored volume gateway types. """ def list_volume_initiators(client, input, options \\ []) do request(client, "ListVolumeInitiators", input, options) end @doc """ Lists the recovery points for a specified gateway. This operation is only supported in the cached volume gateway type. Each cache volume has one recovery point. A volume recovery point is a point in time at which all data of the volume is consistent and from which you can create a snapshot or clone a new cached volume from a source volume. To create a snapshot from a volume recovery point use the `CreateSnapshotFromVolumeRecoveryPoint` operation. """ def list_volume_recovery_points(client, input, options \\ []) do request(client, "ListVolumeRecoveryPoints", input, options) end @doc """ Lists the iSCSI stored volumes of a gateway. Results are sorted by volume ARN. The response includes only the volume ARNs. If you want additional volume information, use the `DescribeStorediSCSIVolumes` or the `DescribeCachediSCSIVolumes` API. The operation supports pagination. By default, the operation returns a maximum of up to 100 volumes. You can optionally specify the `Limit` field in the body to limit the number of volumes in the response. If the number of volumes returned in the response is truncated, the response includes a Marker field. You can use this Marker value in your subsequent request to retrieve the next set of volumes. This operation is only supported in the cached volume and stored volume gateway types. """ def list_volumes(client, input, options \\ []) do request(client, "ListVolumes", input, options) end @doc """ Sends you notification through CloudWatch Events when all files written to your NFS file share have been uploaded to Amazon S3. AWS Storage Gateway can send a notification through Amazon CloudWatch Events when all files written to your file share up to that point in time have been uploaded to Amazon S3. These files include files written to the NFS file share up to the time that you make a request for notification. When the upload is done, Storage Gateway sends you notification through an Amazon CloudWatch Event. You can configure CloudWatch Events to send the notification through event targets such as Amazon SNS or AWS Lambda function. This operation is only supported in the file gateway type. For more information, see Getting File Upload Notification in the Storage Gateway User Guide (https://docs.aws.amazon.com/storagegateway/latest/userguide/monitoring-file-gateway.html#get-upload-notification). """ def notify_when_uploaded(client, input, options \\ []) do request(client, "NotifyWhenUploaded", input, options) end @doc """ Refreshes the cache for the specified file share. This operation finds objects in the Amazon S3 bucket that were added, removed or replaced since the gateway last listed the bucket's contents and cached the results. This operation is only supported in the file gateway type. """ def refresh_cache(client, input, options \\ []) do request(client, "RefreshCache", input, options) end @doc """ Removes one or more tags from the specified resource. This operation is only supported in the cached volume, stored volume and tape gateway types. """ def remove_tags_from_resource(client, input, options \\ []) do request(client, "RemoveTagsFromResource", input, options) end @doc """ Resets all cache disks that have encountered a error and makes the disks available for reconfiguration as cache storage. If your cache disk encounters a error, the gateway prevents read and write operations on virtual tapes in the gateway. For example, an error can occur when a disk is corrupted or removed from the gateway. When a cache is reset, the gateway loses its cache storage. At this point you can reconfigure the disks as cache disks. This operation is only supported in the cached volume and tape types. <important> If the cache disk you are resetting contains data that has not been uploaded to Amazon S3 yet, that data can be lost. After you reset cache disks, there will be no configured cache disks left in the gateway, so you must configure at least one new cache disk for your gateway to function properly. </important> """ def reset_cache(client, input, options \\ []) do request(client, "ResetCache", input, options) end @doc """ Retrieves an archived virtual tape from the virtual tape shelf (VTS) to a tape gateway. Virtual tapes archived in the VTS are not associated with any gateway. However after a tape is retrieved, it is associated with a gateway, even though it is also listed in the VTS, that is, archive. This operation is only supported in the tape gateway type. Once a tape is successfully retrieved to a gateway, it cannot be retrieved again to another gateway. You must archive the tape again before you can retrieve it to another gateway. This operation is only supported in the tape gateway type. """ def retrieve_tape_archive(client, input, options \\ []) do request(client, "RetrieveTapeArchive", input, options) end @doc """ Retrieves the recovery point for the specified virtual tape. This operation is only supported in the tape gateway type. A recovery point is a point in time view of a virtual tape at which all the data on the tape is consistent. If your gateway crashes, virtual tapes that have recovery points can be recovered to a new gateway. <note> The virtual tape can be retrieved to only one gateway. The retrieved tape is read-only. The virtual tape can be retrieved to only a tape gateway. There is no charge for retrieving recovery points. </note> """ def retrieve_tape_recovery_point(client, input, options \\ []) do request(client, "RetrieveTapeRecoveryPoint", input, options) end @doc """ Sets the password for your VM local console. When you log in to the local console for the first time, you log in to the VM with the default credentials. We recommend that you set a new password. You don't need to know the default password to set a new password. """ def set_local_console_password(client, input, options \\ []) do request(client, "SetLocalConsolePassword", input, options) end @doc """ Shuts down a gateway. To specify which gateway to shut down, use the Amazon Resource Name (ARN) of the gateway in the body of your request. The operation shuts down the gateway service component running in the gateway's virtual machine (VM) and not the host VM. <note> If you want to shut down the VM, it is recommended that you first shut down the gateway component in the VM to avoid unpredictable conditions. </note> After the gateway is shutdown, you cannot call any other API except `StartGateway`, `DescribeGatewayInformation`, and `ListGateways`. For more information, see `ActivateGateway`. Your applications cannot read from or write to the gateway's storage volumes, and there are no snapshots taken. <note> When you make a shutdown request, you will get a `200 OK` success response immediately. However, it might take some time for the gateway to shut down. You can call the `DescribeGatewayInformation` API to check the status. For more information, see `ActivateGateway`. </note> If do not intend to use the gateway again, you must delete the gateway (using `DeleteGateway`) to no longer pay software charges associated with the gateway. """ def shutdown_gateway(client, input, options \\ []) do request(client, "ShutdownGateway", input, options) end @doc """ Starts a gateway that you previously shut down (see `ShutdownGateway`). After the gateway starts, you can then make other API calls, your applications can read from or write to the gateway's storage volumes and you will be able to take snapshot backups. <note> When you make a request, you will get a 200 OK success response immediately. However, it might take some time for the gateway to be ready. You should call `DescribeGatewayInformation` and check the status before making any additional API calls. For more information, see `ActivateGateway`. </note> To specify which gateway to start, use the Amazon Resource Name (ARN) of the gateway in your request. """ def start_gateway(client, input, options \\ []) do request(client, "StartGateway", input, options) end @doc """ Updates the bandwidth rate limits of a gateway. You can update both the upload and download bandwidth rate limit or specify only one of the two. If you don't set a bandwidth rate limit, the existing rate limit remains. By default, a gateway's bandwidth rate limits are not set. If you don't set any limit, the gateway does not have any limitations on its bandwidth usage and could potentially use the maximum available bandwidth. To specify which gateway to update, use the Amazon Resource Name (ARN) of the gateway in your request. """ def update_bandwidth_rate_limit(client, input, options \\ []) do request(client, "UpdateBandwidthRateLimit", input, options) end @doc """ Updates the Challenge-Handshake Authentication Protocol (CHAP) credentials for a specified iSCSI target. By default, a gateway does not have CHAP enabled; however, for added security, you might use it. <important> When you update CHAP credentials, all existing connections on the target are closed and initiators must reconnect with the new credentials. </important> """ def update_chap_credentials(client, input, options \\ []) do request(client, "UpdateChapCredentials", input, options) end @doc """ Updates a gateway's metadata, which includes the gateway's name and time zone. To specify which gateway to update, use the Amazon Resource Name (ARN) of the gateway in your request. <note> For Gateways activated after September 2, 2015, the gateway's ARN contains the gateway ID rather than the gateway name. However, changing the name of the gateway has no effect on the gateway's ARN. </note> """ def update_gateway_information(client, input, options \\ []) do request(client, "UpdateGatewayInformation", input, options) end @doc """ Updates the gateway virtual machine (VM) software. The request immediately triggers the software update. <note> When you make this request, you get a `200 OK` success response immediately. However, it might take some time for the update to complete. You can call `DescribeGatewayInformation` to verify the gateway is in the `STATE_RUNNING` state. </note> <important> A software update forces a system restart of your gateway. You can minimize the chance of any disruption to your applications by increasing your iSCSI Initiators' timeouts. For more information about increasing iSCSI Initiator timeouts for Windows and Linux, see [Customizing Your Windows iSCSI Settings](http://docs.aws.amazon.com/storagegateway/latest/userguide/ConfiguringiSCSIClientInitiatorWindowsClient.html#CustomizeWindowsiSCSISettings) and [Customizing Your Linux iSCSI Settings](http://docs.aws.amazon.com/storagegateway/latest/userguide/ConfiguringiSCSIClientInitiatorRedHatClient.html#CustomizeLinuxiSCSISettings), respectively. </important> """ def update_gateway_software_now(client, input, options \\ []) do request(client, "UpdateGatewaySoftwareNow", input, options) end @doc """ Updates a gateway's weekly maintenance start time information, including day and time of the week. The maintenance time is the time in your gateway's time zone. """ def update_maintenance_start_time(client, input, options \\ []) do request(client, "UpdateMaintenanceStartTime", input, options) end @doc """ Updates a file share. This operation is only supported in the file gateway type. <note> To leave a file share field unchanged, set the corresponding input field to null. </note> Updates the following file share setting: <ul> <li> Default storage class for your S3 bucket </li> <li> Metadata defaults for your S3 bucket </li> <li> Allowed NFS clients for your file share </li> <li> Squash settings </li> <li> Write status of your file share </li> </ul> <note> To leave a file share field unchanged, set the corresponding input field to null. This operation is only supported in file gateways. </note> """ def update_nfs_file_share(client, input, options \\ []) do request(client, "UpdateNFSFileShare", input, options) end @doc """ Updates a snapshot schedule configured for a gateway volume. This operation is only supported in the cached volume and stored volume gateway types. The default snapshot schedule for volume is once every 24 hours, starting at the creation time of the volume. You can use this API to change the snapshot schedule configured for the volume. In the request you must identify the gateway volume whose snapshot schedule you want to update, and the schedule information, including when you want the snapshot to begin on a day and the frequency (in hours) of snapshots. """ def update_snapshot_schedule(client, input, options \\ []) do request(client, "UpdateSnapshotSchedule", input, options) end @doc """ Updates the type of medium changer in a tape gateway. When you activate a tape gateway, you select a medium changer type for the tape gateway. This operation enables you to select a different type of medium changer after a tape gateway is activated. This operation is only supported in the tape gateway type. """ def update_vtl_device_type(client, input, options \\ []) do request(client, "UpdateVTLDeviceType", input, options) end @spec request(map(), binary(), map(), list()) :: {:ok, Poison.Parser.t | nil, Poison.Response.t} | {:error, Poison.Parser.t} | {:error, HTTPoison.Error.t} defp request(client, action, input, options) do client = %{client | service: "storagegateway"} host = get_host("storagegateway", client) url = get_url(host, client) headers = [{"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}, {"X-Amz-Target", "StorageGateway_20130630.#{action}"}] payload = Poison.Encoder.encode(input, []) headers = AWS.Request.sign_v4(client, "POST", url, headers, payload) case HTTPoison.post(url, payload, headers, options) do {:ok, response=%HTTPoison.Response{status_code: 200, body: ""}} -> {:ok, nil, response} {:ok, response=%HTTPoison.Response{status_code: 200, body: body}} -> {:ok, Poison.Parser.parse!(body), response} {:ok, _response=%HTTPoison.Response{body: body}} -> error = Poison.Parser.parse!(body) exception = error["__type"] message = error["message"] {:error, {exception, message}} {:error, %HTTPoison.Error{reason: reason}} -> {:error, %HTTPoison.Error{reason: reason}} end end defp get_host(endpoint_prefix, client) do if client.region == "local" do "localhost" else "#{endpoint_prefix}.#{client.region}.#{client.endpoint}" end end defp get_url(host, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}/" end end
42.019663
151
0.745571
1c8d7710730d81e21795a1ff8d0c829d410f75c6
80
ex
Elixir
lib/retroflect_web/views/user_reset_password_view.ex
gaslight/retroflect
d98a52dbe4ef14dd50ef06970fba9c673e456647
[ "MIT" ]
3
2021-10-04T15:03:09.000Z
2021-10-05T00:42:19.000Z
lib/retroflect_web/views/user_reset_password_view.ex
gaslight/retroflect
d98a52dbe4ef14dd50ef06970fba9c673e456647
[ "MIT" ]
29
2021-10-04T12:56:21.000Z
2021-10-20T17:38:12.000Z
lib/retroflect_web/views/user_reset_password_view.ex
gaslight/retroflect
d98a52dbe4ef14dd50ef06970fba9c673e456647
[ "MIT" ]
null
null
null
defmodule RetroflectWeb.UserResetPasswordView do use RetroflectWeb, :view end
20
48
0.85
1c8d9ee1d9e8265e5c81bc158052528a676debd7
3,717
ex
Elixir
lib/ash/resource.ex
smt116/ash
880a17f197873eb1c8dc8d81a8b4d6d9cb570b3f
[ "MIT" ]
null
null
null
lib/ash/resource.ex
smt116/ash
880a17f197873eb1c8dc8d81a8b4d6d9cb570b3f
[ "MIT" ]
null
null
null
lib/ash/resource.ex
smt116/ash
880a17f197873eb1c8dc8d81a8b4d6d9cb570b3f
[ "MIT" ]
null
null
null
defmodule Ash.Resource do @moduledoc """ A resource is a static definition of an entity in your system. Resource DSL documentation: `Ash.Resource.Dsl` """ @type t :: module @type record :: struct() use Ash.Dsl, single_extension_kinds: [:data_layer], many_extension_kinds: [ :authorizers, :notifiers ], default_extensions: [ data_layer: Ash.DataLayer.Simple, extensions: [Ash.Resource.Dsl] ] def init(opts) do if opts[:data_layer] == :embedded do {:ok, opts |> Keyword.put(:data_layer, Ash.DataLayer.Simple) |> Keyword.put(:embedded?, true)} else {:ok, opts} end end def handle_opts(opts) do quote bind_quoted: [embedded?: opts[:embedded?]] do if embedded? do @persist {:embedded?, true} require Ash.EmbeddableType Ash.EmbeddableType.define_embeddable_type() end end end def handle_before_compile(_opts) do quote do require Ash.Schema if !@moduledoc do @moduledoc Ash.Resource.Info.description(__MODULE__) || false end Ash.Schema.define_schema() @all_arguments __MODULE__ |> Ash.Resource.Info.actions() |> Enum.flat_map(& &1.arguments) |> Enum.map(& &1.name) |> Enum.uniq() @arguments_by_action __MODULE__ |> Ash.Resource.Info.actions() |> Map.new(fn action -> {action.name, Enum.map(action.arguments, & &1.name)} end) @all_attributes __MODULE__ |> Ash.Resource.Info.attributes() |> Enum.map(& &1.name) |> Enum.uniq() if api = Ash.Resource.Info.define_interface_for(__MODULE__) do require Ash.CodeInterface Ash.CodeInterface.define_interface(api, __MODULE__) end @doc """ Validates that the keys in the provided input are valid for at least one action on the resource. Raises a KeyError error at compile time if not. This exists because generally a struct should only ever be created by Ash as a result of a successful action. You should not be creating records manually in code, e.g `%MyResource{value: 1, value: 2}`. Generally that is fine, but often with embedded resources it is nice to be able to validate the keys that are being provided, e.g ```elixir Resource |> Ash.Changeset.for_create(:create, %{embedded: EmbeddedResource.input(foo: 1, bar: 2)}) |> MyApp.Api.create() ``` """ @spec input(values :: map | Keyword.t()) :: map | no_return def input(opts) do Map.new(opts, fn {key, value} -> if key in @all_arguments || key in @all_attributes do {key, value} else raise KeyError, key: key end end) end @doc """ Same as `input/1`, except restricts the keys to values accepted by the action provided. """ @spec input(values :: map | Keyword.t(), action :: atom) :: map | no_return def input(opts, action) do case Map.fetch(@arguments_by_action, action) do :error -> raise ArgumentError, message: "No such action #{inspect(action)}" {:ok, args} -> action = Ash.Resource.Info.action(__MODULE__, action) Map.new(opts, fn {key, value} -> if key in action.accept do {key, value} else raise KeyError, key: key end end) end end end end end
29.5
113
0.566317
1c8e0bfb023ac20a0924eaf84c021321b3aed090
1,734
ex
Elixir
lib/has_my_gsuite_been_pwned_web/endpoint.ex
obahareth/has-my-gsuite-been-pwned
03762027e94c16fc939ec6a7174b13f2a622d456
[ "MIT" ]
4
2018-09-21T19:41:02.000Z
2019-06-12T04:40:42.000Z
lib/has_my_gsuite_been_pwned_web/endpoint.ex
obahareth/has-my-gsuite-been-pwned
03762027e94c16fc939ec6a7174b13f2a622d456
[ "MIT" ]
9
2018-10-05T15:02:33.000Z
2018-10-30T03:12:50.000Z
lib/has_my_gsuite_been_pwned_web/endpoint.ex
obahareth/has-my-gsuite-been-pwned
03762027e94c16fc939ec6a7174b13f2a622d456
[ "MIT" ]
1
2018-10-06T15:46:15.000Z
2018-10-06T15:46:15.000Z
defmodule HasMyGsuiteBeenPwnedWeb.Endpoint do use Phoenix.Endpoint, otp_app: :has_my_gsuite_been_pwned socket "/socket", HasMyGsuiteBeenPwnedWeb.UserSocket # Serve at "/" the static files from "priv/static" directory. # # You should set gzip to true if you are running phoenix.digest # when deploying your static files in production. plug Plug.Static, at: "/", from: :has_my_gsuite_been_pwned, gzip: false, only: ~w(css fonts images js favicon.ico robots.txt) # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. if code_reloading? do socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket plug Phoenix.LiveReloader plug Phoenix.CodeReloader end plug Plug.Logger plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Poison plug Plug.MethodOverride plug Plug.Head # The session will be stored in the cookie and signed, # this means its contents can be read but not tampered with. # Set :encryption_salt if you would also like to encrypt it. plug Plug.Session, store: :cookie, key: "_has_my_gsuite_been_pwned_key", signing_salt: "H11M7D1L" plug HasMyGsuiteBeenPwnedWeb.Router @doc """ Callback invoked for dynamically configuring the endpoint. It receives the endpoint configuration and checks if configuration should be loaded from the system environment. """ def init(_key, config) do if config[:load_from_system_env] do port = System.get_env("PORT") || raise "expected the PORT environment variable to be set" {:ok, Keyword.put(config, :http, [:inet6, port: port])} else {:ok, config} end end end
30.421053
95
0.72203
1c8e640e87f2e3281c5ca132f159d772d86ffdee
715
exs
Elixir
y_combinator.exs
pmarreck/elixir-snippets
5f5ee26087bc2ded4e71c4c3eeff1231310ff358
[ "BSD-3-Clause" ]
34
2015-02-27T14:41:12.000Z
2021-09-26T06:06:18.000Z
y_combinator.exs
pmarreck/elixir-snippets
5f5ee26087bc2ded4e71c4c3eeff1231310ff358
[ "BSD-3-Clause" ]
null
null
null
y_combinator.exs
pmarreck/elixir-snippets
5f5ee26087bc2ded4e71c4c3eeff1231310ff358
[ "BSD-3-Clause" ]
3
2016-02-05T16:09:41.000Z
2017-10-21T15:47:04.000Z
defmodule Combinator do def fix(f) do (fn x -> f.(fn y -> (x.(x)).(y) end) end).(fn x -> f.(fn y -> (x.(x)).(y) end) end) end end # run this inline suite with "elixir #{__ENV__.file} test" if System.argv |> List.first == "test" do ExUnit.start defmodule CombinatorTest do use ExUnit.Case, async: true alias Combinator, as: C test "calling anonymous function recursively that does factorial" do fact = C.fix(fn this_function -> fn 0 -> 1 x when x > 0 -> x * this_function.(x-1) end end) assert 120 == fact.(5) end end end
22.34375
72
0.490909
1c8e7a9a9c2414eb12e8c215babcff35ecf7d6e0
148
ex
Elixir
web/controllers/page_controller.ex
simonasdev/splurty
0bee8871803b25d19d4ba96c872d51321ce81d2f
[ "MIT" ]
null
null
null
web/controllers/page_controller.ex
simonasdev/splurty
0bee8871803b25d19d4ba96c872d51321ce81d2f
[ "MIT" ]
null
null
null
web/controllers/page_controller.ex
simonasdev/splurty
0bee8871803b25d19d4ba96c872d51321ce81d2f
[ "MIT" ]
null
null
null
defmodule Splurty.PageController do use Phoenix.Controller plug :action def index(conn, _params) do render conn, "index.html" end end
14.8
35
0.72973
1c8e7df4faddde4486e0638c3fc2b3b61dd214fd
687
exs
Elixir
test/acceptance/transform/meta_test.exs
feld/earmark
149a174e8955de2c6833d4497e5d445dceea63dc
[ "Apache-1.1" ]
null
null
null
test/acceptance/transform/meta_test.exs
feld/earmark
149a174e8955de2c6833d4497e5d445dceea63dc
[ "Apache-1.1" ]
null
null
null
test/acceptance/transform/meta_test.exs
feld/earmark
149a174e8955de2c6833d4497e5d445dceea63dc
[ "Apache-1.1" ]
null
null
null
defmodule Acceptance.Transform.MetaTest do use ExUnit.Case import Support.AstHelpers, only: [ast_from_md: 1] import Earmark.Transform # Needs to pass with #359 describe "pre and verbatim" do @pre """ some code """ test "base case w/o verbatim" do {:ok, ast, _} = ast_from_md(@pre) expected = "<pre><code> some code</code></pre>\n" assert transform(ast) == expected end test "base case with verbatim" do {:ok, [{"pre", atts, children, _}], _} = ast_from_md(@pre) expected = "<pre><code> some code</code></pre>\n" assert transform([{"pre", atts, children, %{verbatim: true}}]) == expected end end end
26.423077
80
0.608443
1c8eb955d44aed4a4e7219cdb014a21785f63b03
2,353
ex
Elixir
lib/exfavicon/finder.ex
ikeikeikeike/exfavicon
c3248befb037f3579891b79ef91da479bc25a754
[ "MIT" ]
8
2015-12-13T05:08:43.000Z
2021-06-04T15:59:21.000Z
lib/exfavicon/finder.ex
ikeikeikeike/exfavicon
c3248befb037f3579891b79ef91da479bc25a754
[ "MIT" ]
null
null
null
lib/exfavicon/finder.ex
ikeikeikeike/exfavicon
c3248befb037f3579891b79ef91da479bc25a754
[ "MIT" ]
null
null
null
defmodule Exfavicon.Finder do use HTTPoison.Base def find(url) do {:ok, location, resp} = req(url) icon_url = find_from_html(resp.body, location) if icon_url, do: icon_url, else: default_path(location) end def find_from_html(html, url) do case detect(html, url) do {:ok, icon_url} -> if valid_favicon_url?(icon_url), do: icon_url, else: nil _ -> nil end end def valid_favicon_url?(url) do case head(url) do {:ok, resp} -> ctype = resp.headers |> get_header("content-type") if Regex.match?(~r/image/, ctype), do: true, else: false _ -> false end end defp req(url) do {:ok, resp} = get(url) headers = resp.headers |> Enum.map(fn({k, v}) -> {k |> String.downcase, v} end) case List.keyfind(headers, "location", 0) do {"location", location} -> req(location) _ -> {:ok, url, resp} end end defp detect(html, url) do {:ok, ptn} = Regex.compile("^(shortcut )?icon$", "i") favicon_url_or_path = html |> Floki.find("link") |> Enum.filter(&(Regex.match?(ptn, List.first(Floki.attribute(&1, "rel"))))) |> Enum.flat_map(&(Floki.attribute(&1, "href"))) |> List.first case favicon_url_or_path do "" -> {:error, "blank"} nil -> {:error, "blank"} _ -> case Regex.match?(~r/^https?/, favicon_url_or_path) do true -> {:ok, favicon_url_or_path} false -> uri = URI.parse(favicon_url_or_path) case uri do %URI{host: nil} -> {:ok, %{URI.parse(url) | path: uri.path} |> URI.to_string} %URI{scheme: nil} -> {:ok, %{uri | scheme: "http"} |> URI.to_string} _ -> {:error, "unknown uri"} end end end end defp get_header(headers, key) do ctype = headers |> Enum.map(fn({k, v}) -> {k |> String.downcase, v} end) |> Enum.filter(fn({k, _}) -> k == (key |> String.downcase) end) case ctype do [] -> "" _ -> ctype |> hd |> elem(1) end end defp default_path(url) do %{URI.parse(url) | path: "/favicon.ico", query: nil, fragment: nil} |> URI.to_string end end
24.010204
82
0.514237
1c8ecd42be645911ceb903730658eb811bc2c798
1,613
ex
Elixir
lib/shipsim/extract_map.ex
jeremysquires/shipsim
cacf0b7b825a3086e1cc1676374691de3d1cb0c5
[ "MIT" ]
null
null
null
lib/shipsim/extract_map.ex
jeremysquires/shipsim
cacf0b7b825a3086e1cc1676374691de3d1cb0c5
[ "MIT" ]
null
null
null
lib/shipsim/extract_map.ex
jeremysquires/shipsim
cacf0b7b825a3086e1cc1676374691de3d1cb0c5
[ "MIT" ]
1
2019-06-04T04:49:42.000Z
2019-06-04T04:49:42.000Z
defmodule ShipSim.ExtractMap do @doc """ Extract all the data from the JSON maps into the arrays and maps needed to do the next steps of calculation Also use: Map.fetch!(extract_article_content, "key") Enum.find(fn {key, _value} -> case Integer.parse(key) do :error -> false _ -> key end end) """ def output_content(map) do {:ok, body} = map all = fn :get, data, next -> Enum.map(data, next) end extract_vessels = get_in(body, ["vessels", all]) IO.inspect extract_vessels end def extract_vessels_names(map) do {:ok, body} = map all = fn :get, data, next -> Enum.map(data, next) end vessels_names = get_in(body, ["vessels", all, "name"]) if (length(vessels_names) > 0) do {:ok, vessels_names} else {:err, "no vessels found"} end end def extract_positions_by_vessel(map, vessel_name) do vessels = map["vessels"] %{"name" => _, "positions" => positions} = Enum.find(vessels, [], fn vessel -> if (vessel["name"] == vessel_name) do vessel["positions"] else false end end ) if (length(positions) > 0) do {:ok, positions} else {:err, "no positions found"} end end def extract_vessel_by_name(map, vessel_name) do vessels = map["vessels"] ship = Enum.find(vessels, [], fn vessel -> if (vessel["name"] == vessel_name) do vessel else false end end ) if (ship) do {:ok, ship} else {:err, "no ship found"} end end end
23.042857
69
0.568506
1c8ed19d4df63d39db36bdc1d8f86f4a4c4ab19b
3,506
exs
Elixir
farmbot_ext/test/farmbot_ext/amqp/terminal_channel_test.exs
va2ron1/farmbot_os
c80a38058713adc2ad91a4802664bcfe8da9d96c
[ "MIT" ]
null
null
null
farmbot_ext/test/farmbot_ext/amqp/terminal_channel_test.exs
va2ron1/farmbot_os
c80a38058713adc2ad91a4802664bcfe8da9d96c
[ "MIT" ]
null
null
null
farmbot_ext/test/farmbot_ext/amqp/terminal_channel_test.exs
va2ron1/farmbot_os
c80a38058713adc2ad91a4802664bcfe8da9d96c
[ "MIT" ]
null
null
null
defmodule FarmbotExt.AMQP.TerminalChannelTest do require Helpers use ExUnit.Case, async: false use Mimic setup :verify_on_exit! setup :set_mimic_global alias FarmbotExt.AMQP.TerminalChannel alias FarmbotExt.AMQP.TerminalChannelSupport, as: Support @jwt %FarmbotExt.JWT{bot: "device_#{Enum.random(1000..100_000)}"} @chan %{fake_chan: true} def tty_send(pid, data) do mesg = {:basic_deliver, data, %{routing_key: "UNIT_TESTS"}} send(pid, mesg) pid end def base_case() do simulate_network([{:ok, @chan}]) {:ok, pid} = TerminalChannel.start_link([jwt: @jwt], []) pid end # Simulates a series of network return values for a stubbed # version of TerminalChannelSupport.get_channel/1 def expect_response(expectations) do total = Enum.count(expectations) {:ok, counter} = SimpleCounter.new() expect(Support, :tty_send, total, fn _, _, actual -> current_index = SimpleCounter.bump(counter, 1) - 1 expected = Enum.at(expectations, current_index) assert expected == actual :ok end) end # Simulates a series of network return values for a stubbed # version of TerminalChannelSupport.get_channel/1 def simulate_network(return_values) do total = Enum.count(return_values) {:ok, counter} = SimpleCounter.new() expect(Support, :get_channel, total, fn bot -> current_index = SimpleCounter.bump(counter, 1) - 1 next_value = Enum.at(return_values, current_index) assert bot == @jwt.bot next_value end) end test "terminal channel startup" do Helpers.expect_log("Connected to terminal channel") pid = base_case() actual = :sys.get_state(pid) expected = %TerminalChannel{chan: @chan, iex_pid: nil, jwt: @jwt} assert actual == expected GenServer.stop(pid, :normal) end test "terminal channel startup - nil return value" do Helpers.expect_log("Connected to terminal channel") simulate_network([nil, {:ok, @chan}]) {:ok, pid} = TerminalChannel.start_link([jwt: @jwt], []) actual = :sys.get_state(pid) expected = %TerminalChannel{chan: @chan, iex_pid: nil, jwt: @jwt} assert actual == expected GenServer.stop(pid, :normal) end test "terminal channel startup - return an error" do Helpers.expect_log("Terminal connection failed: {:error, \"Try again\"}") simulate_network([{:error, "Try again"}, {:ok, @chan}]) {:ok, pid} = TerminalChannel.start_link([jwt: @jwt], []) actual = :sys.get_state(pid) expected = %TerminalChannel{chan: @chan, iex_pid: nil, jwt: @jwt} assert actual == expected GenServer.stop(pid, :normal) end test "Connects to AMQP" do Helpers.expect_log("Connected to terminal channel") pid = base_case() previous_state = :sys.get_state(pid) messages = [{:basic_cancel_ok, %{}}, {:basic_consume_ok, %{}}] Enum.map(messages, fn item -> send(pid, item) end) assert previous_state == :sys.get_state(pid) send(pid, {:basic_cancel, %{}}) Process.sleep(1) refute Process.alive?(pid) end test "execute commands over TermincalChannel" do expected = [ "Starting IEx...", "Interactive Elixir (1.10.4) - press Ctrl+C to exit (type h() ENTER for help)\r\n", "iex(1)> " ] expect(Support, :tty_send, 4, fn _bot, _chan, actual -> assert Enum.member?(expected, actual) end) tty_send(base_case(), "\r") Process.sleep(50) tty_send(base_case(), "2 + 2\r") Process.sleep(50) end end
30.486957
89
0.667427
1c8ed8abeaea5a7ec3d93cc3543f735f3c6da7a7
693
ex
Elixir
src/Data/Ord.ex
sriduth/purescript-prelude
018250e052ec11dc6faae61ea41c1a11fdf64e0e
[ "MIT" ]
null
null
null
src/Data/Ord.ex
sriduth/purescript-prelude
018250e052ec11dc6faae61ea41c1a11fdf64e0e
[ "MIT" ]
null
null
null
src/Data/Ord.ex
sriduth/purescript-prelude
018250e052ec11dc6faae61ea41c1a11fdf64e0e
[ "MIT" ]
null
null
null
defmodule Ord.Foreign do def ordArrayImpl do fn(f) -> fn(xs) -> fn(ys) -> 1 end end end end end # "use strict"; # exports.ordArrayImpl = function (f) { # return function (xs) { # return function (ys) { # var i = 0; # var xlen = xs.length; # var ylen = ys.length; # while (i < xlen && i < ylen) { # var x = xs[i]; # var y = ys[i]; # var o = f(x)(y); # if (o !== 0) { # return o; # } # i++; # } # if (xlen === ylen) { # return 0; # } else if (xlen > ylen) { # return -1; # } else { # return 1; # } # }; # }; # };
17.325
39
0.383838
1c8ee6d9b17b0d7fc69c747d5e1000a84dedb8fd
2,612
ex
Elixir
lib/ecto_extract_migrations/commands/create_index.ex
jonseaberg/ecto_extract_migrations
6372825495b702386c291a5dda2f63ad1c8317ca
[ "Apache-2.0" ]
7
2020-09-02T14:50:12.000Z
2021-11-12T20:07:36.000Z
lib/ecto_extract_migrations/commands/create_index.ex
jonseaberg/ecto_extract_migrations
6372825495b702386c291a5dda2f63ad1c8317ca
[ "Apache-2.0" ]
2
2020-10-31T12:17:25.000Z
2020-11-05T13:13:13.000Z
lib/ecto_extract_migrations/commands/create_index.ex
jonseaberg/ecto_extract_migrations
6372825495b702386c291a5dda2f63ad1c8317ca
[ "Apache-2.0" ]
3
2020-10-31T11:46:31.000Z
2022-02-11T15:23:10.000Z
defmodule EctoExtractMigrations.Commands.CreateIndex do @moduledoc "Handle CREATE INDEX." def type, do: :create_index defdelegate parse(sql), to: EctoExtractMigrations.Parsers.CreateIndex defdelegate parse(sql, state), to: EctoExtractMigrations.Parsers.CreateIndex defdelegate match(sql), to: EctoExtractMigrations.Parsers.CreateIndex @spec file_name(map, Keyword.t) :: binary def file_name(data, bindings) def file_name(%{name: name}, _bindings), do: "index_#{name}.exs" # %{key: [:member_id], name: "t_eligibility_member_id_idx", table_name: ["bnd", "t_eligibility"], using: "btree"} # CREATE INDEX t_eligibility_member_id_idx ON bnd.t_eligibility USING btree (member_id); def migration(data, bindings) do module_name = module_name(data, bindings) # table_name = table_name(data) [_prefix, table_name] = data.table_name # :name - the name of the index. Defaults to "#{table}_#{column}_index". # :unique - indicates whether the index should be unique. Defaults to false. # :concurrently - indicates whether the index should be created/dropped concurrently. # :using - configures the index type. # :prefix - specify an optional prefix for the index. # :where - specify conditions for a partial index. # :include - specify fields for a covering index. This is not supported by all databases. For more information on PostgreSQL support, please read the official docs. opts = [ name: data[:name], unique: data[:unique], concurrently: data[:concurrently], using: data[:using], prefix: table_opt_prefix(data), where: data[:where], include: data[:include], ] |> Enum.reject(fn {_key, value} -> value == nil end) ast = quote do defmodule unquote(module_name) do use Ecto.Migration def change do create index(unquote(table_name), unquote(data.key), unquote(opts)) end end end {:ok, Macro.to_string(ast)} end def module_name(%{name: name}, bindings) do [bindings[:repo], "migrations", "index"] ++ [name] |> Enum.map(&Macro.camelize/1) |> Module.concat() end def module_name(%{table_name: table_name, key: key}, bindings) do [bindings[:repo], "migrations", "index"] ++ table_name ++ [key] |> Enum.map(&Macro.camelize/1) |> Module.concat() end # Get schema prefix if it is not public defp table_opt_prefix(%{table_name: ["public", _table]}), do: nil defp table_opt_prefix(%{table_name: [schema, _table]}), do: schema defp table_opt_prefix(%{table_name: value}) when is_binary(value), do: nil end
37.855072
168
0.685681
1c8f0130e027dad002357a8e7a14393a3f885389
8,431
exs
Elixir
test/groupher_server/cms/comments/drink_comment_replies_test.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
240
2018-11-06T09:36:54.000Z
2022-02-20T07:12:36.000Z
test/groupher_server/cms/comments/drink_comment_replies_test.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
363
2018-07-11T03:38:14.000Z
2021-12-14T01:42:40.000Z
test/groupher_server/cms/comments/drink_comment_replies_test.exs
mydearxym/mastani_server
f24034a4a5449200165cf4a547964a0961793eab
[ "Apache-2.0" ]
22
2019-01-27T11:47:56.000Z
2021-02-28T13:17:52.000Z
defmodule GroupherServer.Test.CMS.Comments.DrinkCommentReplies do @moduledoc false use GroupherServer.TestTools alias Helper.ORM alias GroupherServer.CMS alias CMS.Model.{Comment, Drink} @max_parent_replies_count Comment.max_parent_replies_count() setup do {:ok, user} = db_insert(:user) {:ok, user2} = db_insert(:user) {:ok, drink} = db_insert(:drink) {:ok, ~m(user user2 drink)a} end describe "[basic article comment replies]" do test "exsit comment can be reply", ~m(drink user user2)a do {:ok, parent_comment} = CMS.create_comment(:drink, drink.id, mock_comment(), user) {:ok, replyed_comment} = CMS.reply_comment(parent_comment.id, mock_comment(), user2) assert replyed_comment.reply_to.id == parent_comment.id {:ok, parent_comment} = ORM.find(Comment, parent_comment.id) assert exist_in?(replyed_comment, parent_comment.replies) end test "deleted comment can not be reply", ~m(drink user user2)a do {:ok, parent_comment} = CMS.create_comment(:drink, drink.id, mock_comment(), user) {:ok, _} = CMS.delete_comment(parent_comment) {:error, _} = CMS.reply_comment(parent_comment.id, mock_comment(), user2) end test "multi reply should belong to one parent comment", ~m(drink user user2)a do {:ok, parent_comment} = CMS.create_comment(:drink, drink.id, mock_comment(), user) {:ok, replyed_comment_1} = CMS.reply_comment(parent_comment.id, mock_comment(), user2) {:ok, replyed_comment_2} = CMS.reply_comment(parent_comment.id, mock_comment(), user2) {:ok, parent_comment} = ORM.find(Comment, parent_comment.id) assert exist_in?(replyed_comment_1, parent_comment.replies) assert exist_in?(replyed_comment_2, parent_comment.replies) end test "reply to reply inside a comment should belong same parent comment", ~m(drink user user2)a do {:ok, parent_comment} = CMS.create_comment(:drink, drink.id, mock_comment(), user) {:ok, replyed_comment_1} = CMS.reply_comment(parent_comment.id, mock_comment(), user2) {:ok, replyed_comment_2} = CMS.reply_comment(replyed_comment_1.id, mock_comment(), user2) {:ok, replyed_comment_3} = CMS.reply_comment(replyed_comment_2.id, mock_comment(), user) {:ok, parent_comment} = ORM.find(Comment, parent_comment.id) # IO.inspect(parent_comment.replies, label: "parent_comment.replies") assert exist_in?(replyed_comment_1, parent_comment.replies) assert exist_in?(replyed_comment_2, parent_comment.replies) assert exist_in?(replyed_comment_3, parent_comment.replies) {:ok, replyed_comment_1} = ORM.find(Comment, replyed_comment_1.id) {:ok, replyed_comment_2} = ORM.find(Comment, replyed_comment_2.id) {:ok, replyed_comment_3} = ORM.find(Comment, replyed_comment_3.id) assert replyed_comment_1.reply_to_id == parent_comment.id assert replyed_comment_2.reply_to_id == replyed_comment_1.id assert replyed_comment_3.reply_to_id == replyed_comment_2.id end test "reply to reply inside a comment should have is_reply_to_others flag in meta", ~m(drink user user2)a do {:ok, parent_comment} = CMS.create_comment(:drink, drink.id, mock_comment(), user) {:ok, replyed_comment_1} = CMS.reply_comment(parent_comment.id, mock_comment(), user2) {:ok, replyed_comment_2} = CMS.reply_comment(replyed_comment_1.id, mock_comment(), user2) {:ok, replyed_comment_3} = CMS.reply_comment(replyed_comment_2.id, mock_comment(), user) {:ok, _parent_comment} = ORM.find(Comment, parent_comment.id) {:ok, replyed_comment_1} = ORM.find(Comment, replyed_comment_1.id) {:ok, replyed_comment_2} = ORM.find(Comment, replyed_comment_2.id) {:ok, replyed_comment_3} = ORM.find(Comment, replyed_comment_3.id) assert not replyed_comment_1.meta.is_reply_to_others assert replyed_comment_2.meta.is_reply_to_others assert replyed_comment_3.meta.is_reply_to_others end test "comment replies only contains @max_parent_replies_count replies", ~m(drink user)a do total_reply_count = @max_parent_replies_count + 1 {:ok, parent_comment} = CMS.create_comment(:drink, drink.id, mock_comment(), user) reply_comment_list = Enum.reduce(1..total_reply_count, [], fn n, acc -> {:ok, replyed_comment} = CMS.reply_comment(parent_comment.id, mock_comment("reply_content_#{n}"), user) acc ++ [replyed_comment] end) {:ok, parent_comment} = ORM.find(Comment, parent_comment.id) assert length(parent_comment.replies) == @max_parent_replies_count assert exist_in?(Enum.at(reply_comment_list, 0), parent_comment.replies) assert exist_in?(Enum.at(reply_comment_list, 1), parent_comment.replies) assert exist_in?(Enum.at(reply_comment_list, 2), parent_comment.replies) assert not exist_in?(List.last(reply_comment_list), parent_comment.replies) end test "replyed user should appear in article comment participants", ~m(drink user user2)a do {:ok, parent_comment} = CMS.create_comment(:drink, drink.id, mock_comment(), user) {:ok, _} = CMS.reply_comment(parent_comment.id, mock_comment(), user2) {:ok, article} = ORM.find(Drink, drink.id) assert exist_in?(user, article.comments_participants) assert exist_in?(user2, article.comments_participants) end test "replies count should inc by 1 after got replyed", ~m(drink user user2)a do {:ok, parent_comment} = CMS.create_comment(:drink, drink.id, mock_comment(), user) assert parent_comment.replies_count === 0 {:ok, _} = CMS.reply_comment(parent_comment.id, mock_comment(), user2) {:ok, parent_comment} = ORM.find(Comment, parent_comment.id) assert parent_comment.replies_count === 1 {:ok, _} = CMS.reply_comment(parent_comment.id, mock_comment(), user2) {:ok, parent_comment} = ORM.find(Comment, parent_comment.id) assert parent_comment.replies_count === 2 end end describe "[paged article comment replies]" do test "can get paged replies of a parent comment", ~m(drink user)a do {:ok, parent_comment} = CMS.create_comment(:drink, drink.id, mock_comment(), user) {:ok, paged_replies} = CMS.paged_comment_replies(parent_comment.id, %{page: 1, size: 20}) assert is_valid_pagination?(paged_replies, :raw, :empty) total_reply_count = 30 reply_comment_list = Enum.reduce(1..total_reply_count, [], fn n, acc -> {:ok, replyed_comment} = CMS.reply_comment(parent_comment.id, mock_comment("reply_content_#{n}"), user) acc ++ [replyed_comment] end) {:ok, paged_replies} = CMS.paged_comment_replies(parent_comment.id, %{page: 1, size: 20}) assert total_reply_count == paged_replies.total_count assert is_valid_pagination?(paged_replies, :raw) assert exist_in?(Enum.at(reply_comment_list, 0), paged_replies.entries) assert exist_in?(Enum.at(reply_comment_list, 1), paged_replies.entries) assert exist_in?(Enum.at(reply_comment_list, 2), paged_replies.entries) assert exist_in?(Enum.at(reply_comment_list, 3), paged_replies.entries) end test "can get reply_to info of a parent comment", ~m(drink user)a do page_number = 1 page_size = 10 {:ok, parent_comment} = CMS.create_comment(:drink, drink.id, mock_comment(), user) {:ok, reply_comment} = CMS.reply_comment(parent_comment.id, mock_comment(), user) {:ok, reply_comment2} = CMS.reply_comment(parent_comment.id, mock_comment(), user) {:ok, paged_comments} = CMS.paged_comments( :drink, drink.id, %{page: page_number, size: page_size}, :timeline ) reply_comment = Enum.find(paged_comments.entries, &(&1.id == reply_comment.id)) assert reply_comment.reply_to.id == parent_comment.id assert reply_comment.reply_to.body_html == parent_comment.body_html assert reply_comment.reply_to.author.id == parent_comment.author_id reply_comment2 = Enum.find(paged_comments.entries, &(&1.id == reply_comment2.id)) assert reply_comment2.reply_to.id == parent_comment.id assert reply_comment2.reply_to.body_html == parent_comment.body_html assert reply_comment2.reply_to.author.id == parent_comment.author_id end end end
41.126829
95
0.703594
1c8f12728306e368d146e3a6b7f1bda6fc62fdc9
1,451
exs
Elixir
test/test_helper.exs
summerchat/dlex
58f8624d047b93b3ce026b65c7cf8a1d85d13f85
[ "Apache-2.0" ]
79
2018-12-22T23:15:55.000Z
2021-11-14T05:56:31.000Z
test/test_helper.exs
m0dnar/dlex
1a3d0216d0aabb8c1ab5c92c5e6847c140769201
[ "Apache-2.0" ]
120
2019-02-26T17:44:39.000Z
2021-11-12T23:07:51.000Z
test/test_helper.exs
m0dnar/dlex
1a3d0216d0aabb8c1ab5c92c5e6847c140769201
[ "Apache-2.0" ]
25
2018-12-22T23:15:57.000Z
2021-12-28T18:43:24.000Z
defmodule Dlex.TestHelper do @dlex_adapter :"#{System.get_env("DLEX_ADAPTER", "grpc")}" @offset String.to_integer(System.get_env("DLEX_PORT_OFFSET", "0")) def opts() do case @dlex_adapter do :http -> [transport: :http, port: 8080 + @offset] :grpc -> [transport: :grpc, port: 9080 + @offset] end end def drop_all(pid) do Dlex.alter(pid, %{drop_all: true}) end def adapter(), do: @dlex_adapter end defmodule Dlex.Geo do use Ecto.Type defstruct lon: 0.0, lat: 0.0 @impl true def type(), do: :geo @impl true def cast(%{lat: lat, lon: lon}), do: {:ok, %__MODULE__{lat: lat, lon: lon}} def cast(_), do: :error @impl true def load(%{"type" => "Point", "coordinates" => [lat, lon]}) do {:ok, %__MODULE__{lat: lat, lon: lon}} end @impl true def dump(%__MODULE__{lat: lat, lon: lon}) do {:ok, %{"type" => "Point", "coordinates" => [lat, lon]}} end def dump(_), do: :error end defmodule Dlex.User do use Dlex.Node schema "user" do field :name, :string, index: ["term"] field :age, :integer field :friends, :uid field :location, Dlex.Geo field :cache, :any, virtual: true end end defmodule Dlex.TestRepo do use Dlex.Repo, otp_app: :dlex, modules: [Dlex.User] end to_skip = case Dlex.TestHelper.adapter() do :http -> [:grpc] :grpc -> [:http] end {:ok, _} = Application.ensure_all_started(:grpc) ExUnit.start(exclude: [:skip | to_skip])
21.656716
77
0.623019
1c8f187176594c0e45a65af241fa1f2ecd99e0f1
44
exs
Elixir
config/prod.exs
niahoo/elixir-todo
ae5cc01e5770387c753cb735b43fa38a69566383
[ "MIT" ]
8
2015-09-10T21:19:01.000Z
2020-03-25T02:19:02.000Z
config/prod.exs
niahoo/elixir-todo
ae5cc01e5770387c753cb735b43fa38a69566383
[ "MIT" ]
2
2016-03-16T22:56:00.000Z
2016-03-18T14:39:06.000Z
config/prod.exs
niahoo/elixir-todo
ae5cc01e5770387c753cb735b43fa38a69566383
[ "MIT" ]
1
2020-01-29T16:12:34.000Z
2020-01-29T16:12:34.000Z
import Config # config :todo, persist: true
14.666667
29
0.75
1c8f266afdd8cbef8829345ddf11b1a6d2ccaf91
14,842
ex
Elixir
lib/joken.ex
echenim/joken
91b3f2560d2f5b88230926cab0f674bcf237109a
[ "Apache-2.0" ]
1
2019-02-11T20:46:56.000Z
2019-02-11T20:46:56.000Z
lib/joken.ex
echenim/joken
91b3f2560d2f5b88230926cab0f674bcf237109a
[ "Apache-2.0" ]
null
null
null
lib/joken.ex
echenim/joken
91b3f2560d2f5b88230926cab0f674bcf237109a
[ "Apache-2.0" ]
null
null
null
defmodule Joken do @moduledoc """ Joken is a library for working with standard JSON Web Tokens. It provides 4 basic operations: - Verify: the act of confirming the signature of the JWT; - Validate: processing validation logic on the set of claims; - Claim generation: generate dynamic value at token creation time; - Signature creation: encoding header and claims and generate a signature of their value. ## Architecture The core of Joken is `JOSE`, a library which provides all facilities to sign and verify tokens. Joken brings an easier Elixir API with some added functionality: - Validating claims. JOSE does not provide validation other than signature verification. - `config.exs` friendly. You can optionally define your signer configuration straight in your `config.exs`. - Portable configuration. All your token logic can be encapsulated in a module with behaviours. - Enhanced errors. Joken strives to be as informative as it can when errors happen be it at compilation or at validation time. - Debug friendly. When a token fails validation, a `Logger` debug message will show which claim failed validation with which value. The return value, though for security reasons, does not contain these information. - Performance. We have a benchmark suite for identifying where we can have a better performance. From this analysis came: Jason adapter for JOSE and other minor tweaks. ## Usage Joken has 3 basic concepts: - Portable token claims configuration - Signer configuration - Hooks The portable token claims configuration is a map of binary keys to `Joken.Claim` structs and is used to dynamically generate and validate tokens. A signer is an instance of `Joken.Signer` that encapsulates the algorithm and the key configuration used to sign and verify a token. A hook is an implementation of the behaviour `Joken.Hooks` for easy plugging into the lifecycle of Joken operations. There are 2 forms of using Joken: 1. Pure data structures. You can create your token configuration and signer and use them with this module for all 4 operations: verify, validate, generate and sign. ``` iex> token_config = %{} # empty config iex> token_config = Map.put(token_config, "scope", %Joken.Claim{ ...> generate_function: fn -> "user" end, ...> validate_function: fn val, _claims, _context -> val in ["user", "admin"] end ...> }) iex> signer = Joken.Signer.create("HS256", "my secret") iex> claims = Joken.generate_claims(token_config, %{"extra"=> "claim"}) iex> {:ok, jwt, claims} = Joken.encode_and_sign(claims, signer) ``` 2. With the encapsulated module approach using `Joken.Config`. See the docs for `Joken.Config` for more details. ``` iex> defmodule MyAppToken do ...> use Joken.Config, default_signer: :pem_rs256 ...> ...> @impl Joken.Config ...> def token_config do ...> default_claims() ...> |> add_claim("role", fn -> "USER" end, &(&1 in ["ADMIN", "USER"])) ...> end ...> end iex> {:ok, token, _claims} = MyAppToken.generate_and_sign(%{"user_id" => "1234567890"}) iex> {:ok, _claim_map} = MyAppToken.verify_and_validate(token) ``` """ alias Joken.{Claim, Hooks, Signer} require Logger @typedoc """ A signer argument that can be a key in the configuration or an instance of `Joken.Signer`. """ @type signer_arg :: atom | Joken.Signer.t() @typedoc "A binary representing a bearer token." @type bearer_token :: binary @typedoc "A map with binary keys that represents a claim set." @type claims :: %{binary => term} @typedoc "A portable configuration of claims for generation and validation." @type token_config :: %{binary => Joken.Claim.t()} @typedoc "Error reason which might contain dynamic data for helping understand the cause." @type error_reason :: atom | Keyword.t() @type generate_result :: {:ok, claims} | {:error, error_reason} @type sign_result :: {:ok, bearer_token, claims} | {:error, error_reason} @type verify_result :: {:ok, claims} | {:error, error_reason} @type validate_result :: {:ok, claims} | {:error, error_reason} # This ensures we provide an easy to setup test environment @current_time_adapter Application.get_env(:joken, :current_time_adapter, Joken.CurrentTime.OS) @doc """ Retrieves current time in seconds. This implementation uses an adapter so that you can replace it on your tests. The adapter is set through `config.exs`. Example: config :joken, current_time_adapter: Joken.CurrentTime.OS See Joken's own tests for an example of how to override this with a customizable time mock. """ @spec current_time() :: pos_integer def current_time, do: @current_time_adapter.current_time() @doc """ Decodes the header of a token without validation. **Use this with care!** This DOES NOT validate the token signature and therefore the token might be invalid. The common use case for this function is when you need info to decide on which signer will be used. Even though there is a use case for this, be extra careful to handle data without validation. """ @spec peek_header(bearer_token) :: {:ok, claims} | {:error, error_reason} def peek_header(token) when is_binary(token) do with {:ok, %{"protected" => protected}} <- expand(token), {:ok, decoded_str} <- Base.url_decode64(protected, padding: false), {:ok, header} <- Jason.decode(decoded_str) do {:ok, header} else error -> error end end @doc """ Decodes the claim set of a token without validation. **Use this with care!** This DOES NOT validate the token signature and therefore the token might be invalid. The common use case for this function is when you need info to decide on which signer will be used. Even though there is a use case for this, be extra careful to handle data without validation. """ @spec peek_claims(bearer_token) :: {:ok, claims} | {:error, error_reason} def peek_claims(token) when is_binary(token) do with {:ok, %{"payload" => payload}} <- expand(token), {:ok, decoded_str} <- Base.url_decode64(payload, padding: false), {:ok, claims} <- Jason.decode(decoded_str) do {:ok, claims} else error -> error end end @doc """ Expands a signed token into its 3 parts: protected, payload and signature. Protected is also called the JOSE header. It contains metadata only like: - "typ": the token type - "kid": an id for the key used in the signing - "alg": the algorithm used to sign a token Payload is the set of claims and signature is, well, the signature. """ def expand(signed_token) do case String.split(signed_token, ".") do [header, payload, signature] -> {:ok, %{ "protected" => header, "payload" => payload, "signature" => signature }} _ -> {:error, :token_malformed} end end @doc """ Default function for generating `jti` claims. This was inspired by the `Plug.RequestId` generation. It avoids using `strong_rand_bytes` as it is known to have some contention when running with many schedulers. """ @spec generate_jti() :: binary def generate_jti do binary = << System.system_time(:nanosecond)::64, :erlang.phash2({node(), self()}, 16_777_216)::24, :erlang.unique_integer()::32 >> Base.hex_encode32(binary, case: :lower) end @doc "Combines `generate_claims/3` with `encode_and_sign/3`" @spec generate_and_sign(token_config, claims, signer_arg, [module]) :: {:ok, bearer_token, claims} | {:error, error_reason} def generate_and_sign( token_config, extra_claims \\ %{}, signer_arg \\ :default_signer, hooks \\ [] ) do with {:ok, claims} <- generate_claims(token_config, extra_claims, hooks), {:ok, token, claims} <- encode_and_sign(claims, signer_arg, hooks) do {:ok, token, claims} end end @doc "Same as `generate_and_sign/4` but raises if result is an error" @spec generate_and_sign!(token_config, claims, signer_arg, [module]) :: bearer_token | no_return() def generate_and_sign!( token_config, extra_claims \\ %{}, signer_arg \\ :default_signer, hooks \\ [] ) do result = generate_and_sign(token_config, extra_claims, signer_arg, hooks) case result do {:ok, token, _claims} -> token {:error, reason} -> raise Joken.Error, [:bad_generate_and_sign, reason: reason] end end @doc """ Verifies a bearer_token using the given signer and executes hooks if any are given. """ @spec verify(bearer_token, signer_arg, [module]) :: verify_result() def verify(bearer_token, signer, hooks \\ []) def verify(bearer_token, nil, hooks) when is_binary(bearer_token) and is_list(hooks), do: verify(bearer_token, %Signer{}, hooks) def verify(bearer_token, signer, hooks) when is_binary(bearer_token) and is_atom(signer), do: verify(bearer_token, parse_signer(signer), hooks) def verify(bearer_token, signer = %Signer{}, hooks) when is_binary(bearer_token) do with {:ok, {bearer_token, signer}} <- Hooks.run_before_hook(hooks, :before_verify, {bearer_token, signer}), :ok <- check_signer_not_empty(signer), result <- Signer.verify(bearer_token, signer), {:ok, claims_map} <- Hooks.run_after_hook(hooks, :after_verify, result, {bearer_token, signer}) do {:ok, claims_map} end end defp check_signer_not_empty(%Signer{alg: nil}), do: {:error, :empty_signer} defp check_signer_not_empty(%Signer{}), do: :ok @doc """ Validates the claim map with the given token configuration and the context. Context can by any term. It is always passed as the second argument to the validate function. It can be, for example, a user struct or anything. It also executes hooks if any are given. """ @spec validate(token_config, claims, term, [module]) :: validate_result() def validate(token_config, claims_map, context \\ nil, hooks \\ []) do with {:ok, {token_config, claims_map, context}} <- Hooks.run_before_hook(hooks, :before_validate, {token_config, claims_map, context}), result <- reduce_validations(token_config, claims_map, context), {:ok, _config, claims, _context} <- Hooks.run_after_hook( hooks, :after_validate, result, {token_config, claims_map, context} ) do {:ok, claims} end end @doc "Combines `verify/3` and `validate/4` operations" @spec verify_and_validate(token_config, bearer_token, signer_arg, term, [module]) :: {:ok, claims} | {:error, error_reason} def verify_and_validate( token_config, bearer_token, signer \\ :default_signer, context \\ nil, hooks \\ [] ) do with {:ok, claims} <- verify(bearer_token, signer, hooks), {:ok, claims} <- validate(token_config, claims, context, hooks) do {:ok, claims} end end @doc "Same as `verify_and_validate/5` but raises on error" @spec verify_and_validate!(token_config, bearer_token, signer_arg, term, [module]) :: claims | no_return() def verify_and_validate!( token_config, bearer_token, signer \\ :default_signer, context \\ nil, hooks \\ [] ) do token_config |> verify_and_validate(bearer_token, signer, context, hooks) |> case do {:ok, claims} -> claims {:error, reason} -> raise Joken.Error, [:bad_verify_and_validate, reason: reason] end end @doc """ Generates claims with the given token configuration and merges them with the given extra claims. It also executes hooks if any are given. """ @spec generate_claims(token_config, claims | nil, [module]) :: generate_result def generate_claims(token_config, extra \\ %{}, hooks \\ []) def generate_claims(token_config, nil, hooks), do: generate_claims(token_config, %{}, hooks) def generate_claims(token_config, extra_claims, hooks) do with {:ok, {token_config, extra_claims}} <- Hooks.run_before_hook(hooks, :before_generate, {token_config, extra_claims}), claims <- Enum.reduce(token_config, extra_claims, &Claim.__generate_claim__/2), {:ok, claims} <- Hooks.run_after_hook( hooks, :after_generate, {:ok, claims}, {token_config, extra_claims} ) do {:ok, claims} end end @doc """ Encodes and generates a token from the given claim map and signs the result with the given signer. It also executes hooks if any are given. """ @spec encode_and_sign(claims, signer_arg, [module]) :: sign_result def encode_and_sign(claims, signer, hooks \\ []) def encode_and_sign(claims, nil, hooks), do: encode_and_sign(claims, %Signer{}, hooks) def encode_and_sign(claims, signer, hooks) when is_atom(signer), do: encode_and_sign(claims, parse_signer(signer), hooks) def encode_and_sign(claims, %Signer{} = signer, hooks) do with {:ok, {claims, signer}} <- Hooks.run_before_hook(hooks, :before_sign, {claims, signer}), :ok <- check_signer_not_empty(signer), result <- Signer.sign(claims, signer), {:ok, token} <- Hooks.run_after_hook(hooks, :after_sign, result, {claims, signer}) do {:ok, token, claims} end end defp parse_signer(signer_key) do Signer.parse_config(signer_key) || raise(Joken.Error, :no_default_signer) end defp reduce_validations(_config, %{} = claims, _context) when map_size(claims) == 0, do: {:ok, claims} defp reduce_validations(config, claim_map, context) do claim_map |> Enum.reduce_while(nil, fn {key, claim_val}, _acc -> # When there is a function for validating the token with %Claim{validate: val_func} when not is_nil(val_func) <- config[key], true <- val_func.(claim_val, claim_map, context) do {:cont, :ok} else # When there is no configuration for the claim nil -> {:cont, :ok} # When there is a configuration but no validation function %Claim{validate: nil} -> {:cont, :ok} # When it fails validation false -> Logger.debug(fn -> """ Claim %{"#{key}" => #{inspect(claim_val)}} did not pass validation. Current time: #{inspect(Joken.current_time())} """ end) {:halt, {:error, message: "Invalid token", claim: key, claim_val: claim_val}} end end) |> case do :ok -> {:ok, claim_map} err -> err end end end
36.024272
103
0.664196
1c8f2d95c654639aaf1911be50a4b667d655313a
759
exs
Elixir
mix.exs
smartvokat/door_frame
9052ab233b2af65582dd1925a998e2b46b0eb569
[ "Apache-2.0" ]
5
2019-06-12T11:26:12.000Z
2022-01-28T19:45:47.000Z
mix.exs
smartvokat/door_frame
9052ab233b2af65582dd1925a998e2b46b0eb569
[ "Apache-2.0" ]
2
2019-06-04T13:19:55.000Z
2021-04-19T07:17:34.000Z
mix.exs
smartvokat/door_frame
9052ab233b2af65582dd1925a998e2b46b0eb569
[ "Apache-2.0" ]
1
2019-06-12T11:26:14.000Z
2019-06-12T11:26:14.000Z
defmodule DoorFrame.MixProject do use Mix.Project def project do [ app: :door_frame, version: "0.1.0", elixir: "~> 1.7", elixirc_paths: elixirc_paths(Mix.env()), start_permanent: Mix.env() == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Run "mix help deps" to learn about dependencies. defp deps do [ {:jason, "~> 1.2"}, {:mix_test_watch, "~> 1.0", only: :dev, runtime: false}, {:plug, "~> 1.11"} ] end end
21.685714
62
0.587615
1c8f3e8429ab9812a43e7c5396b726a3e1542fc5
1,062
ex
Elixir
lib/nlw_05_elixir_web/router.ex
wfercosta/nlw_05_elexir
a833f62c6a9985fe43a22f8450250b8ceea3dd34
[ "MIT" ]
null
null
null
lib/nlw_05_elixir_web/router.ex
wfercosta/nlw_05_elexir
a833f62c6a9985fe43a22f8450250b8ceea3dd34
[ "MIT" ]
null
null
null
lib/nlw_05_elixir_web/router.ex
wfercosta/nlw_05_elexir
a833f62c6a9985fe43a22f8450250b8ceea3dd34
[ "MIT" ]
null
null
null
defmodule Nlw05ElixirWeb.Router do use Nlw05ElixirWeb, :router pipeline :api do plug :accepts, ["json"] end scope "/api", Nlw05ElixirWeb do pipe_through :api get "/", WelcomeController, :index post "/restaurants", RestaurantsController, :create resources "/supplies", SuppliesController, only: [:create, :show] end # Enables LiveDashboard only for development # # If you want to use the LiveDashboard in production, you should put # it behind authentication and allow only admins to access it. # If your application does not have an admins-only section yet, # you can use Plug.BasicAuth to set up some basic authentication # as long as you are also using SSL (which you should anyway). if Mix.env() in [:dev, :test] do import Phoenix.LiveDashboard.Router scope "/" do pipe_through [:fetch_session, :protect_from_forgery] live_dashboard "/dashboard", metrics: Nlw05ElixirWeb.Telemetry end end if Mix.env() == :dev do forward "/sent_emails", Bamboo.SentEmailViewerPlug end end
28.702703
70
0.712806
1c8f6b26e1b94998946d05fafcdb05201bc17358
4,978
exs
Elixir
mix.exs
alexgriff/phoenix
87244793035572d9b119a90b1294db8e34961f8b
[ "MIT" ]
1
2019-04-24T09:28:15.000Z
2019-04-24T09:28:15.000Z
mix.exs
alexgriff/phoenix
87244793035572d9b119a90b1294db8e34961f8b
[ "MIT" ]
null
null
null
mix.exs
alexgriff/phoenix
87244793035572d9b119a90b1294db8e34961f8b
[ "MIT" ]
null
null
null
defmodule Phoenix.MixProject do use Mix.Project @version "1.4.0" def project do [ app: :phoenix, version: @version, elixir: "~> 1.4", deps: deps(), package: package(), lockfile: lockfile(), preferred_cli_env: [docs: :docs], consolidate_protocols: Mix.env != :test, xref: [exclude: [Ecto.Type, :ranch, {:cowboy_req, :compact, 1}, Plug.Adapters.Cowboy.Conn, Plug.Cowboy.Conn]], elixirc_paths: elixirc_paths(Mix.env), name: "Phoenix", docs: docs(), aliases: aliases(), source_url: "https://github.com/phoenixframework/phoenix", homepage_url: "http://www.phoenixframework.org", description: """ Productive. Reliable. Fast. A productive web framework that does not compromise speed and 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], env: [ 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) ] ] end defp deps do [ {:plug_cowboy, "~> 1.0 or ~> 2.0", optional: true}, {:plug, "~> 1.7"}, {:phoenix_pubsub, "~> 1.1"}, {:jason, "~> 1.0", optional: true}, # Docs dependencies {:ex_doc, "~> 0.19.1", only: :docs}, {:inch_ex, "~> 0.2", only: :docs}, # Test dependencies {:gettext, "~> 0.15.0", only: :test}, {:phoenix_html, "~> 2.11", only: :test}, {:websocket_client, git: "https://github.com/jeremyong/websocket_client.git", only: :test} ] end defp lockfile() do case System.get_env("COWBOY_VERSION") do "1" <> _ -> "mix-cowboy1.lock" _ -> "mix.lock" end end defp package do [ maintainers: [ "Chris McCord", "José Valim", "Lance Halvorsen", "Gary Rennie", "Jason Stiebs", "Eric Meadows-Jönsson", "Sonny Scroggin" ], licenses: ["MIT"], links: %{github: "https://github.com/phoenixframework/phoenix"}, files: ~w(assets lib priv) ++ ~w(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/learning.md", "guides/introduction/community.md", "guides/up_and_running.md", "guides/adding_pages.md", "guides/routing.md", "guides/plug.md", "guides/endpoint.md", "guides/controllers.md", "guides/views.md", "guides/templates.md", "guides/channels.md", "guides/presence.md", "guides/ecto.md", "guides/contexts.md", "guides/phoenix_mix_tasks.md", "guides/errors.md", "guides/testing/testing.md", "guides/testing/testing_schemas.md", "guides/testing/testing_controllers.md", "guides/testing/testing_channels.md", "guides/deployment/deployment.md", "guides/deployment/heroku.md" ] end defp groups_for_extras do [ "Introduction": ~r/guides\/introduction\/.?/, "Guides": ~r/guides\/[^\/]+\.md/, "Testing": ~r/guides\/testing\/.?/, "Deployment": ~r/guides\/deployment\/.?/ ] end defp groups_for_modules do # Ungrouped Modules: # # Phoenix # Phoenix.Channel # Phoenix.Controller # Phoenix.Endpoint # Phoenix.Naming # Phoenix.Param # Phoenix.Presence # Phoenix.Router # Phoenix.Token # Phoenix.View [ "Testing": [ Phoenix.ChannelTest, Phoenix.ConnTest, ], "Adapters and Plugs": [ Phoenix.CodeReloader, Phoenix.Endpoint.CowboyAdapter, Phoenix.Endpoint.Cowboy2Adapter, Phoenix.Logger, ], "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, Phoenix.Template.HTML, ], ] 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
25.141414
116
0.581961
1c8f6fd36f2a4b0f686f577fad1e679ca06dba57
3,234
ex
Elixir
clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1p1beta1__logo_recognition_annotation.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1p1beta1__logo_recognition_annotation.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1p1beta1__logo_recognition_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.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation do @moduledoc """ Annotation corresponding to one detected, tracked and recognized logo class. ## Attributes * `entity` (*type:* `GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_Entity.t`, *default:* `nil`) - Entity category information to specify the logo class that all the logo tracks within this LogoRecognitionAnnotation are recognized as. * `segments` (*type:* `list(GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_VideoSegment.t)`, *default:* `nil`) - All video segments where the recognized logo appears. There might be multiple instances of the same logo class appearing in one VideoSegment. * `tracks` (*type:* `list(GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_Track.t)`, *default:* `nil`) - All logo tracks where the recognized logo appears. Each track corresponds to one logo instance appearing in consecutive frames. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :entity => GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_Entity.t() | nil, :segments => list( GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_VideoSegment.t() ) | nil, :tracks => list( GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_Track.t() ) | nil } field(:entity, as: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_Entity ) field(:segments, as: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_VideoSegment, type: :list ) field(:tracks, as: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_Track, type: :list ) end defimpl Poison.Decoder, for: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation do def decode(value, options) do GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.425
286
0.750155
1c8f73b5f4e3a764449e5bb5ce70149cc448b826
1,866
exs
Elixir
test/is_type_test.exs
DoggettCK/is_type
1770e506413b6d8096ddf6b72f4d188ccbac96f8
[ "MIT" ]
null
null
null
test/is_type_test.exs
DoggettCK/is_type
1770e506413b6d8096ddf6b72f4d188ccbac96f8
[ "MIT" ]
null
null
null
test/is_type_test.exs
DoggettCK/is_type
1770e506413b6d8096ddf6b72f4d188ccbac96f8
[ "MIT" ]
null
null
null
defmodule IsTypeTest do use ExUnit.Case doctest IsType describe "injects is_type_name? method" do defmodule Person do use IsType defstruct id: nil, name: nil end test "injected method properly matches against type" do assert Person.is_person?(%Person{id: 1, name: "Chris"}) refute Person.is_person?(%{id: 1, name: "Chris"}) refute Person.is_person?(DateTime.utc_now()) refute Person.is_person?("not a struct") refute Person.is_person?(123.45) end end describe "behaves well with acronyms in module names" do defmodule HTTPResponse do use IsType defstruct body: nil, status_code: nil end test "injected method properly matches against type" do assert HTTPResponse.is_http_response?(%HTTPResponse{body: "", status_code: 200}) refute HTTPResponse.is_http_response?(%{body: "", status_code: 200}) refute HTTPResponse.is_http_response?(DateTime.utc_now()) refute HTTPResponse.is_http_response?("not a struct") refute HTTPResponse.is_http_response?(123.45) end end describe "injects alternate named method" do defmodule DifferentName do use IsType, function_name: :is_the_expected_type defstruct name: nil end test "injected method properly matches against type" do assert DifferentName.is_the_expected_type(%DifferentName{name: "Chris"}) refute DifferentName.is_the_expected_type(%{name: "Chris"}) refute DifferentName.is_the_expected_type(DateTime.utc_now()) refute DifferentName.is_the_expected_type("not a struct") refute DifferentName.is_the_expected_type(123.45) end test "default named function isn't injected" do assert_raise UndefinedFunctionError, fn -> DifferentName.is_different_name?(%DifferentName{name: "Chris"}) end end end end
31.627119
86
0.710075
1c8f8392433aaad72b0832197b5d3135b7daf201
232
ex
Elixir
test/support/schema/room.ex
eahanson/schema_assertions
35760374e2c1e837c5ea6fc0bde4baea53677c83
[ "Apache-2.0" ]
null
null
null
test/support/schema/room.ex
eahanson/schema_assertions
35760374e2c1e837c5ea6fc0bde4baea53677c83
[ "Apache-2.0" ]
null
null
null
test/support/schema/room.ex
eahanson/schema_assertions
35760374e2c1e837c5ea6fc0bde4baea53677c83
[ "Apache-2.0" ]
null
null
null
defmodule SchemaAssertions.Test.Schema.Room do @moduledoc false use Ecto.Schema schema "rooms" do belongs_to :house, SchemaAssertions.Test.Schema.House has_many :windows, SchemaAssertions.Test.Schema.Window end end
23.2
58
0.775862
1c8fbdbe3a50dbc156f672b861075e29595482ca
74
ex
Elixir
apps/emporium_api/lib/emporium_api/repo.ex
impressarix/Phoenix-Webstore
31376183b853e594b224fb1051897a00cd20b6ec
[ "Apache-2.0" ]
null
null
null
apps/emporium_api/lib/emporium_api/repo.ex
impressarix/Phoenix-Webstore
31376183b853e594b224fb1051897a00cd20b6ec
[ "Apache-2.0" ]
null
null
null
apps/emporium_api/lib/emporium_api/repo.ex
impressarix/Phoenix-Webstore
31376183b853e594b224fb1051897a00cd20b6ec
[ "Apache-2.0" ]
null
null
null
defmodule EmporiumApi.Repo do use Ecto.Repo, otp_app: :emporium_api end
18.5
39
0.797297
1c8fd1b351acca689fe7fd38c4f224c93bc5399a
2,194
exs
Elixir
traceme/config/dev.exs
derailed/ex_ray_tracers
a687baedde8c472ce426afba02902a336a403a7f
[ "Apache-2.0" ]
9
2017-10-29T17:35:14.000Z
2020-04-19T14:06:50.000Z
traceme/config/dev.exs
derailed/ex_ray_tracers
a687baedde8c472ce426afba02902a336a403a7f
[ "Apache-2.0" ]
null
null
null
traceme/config/dev.exs
derailed/ex_ray_tracers
a687baedde8c472ce426afba02902a336a403a7f
[ "Apache-2.0" ]
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 :traceme, TracemeWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin", cd: Path.expand("../assets", __DIR__)]] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # command from your terminal: # # openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem # # The `http:` config above can be replaced with: # # https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :traceme, TracemeWeb.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{priv/gettext/.*(po)$}, ~r{lib/traceme_web/views/.*(ex)$}, ~r{lib/traceme_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 :traceme, Traceme.Repo, adapter: Ecto.Adapters.Postgres, username: "fernand", password: "Blee!", database: "traceme_dev", hostname: "localhost", port: 5432, pool_size: 10 # loggers: [Traceme.EctoTracer, Ecto.LogEntry] config :otter, zipkin_collector_uri: 'http://127.0.0.1:9411/api/v1/spans', zipkin_tag_host_ip: {127,0,0,1}, zipkin_tag_host_port: 14268, zipkin_tag_host_service: "TraceMe", http_client: :ibrowse
32.264706
170
0.705105
1c8fd772e765ec283f616c5fa8bde8dd087d24d3
2,052
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/directory_sites_list_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/directory_sites_list_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/directory_sites_list_response.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.DFAReporting.V34.Model.DirectorySitesListResponse do @moduledoc """ Directory Site List Response ## Attributes * `directorySites` (*type:* `list(GoogleApi.DFAReporting.V34.Model.DirectorySite.t)`, *default:* `nil`) - Directory site collection. * `kind` (*type:* `String.t`, *default:* `dfareporting#directorySitesListResponse`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#directorySitesListResponse". * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Pagination token to be used for the next list operation. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :directorySites => list(GoogleApi.DFAReporting.V34.Model.DirectorySite.t()), :kind => String.t(), :nextPageToken => String.t() } field(:directorySites, as: GoogleApi.DFAReporting.V34.Model.DirectorySite, type: :list) field(:kind) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V34.Model.DirectorySitesListResponse do def decode(value, options) do GoogleApi.DFAReporting.V34.Model.DirectorySitesListResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V34.Model.DirectorySitesListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.716981
198
0.741715
1c8fde0537788d3d97250d6cfc59115d75b5ed8f
295
ex
Elixir
lib/dealer_rater/dealership.ex
andrhevictor/review_scraper
7628b814d7d35b185bd9bfbe83400c68486bd19a
[ "MIT" ]
null
null
null
lib/dealer_rater/dealership.ex
andrhevictor/review_scraper
7628b814d7d35b185bd9bfbe83400c68486bd19a
[ "MIT" ]
null
null
null
lib/dealer_rater/dealership.ex
andrhevictor/review_scraper
7628b814d7d35b185bd9bfbe83400c68486bd19a
[ "MIT" ]
null
null
null
defmodule ReviewScraper.DealerRater.Dealership do defstruct dealer_id: "", dealer_name: "", dealer_name_encoded: "" @type t() :: %__MODULE__{ dealer_id: String.t(), dealer_name: String.t(), dealer_name_encoded: String.t() } end
24.583333
49
0.579661