hexsha
stringlengths 40
40
| size
int64 2
991k
| ext
stringclasses 2
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
208
| max_stars_repo_name
stringlengths 6
106
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
33.5k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
208
| max_issues_repo_name
stringlengths 6
106
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
16.3k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
208
| max_forks_repo_name
stringlengths 6
106
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
6.91k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 2
991k
| avg_line_length
float64 1
36k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
793b2e6b7342a83b998101530e3daa8e8fa7e994 | 444 | exs | Elixir | config/test.exs | tomkonidas/pebl | 6a43570885fba5cf6cdf15c48d843116eedab79b | [
"MIT"
] | 6 | 2020-08-26T11:29:36.000Z | 2021-11-25T08:37:28.000Z | config/test.exs | tomkonidas/pebl | 6a43570885fba5cf6cdf15c48d843116eedab79b | [
"MIT"
] | 20 | 2020-03-06T05:33:35.000Z | 2022-02-17T17:20:38.000Z | config/test.exs | tomkonidas/pebl | 6a43570885fba5cf6cdf15c48d843116eedab79b | [
"MIT"
] | 2 | 2020-12-11T16:24:59.000Z | 2021-08-16T11:31:08.000Z | use Mix.Config
# Configure your database
config :pebl, Pebl.Repo,
username: "postgres",
password: "postgres",
database: "pebl_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :pebl, PeblWeb.Endpoint,
http: [port: 4002],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
| 23.368421 | 56 | 0.722973 |
793b3effa51481fa5e761b53f21426bab3c00b84 | 3,493 | ex | Elixir | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_privacy_metric.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_privacy_metric.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_privacy_metric.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.DLP.V2.Model.GooglePrivacyDlpV2PrivacyMetric do
@moduledoc """
Privacy metric to compute for reidentification risk analysis.
## Attributes
* `categoricalStatsConfig` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2CategoricalStatsConfig.t`, *default:* `nil`) - Categorical stats
* `deltaPresenceEstimationConfig` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2DeltaPresenceEstimationConfig.t`, *default:* `nil`) - delta-presence
* `kAnonymityConfig` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2KAnonymityConfig.t`, *default:* `nil`) - K-anonymity
* `kMapEstimationConfig` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2KMapEstimationConfig.t`, *default:* `nil`) - k-map
* `lDiversityConfig` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2LDiversityConfig.t`, *default:* `nil`) - l-diversity
* `numericalStatsConfig` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2NumericalStatsConfig.t`, *default:* `nil`) - Numerical stats
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:categoricalStatsConfig =>
GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2CategoricalStatsConfig.t() | nil,
:deltaPresenceEstimationConfig =>
GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2DeltaPresenceEstimationConfig.t() | nil,
:kAnonymityConfig =>
GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2KAnonymityConfig.t() | nil,
:kMapEstimationConfig =>
GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2KMapEstimationConfig.t() | nil,
:lDiversityConfig =>
GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2LDiversityConfig.t() | nil,
:numericalStatsConfig =>
GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2NumericalStatsConfig.t() | nil
}
field(:categoricalStatsConfig,
as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2CategoricalStatsConfig
)
field(:deltaPresenceEstimationConfig,
as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2DeltaPresenceEstimationConfig
)
field(:kAnonymityConfig, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2KAnonymityConfig)
field(:kMapEstimationConfig, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2KMapEstimationConfig)
field(:lDiversityConfig, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2LDiversityConfig)
field(:numericalStatsConfig, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2NumericalStatsConfig)
end
defimpl Poison.Decoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2PrivacyMetric do
def decode(value, options) do
GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2PrivacyMetric.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2PrivacyMetric do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 47.202703 | 157 | 0.755225 |
793b58025da24e926fb67bea7ce8a458889dfbcb | 232 | ex | Elixir | lib/web/plugs/active_tab.ex | christhekeele/ex_venture | 4f4b329f50a133e219969f9823144a4cb9bf738d | [
"MIT"
] | 610 | 2017-08-09T15:20:25.000Z | 2022-03-27T15:49:07.000Z | lib/web/plugs/active_tab.ex | christhekeele/ex_venture | 4f4b329f50a133e219969f9823144a4cb9bf738d | [
"MIT"
] | 69 | 2017-09-23T04:02:30.000Z | 2022-03-19T21:08:21.000Z | lib/web/plugs/active_tab.ex | christhekeele/ex_venture | 4f4b329f50a133e219969f9823144a4cb9bf738d | [
"MIT"
] | 85 | 2017-09-23T04:07:11.000Z | 2021-11-20T06:44:56.000Z | defmodule Web.Plugs.ActiveTab do
@moduledoc """
Set the active admin side tab
"""
import Plug.Conn
def init(default), do: default
def call(conn, tab: active_tab) do
assign(conn, :active_tab, active_tab)
end
end
| 16.571429 | 41 | 0.689655 |
793b94ae8fd35b89d44f9e86787fe6af1dcc9dec | 1,651 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/managed_instance_version.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/compute/lib/google_api/compute/v1/model/managed_instance_version.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/compute/lib/google_api/compute/v1/model/managed_instance_version.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Compute.V1.Model.ManagedInstanceVersion do
@moduledoc """
## Attributes
* `instanceTemplate` (*type:* `String.t`, *default:* `nil`) - [Output Only] The intended template of the instance. This field is empty when current_action is one of { DELETING, ABANDONING }.
* `name` (*type:* `String.t`, *default:* `nil`) - [Output Only] Name of the version.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:instanceTemplate => String.t() | nil,
:name => String.t() | nil
}
field(:instanceTemplate)
field(:name)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.ManagedInstanceVersion do
def decode(value, options) do
GoogleApi.Compute.V1.Model.ManagedInstanceVersion.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.ManagedInstanceVersion do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.02 | 194 | 0.725015 |
793bd6c100b1d8f5f1f9cb3ed7e1ffa0907ee1bd | 1,985 | ex | Elixir | clients/domains/lib/google_api/domains/v1beta1/model/audit_log_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/domains/lib/google_api/domains/v1beta1/model/audit_log_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/domains/lib/google_api/domains/v1beta1/model/audit_log_config.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.Domains.V1beta1.Model.AuditLogConfig do
@moduledoc """
Provides the configuration for logging a type of permissions. Example: { "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:[email protected]" ] }, { "log_type": "DATA_WRITE" } ] } This enables 'DATA_READ' and 'DATA_WRITE' logging, while exempting [email protected] from DATA_READ logging.
## Attributes
* `exemptedMembers` (*type:* `list(String.t)`, *default:* `nil`) - Specifies the identities that do not cause logging for this type of permission. Follows the same format of Binding.members.
* `logType` (*type:* `String.t`, *default:* `nil`) - The log type that this config enables.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:exemptedMembers => list(String.t()) | nil,
:logType => String.t() | nil
}
field(:exemptedMembers, type: :list)
field(:logType)
end
defimpl Poison.Decoder, for: GoogleApi.Domains.V1beta1.Model.AuditLogConfig do
def decode(value, options) do
GoogleApi.Domains.V1beta1.Model.AuditLogConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Domains.V1beta1.Model.AuditLogConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.7 | 316 | 0.728463 |
793c0dcd0a9705d47e3ada449c463e52c168b70d | 12,614 | ex | Elixir | lib/grizzly/icon_type.ex | ryanwinchester/grizzly | 86002e01debe63c18f85270ddc948e3875f25043 | [
"Apache-2.0"
] | null | null | null | lib/grizzly/icon_type.ex | ryanwinchester/grizzly | 86002e01debe63c18f85270ddc948e3875f25043 | [
"Apache-2.0"
] | null | null | null | lib/grizzly/icon_type.ex | ryanwinchester/grizzly | 86002e01debe63c18f85270ddc948e3875f25043 | [
"Apache-2.0"
] | null | null | null | defmodule Grizzly.IconType do
@moduledoc """
The installer icon type is used in Z-Wave Plus devices to allow
interoperability with generic Z-Wave graphical user interfaces.
These interfaces are useful when using generic Z-Wave tooling
and debugging to allow the user to get a meaningful representation
of any product included in the network, and is mandatory according
the Z-Wave Plus specification.
See `SDS11847 Z-Wave Plus Device Type Specification.pdf` Appendix A
provided by Silicon Labs for more information.
"""
defmodule Generate do
@moduledoc false
@mappings [
{0x0000, :icon_type_unassigned},
{0x0100, :icon_type_generic_central_controller},
{0x0200, :icon_type_generic_display_simple},
{0x0300, :icon_type_generic_door_lock_keypad},
{0x0400, :icon_type_generic_fan_switch_device_type},
{0x0500, :icon_type_gateway},
{0x0600, :icon_type_generic_light_dimmer_switch},
{0x0601, :icon_type_specific_light_dimmer_plugin},
{0x0602, :icon_type_specific_light_dimmer_switch_wall_outlet},
{0x0603, :icon_type_specific_light_dimmer_switch_ceiling_outlet},
{0x0604, :icon_type_specific_light_dimmer_switch_wall_lamp},
{0x0605, :icon_type_specific_light_dimmer_switch_lamp_post_high},
{0x0606, :icon_type_specific_light_dimmer_switch_lamp_post_low},
{0x0607, :icon_type_specific_light_dimmer_switch_din_rail_module},
{0x0700, :icon_type_generic_on_off_power_switch},
{0x0701, :icon_type_specific_on_off_power_switch_plugin},
{0x0702, :icon_type_specific_on_off_power_switch_wall_outlet},
{0x0703, :icon_type_specific_on_off_power_switch_ceiling_outlet},
{0x0704, :icon_type_specific_on_off_power_switch_wall_lamp},
{0x0705, :icon_type_specific_on_off_power_switch_lamp_post_high},
{0x0706, :icon_type_specific_on_off_power_switch_lamp_post_low},
{0x0707, :icon_type_specific_on_off_power_switch_din_rail_module},
{0x0800, :icon_type_generic_power_strip},
{0x08FF, :icon_type_specific_power_strip_individual_outlet},
{0x0900, :icon_type_generic_remote_control_av},
{0x0A00, :icon_type_generic_remote_control_multi_purpose},
{0x0B00, :icon_type_generic_remote_control_simple},
{0x0B01, :icon_type_specific_remote_control_simple_keyfob},
{0x0C00, :icon_type_generic_sensor_notification},
{0x0C01, :icon_type_specific_sensor_notification_smoke_alarm},
{0x0C02, :icon_type_specific_sensor_notification_co_alarm},
{0x0C03, :icon_type_specific_sensor_notification_co2_alarm},
{0x0C04, :icon_type_specific_sensor_notification_heat_alarm},
{0x0C05, :icon_type_specific_sensor_notification_water_alarm},
{0x0C06, :icon_type_specific_sensor_notification_door_window},
{0x0C07, :icon_type_specific_sensor_notification_motion_alarm},
{0x0C08, :icon_type_specific_sensor_notification_power_management},
{0x0C09, :icon_type_specific_sensor_notification_system},
{0x0C0A, :icon_type_specific_sensor_notification_emergency_alarm},
{0x0C0B, :icon_type_specific_sensor_notification_clock},
{0x0C0C, :icon_type_specific_sensor_notification_appliance},
{0x0C0D, :icon_type_specific_sensor_notification_home_health},
{0x0C0E, :icon_type_specific_sensor_notification_siren},
{0x0C0F, :icon_type_specific_sensor_notification_water_valve},
{0x0C10, :icon_type_specific_sensor_notification_weather_alarm},
{0x0C11, :icon_type_specific_sensor_notification_irrigation},
{0x0C12, :icon_type_specific_sensor_notification_gas_alarm},
{0x0C13, :icon_type_specific_sensor_notification_pest_control},
{0x0C14, :icon_type_specific_sensor_notification_light_sensor},
{0x0CFF, :icon_type_specific_sensor_notification_multidevice},
{0x0D00, :icon_type_generic_sensor_multilevel},
{0x0D01, :icon_type_specific_sensor_multilevel_air_temperature},
{0x0D02, :icon_type_specific_sensor_multilevel_general_purpose_value},
{0x0D03, :icon_type_specific_sensor_multilevel_luminance},
{0x0D04, :icon_type_specific_sensor_multilevel_power},
{0x0D05, :icon_type_specific_sensor_multilevel_humidity},
{0x0D06, :icon_type_specific_sensor_multilevel_velocity},
{0x0D07, :icon_type_specific_sensor_multilevel_direction},
{0x0D08, :icon_type_specific_sensor_multilevel_atmospheric_pressure},
{0x0D09, :icon_type_specific_sensor_multilevel_barometric_pressure},
{0x0D0A, :icon_type_specific_sensor_multilevel_solor_radiation},
{0x0D0B, :icon_type_specific_sensor_multilevel_dew_point},
{0x0D0C, :icon_type_specific_sensor_multilevel_rain_rate},
{0x0D0D, :icon_type_specific_sensor_multilevel_tide_level},
{0x0D0E, :icon_type_specific_sensor_multilevel_weight},
{0x0D0F, :icon_type_specific_sensor_multilevel_voltage},
{0x0D10, :icon_type_specific_sensor_multilevel_current},
{0x0D11, :icon_type_specific_sensor_multilevel_co2_level},
{0x0D12, :icon_type_specific_sensor_multilevel_air_flow},
{0x0D13, :icon_type_specific_sensor_multilevel_tank_capacity},
{0x0D14, :icon_type_specific_sensor_multilevel_distance},
{0x0D15, :icon_type_specific_sensor_multilevel_angle_position},
{0x0D16, :icon_type_specific_sensor_multilevel_rotation},
{0x0D17, :icon_type_specific_sensor_multilevel_water_temperature},
{0x0D18, :icon_type_specific_sensor_multilevel_soil_temperature},
{0x0D19, :icon_type_specific_sensor_multilevel_seismic_intensity},
{0x0D1A, :icon_type_specific_sensor_multilevel_seismic_magnitude},
{0x0D1B, :icon_type_specific_sensor_multilevel_ultraviolet},
{0x0D1C, :icon_type_specific_sensor_multilevel_electrical_resistivity},
{0x0D1D, :icon_type_specific_sensor_multilevel_electrical_conductivity},
{0x0D1E, :icon_type_specific_sensor_multilevel_loudness},
{0x0D1F, :icon_type_specific_sensor_multilevel_moisture},
{0x0D20, :icon_type_specific_sensor_multilevel_frequency},
{0x0D21, :icon_type_specific_sensor_multilevel_time},
{0x0D22, :icon_type_specific_sensor_multilevel_target_temperature},
{0x0D23, :icon_type_specific_sensor_multilevel_particulate_matter_2_5},
{0x0D24, :icon_type_specific_sensor_multilevel_formaldehyde_ch2o_level},
{0x0D25, :icon_type_specific_sensor_multilevel_radon_concentration},
{0x0D26, :icon_type_specific_sensor_multilevel_methane_density},
{0x0D27, :icon_type_specific_sensor_multilevel_volatile_organic_compound_level},
{0x0D28, :icon_type_specific_sensor_multilevel_carbon_monoxide_level},
{0x0D29, :icon_type_specific_sensor_multilevel_soil_humidity},
{0x0D2A, :icon_type_specific_sensor_multilevel_soil_reactivity},
{0x0D2B, :icon_type_specific_sensor_multilevel_soil_salinity},
{0x0D2C, :icon_type_specific_sensor_multilevel_heart_rate},
{0x0D2D, :icon_type_specific_sensor_multilevel_blood_pressure},
{0x0D2E, :icon_type_specific_sensor_multilevel_muscle_mass},
{0x0D2F, :icon_type_specific_sensor_multilevel_fat_mass},
{0x0D30, :icon_type_specific_sensor_multilevel_bone_mass},
{0x0D31, :icon_type_specific_sensor_multilevel_total_body_water},
{0x0D32, :icon_type_specific_sensor_multilevel_basis_metabolic_rate},
{0x0D33, :icon_type_specific_sensor_multilevel_body_mass_index},
{0x0D34, :icon_type_specific_sensor_multilevel_acceleration_x_axis},
{0x0D35, :icon_type_specific_sensor_multilevel_acceleration_y_axis},
{0x0D36, :icon_type_specific_sensor_multilevel_acceleration_z_axis},
{0x0D37, :icon_type_specific_sensor_multilevel_smoke_density},
{0x0D38, :icon_type_specific_sensor_multilevel_water_flow},
{0x0D39, :icon_type_specific_sensor_multilevel_water_density},
{0x0D3A, :icon_type_specific_sensor_multilevel_rf_signal_strength},
{0x0D3B, :icon_type_specific_sensor_multilevel_particulate_matter_10},
{0x0D3C, :icon_type_specific_sensor_multilevel_respiratory_rate},
{0x0D3D, :icon_type_specific_sensor_multilevel_relative_modulation_level},
{0x0D3E, :icon_type_specific_sensor_multilevel_boiler_water_temperature},
{0x0D3F, :icon_type_specific_sensor_multilevel_domestic_hot_water_temperature},
{0x0D40, :icon_type_specific_sensor_multilevel_outside_temperature},
{0x0D41, :icon_type_specific_sensor_multilevel_exhaust_temperature},
{0x0D42, :icon_type_specific_sensor_multilevel_water_chlorine_level},
{0x0D43, :icon_type_specific_sensor_multilevel_water_acidity},
{0x0D44, :icon_type_specific_sensor_multilevel_water_oxidation_reduction_potential},
{0x0DFF, :icon_type_specific_sensor_multilevel_multidevice},
{0x0E00, :icon_type_generic_set_top_box},
{0x0F00, :icon_type_generic_siren},
{0x1000, :icon_type_generic_sub_energy_meter},
{0x1100, :icon_type_generic_sub_system_controller},
{0x1200, :icon_type_generic_thermostat},
{0x1201, :icon_type_specific_thermostat_line_voltage},
{0x1202, :icon_type_specific_thermostat_setback},
{0x1300, :icon_type_generic_thermostat_setback_obsoleted},
{0x1400, :icon_type_generic_tv},
{0x1500, :icon_type_generic_valve_open_close},
{0x1600, :icon_type_generic_wall_controller},
{0x1700, :icon_type_generic_whole_home_meter_simple},
{0x1800, :icon_type_generic_window_covering_no_position_endpoint},
{0x1900, :icon_type_generic_window_covering_endpoint_aware},
{0x1A00, :icon_type_generic_window_covering_position_endpoint_aware},
{0x1B00, :icon_type_generic_repeater},
{0x1B01, :icon_type_specific_repeater_slave},
{0x1B03, :icon_type_specific_ir_repeater},
{0x1C00, :icon_type_generic_dimmer_wall_switch},
{0x1C01, :icon_type_specific_dimmer_wall_switch_one_button},
{0x1C02, :icon_type_specific_dimmer_wall_switch_two_buttons},
{0x1C03, :icon_type_specific_dimmer_wall_switch_three_buttons},
{0x1C04, :icon_type_specific_dimmer_wall_switch_four_buttons},
{0x1CF1, :icon_type_specific_dimmer_wall_switch_one_rotary},
{0x1D00, :icon_type_generic_on_off_wall_switch},
{0x1D01, :icon_type_specific_on_off_wall_switch_one_button},
{0x1D02, :icon_type_specific_on_off_wall_switch_two_buttons},
{0x1D03, :icon_type_specific_on_off_wall_switch_three_buttons},
{0x1D04, :icon_type_specific_on_off_wall_switch_four_buttons},
{0x1DE1, :icon_type_specific_on_off_wall_switch_door_bell},
{0x1DF1, :icon_type_specific_on_off_wall_switch_one_rotary},
{0x1E00, :icon_type_generic_barrier},
{0x1F00, :icon_type_generic_irrigation},
{0x2000, :icon_type_generic_entry_control},
{0x2001, :icon_type_specific_entry_control_keypad_0_9},
{0x2002, :icon_type_specific_entry_control_rfid_tag_reader_no_button},
{0x2003, :icon_type_specific_entry_control_keypad_0_9_ok_cancel},
{0x2004, :icon_type_specific_entry_control_keypad_0_9_ok_cancel_home_stay_away},
{0x2100, :icon_type_generic_sensor_notification_home_security},
{0x2101, :icon_type_specific_sensor_notification_home_security_intrusion},
{0x2102, :icon_type_specific_sensor_notification_home_security_glass_breakage},
{0x2200, :icon_type_generic_sound_switch},
{0x2201, :icon_type_specific_sound_switch_doorbell},
{0x2202, :icon_type_specific_sound_switch_chime},
{0x2203, :icon_type_specific_sound_switch_alarm_clock}
]
defmacro __before_compile__(_) do
from_integer =
for {integer, name} <- @mappings do
quote do
def from_integer(unquote(integer)), do: {:ok, unquote(name)}
end
end
to_integer =
for {integer, name} <- @mappings do
quote do
def to_integer(unquote(name)), do: {:ok, unquote(integer)}
end
end
quote do
@type icon_name :: atom()
@type icon_integer :: 0x0000..0x2203
@doc """
Get the icon type from a 16 bit integer
"""
@spec from_integer(icon_integer()) :: {:ok, icon_name()} | {:error, :unknown_icon_type}
unquote(from_integer)
def from_integer(_), do: {:error, :unknown_icon_type}
@doc """
Get the 16 bit integer from the icon type
"""
@spec to_integer(icon_name()) :: {:ok, icon_integer()} | {:error, :unknown_icon_type}
unquote(to_integer)
def to_integer(_), do: {:error, :unknown_icon_type}
end
end
end
@before_compile Generate
end
| 56.062222 | 95 | 0.780323 |
793c872342a6d3dd720fbdb12e77831fa36d6ccc | 2,325 | ex | Elixir | lib/ecto/associations/has_one.ex | knewter/ecto | faacfeef25e35c42b1e97323b03d5bed9ba51416 | [
"Apache-2.0"
] | null | null | null | lib/ecto/associations/has_one.ex | knewter/ecto | faacfeef25e35c42b1e97323b03d5bed9ba51416 | [
"Apache-2.0"
] | null | null | null | lib/ecto/associations/has_one.ex | knewter/ecto | faacfeef25e35c42b1e97323b03d5bed9ba51416 | [
"Apache-2.0"
] | null | null | null | defrecord Ecto.Reflections.HasOne, [ :field, :owner, :associated,
:foreign_key, :primary_key ]
defmodule Ecto.Associations.HasOne do
@moduledoc """
A has_one association.
"""
alias Ecto.Reflections.HasOne, as: Refl
@not_loaded :not_loaded
# Needs to be defrecordp because we don't want pollute the module
# with functions generated for the record
defrecordp :assoc, __MODULE__, [:loaded, :target, :name, :primary_key]
@doc """
Creates a new record of the associated entity with the foreign key field set
to the primary key of the parent entity.
"""
def new(params // [], assoc(target: target, name: name, primary_key: pk_value)) do
refl = Refl[] = target.__entity__(:association, name)
fk = refl.foreign_key
refl.associated.new([{ fk, pk_value }] ++ params)
end
@doc """
Returns the associated record. Raises `AssociationNotLoadedError` if the
association is not loaded.
"""
def get(assoc(loaded: @not_loaded, target: target, name: name)) do
refl = target.__entity__(:association, name)
raise Ecto.AssociationNotLoadedError,
type: :has_one, owner: refl.owner, name: name
end
def get(assoc(loaded: loaded)) do
loaded
end
@doc """
Returns `true` if the association is loaded.
"""
def loaded?(assoc(loaded: @not_loaded)), do: false
def loaded?(_), do: true
@doc false
Enum.each [:loaded, :target, :name, :primary_key], fn field ->
def __assoc__(unquote(field), record) do
assoc(record, unquote(field))
end
def __assoc__(unquote(field), value, record) do
assoc(record, [{ unquote(field), value }])
end
end
def __assoc__(:new, name, target) do
assoc(name: name, target: target, loaded: @not_loaded)
end
end
defimpl Inspect, for: Ecto.Associations.HasOne do
import Inspect.Algebra
def inspect(assoc, opts) do
name = assoc.__assoc__(:name)
target = assoc.__assoc__(:target)
refl = target.__entity__(:association, name)
associated = refl.associated
primary_key = refl.primary_key
foreign_key = refl.foreign_key
kw = [
name: name,
target: target,
associated: associated,
primary_key: primary_key,
foreign_key: foreign_key
]
concat ["#Ecto.Associations.HasOne<", Kernel.inspect(kw, opts), ">"]
end
end
| 28.012048 | 84 | 0.675269 |
793c87f0b70566ca7d8d86fac757928ad9f48c36 | 2,230 | exs | Elixir | test/petal/dropdown_test.exs | cohawk/petal_components | 2741c4de66fa8dfa2896fe1e6e02f1d1653422cd | [
"MIT"
] | null | null | null | test/petal/dropdown_test.exs | cohawk/petal_components | 2741c4de66fa8dfa2896fe1e6e02f1d1653422cd | [
"MIT"
] | null | null | null | test/petal/dropdown_test.exs | cohawk/petal_components | 2741c4de66fa8dfa2896fe1e6e02f1d1653422cd | [
"MIT"
] | null | null | null | defmodule PetalComponents.DropdownTest do
use ComponentCase
import PetalComponents.Dropdown
alias PetalComponents.Heroicons
test "dropdown" do
assigns = %{}
html = rendered_to_string(
~H"""
<.dropdown label="Dropdown">
<.dropdown_menu_item type="button">
<Heroicons.Outline.home class="w-5 h-5 text-gray-500" />
Button item with icon
</.dropdown_menu_item>
</.dropdown>
"""
)
assert html =~ "x-data"
assert html =~ "x-show"
assert html =~ "<svg class="
assert html =~ "dark:"
# Test js_lib option
html = rendered_to_string(
~H"""
<.dropdown label="Dropdown" js_lib="live_view_js">
<.dropdown_menu_item label="Option" />
</.dropdown>
"""
)
refute html =~ "x-data"
assert html =~ "phx-click"
# Test placement option
assert rendered_to_string(
~H"""
<.dropdown label="Dropdown" placement="left">
<.dropdown_menu_item label="Option" />
</.dropdown>
"""
) =~ "right-0"
assert rendered_to_string(
~H"""
<.dropdown label="Dropdown" placement="right">
<.dropdown_menu_item label="Option" />
</.dropdown>
"""
) =~ "left-0"
end
test "it works with a custom trigger" do
assigns = %{}
html = rendered_to_string(
~H"""
<.dropdown>
<:trigger_element>
<div>Custom trigger</div>
</:trigger_element>
<.dropdown_menu_item label="Item 1" />
<.dropdown_menu_item label="Item 2" />
</.dropdown>
"""
)
assert html =~ "<div>Custom trigger</div>"
end
test "it works without a label" do
assigns = %{}
html = rendered_to_string(
~H"""
<.dropdown>
<.dropdown_menu_item>Option</.dropdown_menu_item>
</.dropdown>
"""
)
assert html =~ "<svg"
end
test "extra_attributes works on buttons" do
assigns = %{}
html = rendered_to_string(
~H"""
<.dropdown>
<.dropdown_menu_item link_type="button" phx-click="some_event">Option</.dropdown_menu_item>
</.dropdown>
"""
)
assert html =~ "phx-click"
assert html =~ "some_event"
end
end
| 23.473684 | 99 | 0.569507 |
793cd35d1e06552a6ac0d08efed2d5f4ef1b2fc0 | 2,591 | ex | Elixir | clients/you_tube/lib/google_api/you_tube/v3/model/live_broadcast_status.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/you_tube/lib/google_api/you_tube/v3/model/live_broadcast_status.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/you_tube/lib/google_api/you_tube/v3/model/live_broadcast_status.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 "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.YouTube.V3.Model.LiveBroadcastStatus do
@moduledoc """
## Attributes
- lifeCycleStatus (String.t): The broadcast's status. The status can be updated using the API's liveBroadcasts.transition method. Defaults to: `null`.
- Enum - one of [abandoned, complete, completeStarting, created, live, liveStarting, ready, reclaimed, revoked, testStarting, testing]
- liveBroadcastPriority (String.t): Priority of the live broadcast event (internal state). Defaults to: `null`.
- Enum - one of [high, low, normal]
- privacyStatus (String.t): The broadcast's privacy status. Note that the broadcast represents exactly one YouTube video, so the privacy settings are identical to those supported for videos. In addition, you can set this field by modifying the broadcast resource or by setting the privacyStatus field of the corresponding video resource. Defaults to: `null`.
- Enum - one of [private, public, unlisted, unlisted_new]
- recordingStatus (String.t): The broadcast's recording status. Defaults to: `null`.
- Enum - one of [notRecording, recorded, recording]
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:lifeCycleStatus => any(),
:liveBroadcastPriority => any(),
:privacyStatus => any(),
:recordingStatus => any()
}
field(:lifeCycleStatus)
field(:liveBroadcastPriority)
field(:privacyStatus)
field(:recordingStatus)
end
defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.LiveBroadcastStatus do
def decode(value, options) do
GoogleApi.YouTube.V3.Model.LiveBroadcastStatus.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.LiveBroadcastStatus do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 42.47541 | 364 | 0.740641 |
793cee7941bbe1275e39ff2b2f57d4987463ad09 | 2,115 | exs | Elixir | test/apoc/mac/hmac_test.exs | CDThomas/apoc | bcd4dde06d418769a5bf9daf6fc92fd2a0902aec | [
"Apache-2.0"
] | null | null | null | test/apoc/mac/hmac_test.exs | CDThomas/apoc | bcd4dde06d418769a5bf9daf6fc92fd2a0902aec | [
"Apache-2.0"
] | null | null | null | test/apoc/mac/hmac_test.exs | CDThomas/apoc | bcd4dde06d418769a5bf9daf6fc92fd2a0902aec | [
"Apache-2.0"
] | null | null | null | defmodule ApocTest.MAC.HMACTest do
@moduledoc """
The test vectors used in this test are
defined in [RFC4231](https://tools.ietf.org/html/rfc4231)
"""
use ApocTest.Case
alias Apoc.MAC.HMAC
doctest HMAC
describe "signing message [Test Case 1]" do
setup do
%{
key: Base.decode16!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", case: :lower),
data: Base.decode16!("4869205468657265", case: :lower)
}
end
test "sign_hex HMAC-SHA-256", %{key: key, data: data} do
tag = HMAC.sign_hex(data, key)
assert tag == "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
end
test "sign_hex HMAC-SHA-224", %{key: key, data: data} do
tag = HMAC.sign_hex(data, key, scheme: :sha224)
assert tag == "896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22"
end
test "sign_hex HMAC-SHA-384", %{key: key, data: data} do
tag = HMAC.sign_hex(data, key, scheme: :sha384)
assert tag == block_str """
afd03944d84895626b0825f4ab46907f
15f9dadbe4101ec682aa034c7cebc59c
faea9ea9076ede7f4af152e8b2fa9cb6
"""
end
test "sign_hex HMAC-SHA-512", %{key: key, data: data} do
tag = HMAC.sign_hex(data, key, scheme: :sha512)
assert tag == block_str """
87aa7cdea5ef619d4ff0b4241a1d6cb0
2379f4e2ce4ec2787ad0b30545e17cde
daa833b7d6b8a702038b274eaea3f4e4
be9d914eeb61f1702e696c203a126854
"""
end
end
describe "Verify" do
test "passes for a correct tag" do
key = Apoc.rand_bytes(32)
message = "test message"
tag = HMAC.sign(message, key)
assert {:ok, message} == HMAC.verify(tag, message, key)
end
test "fails for an incorrect tag" do
key = Apoc.rand_bytes(32)
message = "test message"
assert :error == HMAC.verify("badtag", message, key)
end
test "fails when the wrong key is used to verify" do
key = Apoc.rand_bytes(32)
message = "test message"
tag = HMAC.sign(message, key)
assert :error == HMAC.verify(tag, message, Apoc.rand_bytes(32))
end
end
end
| 28.972603 | 86 | 0.658629 |
793cf09b67d5f7772ddba4818d9df66c777ca15e | 39,873 | exs | Elixir | apps/omg_watcher/test/omg_watcher/web/controllers/transaction_test.exs | kendricktan/elixir-omg | 834c103fd5c4b9e063c1d32b9b4e5728abb64009 | [
"Apache-2.0"
] | null | null | null | apps/omg_watcher/test/omg_watcher/web/controllers/transaction_test.exs | kendricktan/elixir-omg | 834c103fd5c4b9e063c1d32b9b4e5728abb64009 | [
"Apache-2.0"
] | null | null | null | apps/omg_watcher/test/omg_watcher/web/controllers/transaction_test.exs | kendricktan/elixir-omg | 834c103fd5c4b9e063c1d32b9b4e5728abb64009 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule OMG.Watcher.Web.Controller.TransactionTest do
use ExUnitFixtures
use ExUnit.Case, async: false
use OMG.Fixtures
alias OMG.TestHelper, as: Test
alias OMG.Watcher.DB
alias OMG.Watcher.TestHelper
alias OMG.Utils.HttpRPC.Encoding
@eth OMG.Eth.RootChain.eth_pseudo_address()
@other_token <<127::160>>
@eth_hex OMG.Eth.zero_address() |> Encoding.to_hex()
@other_token_hex @other_token |> Encoding.to_hex()
describe "getting transaction by id" do
@tag fixtures: [:blocks_inserter, :initial_deposits, :alice, :bob]
test "returns transaction in expected format", %{
blocks_inserter: blocks_inserter,
alice: alice,
bob: bob
} do
[{blknum, txindex, txhash, _recovered_tx}] =
blocks_inserter.([
{1000,
[
Test.create_recovered([{1, 0, 0, alice}], @eth, [{bob, 300}])
]}
])
%DB.Block{timestamp: timestamp, eth_height: eth_height, hash: block_hash} = DB.Block.get(blknum)
bob_addr = bob.addr |> Encoding.to_hex()
alice_addr = alice.addr |> Encoding.to_hex()
txhash = txhash |> Encoding.to_hex()
block_hash = block_hash |> Encoding.to_hex()
assert %{
"block" => %{
"blknum" => ^blknum,
"eth_height" => ^eth_height,
"hash" => ^block_hash,
"timestamp" => ^timestamp
},
"inputs" => [
%{
"amount" => 333,
"blknum" => 1,
"currency" => @eth_hex,
"oindex" => 0,
"owner" => ^alice_addr,
"txindex" => 0,
"utxo_pos" => 1_000_000_000
}
],
"outputs" => [
%{
"amount" => 300,
"blknum" => 1000,
"currency" => @eth_hex,
"oindex" => 0,
"owner" => ^bob_addr,
"txindex" => 0,
"utxo_pos" => 1_000_000_000_000
}
],
"txhash" => ^txhash,
"txbytes" => "0x" <> txbytes,
"txindex" => ^txindex
} = TestHelper.success?("transaction.get", %{"id" => txhash})
assert {:ok, _} = Base.decode16(txbytes, case: :lower)
end
@tag fixtures: [:blocks_inserter, :initial_deposits, :alice, :bob]
test "returns up to 4 inputs / 4 outputs", %{
blocks_inserter: blocks_inserter,
alice: alice
} do
[_, {_, _, txhash, _recovered_tx}] =
blocks_inserter.([
{1000,
[
Test.create_recovered(
[{1, 0, 0, alice}],
@eth,
[{alice, 10}, {alice, 20}, {alice, 30}, {alice, 40}]
),
Test.create_recovered(
[{1000, 0, 0, alice}, {1000, 0, 1, alice}, {1000, 0, 2, alice}, {1000, 0, 3, alice}],
@eth,
[{alice, 1}, {alice, 2}, {alice, 3}, {alice, 4}]
)
]}
])
txhash = txhash |> Encoding.to_hex()
assert %{
"inputs" => [%{"amount" => 10}, %{"amount" => 20}, %{"amount" => 30}, %{"amount" => 40}],
"outputs" => [%{"amount" => 1}, %{"amount" => 2}, %{"amount" => 3}, %{"amount" => 4}],
"txhash" => ^txhash,
"txindex" => 1
} = TestHelper.success?("transaction.get", %{"id" => txhash})
end
@tag fixtures: [:phoenix_ecto_sandbox]
test "returns error for non exsiting transaction" do
txhash = <<0::256>> |> Encoding.to_hex()
assert %{
"object" => "error",
"code" => "transaction:not_found",
"description" => "Transaction doesn't exist for provided search criteria"
} == TestHelper.no_success?("transaction.get", %{"id" => txhash})
end
@tag fixtures: [:phoenix_ecto_sandbox]
test "handles improper length of id parameter" do
assert %{
"object" => "error",
"code" => "operation:bad_request",
"description" => "Parameters required by this operation are missing or incorrect.",
"messages" => %{
"validation_error" => %{
"parameter" => "id",
"validator" => "{:length, 32}"
}
}
} == TestHelper.no_success?("transaction.get", %{"id" => "0x50e901b98fe3389e32d56166a13a88208b03ea75"})
end
end
describe "getting multiple transactions" do
@tag fixtures: [:initial_blocks]
test "returns multiple transactions in expected format", %{initial_blocks: initial_blocks} do
{blknum, txindex, txhash, _recovered_tx} = initial_blocks |> Enum.reverse() |> hd()
%DB.Block{timestamp: timestamp, eth_height: eth_height, hash: block_hash} = DB.Block.get(blknum)
txhash = txhash |> Encoding.to_hex()
block_hash = block_hash |> Encoding.to_hex()
assert [
%{
"block" => %{
"blknum" => ^blknum,
"eth_height" => ^eth_height,
"hash" => ^block_hash,
"timestamp" => ^timestamp
},
"results" => [
%{
"currency" => @eth_hex,
"value" => value
}
],
"txhash" => ^txhash,
"txindex" => ^txindex
}
| _
] = TestHelper.success?("transaction.all")
assert is_integer(value)
end
@tag fixtures: [:blocks_inserter, :alice]
test "returns tx from a particular block", %{
blocks_inserter: blocks_inserter,
alice: alice
} do
blocks_inserter.([
{1000, [Test.create_recovered([{1, 0, 0, alice}], @eth, [{alice, 300}])]},
{2000,
[
Test.create_recovered([{1000, 0, 0, alice}], @eth, [{alice, 300}]),
Test.create_recovered([{2000, 1, 0, alice}], @eth, [{alice, 300}])
]}
])
assert [%{"block" => %{"blknum" => 2000}, "txindex" => 1}, %{"block" => %{"blknum" => 2000}, "txindex" => 0}] =
TestHelper.success?("transaction.all", %{"blknum" => 2000})
assert [] = TestHelper.success?("transaction.all", %{"blknum" => 3000})
end
@tag fixtures: [:blocks_inserter, :alice, :bob]
test "returns tx from a particular block that contains requested address as the sender", %{
blocks_inserter: blocks_inserter,
alice: alice,
bob: bob
} do
blocks_inserter.([
{1000, [Test.create_recovered([{1, 0, 0, alice}], @eth, [{alice, 300}])]},
{2000,
[
Test.create_recovered([{1000, 0, 0, alice}], @eth, [{alice, 300}]),
Test.create_recovered([{2, 0, 0, bob}], @eth, [{bob, 300}])
]}
])
address = bob.addr |> Encoding.to_hex()
assert [%{"block" => %{"blknum" => 2000}, "txindex" => 1}] =
TestHelper.success?("transaction.all", %{"address" => address, "blknum" => 2000})
end
@tag fixtures: [:blocks_inserter, :initial_deposits, :alice, :bob]
test "returns tx that contains requested address as the sender and not recipient", %{
blocks_inserter: blocks_inserter,
alice: alice,
bob: bob
} do
blocks_inserter.([
{1000,
[
Test.create_recovered([{1, 0, 0, alice}], @eth, [{bob, 300}])
]}
])
address = alice.addr |> Encoding.to_hex()
assert [%{"block" => %{"blknum" => 1000}, "txindex" => 0}] =
TestHelper.success?("transaction.all", %{"address" => address})
end
@tag fixtures: [:blocks_inserter, :initial_deposits, :alice, :bob, :carol]
test "returns only and all txs that match the address filtered", %{
blocks_inserter: blocks_inserter,
alice: alice,
bob: bob,
carol: carol
} do
blocks_inserter.([
{1000,
[
Test.create_recovered([{1, 0, 0, alice}], @eth, [{bob, 300}]),
Test.create_recovered([{2, 0, 0, bob}], @eth, [{bob, 300}]),
Test.create_recovered([{1000, 1, 0, bob}], @eth, [{alice, 300}])
]}
])
alice_addr = alice.addr |> Encoding.to_hex()
carol_addr = carol.addr |> Encoding.to_hex()
assert [%{"block" => %{"blknum" => 1000}, "txindex" => 2}, %{"block" => %{"blknum" => 1000}, "txindex" => 0}] =
TestHelper.success?("transaction.all", %{"address" => alice_addr})
assert [] = TestHelper.success?("transaction.all", %{"address" => carol_addr})
end
@tag fixtures: [:blocks_inserter, :alice, :bob]
test "returns tx that contains requested address as the recipient and not sender", %{
blocks_inserter: blocks_inserter,
alice: alice,
bob: bob
} do
blocks_inserter.([
{1000,
[
Test.create_recovered([{2, 0, 0, bob}], @eth, [{alice, 100}])
]}
])
address = alice.addr |> Encoding.to_hex()
assert [%{"block" => %{"blknum" => 1000}, "txindex" => 0}] =
TestHelper.success?("transaction.all", %{"address" => address})
end
@tag fixtures: [:blocks_inserter, :alice]
test "returns tx that contains requested address as both sender & recipient is listed once", %{
blocks_inserter: blocks_inserter,
alice: alice
} do
blocks_inserter.([
{1000,
[
Test.create_recovered([{1, 0, 0, alice}], @eth, [{alice, 100}])
]}
])
address = alice.addr |> Encoding.to_hex()
assert [%{"block" => %{"blknum" => 1000}, "txindex" => 0}] =
TestHelper.success?("transaction.all", %{"address" => address})
end
@tag fixtures: [:blocks_inserter, :alice]
test "returns tx without inputs and contains requested address as recipient", %{
blocks_inserter: blocks_inserter,
alice: alice
} do
blocks_inserter.([
{1000,
[
Test.create_recovered([], @eth, [{alice, 10}])
]}
])
address = alice.addr |> Encoding.to_hex()
assert [%{"block" => %{"blknum" => 1000}, "txindex" => 0}] =
TestHelper.success?("transaction.all", %{"address" => address})
end
@tag fixtures: [:blocks_inserter, :initial_deposits, :alice, :bob]
test "returns tx without outputs (amount = 0) and contains requested address as sender", %{
blocks_inserter: blocks_inserter,
alice: alice,
bob: bob
} do
blocks_inserter.([
{1000,
[
Test.create_recovered([{1, 0, 0, alice}], @eth, [{bob, 0}])
]}
])
address = alice.addr |> Encoding.to_hex()
assert [%{"block" => %{"blknum" => 1000}, "txindex" => 0}] =
TestHelper.success?("transaction.all", %{"address" => address})
end
@tag fixtures: [:alice, :blocks_inserter]
test "digests transactions correctly", %{
blocks_inserter: blocks_inserter,
alice: alice
} do
not_eth = <<1::160>>
not_eth_enc = not_eth |> Encoding.to_hex()
blocks_inserter.([
{1000,
[
Test.create_recovered([{1, 0, 0, alice}], [
{alice, @eth, 3},
{alice, not_eth, 4},
{alice, not_eth, 5}
])
]}
])
assert [
%{
"results" => [
%{"currency" => @eth_hex, "value" => 3},
%{"currency" => ^not_eth_enc, "value" => 9}
]
}
] = TestHelper.success?("transaction.all")
end
@tag fixtures: [:initial_blocks]
test "returns transactions containing metadata", %{initial_blocks: initial_blocks} do
{blknum, txindex, txhash, recovered_tx} = initial_blocks |> Enum.find(&match?({2000, 0, _, _}, &1))
expected_metadata = recovered_tx.signed_tx.raw_tx.metadata |> Encoding.to_hex()
expected_txhash = Encoding.to_hex(txhash)
assert [
%{
"block" => %{"blknum" => ^blknum},
"metadata" => ^expected_metadata,
"txhash" => ^expected_txhash,
"txindex" => ^txindex
}
] = TestHelper.success?("transaction.all", %{"metadata" => expected_metadata})
end
end
describe "getting transactions with limit on number of transactions" do
@tag fixtures: [:alice, :bob, :initial_deposits, :blocks_inserter]
test "returns only limited list of transactions", %{
blocks_inserter: blocks_inserter,
alice: alice,
bob: bob
} do
blocks_inserter.([
{1000,
[
Test.create_recovered([{1, 0, 0, alice}], @eth, [{bob, 3}]),
Test.create_recovered([{1_000, 0, 0, bob}], @eth, [{bob, 2}])
]},
{2000,
[
Test.create_recovered([{1_000, 1, 0, bob}], @eth, [{alice, 1}])
]}
])
address = alice.addr |> Encoding.to_hex()
assert [%{"block" => %{"blknum" => 2000}, "txindex" => 0}, %{"block" => %{"blknum" => 1000}, "txindex" => 1}] =
TestHelper.success?("transaction.all", %{limit: 2})
assert [%{"block" => %{"blknum" => 2000}, "txindex" => 0}, %{"block" => %{"blknum" => 1000}, "txindex" => 0}] =
TestHelper.success?("transaction.all", %{address: address, limit: 2})
end
@tag fixtures: [:alice, :bob, :blocks_inserter]
test "limiting all transactions without address filter", %{
blocks_inserter: blocks_inserter,
alice: alice,
bob: bob
} do
blocks_inserter.([
{1000,
[
Test.create_recovered([{1, 0, 0, alice}], @eth, [{bob, 3}]),
Test.create_recovered([{1_000, 0, 0, bob}], @eth, [{alice, 2}])
]},
{2000,
[
Test.create_recovered([{1_000, 1, 0, alice}], @eth, [{bob, 1}])
]}
])
assert [_, _, _] = TestHelper.success?("transaction.all")
end
end
describe "submitting transaction to child chain" do
@tag fixtures: [:phoenix_ecto_sandbox]
test "handles incorrectly encoded parameter" do
hex_without_0x = "5df13a6bf96dbcf6e66d8babd6b55bd40d64d4320c3b115364c6588fc18c2a21"
assert %{
"object" => "error",
"code" => "operation:bad_request",
"description" => "Parameters required by this operation are missing or incorrect.",
"messages" => %{
"validation_error" => %{
"parameter" => "transaction",
"validator" => ":hex"
}
}
} == TestHelper.no_success?("transaction.submit", %{"transaction" => hex_without_0x})
end
end
describe "creating transaction" do
deffixture more_utxos(alice, blocks_inserter) do
[
{5000,
[
Test.create_recovered([], @eth, [{alice, 40}, {alice, 42}, {alice, 43}, {alice, 44}]),
Test.create_recovered([], @eth, [{alice, 41}, {alice, 45}]),
Test.create_recovered([], @other_token, [{alice, 5}, {alice, 110}, {alice, 15}]),
Test.create_recovered([], @other_token, [{alice, 105}, {alice, 10}, {alice, 115}])
]}
]
|> blocks_inserter.()
end
@tag fixtures: [:alice, :bob, :more_utxos]
test "returns appropriate schema", %{alice: alice, bob: bob} do
alias OMG.Utxo
require Utxo
alice_to_bob = 100
fee = 5
metadata = (alice.addr <> bob.addr) |> OMG.Crypto.hash() |> Encoding.to_hex()
alice_addr = Encoding.to_hex(alice.addr)
bob_addr = Encoding.to_hex(bob.addr)
blknum = 5000
assert %{
"result" => "complete",
"transactions" => [
%{
"inputs" => [
%{
"owner" => ^alice_addr,
"currency" => @eth_hex,
"blknum" => ^blknum,
"txindex" => txindex,
"oindex" => oindex,
"utxo_pos" => utxo_pos
}
| _
],
"outputs" => [
%{"amount" => ^alice_to_bob, "currency" => @eth_hex, "owner" => ^bob_addr},
%{"currency" => @eth_hex, "owner" => ^alice_addr, "amount" => _rest}
],
"metadata" => ^metadata,
"fee" => %{"amount" => ^fee, "currency" => @eth_hex},
"txbytes" => "0x" <> _txbytes
}
]
} =
TestHelper.success?(
"transaction.create",
%{
"owner" => alice_addr,
"payments" => [
%{"amount" => alice_to_bob, "currency" => @eth_hex, "owner" => bob_addr}
],
"fee" => %{"amount" => fee, "currency" => @eth_hex},
"metadata" => metadata
}
)
assert Utxo.position(blknum, txindex, oindex) |> Utxo.Position.encode() == utxo_pos
end
@tag fixtures: [:alice, :bob, :more_utxos]
test "returns correctly formed transaction, identical with the verbose form", %{alice: alice, bob: bob} do
alias OMG.State.Transaction
assert %{
"result" => "complete",
"transactions" => [
%{
"inputs" => verbose_inputs,
"outputs" => verbose_outputs,
"metadata" => verbose_metadata,
"txbytes" => tx_hex
}
]
} =
TestHelper.success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => [%{"amount" => 100, "currency" => @eth_hex, "owner" => Encoding.to_hex(bob.addr)}],
"fee" => %{"amount" => 5, "currency" => @eth_hex},
"metadata" => Encoding.to_hex(<<123::256>>)
}
)
verbose_tx =
Transaction.new(
verbose_inputs |> Enum.map(&{&1["blknum"], &1["txindex"], &1["oindex"]}),
verbose_outputs |> Enum.map(&{from_hex!(&1["owner"]), from_hex!(&1["currency"]), &1["amount"]}),
from_hex!(verbose_metadata)
)
assert tx_hex == verbose_tx |> Transaction.raw_txbytes() |> Encoding.to_hex()
end
@tag fixtures: [:alice, :bob, :more_utxos, :blocks_inserter]
test "allows to pay single token tx", %{alice: alice, bob: bob, blocks_inserter: blocks_inserter} do
alice_balance = balance_in_token(alice.addr, @eth)
bob_balance = balance_in_token(bob.addr, @eth)
payment = 100
fee = 5
assert %{
"result" => "complete",
"transactions" => [%{"txbytes" => tx_hex}]
} =
TestHelper.success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => [
%{"amount" => payment, "currency" => @eth_hex, "owner" => Encoding.to_hex(bob.addr)}
],
"fee" => %{"amount" => fee, "currency" => @eth_hex}
}
)
make_payments(7000, alice, [tx_hex], blocks_inserter)
assert alice_balance - (payment + fee) == balance_in_token(alice.addr, @eth)
assert bob_balance + payment == balance_in_token(bob.addr, @eth)
end
@tag fixtures: [:alice, :bob, :more_utxos, :blocks_inserter]
test "advice on merge single token tx", %{alice: alice, bob: bob, blocks_inserter: blocks_inserter} do
alice_balance = balance_in_token(alice.addr, @eth)
max_spendable = max_amount_spendable_in_single_tx(alice.addr, @eth)
payment = max_spendable + 10
fee = 5
assert %{
"result" => "intermediate",
"transactions" => transactions
} =
TestHelper.success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => [
%{"amount" => payment, "currency" => @eth_hex, "owner" => Encoding.to_hex(bob.addr)}
],
"fee" => %{"amount" => fee, "currency" => @eth_hex}
}
)
make_payments(7000, alice, Enum.map(transactions, & &1["txbytes"]), blocks_inserter)
assert alice_balance == balance_in_token(alice.addr, @eth)
assert max_amount_spendable_in_single_tx(alice.addr, @eth) >= payment
end
@tag fixtures: [:alice, :bob, :more_utxos]
test "advice on merge does not merge single utxo", %{alice: alice, bob: bob} do
max_spendable = max_amount_spendable_in_single_tx(alice.addr, @eth)
payment = max_spendable + 1
assert %{
"result" => "intermediate",
"transactions" => [transaction]
} =
TestHelper.success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => [
%{"amount" => payment, "currency" => @eth_hex, "owner" => Encoding.to_hex(bob.addr)}
],
"fee" => %{"amount" => 0, "currency" => @eth_hex}
}
)
require OMG.State.Transaction
assert OMG.State.Transaction.max_inputs() == length(transaction["inputs"])
end
@tag fixtures: [:alice, :bob, :more_utxos, :blocks_inserter]
test "allows to pay multi token tx", %{alice: alice, bob: bob, blocks_inserter: blocks_inserter} do
alice_eth = balance_in_token(alice.addr, @eth)
alice_token = balance_in_token(alice.addr, @other_token)
bob_eth = balance_in_token(bob.addr, @eth)
bob_token = balance_in_token(bob.addr, @other_token)
payment_eth = 100
payment_token = 110
fee = 5
assert %{
"result" => "complete",
"transactions" => [%{"txbytes" => tx_hex}]
} =
TestHelper.success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => [
%{"amount" => payment_eth, "currency" => @eth_hex, "owner" => Encoding.to_hex(bob.addr)},
%{"amount" => payment_token, "currency" => @other_token_hex, "owner" => Encoding.to_hex(bob.addr)}
],
"fee" => %{"amount" => fee, "currency" => @eth_hex}
}
)
make_payments(7000, alice, [tx_hex], blocks_inserter)
assert alice_eth - (payment_eth + fee) == balance_in_token(alice.addr, @eth)
assert alice_token - payment_token == balance_in_token(alice.addr, @other_token)
assert bob_eth + payment_eth == balance_in_token(bob.addr, @eth)
assert bob_token + payment_token == balance_in_token(bob.addr, @other_token)
end
@tag fixtures: [:alice, :bob, :more_utxos, :blocks_inserter]
test "allows to pay other token tx with fee in different currency",
%{alice: alice, bob: bob, blocks_inserter: blocks_inserter} do
alice_eth = balance_in_token(alice.addr, @eth)
alice_token = balance_in_token(alice.addr, @other_token)
bob_token = balance_in_token(bob.addr, @other_token)
payment_token = 110
fee = 5
assert %{
"result" => "complete",
"transactions" => [%{"txbytes" => tx_hex}]
} =
TestHelper.success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => [
%{"amount" => payment_token, "currency" => @other_token_hex, "owner" => Encoding.to_hex(bob.addr)}
],
"fee" => %{"amount" => fee, "currency" => @eth_hex}
}
)
make_payments(7000, alice, [tx_hex], blocks_inserter)
assert alice_eth - fee == balance_in_token(alice.addr, @eth)
assert alice_token - payment_token == balance_in_token(alice.addr, @other_token)
assert bob_token + payment_token == balance_in_token(bob.addr, @other_token)
end
@tag fixtures: [:alice, :bob, :more_utxos, :blocks_inserter]
test "advice on merge multi token tx", %{alice: alice, bob: bob, blocks_inserter: blocks_inserter} do
alice_eth = balance_in_token(alice.addr, @eth)
alice_token = balance_in_token(alice.addr, @other_token)
bob_eth = balance_in_token(bob.addr, @eth)
bob_token = balance_in_token(bob.addr, @other_token)
payment_eth = max_amount_spendable_in_single_tx(alice.addr, @eth) + 10
payment_token = max_amount_spendable_in_single_tx(alice.addr, @other_token) + 10
fee = 5
assert %{
"result" => "intermediate",
"transactions" => transactions
} =
TestHelper.success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => [
%{"amount" => payment_eth, "currency" => @eth_hex, "owner" => Encoding.to_hex(bob.addr)},
%{"amount" => payment_token, "currency" => @other_token_hex, "owner" => Encoding.to_hex(bob.addr)}
],
"fee" => %{"amount" => fee, "currency" => @eth_hex}
}
)
make_payments(7000, alice, Enum.map(transactions, & &1["txbytes"]), blocks_inserter)
assert alice_eth == balance_in_token(alice.addr, @eth)
assert alice_token == balance_in_token(alice.addr, @other_token)
assert bob_eth == balance_in_token(bob.addr, @eth)
assert bob_token == balance_in_token(bob.addr, @other_token)
assert max_amount_spendable_in_single_tx(alice.addr, @eth) >= payment_eth
assert max_amount_spendable_in_single_tx(alice.addr, @other_token) >= payment_token
end
@tag fixtures: [:alice, :bob, :more_utxos]
test "insufficient funds returns custom error", %{alice: alice, bob: bob} do
balance = balance_in_token(alice.addr, @eth)
payment = balance + 10
fee = 5
assert %{
"object" => "error",
"code" => "transaction.create:insufficient_funds",
"description" => "Account balance is too low to satisfy the payment.",
"messages" => [%{"token" => @eth_hex, "missing" => payment + fee - balance}]
} ==
TestHelper.no_success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => [
%{"amount" => payment, "currency" => @eth_hex, "owner" => Encoding.to_hex(bob.addr)}
],
"fee" => %{"amount" => fee, "currency" => @eth_hex}
}
)
end
@tag fixtures: [:alice, :bob, :more_utxos]
test "unknown owner returns insufficient funds error", %{alice: alice, bob: bob} do
assert 0 == balance_in_token(bob.addr, @eth)
payment = 25
fee = 5
assert %{
"object" => "error",
"code" => "transaction.create:insufficient_funds",
"description" => "Account balance is too low to satisfy the payment.",
"messages" => [%{"token" => @eth_hex, "missing" => payment + fee}]
} ==
TestHelper.no_success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(bob.addr),
"payments" => [
%{"amount" => payment, "currency" => @eth_hex, "owner" => Encoding.to_hex(alice.addr)}
],
"fee" => %{"amount" => fee, "currency" => @eth_hex}
}
)
end
@tag fixtures: [:alice, :more_utxos, :blocks_inserter]
test "does not return txbytes when spend owner is not provided", %{alice: alice} do
payment = 100
fee = 5
alice_addr = Encoding.to_hex(alice.addr)
assert %{
"result" => "complete",
"transactions" => [
%{
"txbytes" => nil,
"outputs" => [
%{"amount" => ^payment, "currency" => @eth_hex, "owner" => nil},
%{"currency" => @eth_hex, "owner" => ^alice_addr}
]
}
]
} =
TestHelper.success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => [
%{"amount" => payment, "currency" => @eth_hex}
],
"fee" => %{"amount" => fee, "currency" => @eth_hex}
}
)
end
@tag fixtures: [:alice, :bob, :more_utxos]
test "total number of outputs exceeds allowed outputs returns custom error", %{alice: alice, bob: bob} do
bob_addr = Encoding.to_hex(bob.addr)
assert %{
"object" => "error",
"code" => "transaction.create:too_many_outputs",
"description" => "Total number of payments + change + fees exceed maximum allowed outputs."
} ==
TestHelper.no_success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => [
%{"amount" => 1, "currency" => @other_token_hex, "owner" => bob_addr},
%{"amount" => 2, "currency" => @other_token_hex, "owner" => bob_addr},
%{"amount" => 3, "currency" => @other_token_hex, "owner" => bob_addr}
],
"fee" => %{"amount" => 5, "currency" => @eth_hex}
}
)
end
@tag fixtures: [:alice, :more_utxos, :blocks_inserter]
test "transaction without payments that burns funds in fees is correct",
%{alice: alice, blocks_inserter: blocks_inserter} do
alice_addr = Encoding.to_hex(alice.addr)
alice_balance = balance_in_token(alice.addr, @other_token)
fee = 15
assert %{
"result" => "complete",
"transactions" => [%{"txbytes" => tx_hex}]
} =
TestHelper.success?(
"transaction.create",
%{
"owner" => alice_addr,
"payments" => [],
"fee" => %{"amount" => fee, "currency" => @other_token_hex}
}
)
make_payments(7000, alice, [tx_hex], blocks_inserter)
assert alice_balance - fee == balance_in_token(alice.addr, @other_token)
end
defp balance_in_token(address, token) do
currency = Encoding.to_hex(token)
TestHelper.get_balance(address)
|> Enum.find_value(0, fn
%{"currency" => ^currency, "amount" => amount} -> amount
_ -> false
end)
end
defp max_amount_spendable_in_single_tx(address, token) do
alias OMG.State.Transaction
require Transaction
currency = Encoding.to_hex(token)
TestHelper.get_utxos(address)
|> Stream.filter(&(&1["currency"] == currency))
|> Enum.sort_by(& &1["amount"], &>=/2)
|> Stream.take(Transaction.max_inputs())
|> Stream.map(& &1["amount"])
|> Enum.sum()
end
defp make_payments(blknum, spender, txs_bytes, blocks_inserter) when is_list(txs_bytes) do
alias OMG.DevCrypto
alias OMG.State.Transaction
recovered_txs =
txs_bytes
|> Enum.map(fn "0x" <> tx ->
raw_tx = tx |> Base.decode16!(case: :lower) |> Transaction.decode!()
n_inputs = raw_tx |> Transaction.get_inputs() |> length
raw_tx
|> DevCrypto.sign(List.duplicate(spender.priv, n_inputs))
|> Transaction.Signed.encode()
|> Transaction.Recovered.recover_from!()
end)
[{blknum, recovered_txs}] |> blocks_inserter.()
end
end
describe "creating transaction: Validation" do
@tag fixtures: [:alice, :more_utxos]
test "empty transaction without payments list is not allowed", %{alice: alice} do
alice_addr = Encoding.to_hex(alice.addr)
assert %{
"object" => "error",
"code" => "transaction.create:empty_transaction",
"description" => "Requested payment transfers no funds."
} ==
TestHelper.no_success?(
"transaction.create",
%{"owner" => alice_addr, "payments" => [], "fee" => %{"amount" => 0, "currency" => @eth_hex}}
)
end
@tag fixtures: [:alice, :more_utxos]
test "incorrect payment in payment list", %{alice: alice} do
alice_addr = Encoding.to_hex(alice.addr)
assert %{
"object" => "error",
"code" => "operation:bad_request",
"description" => "Parameters required by this operation are missing or incorrect.",
"messages" => %{"validation_error" => %{"parameter" => "amount", "validator" => ":integer"}}
} ==
TestHelper.no_success?(
"transaction.create",
%{
"owner" => alice_addr,
"payments" => [%{"amount" => "zonk", "currency" => @other_token_hex, "owner" => alice_addr}],
"fee" => %{"amount" => 0, "currency" => @eth_hex}
}
)
end
@tag fixtures: [:alice, :more_utxos]
test "too many payments attempted", %{alice: alice} do
alice_addr = Encoding.to_hex(alice.addr)
too_many_payments = List.duplicate(%{"amount" => 1, "currency" => @other_token_hex, "owner" => alice_addr}, 5)
assert %{
"object" => "error",
"code" => "operation:bad_request",
"description" => "Parameters required by this operation are missing or incorrect.",
"messages" => %{
"validation_error" => %{"parameter" => "payments", "validator" => "{:too_many_payments, 4}"}
}
} ==
TestHelper.no_success?(
"transaction.create",
%{
"owner" => alice_addr,
"payments" => too_many_payments,
"fee" => %{"amount" => 0, "currency" => @eth_hex}
}
)
end
@tag fixtures: [:phoenix_ecto_sandbox]
test "owner should be hex-encoded address" do
assert %{
"object" => "error",
"code" => "operation:bad_request",
"description" => "Parameters required by this operation are missing or incorrect.",
"messages" => %{
"validation_error" => %{
"parameter" => "owner",
"validator" => ":hex"
}
}
} ==
TestHelper.no_success?(
"transaction.create",
%{"owner" => "not-a-hex"}
)
end
@tag fixtures: [:phoenix_ecto_sandbox, :alice]
test "metadata should be hex-encoded hash", %{alice: alice} do
assert %{
"object" => "error",
"code" => "operation:bad_request",
"description" => "Parameters required by this operation are missing or incorrect.",
"messages" => %{
"validation_error" => %{
"parameter" => "metadata",
"validator" => ":hex"
}
}
} ==
TestHelper.no_success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => [],
"fee" => %{"amount" => 5, "currency" => @eth_hex},
"metadata" => "no-a-hex"
}
)
end
@tag fixtures: [:phoenix_ecto_sandbox, :alice]
test "payment should have valid fields", %{alice: alice} do
assert %{
"object" => "error",
"code" => "operation:bad_request",
"description" => "Parameters required by this operation are missing or incorrect.",
"messages" => %{
"validation_error" => %{
"parameter" => "payments",
"validator" => ":list"
}
}
} ==
TestHelper.no_success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => "not-a-list",
"fee" => %{"amount" => 5, "currency" => @eth_hex}
}
)
end
@tag fixtures: [:phoenix_ecto_sandbox, :alice]
test "fee should have valid fields", %{alice: alice} do
assert %{
"object" => "error",
"code" => "operation:bad_request",
"description" => "Parameters required by this operation are missing or incorrect.",
"messages" => %{
"validation_error" => %{
"parameter" => "amount",
"validator" => "{:greater, -1}"
}
}
} ==
TestHelper.no_success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => [],
"fee" => %{"amount" => -10, "currency" => @eth_hex}
}
)
end
@tag fixtures: [:phoenix_ecto_sandbox, :alice]
test "request's fee object is mandatory", %{alice: alice} do
assert %{
"object" => "error",
"code" => "operation:bad_request",
"description" => "Parameters required by this operation are missing or incorrect.",
"messages" => %{
"validation_error" => %{
"parameter" => "fee",
"validator" => ":missing"
}
}
} ==
TestHelper.no_success?(
"transaction.create",
%{
"owner" => Encoding.to_hex(alice.addr),
"payments" => []
}
)
end
end
defp from_hex!(hex) do
{:ok, result} = Encoding.from_hex(hex)
result
end
end
| 36.580734 | 119 | 0.499862 |
793cf32c5aa152829f668f700b4f0f46e20f08f6 | 356 | ex | Elixir | 52_time_service/time_service/lib/time_service.ex | mkchandler/elixir-school | cc08bd723db00cc35cd2d6b07abe519e5d102ca0 | [
"MIT"
] | 1 | 2015-12-15T04:46:41.000Z | 2015-12-15T04:46:41.000Z | 52_time_service/time_service/lib/time_service.ex | mkchandler/elixir-school | cc08bd723db00cc35cd2d6b07abe519e5d102ca0 | [
"MIT"
] | null | null | null | 52_time_service/time_service/lib/time_service.ex | mkchandler/elixir-school | cc08bd723db00cc35cd2d6b07abe519e5d102ca0 | [
"MIT"
] | null | null | null | defmodule TimeService do
use Application
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
# Define workers and child supervisors to be supervised
worker(TimeService.Starter, [])
]
opts = [strategy: :one_for_one, name: TimeService.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 22.25 | 65 | 0.699438 |
793d5ffc86477e4dad01aeb9defaf1d1ff355d85 | 529 | ex | Elixir | lib/new_relic/application.ex | alejandrodnm/elixir_agent | b2264d8f54244d136950cadd02f2533967a8e7cb | [
"Apache-2.0"
] | null | null | null | lib/new_relic/application.ex | alejandrodnm/elixir_agent | b2264d8f54244d136950cadd02f2533967a8e7cb | [
"Apache-2.0"
] | null | null | null | lib/new_relic/application.ex | alejandrodnm/elixir_agent | b2264d8f54244d136950cadd02f2533967a8e7cb | [
"Apache-2.0"
] | null | null | null | defmodule NewRelic.Application do
use Application
@moduledoc false
def start(_type, _args) do
import Supervisor.Spec
NewRelic.Init.run()
children = [
worker(NewRelic.Logger, []),
supervisor(NewRelic.AlwaysOnSupervisor, []),
supervisor(NewRelic.EnabledSupervisor, [[enabled: NewRelic.Config.enabled?()]]),
worker(NewRelic.GracefulShutdown, [], shutdown: 30_000)
]
opts = [strategy: :one_for_one, name: NewRelic.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 24.045455 | 86 | 0.693762 |
793d69d8cd85c514b7a4dedebceb30c6cd127487 | 26,309 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/api/tables.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | 1 | 2021-10-01T09:20:41.000Z | 2021-10-01T09:20:41.000Z | clients/big_query/lib/google_api/big_query/v2/api/tables.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/api/tables.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.BigQuery.V2.Api.Tables do
@moduledoc """
API calls for all endpoints tagged `Tables`.
"""
alias GoogleApi.BigQuery.V2.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Deletes the table specified by tableId from the dataset. If the table contains data, all the data will be deleted.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Project ID of the table to delete
* `dataset_id` (*type:* `String.t`) - Dataset ID of the table to delete
* `table_id` (*type:* `String.t`) - Table ID of the table to delete
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_tables_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()}
def bigquery_tables_delete(
connection,
project_id,
dataset_id,
table_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables/{tableId}", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"datasetId" => URI.encode(dataset_id, &URI.char_unreserved?/1),
"tableId" => URI.encode(table_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 table resource by table ID. This method does not return the data in the table, it only returns the table resource, which describes the structure of this table.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Project ID of the requested table
* `dataset_id` (*type:* `String.t`) - Dataset ID of the requested table
* `table_id` (*type:* `String.t`) - Table ID of the requested table
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:selectedFields` (*type:* `String.t`) - List of fields to return (comma-separated). If unspecified, all fields are returned
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.Table{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_tables_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQuery.V2.Model.Table.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def bigquery_tables_get(
connection,
project_id,
dataset_id,
table_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:selectedFields => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables/{tableId}", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"datasetId" => URI.encode(dataset_id, &URI.char_unreserved?/1),
"tableId" => URI.encode(table_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.BigQuery.V2.Model.Table{}])
end
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.BigQuery.V2.Model.GetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_tables_get_iam_policy(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.BigQuery.V2.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def bigquery_tables_get_iam_policy(connection, resource, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/bigquery/v2/{+resource}:getIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQuery.V2.Model.Policy{}])
end
@doc """
Creates a new, empty table in the dataset.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Project ID of the new table
* `dataset_id` (*type:* `String.t`) - Dataset ID of the new table
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.BigQuery.V2.Model.Table.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.Table{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_tables_insert(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.BigQuery.V2.Model.Table.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def bigquery_tables_insert(
connection,
project_id,
dataset_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"datasetId" => URI.encode(dataset_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.BigQuery.V2.Model.Table{}])
end
@doc """
Lists all tables in the specified dataset. Requires the READER dataset role.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Project ID of the tables to list
* `dataset_id` (*type:* `String.t`) - Dataset ID of the tables to list
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:maxResults` (*type:* `integer()`) - Maximum number of results to return
* `:pageToken` (*type:* `String.t`) - Page token, returned by a previous call, to request the next page of results
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.TableList{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_tables_list(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.BigQuery.V2.Model.TableList.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def bigquery_tables_list(connection, project_id, dataset_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:maxResults => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"datasetId" => URI.encode(dataset_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.BigQuery.V2.Model.TableList{}])
end
@doc """
Updates information in an existing table. The update method replaces the entire table resource, whereas the patch method only replaces fields that are provided in the submitted table resource. This method supports patch semantics.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Project ID of the table to update
* `dataset_id` (*type:* `String.t`) - Dataset ID of the table to update
* `table_id` (*type:* `String.t`) - Table ID of the table to update
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.BigQuery.V2.Model.Table.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.Table{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_tables_patch(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQuery.V2.Model.Table.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def bigquery_tables_patch(
connection,
project_id,
dataset_id,
table_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables/{tableId}", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"datasetId" => URI.encode(dataset_id, &URI.char_unreserved?/1),
"tableId" => URI.encode(table_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.BigQuery.V2.Model.Table{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy. Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.BigQuery.V2.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_tables_set_iam_policy(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.BigQuery.V2.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def bigquery_tables_set_iam_policy(connection, resource, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/bigquery/v2/{+resource}:setIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQuery.V2.Model.Policy{}])
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.BigQuery.V2.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_tables_test_iam_permissions(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.BigQuery.V2.Model.TestIamPermissionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def bigquery_tables_test_iam_permissions(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/bigquery/v2/{+resource}:testIamPermissions", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQuery.V2.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Updates information in an existing table. The update method replaces the entire table resource, whereas the patch method only replaces fields that are provided in the submitted table resource.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Project ID of the table to update
* `dataset_id` (*type:* `String.t`) - Dataset ID of the table to update
* `table_id` (*type:* `String.t`) - Table ID of the table to update
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.BigQuery.V2.Model.Table.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.Table{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_tables_update(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQuery.V2.Model.Table.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def bigquery_tables_update(
connection,
project_id,
dataset_id,
table_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables/{tableId}", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"datasetId" => URI.encode(dataset_id, &URI.char_unreserved?/1),
"tableId" => URI.encode(table_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.BigQuery.V2.Model.Table{}])
end
end
| 43.921536 | 351 | 0.620282 |
793daabff00c8184b12c4dde086083781b6758d8 | 456 | exs | Elixir | priv/repo/migrations/20171218113116_use_timestamps_with_timezone.exs | MatthieuSegret/yummy-phoenix-graphql | f0b258293697b0b120ef8e8a3b3905043c998617 | [
"MIT"
] | 122 | 2017-11-24T11:28:17.000Z | 2022-02-25T17:05:20.000Z | priv/repo/migrations/20171218113116_use_timestamps_with_timezone.exs | MatthieuSegret/yummy-phoenix-graphql | f0b258293697b0b120ef8e8a3b3905043c998617 | [
"MIT"
] | 6 | 2018-01-11T22:07:44.000Z | 2021-11-21T15:41:42.000Z | priv/repo/migrations/20171218113116_use_timestamps_with_timezone.exs | MatthieuSegret/yummy-phoenix-graphql | f0b258293697b0b120ef8e8a3b3905043c998617 | [
"MIT"
] | 25 | 2018-04-01T02:43:21.000Z | 2022-02-15T03:22:54.000Z | defmodule Yummy.Repo.Migrations.UseTimestampsWithTimezone do
use Ecto.Migration
def change do
alter table(:users) do
modify :inserted_at, :timestamptz
modify :updated_at, :timestamptz
end
alter table(:recipes) do
modify :inserted_at, :timestamptz
modify :updated_at, :timestamptz
end
alter table(:comments) do
modify :inserted_at, :timestamptz
modify :updated_at, :timestamptz
end
end
end
| 24 | 60 | 0.697368 |
793daec49533b9ca15f01a2fc40a439f5d0c8b4a | 138 | exs | Elixir | test/excamp_test.exs | ponyatov/excamp | 621853e6c2c640f0f1caf79a9a56563527763dbf | [
"MIT"
] | null | null | null | test/excamp_test.exs | ponyatov/excamp | 621853e6c2c640f0f1caf79a9a56563527763dbf | [
"MIT"
] | null | null | null | test/excamp_test.exs | ponyatov/excamp | 621853e6c2c640f0f1caf79a9a56563527763dbf | [
"MIT"
] | null | null | null | # powered by metaL: https://github.com/ponyatov/metaL/wiki/metaL-manifest
defmodule ExcampTest do
use ExUnit.Case
doctest Excamp
end
| 23 | 74 | 0.782609 |
793dc4c9f6e0e3d8e49ff158e8cfc66e817748dd | 605 | ex | Elixir | lib/mastani_server/statistics/user_contribute.ex | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | 1 | 2019-05-07T15:03:54.000Z | 2019-05-07T15:03:54.000Z | lib/mastani_server/statistics/user_contribute.ex | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | null | null | null | lib/mastani_server/statistics/user_contribute.ex | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | null | null | null | defmodule MastaniServer.Statistics.UserContribute do
@moduledoc false
alias __MODULE__
use Ecto.Schema
import Ecto.Changeset
alias MastaniServer.Accounts
@type t :: %UserContribute{}
schema "user_contributes" do
field(:count, :integer)
field(:date, :date)
belongs_to(:user, Accounts.User)
timestamps(type: :utc_datetime)
end
@doc false
def changeset(%UserContribute{} = user_contribute, attrs) do
user_contribute
|> cast(attrs, [:date, :count, :user_id])
|> validate_required([:date, :count, :user_id])
|> foreign_key_constraint(:user_id)
end
end
| 23.269231 | 62 | 0.705785 |
793dc5a436bf656c23a36683a5a0210aebf44a09 | 2,188 | exs | Elixir | apps/theta/test/theta/configuration_test.exs | LangPham/thetaproject | c6479d1b761ff58fe6ae5f82e2d9de87a8658883 | [
"MIT"
] | null | null | null | apps/theta/test/theta/configuration_test.exs | LangPham/thetaproject | c6479d1b761ff58fe6ae5f82e2d9de87a8658883 | [
"MIT"
] | 11 | 2020-07-21T09:34:54.000Z | 2021-08-29T07:38:02.000Z | apps/theta/test/theta/configuration_test.exs | LangPham/thetaproject | c6479d1b761ff58fe6ae5f82e2d9de87a8658883 | [
"MIT"
] | null | null | null | defmodule Theta.ConfigurationTest do
use Theta.DataCase
alias Theta.Configuration
describe "config" do
alias Theta.Configuration.Config
@valid_attrs %{key: "some key", value: "some value"}
@update_attrs %{key: "some updated key", value: "some updated value"}
@invalid_attrs %{key: nil, value: nil}
def config_fixture(attrs \\ %{}) do
{:ok, config} =
attrs
|> Enum.into(@valid_attrs)
|> Configuration.create_config()
config
end
test "list_config/0 returns all config" do
config = config_fixture()
assert Configuration.list_config() == [config]
end
test "get_config!/1 returns the config with given id" do
config = config_fixture()
assert Configuration.get_config!(config.id) == config
end
test "create_config/1 with valid data creates a config" do
assert {:ok, %Config{} = config} = Configuration.create_config(@valid_attrs)
assert config.key == "some key"
assert config.value == "some value"
end
test "create_config/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Configuration.create_config(@invalid_attrs)
end
test "update_config/2 with valid data updates the config" do
config = config_fixture()
assert {:ok, %Config{} = config} = Configuration.update_config(config, @update_attrs)
assert config.key == "some updated key"
assert config.value == "some updated value"
end
test "update_config/2 with invalid data returns error changeset" do
config = config_fixture()
assert {:error, %Ecto.Changeset{}} = Configuration.update_config(config, @invalid_attrs)
assert config == Configuration.get_config!(config.id)
end
test "delete_config/1 deletes the config" do
config = config_fixture()
assert {:ok, %Config{}} = Configuration.delete_config(config)
assert_raise Ecto.NoResultsError, fn -> Configuration.get_config!(config.id) end
end
test "change_config/1 returns a config changeset" do
config = config_fixture()
assert %Ecto.Changeset{} = Configuration.change_config(config)
end
end
end
| 32.656716 | 94 | 0.677788 |
793df8ac32c11821b9aa0cd7a48c3904192a8458 | 8,793 | ex | Elixir | lib/managed_ring.ex | bitwalker/libring | f1eaaad48f5d1e989590b15856b07ef212a06cc9 | [
"MIT"
] | 181 | 2016-09-29T12:57:03.000Z | 2022-02-12T12:50:55.000Z | lib/managed_ring.ex | bitwalker/libring | f1eaaad48f5d1e989590b15856b07ef212a06cc9 | [
"MIT"
] | 26 | 2016-12-12T22:22:43.000Z | 2021-12-15T15:52:06.000Z | lib/managed_ring.ex | bitwalker/libring | f1eaaad48f5d1e989590b15856b07ef212a06cc9 | [
"MIT"
] | 22 | 2017-04-28T08:08:44.000Z | 2022-01-27T16:18:20.000Z | defmodule HashRing.Managed do
@moduledoc """
This module defines the API for working with hash rings where the ring state is managed
in a GenServer process.
There is a performance penalty with working with the ring this way, but it is the best approach
if you need to share the ring across multiple processes, or need to maintain multiple rings.
If your rings map 1:1 with Erlang node membership, you can configure rings to automatically
monitor node up/down events and update the hash ring accordingly, with a default weight,
and either whitelist or blacklist nodes from the ring. You configure this at the ring level in your `config.exs`.
Each ring is configured in `config.exs`, and can contain a list of nodes to seed the ring with,
and you can then dynamically add/remove nodes to the ring using the API here. Each node on the ring can
be configured with a weight, which affects the amount of the total keyspace it owns. The default weight
is `128`. It's best to base the weight of nodes on some concrete relative value, such as the amount of
memory a node has.
"""
@type ring :: pid() | atom()
@type key :: any()
@type weight :: pos_integer
@type node_list :: [term() | {term(), weight}]
@type pattern_list :: [String.t() | Regex.t()]
@type ring_options :: [
nodes: node_list,
monitor_nodes: boolean,
node_blacklist: pattern_list,
node_whitelist: pattern_list
]
@valid_ring_opts [:name, :nodes, :monitor_nodes, :node_blacklist, :node_whitelist, :node_type]
@doc """
Creates a new stateful hash ring with the given name.
This name is how you will refer to the hash ring via other API calls.
It takes an optional set of options which control how the ring behaves.
Valid options are as follows:
* `monitor_nodes: boolean` - will automatically monitor Erlang node membership,
if new nodes are connected or nodes are disconnected, the ring will be updated automatically.
In this configuration, nodes cannot be added or removed via the API. Those requests will be ignored.
* `node_blacklist: [String.t | Regex.t]` - Used in conjunction with `monitor_nodes: true`, this
is a list of patterns, either as literal strings, or as regex patterns (in either string or literal form),
and will be used to ignore nodeup/down events for nodes which are blacklisted. If a node whitelist
is provided, the blacklist has no effect.
* `node_whitelist: [String.t | Regex.t]` - The same as `node_blacklist`, except the opposite; only nodes
which match a pattern in the whitelist will result in the ring being updated.
- `node_type: :all | :hidden | :visible`: refers what kind of nodes will be monitored
when `monitor_nodes` is `true`. For more information, see `:net_kernel.monitor_nodes/2`.
An error is returned if the ring already exists or if bad ring options are provided.
## Examples
iex> {:ok, _pid} = HashRing.Managed.new(:test1, [nodes: ["a", {"b", 64}]])
...> HashRing.Managed.key_to_node(:test1, :foo)
"b"
iex> {:ok, pid} = HashRing.Managed.new(:test2)
...> {:error, {:already_started, existing_pid}} = HashRing.Managed.new(:test2)
...> pid == existing_pid
true
iex> HashRing.Managed.new(:test3, [nodes: "a"])
** (ArgumentError) {:nodes, "a"} is an invalid option for `HashRing.Managed.new/2`
"""
@spec new(ring) :: {:ok, pid} | {:error, {:already_started, pid}}
@spec new(ring, ring_options) ::
{:ok, pid} | {:error, {:already_started, pid}} | {:error, {:invalid_option, term}}
def new(name, ring_options \\ []) when is_list(ring_options) do
opts = [{:name, name} | ring_options]
invalid =
Enum.find(opts, fn
{key, value} when key in @valid_ring_opts ->
case key do
:name when is_atom(value) -> false
:nodes when is_list(value) -> Keyword.keyword?(value)
:monitor_nodes when is_boolean(value) -> false
:node_blacklist when is_list(value) -> false
:node_whitelist when is_list(value) -> false
:node_type when value in [:all, :hidden, :visible] -> false
_ -> true
end
end)
case invalid do
nil ->
case Process.whereis(:"libring_#{name}") do
nil ->
DynamicSupervisor.start_child(HashRing.Supervisor, {HashRing.Worker, opts})
pid ->
{:error, {:already_started, pid}}
end
_ ->
raise ArgumentError,
message: "#{inspect(invalid)} is an invalid option for `HashRing.Managed.new/2`"
end
end
@doc """
Same as `HashRing.nodes/1`, returns a list of nodes on the ring.
## Examples
iex> {:ok, _pid} = HashRing.Managed.new(:nodes_test)
...> HashRing.Managed.add_nodes(:nodes_test, [:a, :b])
...> HashRing.Managed.nodes(:nodes_test)
[:b, :a]
"""
@spec nodes(ring) :: [term()]
def nodes(ring) do
HashRing.Worker.nodes(ring)
end
@doc """
Adds a node to the given hash ring.
An error is returned if the ring does not exist, or the node already exists in the ring.
## Examples
iex> {:ok, _pid} = HashRing.Managed.new(:test4)
...> HashRing.Managed.add_node(:test4, "a")
...> HashRing.Managed.key_to_node(:test4, :foo)
"a"
iex> HashRing.Managed.add_node(:no_exist, "a")
{:error, :no_such_ring}
"""
@spec add_node(ring, key) :: :ok | {:error, :no_such_ring}
def add_node(ring, node) do
HashRing.Worker.add_node(ring, node)
end
@doc """
Same as `add_node/2`, but takes a weight value.
The weight controls the relative presence this node will have on the ring,
the default is `128`, but it's best to give each node a weight value which maps
to a concrete resource such as memory or priority. It's not ideal to have a number
which is too high, as it will make the ring data structure larger, but a good value
is probably in the range of 64-256.
## Examples
iex> {:ok, _pid} = HashRing.Managed.new(:test5)
...> HashRing.Managed.add_node(:test5, "a", 64)
...> HashRing.Managed.key_to_node(:test5, :foo)
"a"
iex> HashRing.Managed.add_node(:no_exist, "a")
{:error, :no_such_ring}
"""
@spec add_node(ring, key, weight) ::
:ok
| {:error, :no_such_ring}
| {:error, {:invalid_weight, key, term}}
def add_node(ring, node, weight)
when is_integer(weight) and weight > 0 do
HashRing.Worker.add_node(ring, node, weight)
end
def add_node(_ring, node, weight) do
{:error, {:invalid_weight, node, weight}}
end
@doc """
Adds a list of nodes to the ring.
The list of nodes can contain either node names or `{node_name, weight}`
tuples. If there is an error with any of the node weights, an error will
be returned, and the ring will remain unchanged.
## Examples
iex> {:ok, _pid} = HashRing.Managed.new(:test6)
...> :ok = HashRing.Managed.add_nodes(:test6, ["a", {"b", 64}])
...> HashRing.Managed.key_to_node(:test6, :foo)
"b"
iex> {:ok, _pid} = HashRing.Managed.new(:test7)
...> HashRing.Managed.add_nodes(:test7, ["a", {"b", :wrong}])
{:error, [{:invalid_weight, "b", :wrong}]}
"""
@spec add_nodes(ring, node_list) ::
:ok
| {:error, :no_such_ring}
| {:error, [{:invalid_weight, key, term}]}
def add_nodes(ring, nodes) when is_list(nodes) do
invalid =
Enum.filter(nodes, fn
{_node, weight} when is_integer(weight) and weight > 0 ->
false
{_node, _weight} ->
true
node when is_binary(node) or is_atom(node) ->
false
_node ->
true
end)
case invalid do
[] ->
HashRing.Worker.add_nodes(ring, nodes)
_ ->
{:error, Enum.map(invalid, fn {k, v} -> {:invalid_weight, k, v} end)}
end
end
@doc """
Removes a node from the given hash ring.
An error is returned if the ring does not exist.
## Examples
iex> {:ok, _pid} = HashRing.Managed.new(:test8)
...> :ok = HashRing.Managed.add_nodes(:test8, ["a", {"b", 64}])
...> :ok = HashRing.Managed.remove_node(:test8, "b")
...> HashRing.Managed.key_to_node(:test8, :foo)
"a"
"""
@spec remove_node(ring, key) :: :ok | {:error, :no_such_ring}
def remove_node(ring, node) do
HashRing.Worker.remove_node(ring, node)
end
@doc """
Maps a key to a node on the hash ring.
An error is returned if the ring does not exist.
"""
@spec key_to_node(ring, any()) ::
key
| {:error, :no_such_ring}
| {:error, {:invalid_ring, :no_nodes}}
def key_to_node(ring, key) do
HashRing.Worker.key_to_node(ring, key)
end
end
| 34.61811 | 115 | 0.638349 |
793e1703fb92d6f0ad5ed1af14200986bfa178d2 | 232 | ex | Elixir | lib/slackex/api.ex | SirFitz/slack | 2843fe07c006f75a20fd652f0ec31e76db923d9d | [
"MIT"
] | null | null | null | lib/slackex/api.ex | SirFitz/slack | 2843fe07c006f75a20fd652f0ec31e76db923d9d | [
"MIT"
] | null | null | null | lib/slackex/api.ex | SirFitz/slack | 2843fe07c006f75a20fd652f0ec31e76db923d9d | [
"MIT"
] | null | null | null | defmodule Slack.Api do
@moduledoc """
API Test Calls for Slack
"""
@doc """
Returns an "ok" message when a
successfull connection to the Slack
API is made
"""
def test do
Slack.request("api.test")
end
end
| 13.647059 | 37 | 0.637931 |
793e44e721d7350c06e1490720860ae21d7ce056 | 1,071 | ex | Elixir | test/support/test_provider.ex | Schultzer/coherence_assent | 5adf518d7760641e686ca2c588def0e8f62ea093 | [
"MIT",
"Unlicense"
] | null | null | null | test/support/test_provider.ex | Schultzer/coherence_assent | 5adf518d7760641e686ca2c588def0e8f62ea093 | [
"MIT",
"Unlicense"
] | null | null | null | test/support/test_provider.ex | Schultzer/coherence_assent | 5adf518d7760641e686ca2c588def0e8f62ea093 | [
"MIT",
"Unlicense"
] | null | null | null | defmodule TestProvider do
alias CoherenceAssent.Strategy.Helpers
alias CoherenceAssent.Strategies.OAuth2, as: OAuth2Helper
def authorize_url(conn: conn, config: config) do
config = config |> set_config
OAuth2Helper.authorize_url(conn: conn, config: config)
end
def callback(conn: conn, config: config, params: params) do
config = config |> set_config
OAuth2Helper.callback(conn: conn, config: config, params: params)
|> normalize
end
defp set_config(config) do
[
site: "http://localhost:4000/",
authorize_url: "/oauth/authorize",
token_url: "/oauth/token",
user_url: "/api/user"
]
|> Keyword.merge(config)
|> Keyword.put(:strategy, OAuth2.Strategy.AuthCode)
end
defp normalize({:ok, %{conn: conn, client: client, user: user}}) do
user = %{"uid" => user["uid"],
"name" => user["name"],
"email" => user["email"]} |> Helpers.prune
{:ok, %{conn: conn, client: client, user: user}}
end
defp normalize({:error, _} = response), do: response
end
| 29.75 | 69 | 0.636788 |
793e4fa04581b7535340f42e0a5e71567686c132 | 1,756 | ex | Elixir | lib/mix/tasks/import.ex | alisinabh/gettext_csv | d5d9a8badcaff2f198f1722c6d795a7a24707e53 | [
"MIT"
] | null | null | null | lib/mix/tasks/import.ex | alisinabh/gettext_csv | d5d9a8badcaff2f198f1722c6d795a7a24707e53 | [
"MIT"
] | null | null | null | lib/mix/tasks/import.ex | alisinabh/gettext_csv | d5d9a8badcaff2f198f1722c6d795a7a24707e53 | [
"MIT"
] | null | null | null | defmodule Mix.Tasks.GettextCsv.Import do
use Mix.Task
import GettextCsv
alias NimbleCSV.RFC4180, as: CSV
@shortdoc "Import csv to po files"
def run(args) do
{opts, [csv_file], _} = OptionParser.parse(args, strict: [pot_file: :string])
pot_file = get_pot_file(opts[:pot_file])
base = Path.dirname(pot_file)
filename = Path.basename(pot_file, Path.extname(pot_file))
[["msgid" | langs] | csv_data] =
csv_file
|> File.read!()
|> CSV.parse_string(skip_headers: false)
po_data =
langs
|> Enum.reduce(%{}, fn lang, acc ->
po_file = po_path(base, lang, filename)
po = Gettext.PO.parse_file!(po_file)
Map.put(acc, lang, po)
end)
po_data =
Enum.reduce(csv_data, po_data, fn row, po_data_1 ->
[msgid | translations] = row
translations = Enum.zip(langs, translations) |> Enum.into(%{})
Enum.reduce(langs, po_data_1, fn lang, po_data_2 ->
po = replace(po_data_2[lang], msgid, translations[lang])
Map.put(po_data_2, lang, po)
end)
end)
Enum.each(po_data, fn {lang, po} ->
po_file = po_path(base, lang, filename)
po_dump = Gettext.PO.dump(po)
File.write!(po_file, po_dump)
IO.puts("Written #{lang} to #{po_file}")
end)
IO.puts("Import finished!")
end
defp replace(po, msgid, translation) do
translations =
Enum.map(po.translations, fn
%Gettext.PO.Translation{} = po_translation ->
if po_translation.msgid == [msgid] do
Map.put(po_translation, :msgstr, [translation])
else
po_translation
end
t ->
t
end)
Map.put(po, :translations, translations)
end
end
| 25.823529 | 81 | 0.599089 |
793e8a1f8b4724259057eb14e1823d422cdac3e9 | 196 | exs | Elixir | priv/repo/migrations/20210209114646_update_evidence.exs | WeLightProject/WeLight-Portal | 6e701469423e3a62affdc415c4e8c186d603d324 | [
"MIT"
] | 2 | 2021-02-12T09:21:56.000Z | 2021-02-22T08:52:20.000Z | priv/repo/migrations/20210209114646_update_evidence.exs | WeLightProject/WeLight-Portal | 6e701469423e3a62affdc415c4e8c186d603d324 | [
"MIT"
] | 4 | 2021-02-22T08:53:43.000Z | 2021-06-09T09:24:46.000Z | priv/repo/migrations/20210209114646_update_evidence.exs | WeLightProject/WeLight-Portal | 6e701469423e3a62affdc415c4e8c186d603d324 | [
"MIT"
] | null | null | null | defmodule SuperIssuer.Repo.Migrations.UpdateEvidence do
use Ecto.Migration
def change do
alter table :evidence do
remove :describe
add :description, :string
end
end
end
| 17.818182 | 55 | 0.714286 |
793e96a395d4fd9cebaa1752051fe1186903369e | 1,565 | ex | Elixir | clients/translate/lib/google_api/translate/v2/model/detect_language_request.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/translate/lib/google_api/translate/v2/model/detect_language_request.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/translate/lib/google_api/translate/v2/model/detect_language_request.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 "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 elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Translate.V2.Model.DetectLanguageRequest do
@moduledoc """
The request message for language detection.
## Attributes
* `q` (*type:* `list(String.t)`, *default:* `nil`) - The input text upon which to perform language detection. Repeat this
parameter to perform language detection on multiple text inputs.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:q => list(String.t())
}
field(:q, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Translate.V2.Model.DetectLanguageRequest do
def decode(value, options) do
GoogleApi.Translate.V2.Model.DetectLanguageRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Translate.V2.Model.DetectLanguageRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.604167 | 125 | 0.741214 |
793e9e95a08b10aeec64fe2de17194c8db8a9c5a | 1,816 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/user_role_permission_group.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/user_role_permission_group.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/user_role_permission_group.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.DFAReporting.V33.Model.UserRolePermissionGroup do
@moduledoc """
Represents a grouping of related user role permissions.
## Attributes
* `id` (*type:* `String.t`, *default:* `nil`) - ID of this user role permission.
* `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRolePermissionGroup".
* `name` (*type:* `String.t`, *default:* `nil`) - Name of this user role permission group.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:id => String.t() | nil,
:kind => String.t() | nil,
:name => String.t() | nil
}
field(:id)
field(:kind)
field(:name)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.UserRolePermissionGroup do
def decode(value, options) do
GoogleApi.DFAReporting.V33.Model.UserRolePermissionGroup.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.UserRolePermissionGroup do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.264151 | 159 | 0.714758 |
793eacf7a147338f50811deeaa9d8b397f1ab588 | 1,392 | ex | Elixir | lib/central/oban_logger.ex | badosu/teiserver | 19b623aeb7c2ab28756405f7486e92b714777c54 | [
"MIT"
] | 4 | 2021-07-29T16:23:20.000Z | 2022-02-23T05:34:36.000Z | lib/central/oban_logger.ex | badosu/teiserver | 19b623aeb7c2ab28756405f7486e92b714777c54 | [
"MIT"
] | 14 | 2021-08-01T02:36:14.000Z | 2022-01-30T21:15:03.000Z | lib/central/oban_logger.ex | badosu/teiserver | 19b623aeb7c2ab28756405f7486e92b714777c54 | [
"MIT"
] | 7 | 2021-05-13T12:55:28.000Z | 2022-01-14T06:39:06.000Z | defmodule Central.ObanLogger do
@moduledoc false
require Logger
import Central.Logging.Helpers, only: [add_error_log: 1]
def handle_event([:oban, :job, :start], _measure, _meta, _) do
# Logger.warn("[Oban] :started #{meta.worker} at #{measure.system_time}")
end
def handle_event([:oban, :job, :exception], _measure, meta, _) do
data = %{
conn: %{
request_path: "Oban:#{meta.worker}",
method: "Oban worker - Error",
assigns: %{current_user: %{id: nil}, cache: %{}},
remote_ip: {},
params: meta.args
},
reason: meta.error,
stack: meta.stack
}
log = add_error_log(data)
error_str = Kernel.inspect(meta.error)
Logger.error("[Oban] [failure] #{error_str} Logged as ##{log.id}")
end
def handle_event([:oban, :circuit, :trip], _measure, meta, _) do
data = %{
conn: %{
request_path: "Oban:#{meta.worker}",
method: "Oban worker - trip_circuit",
assigns: %{current_user: %{id: nil}, cache: %{}},
remote_ip: {},
params: meta.args
},
reason: meta.error,
stack: meta.stack
}
log = add_error_log(data)
Logger.error("[Oban] [failure] {Logged as ##{log.id}}")
end
def handle_event([:oban, :job, event], measure, meta, _) do
Logger.info("[Oban] #{event} #{meta.worker} ran in #{measure.duration}")
end
end
| 26.769231 | 77 | 0.588362 |
793edefc43610499d423449114e186e0884dbc67 | 272 | ex | Elixir | lib/nadia/encoder.ex | angordeyev/nadia | e57b45d1d73be195604e56f4e08fe7ce757518b9 | [
"MIT"
] | 386 | 2015-08-20T21:48:07.000Z | 2022-03-06T21:08:19.000Z | lib/nadia/encoder.ex | angordeyev/nadia | e57b45d1d73be195604e56f4e08fe7ce757518b9 | [
"MIT"
] | 146 | 2015-09-19T07:13:56.000Z | 2022-03-24T20:02:02.000Z | lib/nadia/encoder.ex | cplotter/nadia | a3cb8f8249903a76cbff281c0773087a437df215 | [
"MIT"
] | 107 | 2015-10-23T09:02:13.000Z | 2022-02-07T19:46:15.000Z | defimpl Jason.Encoder, for: Nadia.Model.InlineKeyboardButton do
def encode(button, options) do
Map.from_struct(button)
|> reject_nil
|> Jason.Encoder.encode(options)
end
defp reject_nil(map) do
:maps.filter(fn _, v -> !is_nil(v) end, map)
end
end
| 22.666667 | 63 | 0.691176 |
793ef7c1c06f8677ae25051e5c7600cc3a001f46 | 2,819 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/usable_subnetworks_aggregated_list.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/usable_subnetworks_aggregated_list.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/usable_subnetworks_aggregated_list.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.Compute.V1.Model.UsableSubnetworksAggregatedList do
@moduledoc """
## Attributes
- id (String.t): [Output Only] The unique identifier for the resource. This identifier is defined by the server. Defaults to: `null`.
- items ([UsableSubnetwork]): [Output] A list of usable subnetwork URLs. Defaults to: `null`.
- kind (String.t): [Output Only] Type of resource. Always compute#usableSubnetworksAggregatedList for aggregated lists of usable subnetworks. Defaults to: `null`.
- nextPageToken (String.t): [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results. Defaults to: `null`.
- selfLink (String.t): [Output Only] Server-defined URL for this resource. Defaults to: `null`.
- warning (AcceleratorTypeAggregatedListWarning): Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:id => any(),
:items => list(GoogleApi.Compute.V1.Model.UsableSubnetwork.t()),
:kind => any(),
:nextPageToken => any(),
:selfLink => any(),
:warning => GoogleApi.Compute.V1.Model.AcceleratorTypeAggregatedListWarning.t()
}
field(:id)
field(:items, as: GoogleApi.Compute.V1.Model.UsableSubnetwork, type: :list)
field(:kind)
field(:nextPageToken)
field(:selfLink)
field(:warning, as: GoogleApi.Compute.V1.Model.AcceleratorTypeAggregatedListWarning)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.UsableSubnetworksAggregatedList do
def decode(value, options) do
GoogleApi.Compute.V1.Model.UsableSubnetworksAggregatedList.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.UsableSubnetworksAggregatedList do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.746032 | 381 | 0.743526 |
793efebab6b7bee1be775ed970660848a6c1f0fc | 1,804 | ex | Elixir | elixir/persistent_todo_cache/lib/todo/server.ex | raventid/coursera_learning | 115a03f08d30d8ba49f02c9692c289cbfb242358 | [
"MIT"
] | 1 | 2019-11-28T09:26:00.000Z | 2019-11-28T09:26:00.000Z | elixir/persistent_todo_cache/lib/todo/server.ex | raventid/coursera_learning | 115a03f08d30d8ba49f02c9692c289cbfb242358 | [
"MIT"
] | null | null | null | elixir/persistent_todo_cache/lib/todo/server.ex | raventid/coursera_learning | 115a03f08d30d8ba49f02c9692c289cbfb242358 | [
"MIT"
] | null | null | null | defmodule Todo.Server do
use GenServer
# Client Interface.
def start(name) do
GenServer.start(__MODULE__, name)
end
def add_entry(todo_server, new_entry) do
GenServer.cast(todo_server, {:add_entry, new_entry})
end
def entries(todo_server, date) do
GenServer.call(todo_server, {:entries, date})
end
# Callback functions.
@impl GenServer
def init(name) do
# If I start a very long operation here,
# I may block caller process for a long
# period of time. So we'll use one trick.
# One important note about first signal:
# If you initialize your process here,
# without it being registered under global
# name, then everything is fine. Your
# message will be the first one you send
# to yourself.
# But if you are not using pid
# and you are using named processes
# then caller can send you a message
# before you initialized your process
# with :real_init. To avoid this
# register process name right here
# in init. And forbid standard way.
send(self(), {:real_init, name})
{:ok, nil}
end
@impl GenServer
def handle_info({:real_init, name}, _) do
{:noreply, {name, Todo.Database.get(name) || Todo.List.new()}}
end
@impl GenServer
def handle_cast({:add_entry, new_entry}, {name, todo_list}) do
new_state = Todo.List.add_entry(todo_list, new_entry)
Todo.Database.store(name, new_state)
{:noreply, new_state}
end
@impl GenServer
def handle_call({:entries, date}, _, {name, todo_list}) do
{
:reply,
Todo.List.entries(todo_list, date),
todo_list
}
end
end
# {:ok, cache_pid} = Todo.Cache.start
# bobs_list = Todo.Cache.server_process(cache_pid, "bobs_list")
# Todo.Server.add_entry(bobs_list, %{date: ~D[2018-09-09], title: "Jul"})
| 26.925373 | 73 | 0.674612 |
793f10deb0f1ab654d5895d035c54471cd09aa44 | 8,948 | ex | Elixir | lib/minecraft/packet.ex | thecodeboss/minecraft | e5e6c54a1e93497432363aef4700e4be7a145bb3 | [
"MIT"
] | 29 | 2018-09-03T15:34:33.000Z | 2021-12-30T19:36:42.000Z | lib/minecraft/packet.ex | thecodeboss/minecraft | e5e6c54a1e93497432363aef4700e4be7a145bb3 | [
"MIT"
] | 76 | 2018-07-13T13:19:09.000Z | 2022-03-23T15:27:43.000Z | lib/minecraft/packet.ex | thecodeboss/minecraft | e5e6c54a1e93497432363aef4700e4be7a145bb3 | [
"MIT"
] | 2 | 2020-10-06T15:50:17.000Z | 2021-12-29T08:06:48.000Z | defmodule Minecraft.Packet do
@moduledoc """
Base serialization and deserialization routines for packets.
"""
use Bitwise
alias Minecraft.Packet.Client
alias Minecraft.Packet.Server
@type position :: {x :: -33_554_432..33_554_431, y :: -2048..2047, z :: -33_554_432..33_554_431}
@type varint :: -2_147_483_648..2_147_483_647
@type varlong :: -9_223_372_036_854_775_808..9_223_372_036_854_775_807
@type packet_types ::
Client.Handshake.t()
| Client.Handshake.t()
| Client.Status.Request.t()
| Client.Status.Ping.t()
| Server.Status.Response.t()
| Server.Status.Pong.t()
| Client.Login.LoginStart.t()
| Client.Login.EncryptionResponse.t()
| Server.Login.EncryptionRequest.t()
| Server.Login.LoginSuccess.t()
| Client.Play.TeleportConfirm.t()
| Client.Play.ClientStatus.t()
| Client.Play.ClientSettings.t()
| Client.Play.PluginMessage.t()
| Client.Play.KeepAlive.t()
| Client.Play.PlayerPosition.t()
| Client.Play.PlayerPositionAndLook.t()
| Client.Play.PlayerLook.t()
| Server.Play.JoinGame.t()
| Server.Play.SpawnPosition.t()
| Server.Play.PlayerAbilities.t()
| Server.Play.PlayerPositionAndLook.t()
| Server.Play.KeepAlive.t()
@doc """
Given a raw binary packet, deserializes it into a `Packet` struct.
"""
@spec deserialize(binary, state :: atom, type :: :client | :server) ::
{packet :: term, rest :: binary} | {:error, :invalid_packet}
def deserialize(data, state, type \\ :client) do
{packet_size, data} = decode_varint(data)
<<data::binary-size(packet_size), rest::binary>> = data
{packet_id, data} = decode_varint(data)
case do_deserialize({state, packet_id, type}, data) do
{packet, ""} ->
{packet, rest}
error ->
{error, rest}
end
end
defp do_deserialize({state, packet_id, type}, data) do
case {state, packet_id, type} do
# Client Handshake Packets
{:handshake, 0, :client} ->
Client.Handshake.deserialize(data)
# Client Status Packets
{:status, 0, :client} ->
Client.Status.Request.deserialize(data)
{:status, 1, :client} ->
Client.Status.Ping.deserialize(data)
# Server Status Packets
{:status, 0, :server} ->
Server.Status.Response.deserialize(data)
{:status, 1, :server} ->
Server.Status.Pong.deserialize(data)
# Client Login Packets
{:login, 0, :client} ->
Client.Login.LoginStart.deserialize(data)
{:login, 1, :client} ->
Client.Login.EncryptionResponse.deserialize(data)
# Server Login Packets
# TODO {:login, 0, :server} ->
# Server.Login.Disconnect.deserialize(data)
{:login, 1, :server} ->
Server.Login.EncryptionRequest.deserialize(data)
{:login, 2, :server} ->
Server.Login.LoginSuccess.deserialize(data)
# Client Play Packets
{:play, 0, :client} ->
Client.Play.TeleportConfirm.deserialize(data)
{:play, 3, :client} ->
Client.Play.ClientStatus.deserialize(data)
{:play, 4, :client} ->
Client.Play.ClientSettings.deserialize(data)
{:play, 9, :client} ->
Client.Play.PluginMessage.deserialize(data)
{:play, 0x0B, :client} ->
Client.Play.KeepAlive.deserialize(data)
{:play, 0x0D, :client} ->
Client.Play.PlayerPosition.deserialize(data)
{:play, 0x0E, :client} ->
Client.Play.PlayerPositionAndLook.deserialize(data)
{:play, 0x0F, :client} ->
Client.Play.PlayerLook.deserialize(data)
# Server Play Packets
{:play, 0x1F, :server} ->
Server.Play.KeepAlive.deserialize(data)
{:play, 0x23, :server} ->
Server.Play.JoinGame.deserialize(data)
{:play, 0x46, :server} ->
Server.Play.SpawnPosition.deserialize(data)
{:play, 0x2C, :server} ->
Server.Play.PlayerAbilities.deserialize(data)
{:play, 0x2F, :server} ->
Server.Play.PlayerPositionAndLook.deserialize(data)
_ ->
{:error, :invalid_packet}
end
end
@doc """
Serializes a packet into binary data.
"""
@spec serialize(packet :: struct) :: {:ok, binary} | {:error, term}
def serialize(%struct{} = request) do
{packet_id, packet_binary} = struct.serialize(request)
serialize(packet_id, packet_binary)
end
@doc """
Serializes a packet binary into the standard packet format:
| Field | Type | Description |
| --------- | ------ | ----------------------------------------------- |
| Length | VarInt | Length of packet data + length of the packet ID |
| Packet ID | VarInt | |
| Data | Binary | The serialized packet data |
"""
@spec serialize(packet_id :: integer, binary) :: {:ok, binary} | {:error, term}
def serialize(packet_id, packet_binary) do
packet_id = encode_varint(packet_id)
packet_size = encode_varint(byte_size(packet_binary) + byte_size(packet_id))
response = <<packet_size::binary, packet_id::binary, packet_binary::binary>>
{:ok, response}
end
@doc """
Decodes a boolean.
"""
@spec decode_bool(binary) :: {decoded :: boolean, rest :: binary}
def decode_bool(<<0, rest::binary>>), do: {false, rest}
def decode_bool(<<1, rest::binary>>), do: {true, rest}
@doc """
Decodes a position.
"""
@spec decode_position(binary) :: {position, rest :: binary}
def decode_position(<<x::26-signed, y::12-signed, z::26-signed, rest::binary>>) do
{{x, y, z}, rest}
end
@doc """
Decodes a variable-size integer.
"""
@spec decode_varint(binary) ::
{decoded :: varint, rest :: binary} | {:error, :too_long | :too_short}
def decode_varint(data) do
decode_varint(data, 0, 0)
end
defp decode_varint(<<1::1, value::7, rest::binary>>, num_read, acc) when num_read < 5 do
decode_varint(rest, num_read + 1, acc + (value <<< (7 * num_read)))
end
defp decode_varint(<<0::1, value::7, rest::binary>>, num_read, acc) do
result = acc + (value <<< (7 * num_read))
<<result::32-signed>> = <<result::32-unsigned>>
{result, rest}
end
defp decode_varint(_, num_read, _) when num_read >= 5, do: {:error, :too_long}
defp decode_varint("", _, _), do: {:error, :too_short}
@doc """
Decodes a variable-size long.
"""
@spec decode_varlong(binary) ::
{decoded :: varlong, rest :: binary} | {:error, :too_long | :too_short}
def decode_varlong(data) do
decode_varlong(data, 0, 0)
end
defp decode_varlong(<<1::1, value::7, rest::binary>>, num_read, acc) when num_read < 10 do
decode_varlong(rest, num_read + 1, acc + (value <<< (7 * num_read)))
end
defp decode_varlong(<<0::1, value::7, rest::binary>>, num_read, acc) do
result = acc + (value <<< (7 * num_read))
<<result::64-signed>> = <<result::64-unsigned>>
{result, rest}
end
defp decode_varlong(_, num_read, _) when num_read >= 10, do: {:error, :too_long}
defp decode_varlong("", _, _), do: {:error, :too_short}
@doc """
Decodes a string.
"""
@spec decode_string(binary) :: {decoded :: binary, rest :: binary}
def decode_string(data) do
{strlen, data} = decode_varint(data)
<<string::binary-size(strlen), rest::binary>> = data
{string, rest}
end
@doc """
Encodes a boolean.
"""
@spec encode_bool(boolean) :: binary
def encode_bool(false = _boolean), do: <<0>>
def encode_bool(true), do: <<1>>
@doc """
Encodes a position.
"""
@spec encode_position(position) :: binary
def encode_position({x, y, z}) do
<<x::26-signed, y::12-signed, z::26-signed>>
end
@doc """
Encodes a variable-size integer.
"""
@spec encode_varint(varint) :: binary | {:error, :too_large}
def encode_varint(value) when value in -2_147_483_648..2_147_483_647 do
<<value::32-unsigned>> = <<value::32-signed>>
encode_varint(value, 0, "")
end
def encode_varint(_) do
{:error, :too_large}
end
defp encode_varint(value, _, acc) when value <= 127 do
<<acc::binary, 0::1, value::7>>
end
defp encode_varint(value, num_write, acc) when value > 127 and num_write < 5 do
encode_varint(value >>> 7, num_write + 1, <<acc::binary, 1::1, band(value, 0x7F)::7>>)
end
@doc """
Encodes a string.
"""
@spec encode_string(binary) :: binary
def encode_string(string) do
strlen = encode_varint(byte_size(string))
<<strlen::binary, string::binary>>
end
end
| 31.957143 | 99 | 0.588511 |
793f1cbf66049e268df98a9afc74acf0bf7ba851 | 17,536 | exs | Elixir | test/teslamate_web/controllers/car_controller_test.exs | douglasevaristo/teslamate | d239023942b319e9446d2da316d0afbddf701b9d | [
"MIT"
] | 1 | 2020-08-31T10:21:12.000Z | 2020-08-31T10:21:12.000Z | test/teslamate_web/controllers/car_controller_test.exs | douglasevaristo/teslamate | d239023942b319e9446d2da316d0afbddf701b9d | [
"MIT"
] | null | null | null | test/teslamate_web/controllers/car_controller_test.exs | douglasevaristo/teslamate | d239023942b319e9446d2da316d0afbddf701b9d | [
"MIT"
] | null | null | null | defmodule TeslaMateWeb.CarControllerTest do
use TeslaMateWeb.ConnCase
use TeslaMate.VehicleCase
alias TeslaMate.Settings.CarSettings
alias TeslaMate.{Log, Settings, Repo}
alias TeslaMate.Log.Car
defp table_row(html, key, value, opts \\ []) do
assert {"tr", _, [{"td", _, [^key]}, {"td", [], [v]}]} =
html
|> Floki.parse_document!()
|> Floki.find("tr")
|> Enum.find(&match?({"tr", _, [{"td", _, [^key]}, _td]}, &1))
case Keyword.get(opts, :tooltip) do
nil -> assert value == v
str -> assert {"span", [_, {"data-tooltip", ^str}], [^value]} = v
end
end
defp icon(html, tooltip, icon) do
icon_class = "mdi mdi-#{icon}"
assert {"span", _, [{"span", [{"class", ^icon_class}], _}]} =
html
|> Floki.parse_document!()
|> Floki.find(".icons .icon")
|> Enum.find(&match?({"span", [_, {"data-tooltip", ^tooltip}], _}, &1))
end
defp car_fixture(settings) do
{:ok, car} =
Log.create_car(%{
efficiency: 0.153,
eid: 4242,
vid: 404,
vin: "xxxxx",
model: "S",
name: "foo",
trim_badging: "P100D"
})
{:ok, _settings} =
car.settings
|> Repo.preload(:car)
|> Settings.update_car_settings(settings)
car
end
describe "index" do
test "redirects if not signed in", %{conn: conn} do
assert conn = get(conn, Routes.car_path(conn, :index))
assert redirected_to(conn, 302) == Routes.live_path(conn, TeslaMateWeb.SignInLive.Index)
end
@tag :signed_in
test "lists all active vehicles", %{conn: conn} do
{:ok, _pid} =
start_supervised(
{ApiMock, name: :api_vehicle, events: [{:ok, online_event()}], pid: self()}
)
{:ok, _pid} =
start_supervised(
{TeslaMate.Vehicles,
vehicle: VehicleMock,
vehicles: [
%TeslaApi.Vehicle{display_name: "f0o", id: 4241, vehicle_id: 11111, vin: "1221"},
%TeslaApi.Vehicle{display_name: "fo0", id: 1242, vehicle_id: 22222, vin: "2112"}
]}
)
conn = get(conn, Routes.car_path(conn, :index))
html = response(conn, 200)
assert [
{"div", [{"class", "car card"}], _},
{"div", [{"class", "car card"}], _}
] =
html
|> Floki.parse_document!()
|> Floki.find(".car")
end
@tag :signed_in
test "renders last knwon vehicle stats", %{conn: conn} do
events = [
{:ok, %TeslaApi.Vehicle{state: "asleep", display_name: "FooCar"}}
]
{:ok, car} =
%Car{settings: %CarSettings{}}
|> Car.changeset(%{vid: 404, eid: 404, vin: "xxxxx"})
|> Log.create_or_update_car()
{:ok, _position} =
Log.insert_position(car, %{
date: DateTime.utc_now(),
longitude: 0,
latitude: 0,
rated_battery_range_km: 380.25,
est_battery_range_km: 401.52,
ideal_battery_range_km: 175.1,
battery_level: 80,
outside_temp: 20.1,
inside_temp: 21.0
})
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "asleep")
assert table_row(html, "Range (rated)", "380.26 km")
assert table_row(html, "Range (est.)", "401.52 km")
assert table_row(html, "State of Charge", "80%", tooltip: "≈ 475 km at 100%")
assert table_row(html, "Outside Temperature", "20.1 °C")
assert table_row(html, "Inside Temperature", "21.0 °C")
end
@tag :signed_in
test "renders current vehicle stats [:online]", %{conn: conn} do
now = (DateTime.utc_now() |> DateTime.to_unix()) * 1000
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: now, latitude: 0.0, longitude: 0.0},
charge_state: %{
battery_range: 200,
est_battery_range: 180,
ideal_battery_range: 175,
usable_battery_level: 67,
battery_level: 69
},
climate_state: %{is_preconditioning: true, outside_temp: 24, inside_temp: 23.2},
vehicle_state: %{
timestamp: 0,
car_version: "2019.40.50.7 ad132c7b057e",
software_update: %{status: "available"},
locked: true,
sentry_mode: true,
fd_window: 1,
fp_window: 0,
rd_window: 0,
rp_window: 0,
df: 0,
dr: 0,
pf: 1,
pr: 0,
is_user_present: true,
odometer: 26097.59
},
vehicle_config: %{car_type: "models2", trim_badging: "p90d"}
)}
]
:ok = start_vehicles(events)
Process.sleep(250)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert html =~ ~r/<p class="subtitle is-6 has-text-weight-light">Model S P90D<\/p>/
assert table_row(html, "Status", "online")
assert table_row(html, "Range (rated)", "321.87 km")
assert table_row(html, "Range (est.)", "289.68 km")
assert table_row(html, "State of Charge", "67% (69%)", tooltip: "≈ 480 km at 100%")
assert icon(html, "Locked", "lock")
assert icon(html, "Driver present", "account")
assert icon(html, "Preconditioning", "air-conditioner")
assert icon(html, "Sentry Mode", "shield-check")
assert icon(html, "Windows open", "window-open")
assert icon(html, "Doors open", "car-door")
assert icon(html, "Software Update available", "gift-outline")
assert table_row(html, "Outside Temperature", "24 °C")
assert table_row(html, "Inside Temperature", "23.2 °C")
assert table_row(html, "Mileage", "42000 km")
assert table_row(html, "Version", "2019.40.50.7")
end
@tag :signed_in
test "renders current vehicle stats [:charging]", %{conn: conn} do
car = car_fixture(%{})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
charge_state: %{
timestamp: 0,
charger_power: 11,
charger_phases: 3,
charger_voltage: 229,
charger_actual_current: 16,
battery_range: 200,
est_battery_range: 180,
ideal_battery_range: 175,
charging_state: "Charging",
charge_energy_added: "4.32",
charge_port_latch: "Engaged",
charge_port_door_open: true,
scheduled_charging_start_time: 1_565_620_707,
charge_limit_soc: 85,
time_to_full_charge: 1.83
}
)}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "charging")
assert table_row(html, "Remaining Time", "1 h, 49 min")
assert icon(html, "Plugged In", "power-plug")
assert table_row(html, "Range (rated)", "321.87 km")
assert table_row(html, "Range (est.)", "289.68 km")
assert table_row(html, "Charged", "4.32 kWh")
assert table_row(html, "Charger Power", "11 kW")
assert table_row(
html,
"Scheduled Charging",
{"span",
[
{"data-date", "2019-08-12T14:38:27Z"},
{"id", "scheduled_start_time_#{car.id}"},
{"phx-hook", "LocalTime"}
], []}
)
assert table_row(html, "Charge Limit", "85%")
end
@tag :signed_in
test "does not render remaining seconds", %{conn: conn} do
events = [
{:ok,
online_event(
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
charge_state: %{
timestamp: 0,
charging_state: "Charging",
charge_energy_added: "4.32",
ideal_battery_range: 200,
time_to_full_charge: 0.33
}
)}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert table_row(html, "Remaining Time", "19 min")
end
@tag :signed_in
test "renders current vehicle stats [:driving]", %{conn: conn} do
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{
timestamp: 0,
latitude: 0.0,
longitude: 0.0,
shift_state: "D",
speed: 30
}
)}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "driving")
assert table_row(html, "Speed", "48 km/h")
end
@tag :signed_in
test "renders current vehicle stats [:updating]", %{conn: conn} do
alias TeslaApi.Vehicle.State.VehicleState.SoftwareUpdate
events = [
{:ok,
online_event(
display_name: "FooCar",
vehicle_state: %{
timestamp: 0,
car_version: "2019.8.4 530d1d3",
software_update: %SoftwareUpdate{expected_duration_sec: 2700, status: "installing"}
}
)}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "updating")
end
@tag :signed_in
test "renders current vehicle stats [:asleep]", %{conn: conn} do
events = [
{:ok, %TeslaApi.Vehicle{display_name: "FooCar", state: "asleep"}}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "asleep")
end
@tag :signed_in
test "renders current vehicle stats [:offline]", %{conn: conn} do
events = [
{:ok, %TeslaApi.Vehicle{display_name: "FooCar", state: "offline"}}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "offline")
end
@tag :signed_in
test "renders current vehicle stats [:falling asleep]", %{conn: conn} do
_car = car_fixture(%{suspend_min: 60, suspend_after_idle_min: 1, use_streaming_api: false})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
climate_state: %{is_preconditioning: false}
)}
]
:ok = start_vehicles(events)
Process.sleep(100)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "falling asleep")
end
@tag :capture_log
@tag :signed_in
test "renders current vehicle stats [:unavailable]", %{conn: conn} do
events = [
{:error, :unknown}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5"><\/p>/
assert table_row(html, "Status", "unavailable")
end
@tag :signed_in
test "displays the rated range if preferred", %{conn: conn} do
{:ok, _} =
Settings.get_global_settings!()
|> Settings.update_global_settings(%{preferred_range: :rated})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
charge_state: %{
ideal_battery_range: 200,
est_battery_range: 180,
battery_range: 175,
battery_level: 69
},
climate_state: %{is_preconditioning: false, outside_temp: 24, inside_temp: 23.2},
vehicle_state: %{timestamp: 0, locked: true, sentry_mode: true, car_version: ""},
vehicle_config: %{car_type: "models2", trim_badging: "p90d"}
)}
]
:ok = start_vehicles(events)
Process.sleep(250)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Range (rated)", "281.64 km")
assert table_row(html, "Range (est.)", "289.68 km")
end
@tag :signed_in
@tag :capture_log
test "displays imperial units", %{conn: conn} do
{:ok, _} =
Settings.get_global_settings!()
|> Settings.update_global_settings(%{unit_of_length: :mi, unit_of_temperature: :F})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{
timestamp: 0,
latitude: 0.0,
longitude: 0.0,
shift_state: "D",
speed: 30
},
charge_state: %{
battery_range: 200,
est_battery_range: 180,
ideal_battery_range: 175,
usable_battery_level: 67,
battery_level: 69
},
climate_state: %{
is_preconditioning: false,
outside_temp: 24,
inside_temp: 23.2
},
vehicle_state: %{
odometer: 42000
}
)}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "driving")
assert table_row(html, "Range (rated)", "200.0 mi")
assert table_row(html, "Range (est.)", "180.0 mi")
assert table_row(html, "State of Charge", "67% (69%)", tooltip: "≈ 299 mi at 100%")
assert table_row(html, "Speed", "30 mph")
assert table_row(html, "Outside Temperature", "75.2 °F")
assert table_row(html, "Inside Temperature", "73.8 °F")
assert table_row(html, "Mileage", "42000 mi")
end
end
describe "supsend" do
setup %{conn: conn} do
{:ok, conn: put_req_header(conn, "accept", "application/json")}
end
test "suspends logging", %{conn: conn} do
_car = car_fixture(%{suspend_min: 60, suspend_after_idle_min: 60, use_streaming_api: false})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
climate_state: %{is_preconditioning: false}
)}
]
:ok = start_vehicles(events)
%Car{id: id} = Log.get_car_by(vin: "xxxxx")
conn = put(conn, Routes.car_path(conn, :suspend_logging, id))
assert "" == response(conn, 204)
end
test "returns error if suspending is not possible", %{conn: conn} do
_car = car_fixture(%{suspend_min: 60, suspend_after_idle_min: 60, use_streaming_api: false})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
climate_state: %{is_preconditioning: true}
)}
]
:ok = start_vehicles(events)
%Car{id: id} = Log.get_car_by(vin: "xxxxx")
conn = put(conn, Routes.car_path(conn, :suspend_logging, id))
assert "preconditioning" == json_response(conn, 412)["error"]
end
end
describe "resume" do
test "resumes logging", %{conn: conn} do
alias TeslaMate.Vehicles.Vehicle.Summary
_car = car_fixture(%{suspend_min: 60, suspend_after_idle_min: 1, use_streaming_api: false})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
climate_state: %{is_preconditioning: false}
)}
]
:ok = start_vehicles(events)
Process.sleep(100)
%Car{id: id} = Log.get_car_by(vin: "xxxxx")
assert %Summary{state: :suspended} = TeslaMate.Vehicles.summary(id)
conn = put(conn, Routes.car_path(conn, :resume_logging, id))
assert "" == response(conn, 204)
end
end
def start_vehicles(events \\ []) do
{:ok, _pid} = start_supervised({ApiMock, name: :api_vehicle, events: events, pid: self()})
{:ok, _pid} =
start_supervised(
{TeslaMate.Vehicles,
vehicle: VehicleMock,
vehicles: [
%TeslaApi.Vehicle{
display_name: "foo",
id: 4242,
vehicle_id: 404,
vin: "xxxxx"
}
]}
)
:ok
end
end
| 30.657343 | 98 | 0.549384 |
793f28c788ba7d394175b136e8b48d82a1a5a478 | 238 | ex | Elixir | lib/langue/formatter/java_properties_xml/java_properties_xml.ex | leonardocouy/accent | 29fb324395ff998cc5cdc6947c60070ffabe647c | [
"BSD-3-Clause"
] | null | null | null | lib/langue/formatter/java_properties_xml/java_properties_xml.ex | leonardocouy/accent | 29fb324395ff998cc5cdc6947c60070ffabe647c | [
"BSD-3-Clause"
] | null | null | null | lib/langue/formatter/java_properties_xml/java_properties_xml.ex | leonardocouy/accent | 29fb324395ff998cc5cdc6947c60070ffabe647c | [
"BSD-3-Clause"
] | null | null | null | defmodule Langue.Formatter.JavaPropertiesXml do
alias Langue.Formatter.JavaPropertiesXml.{Parser, Serializer}
def name, do: "java_properties_xml"
defdelegate parse(map), to: Parser
defdelegate serialize(map), to: Serializer
end
| 26.444444 | 63 | 0.794118 |
793f2cf64fd53f6a7ba43e553a372da0595f90e6 | 139 | ex | Elixir | lib/reanix_web/controllers/page_controller.ex | RubyFireStudio/phoenix-api-scaffold | 231c11fe6008a47d51e24b8e26fb6f5dc7a24ca6 | [
"MIT"
] | 1 | 2018-05-13T19:28:48.000Z | 2018-05-13T19:28:48.000Z | lib/reanix_web/controllers/page_controller.ex | RubyFireStudio/phoenix-api-scaffold | 231c11fe6008a47d51e24b8e26fb6f5dc7a24ca6 | [
"MIT"
] | null | null | null | lib/reanix_web/controllers/page_controller.ex | RubyFireStudio/phoenix-api-scaffold | 231c11fe6008a47d51e24b8e26fb6f5dc7a24ca6 | [
"MIT"
] | null | null | null | defmodule ReanixWeb.PageController do
use ReanixWeb, :controller
def index(conn, _params) do
render(conn, "index.html")
end
end
| 17.375 | 37 | 0.733813 |
793f39b8b0124dc65d645c49797fd72d0161fc12 | 4,021 | exs | Elixir | priv/repo/seeds.exs | gautambaghel/stormchat | 1882467113158e7524d02d273e1f88439cc1f152 | [
"MIT"
] | null | null | null | priv/repo/seeds.exs | gautambaghel/stormchat | 1882467113158e7524d02d273e1f88439cc1f152 | [
"MIT"
] | 7 | 2019-06-25T17:21:41.000Z | 2022-02-10T12:09:08.000Z | priv/repo/seeds.exs | gautambaghel/stormchat | 1882467113158e7524d02d273e1f88439cc1f152 | [
"MIT"
] | null | null | null | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Stormchat.Repo.insert!(%Stormchat.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
defmodule Seeds do
alias Stormchat.Repo
alias Stormchat.Locations.Location
alias Stormchat.Accounts.User
alias Stormchat.Social.Post
def run do
p = Comeonin.Argon2.hashpwsalt("password1")
Repo.delete_all(Location)
Repo.insert!(%Location{ name: "Alabama", abb: "AL"})
Repo.insert!(%Location{ name: "Alaska", abb: "AK"})
Repo.insert!(%Location{ name: "Arizona", abb: "AZ"})
Repo.insert!(%Location{ name: "Arkansas", abb: "AR"})
Repo.insert!(%Location{ name: "California", abb: "CA"})
Repo.insert!(%Location{ name: "Colorado", abb: "CO"})
Repo.insert!(%Location{ name: "Connecticut", abb: "CT"})
Repo.insert!(%Location{ name: "Delaware", abb: "DE"})
Repo.insert!(%Location{ name: "Florida", abb: "FL"})
Repo.insert!(%Location{ name: "Georgia", abb: "GA"})
Repo.insert!(%Location{ name: "Hawaii", abb: "HI"})
Repo.insert!(%Location{ name: "Idaho", abb: "ID"})
Repo.insert!(%Location{ name: "Illinois", abb: "IL"})
Repo.insert!(%Location{ name: "Indiana", abb: "IN"})
Repo.insert!(%Location{ name: "Iowa", abb: "IA"})
Repo.insert!(%Location{ name: "Kansas", abb: "KS"})
Repo.insert!(%Location{ name: "Kentucky", abb: "KY"})
Repo.insert!(%Location{ name: "Louisiana", abb: "LA"})
Repo.insert!(%Location{ name: "Maine", abb: "ME"})
Repo.insert!(%Location{ name: "Maryland", abb: "MD"})
Repo.insert!(%Location{ name: "Massachusetts", abb: "MA"})
Repo.insert!(%Location{ name: "Michigan", abb: "MI"})
Repo.insert!(%Location{ name: "Minnesota", abb: "MN"})
Repo.insert!(%Location{ name: "Mississippi", abb: "MS"})
Repo.insert!(%Location{ name: "Missouri", abb: "MO"})
Repo.insert!(%Location{ name: "Montana", abb: "MT"})
Repo.insert!(%Location{ name: "Nebraska", abb: "NE"})
Repo.insert!(%Location{ name: "Nevada", abb: "NV"})
Repo.insert!(%Location{ name: "New Hampshire", abb: "NH"})
Repo.insert!(%Location{ name: "New Jersey", abb: "NJ"})
Repo.insert!(%Location{ name: "New Mexico", abb: "NM"})
Repo.insert!(%Location{ name: "New York", abb: "NY"})
Repo.insert!(%Location{ name: "North Carolina", abb: "NC"})
Repo.insert!(%Location{ name: "North Dakota", abb: "ND"})
Repo.insert!(%Location{ name: "Ohio", abb: "OH"})
Repo.insert!(%Location{ name: "Oklahoma", abb: "OK"})
Repo.insert!(%Location{ name: "Oregon", abb: "OR"})
Repo.insert!(%Location{ name: "Pennsylvania", abb: "PA"})
Repo.insert!(%Location{ name: "Rhode Island", abb: "RI"})
Repo.insert!(%Location{ name: "South Carolina", abb: "SC"})
Repo.insert!(%Location{ name: "South Dakota", abb: "SD"})
Repo.insert!(%Location{ name: "Tennessee", abb: "TN"})
Repo.insert!(%Location{ name: "Texas", abb: "TX"})
Repo.insert!(%Location{ name: "Utah", abb: "UT"})
Repo.insert!(%Location{ name: "Vermont", abb: "VT"})
Repo.insert!(%Location{ name: "Virginia", abb: "VA"})
Repo.insert!(%Location{ name: "Washington", abb: "WA"})
Repo.insert!(%Location{ name: "West Virginia", abb: "WV"})
Repo.insert!(%Location{ name: "Wisconsin", abb: "WI"})
Repo.insert!(%Location{ name: "Wyoming", abb: "WY"})
Repo.delete_all(User)
a = Repo.insert!(%User{ email: "[email protected]", name: "dave", crypted_password: p, location: "MA", subscribed: true})
b = Repo.insert!(%User{ email: "[email protected]", name: "bob", crypted_password: p, location: "MA" })
Repo.delete_all(Post)
Repo.insert!(%Post{ alert: "NWS-IDP-PROD-2768387-2582650", body: "Any one need help?", user: a })
Repo.insert!(%Post{ alert: "NWS-IDP-PROD-2768387-2582650", body: "Yeah, stuck here!", user: b })
end
end
Seeds.run
| 45.179775 | 122 | 0.62671 |
793f65e7e931568787d4dd8332ca6e0d86863a61 | 1,915 | ex | Elixir | clients/jobs/lib/google_api/jobs/v2/model/commute_info.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/jobs/lib/google_api/jobs/v2/model/commute_info.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/jobs/lib/google_api/jobs/v2/model/commute_info.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 "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 elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Jobs.V2.Model.CommuteInfo do
@moduledoc """
Output only.
Commute details related to this job.
## Attributes
* `jobLocation` (*type:* `GoogleApi.Jobs.V2.Model.JobLocation.t`, *default:* `nil`) - Location used as the destination in the commute calculation.
* `travelDuration` (*type:* `String.t`, *default:* `nil`) - The number of seconds required to travel to the job location from the query
location. A duration of 0 seconds indicates that the job is not
reachable within the requested duration, but was returned as part of an
expanded query.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:jobLocation => GoogleApi.Jobs.V2.Model.JobLocation.t(),
:travelDuration => String.t()
}
field(:jobLocation, as: GoogleApi.Jobs.V2.Model.JobLocation)
field(:travelDuration)
end
defimpl Poison.Decoder, for: GoogleApi.Jobs.V2.Model.CommuteInfo do
def decode(value, options) do
GoogleApi.Jobs.V2.Model.CommuteInfo.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Jobs.V2.Model.CommuteInfo do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.818182 | 150 | 0.730548 |
793f6d6fcc5e4715428614e85e0d312167c23908 | 3,884 | exs | Elixir | apps/podder/test/podder/podder/podder_test.exs | chattes/podder_umbrella | a2662a21a067fd3f0cd02b98cb63afd958c895db | [
"MIT"
] | null | null | null | apps/podder/test/podder/podder/podder_test.exs | chattes/podder_umbrella | a2662a21a067fd3f0cd02b98cb63afd958c895db | [
"MIT"
] | null | null | null | apps/podder/test/podder/podder/podder_test.exs | chattes/podder_umbrella | a2662a21a067fd3f0cd02b98cb63afd958c895db | [
"MIT"
] | null | null | null | defmodule Podder.PodderTest do
use Podder.DataCase
alias Podder.Podder
describe "users" do
alias Podder.Podder.User
@valid_attrs %{user_name: "some user_name"}
@update_attrs %{user_name: "some updated user_name"}
@invalid_attrs %{user_name: nil}
def user_fixture(attrs \\ %{}) do
{:ok, user} =
attrs
|> Enum.into(@valid_attrs)
|> Podder.create_user()
user
end
test "list_users/0 returns all users" do
user = user_fixture()
assert Podder.list_users() == [user]
end
test "get_user!/1 returns the user with given id" do
user = user_fixture()
assert Podder.get_user!(user.id) == user
end
test "create_user/1 with valid data creates a user" do
assert {:ok, %User{} = user} = Podder.create_user(@valid_attrs)
assert user.user_name == "some user_name"
end
test "create_user/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Podder.create_user(@invalid_attrs)
end
test "update_user/2 with valid data updates the user" do
user = user_fixture()
assert {:ok, %User{} = user} = Podder.update_user(user, @update_attrs)
assert user.user_name == "some updated user_name"
end
test "update_user/2 with invalid data returns error changeset" do
user = user_fixture()
assert {:error, %Ecto.Changeset{}} = Podder.update_user(user, @invalid_attrs)
assert user == Podder.get_user!(user.id)
end
test "delete_user/1 deletes the user" do
user = user_fixture()
assert {:ok, %User{}} = Podder.delete_user(user)
assert_raise Ecto.NoResultsError, fn -> Podder.get_user!(user.id) end
end
test "change_user/1 returns a user changeset" do
user = user_fixture()
assert %Ecto.Changeset{} = Podder.change_user(user)
end
end
describe "podcasts" do
alias Podder.Podder.Podcast
@valid_attrs %{podcast_name: "some podcast_name"}
@update_attrs %{podcast_name: "some updated podcast_name"}
@invalid_attrs %{podcast_name: nil}
def podcast_fixture(attrs \\ %{}) do
{:ok, podcast} =
attrs
|> Enum.into(@valid_attrs)
|> Podder.create_podcast()
podcast
end
test "list_podcasts/0 returns all podcasts" do
podcast = podcast_fixture()
assert Podder.list_podcasts() == [podcast]
end
test "get_podcast!/1 returns the podcast with given id" do
podcast = podcast_fixture()
assert Podder.get_podcast!(podcast.id) == podcast
end
test "create_podcast/1 with valid data creates a podcast" do
assert {:ok, %Podcast{} = podcast} = Podder.create_podcast(@valid_attrs)
assert podcast.podcast_name == "some podcast_name"
end
test "create_podcast/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Podder.create_podcast(@invalid_attrs)
end
test "update_podcast/2 with valid data updates the podcast" do
podcast = podcast_fixture()
assert {:ok, %Podcast{} = podcast} = Podder.update_podcast(podcast, @update_attrs)
assert podcast.podcast_name == "some updated podcast_name"
end
test "update_podcast/2 with invalid data returns error changeset" do
podcast = podcast_fixture()
assert {:error, %Ecto.Changeset{}} = Podder.update_podcast(podcast, @invalid_attrs)
assert podcast == Podder.get_podcast!(podcast.id)
end
test "delete_podcast/1 deletes the podcast" do
podcast = podcast_fixture()
assert {:ok, %Podcast{}} = Podder.delete_podcast(podcast)
assert_raise Ecto.NoResultsError, fn -> Podder.get_podcast!(podcast.id) end
end
test "change_podcast/1 returns a podcast changeset" do
podcast = podcast_fixture()
assert %Ecto.Changeset{} = Podder.change_podcast(podcast)
end
end
end
| 31.322581 | 89 | 0.667868 |
793f6e89815d8197a941dc98d9d279c7b95afd45 | 148 | exs | Elixir | apps/snitch_core/config/releases.exs | VeryBigThings/avia | 7ce5d5b244ae0dfddc30c09c17efe27f1718a4c9 | [
"MIT"
] | 1 | 2021-04-08T22:29:19.000Z | 2021-04-08T22:29:19.000Z | apps/snitch_core/config/releases.exs | VeryBigThings/avia | 7ce5d5b244ae0dfddc30c09c17efe27f1718a4c9 | [
"MIT"
] | null | null | null | apps/snitch_core/config/releases.exs | VeryBigThings/avia | 7ce5d5b244ae0dfddc30c09c17efe27f1718a4c9 | [
"MIT"
] | null | null | null | import Config
config :snitch_core, Snitch.Repo,
url: System.fetch_env!("DB_URL"),
pool_size: String.to_integer(System.fetch_env!("POOL_SIZE"))
| 24.666667 | 62 | 0.756757 |
793f74441c7e5d6a76b09bdd3adce31d32d38259 | 3,384 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v35/model/file.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v35/model/file.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v35/model/file.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V35.Model.File do
@moduledoc """
Represents a File resource. A file contains the metadata for a report run. It shows the status of the run and holds the URLs to the generated report data if the run is finished and the status is "REPORT_AVAILABLE".
## Attributes
* `dateRange` (*type:* `GoogleApi.DFAReporting.V35.Model.DateRange.t`, *default:* `nil`) - The date range for which the file has report data. The date range will always be the absolute date range for which the report is run.
* `etag` (*type:* `String.t`, *default:* `nil`) - Etag of this resource.
* `fileName` (*type:* `String.t`, *default:* `nil`) - The filename of the file.
* `format` (*type:* `String.t`, *default:* `nil`) - The output format of the report. Only available once the file is available.
* `id` (*type:* `String.t`, *default:* `nil`) - The unique ID of this report file.
* `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#file".
* `lastModifiedTime` (*type:* `String.t`, *default:* `nil`) - The timestamp in milliseconds since epoch when this file was last modified.
* `reportId` (*type:* `String.t`, *default:* `nil`) - The ID of the report this file was generated from.
* `status` (*type:* `String.t`, *default:* `nil`) - The status of the report file.
* `urls` (*type:* `GoogleApi.DFAReporting.V35.Model.FileUrls.t`, *default:* `nil`) - The URLs where the completed report file can be downloaded.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:dateRange => GoogleApi.DFAReporting.V35.Model.DateRange.t() | nil,
:etag => String.t() | nil,
:fileName => String.t() | nil,
:format => String.t() | nil,
:id => String.t() | nil,
:kind => String.t() | nil,
:lastModifiedTime => String.t() | nil,
:reportId => String.t() | nil,
:status => String.t() | nil,
:urls => GoogleApi.DFAReporting.V35.Model.FileUrls.t() | nil
}
field(:dateRange, as: GoogleApi.DFAReporting.V35.Model.DateRange)
field(:etag)
field(:fileName)
field(:format)
field(:id)
field(:kind)
field(:lastModifiedTime)
field(:reportId)
field(:status)
field(:urls, as: GoogleApi.DFAReporting.V35.Model.FileUrls)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V35.Model.File do
def decode(value, options) do
GoogleApi.DFAReporting.V35.Model.File.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V35.Model.File do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 45.72973 | 228 | 0.680851 |
793fb4dc3d626927aef020d36e606768d6886b8a | 3,327 | ex | Elixir | clients/ad_sense/lib/google_api/ad_sense/v14/api/urlchannels.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/ad_sense/lib/google_api/ad_sense/v14/api/urlchannels.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/ad_sense/lib/google_api/ad_sense/v14/api/urlchannels.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.AdSense.V14.Api.Urlchannels do
@moduledoc """
API calls for all endpoints tagged `Urlchannels`.
"""
alias GoogleApi.AdSense.V14.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
List all URL channels in the specified ad client for this AdSense account.
## Parameters
- connection (GoogleApi.AdSense.V14.Connection): Connection to server
- ad_client_id (String.t): Ad client for which to list URL channels.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :maxResults (integer()): The maximum number of URL channels to include in the response, used for paging.
- :pageToken (String.t): A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.
## Returns
{:ok, %GoogleApi.AdSense.V14.Model.UrlChannels{}} on success
{:error, info} on failure
"""
@spec adsense_urlchannels_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.AdSense.V14.Model.UrlChannels.t()} | {:error, Tesla.Env.t()}
def adsense_urlchannels_list(connection, ad_client_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:maxResults => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/adclients/{adClientId}/urlchannels", %{
"adClientId" => URI.encode_www_form(ad_client_id)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AdSense.V14.Model.UrlChannels{}])
end
end
| 42.653846 | 203 | 0.70514 |
7940086095d4a4e34ae74e5376473a36f92612fa | 251 | exs | Elixir | .formatter.exs | pepsico-ecommerce/chore_runner | c84863b7ea5feac20ab4320a5c04ffa534040c3c | [
"Apache-2.0"
] | 16 | 2021-10-31T22:14:29.000Z | 2022-03-31T14:52:36.000Z | .formatter.exs | pepsico-ecommerce/chore_runner | c84863b7ea5feac20ab4320a5c04ffa534040c3c | [
"Apache-2.0"
] | 1 | 2022-01-13T04:53:22.000Z | 2022-02-08T04:28:19.000Z | .formatter.exs | pepsico-ecommerce/chore_runner | c84863b7ea5feac20ab4320a5c04ffa534040c3c | [
"Apache-2.0"
] | 2 | 2021-12-25T18:01:36.000Z | 2022-03-12T20:55:06.000Z | # Used by "mix format"
locals_without_parens = [
input: 2
]
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"],
locals_without_parens: locals_without_parens,
export: [
locals_without_parens: locals_without_parens
]
]
| 19.307692 | 70 | 0.681275 |
79402622fe5b323b76e0616455454b66239edcf8 | 4,345 | ex | Elixir | clients/api_gateway/lib/google_api/api_gateway/v1beta/model/apigateway_binding.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/api_gateway/lib/google_api/api_gateway/v1beta/model/apigateway_binding.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/api_gateway/lib/google_api/api_gateway/v1beta/model/apigateway_binding.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"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.APIGateway.V1beta.Model.ApigatewayBinding do
@moduledoc """
Associates `members`, or principals, with a `role`.
## Attributes
* `condition` (*type:* `GoogleApi.APIGateway.V1beta.Model.ApigatewayExpr.t`, *default:* `nil`) - The condition that is associated with this binding. If the condition evaluates to `true`, then this binding applies to the current request. If the condition evaluates to `false`, then this binding does not apply to the current request. However, a different role binding might grant the same role to one or more of the principals in this binding. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* `members` (*type:* `list(String.t)`, *default:* `nil`) - Specifies the principals requesting access for a Google Cloud resource. `members` can have the following values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific Google account. For example, `[email protected]` . * `serviceAccount:{emailid}`: An email address that represents a service account. For example, `[email protected]`. * `group:{emailid}`: An email address that represents a Google group. For example, `[email protected]`. * `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that has been recently deleted. For example, `[email protected]?uid=123456789012345678901`. If the user is recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. * `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a service account that has been recently deleted. For example, `[email protected]?uid=123456789012345678901`. If the service account is undeleted, this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a Google group that has been recently deleted. For example, `[email protected]?uid=123456789012345678901`. If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that domain. For example, `google.com` or `example.com`.
* `role` (*type:* `String.t`, *default:* `nil`) - Role that is assigned to the list of `members`, or principals. For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:condition => GoogleApi.APIGateway.V1beta.Model.ApigatewayExpr.t() | nil,
:members => list(String.t()) | nil,
:role => String.t() | nil
}
field(:condition, as: GoogleApi.APIGateway.V1beta.Model.ApigatewayExpr)
field(:members, type: :list)
field(:role)
end
defimpl Poison.Decoder, for: GoogleApi.APIGateway.V1beta.Model.ApigatewayBinding do
def decode(value, options) do
GoogleApi.APIGateway.V1beta.Model.ApigatewayBinding.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.APIGateway.V1beta.Model.ApigatewayBinding do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 81.981132 | 1,970 | 0.756962 |
79402e4f3beacabc69fe74a9152542d670940663 | 2,552 | ex | Elixir | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p4beta1_localized_object_annotation.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p4beta1_localized_object_annotation.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p4beta1_localized_object_annotation.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation do
@moduledoc """
Set of detected objects with bounding boxes.
## Attributes
* `boundingPoly` (*type:* `GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1BoundingPoly.t`, *default:* `nil`) - Image region to which this object belongs. This must be populated.
* `languageCode` (*type:* `String.t`, *default:* `nil`) - The BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
* `mid` (*type:* `String.t`, *default:* `nil`) - Object ID that should align with EntityAnnotation mid.
* `name` (*type:* `String.t`, *default:* `nil`) - Object name, expressed in its `language_code` language.
* `score` (*type:* `number()`, *default:* `nil`) - Score of the result. Range [0, 1].
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:boundingPoly =>
GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1BoundingPoly.t() | nil,
:languageCode => String.t() | nil,
:mid => String.t() | nil,
:name => String.t() | nil,
:score => number() | nil
}
field(:boundingPoly, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1BoundingPoly)
field(:languageCode)
field(:mid)
field(:name)
field(:score)
end
defimpl Poison.Decoder,
for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation do
def decode(value, options) do
GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.261538 | 207 | 0.714342 |
79403dd3abde6bb069914898290b861d34665b6d | 1,843 | ex | Elixir | lib/ibmcloud/iam/oauth2.ex | Bhaskers-Blu-Org1/elixir-ibmcloud | 28639020a3e5c222356329917b3fb37c5da3eb42 | [
"Apache-2.0"
] | 1 | 2020-01-13T19:30:37.000Z | 2020-01-13T19:30:37.000Z | lib/ibmcloud/iam/oauth2.ex | Bhaskers-Blu-Org1/elixir-ibmcloud | 28639020a3e5c222356329917b3fb37c5da3eb42 | [
"Apache-2.0"
] | null | null | null | lib/ibmcloud/iam/oauth2.ex | Bhaskers-Blu-Org1/elixir-ibmcloud | 28639020a3e5c222356329917b3fb37c5da3eb42 | [
"Apache-2.0"
] | 1 | 2020-07-30T10:19:52.000Z | 2020-07-30T10:19:52.000Z | defmodule IBMCloud.IAM.OAuth2 do
@moduledoc """
OAuth2 interfaces to IAM.
"""
@default_endpoint "https://iam.cloud.ibm.com"
def build_client(auth \\ [], endpoint \\ @default_endpoint, adapter \\ nil) do
middlewares =
[
{Tesla.Middleware.BaseUrl, endpoint},
Tesla.Middleware.FormUrlencoded,
Tesla.Middleware.DecodeJson
]
|> add_auth_middleware(auth)
Tesla.client(middlewares, adapter)
end
defp add_auth_middleware(middlewares, auth) do
with {:ok, client_id} <- Keyword.fetch(auth, :client_id),
{:ok, client_secret} <- Keyword.fetch(auth, :client_secret) do
[
{Tesla.Middleware.BasicAuth, username: client_id, password: client_secret}
| middlewares
]
else
_ -> middlewares
end
end
@doc """
Creates a token.
## API Key
- `:apikey`
```elixir
{:ok, %{status: 200, body: %{"access_token" => bearer_token}}} =
IBMCloud.IAM.OAuth2.build_client()
|> IBMCloud.IAM.OAuth2.create_token(apikey: apikey)
```
[Create an IAM access token for a user or service ID](https://cloud.ibm.com/apidocs/iam-identity-token-api#create-an-iam-access-token-for-a-user-or-service-i)
## Authorization Code
- `:code`
[Step 4. Developing an authentication flow](https://cloud.ibm.com/docs/third-party?topic=third-party-step4-iam#token-post)
"""
def create_token(client, body \\ [], opts \\ []) do
grant_type =
cond do
Keyword.has_key?(body, :apikey) -> "urn:ibm:params:oauth:grant-type:apikey"
Keyword.has_key?(body, :code) -> "authorization_code"
end
body = Keyword.put_new(body, :grant_type, grant_type)
case Tesla.post(client, "identity/token", body, opts) do
{:ok, %{status: 200} = resp} -> {:ok, resp}
{_, other} -> {:error, other}
end
end
end
| 27.102941 | 160 | 0.639718 |
79405fb704a85605a7243d61a8ffbed0a4ceba07 | 1,575 | ex | Elixir | clients/sas_portal/lib/google_api/sas_portal/v1alpha1/model/sas_portal_empty.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/sas_portal/lib/google_api/sas_portal/v1alpha1/model/sas_portal_empty.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/sas_portal/lib/google_api/sas_portal/v1alpha1/model/sas_portal_empty.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.SASPortal.V1alpha1.Model.SasPortalEmpty do
@moduledoc """
A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`.
## Attributes
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{}
end
defimpl Poison.Decoder, for: GoogleApi.SASPortal.V1alpha1.Model.SasPortalEmpty do
def decode(value, options) do
GoogleApi.SASPortal.V1alpha1.Model.SasPortalEmpty.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.SASPortal.V1alpha1.Model.SasPortalEmpty do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.5 | 345 | 0.765079 |
7940671cf319b81de1654629a977fbbd29a2bfbf | 1,684 | exs | Elixir | farmbot_ext/mix.exs | va2ron1/farmbot_os | c80a38058713adc2ad91a4802664bcfe8da9d96c | [
"MIT"
] | null | null | null | farmbot_ext/mix.exs | va2ron1/farmbot_os | c80a38058713adc2ad91a4802664bcfe8da9d96c | [
"MIT"
] | null | null | null | farmbot_ext/mix.exs | va2ron1/farmbot_os | c80a38058713adc2ad91a4802664bcfe8da9d96c | [
"MIT"
] | null | null | null | defmodule FarmbotExt.MixProject do
use Mix.Project
@version Path.join([__DIR__, "..", "VERSION"]) |> File.read!() |> String.trim()
@elixir_version Path.join([__DIR__, "..", "ELIXIR_VERSION"]) |> File.read!() |> String.trim()
def project do
[
app: :farmbot_ext,
version: @version,
elixir: @elixir_version,
elixirc_options: [warnings_as_errors: true, ignore_module_conflict: true],
start_permanent: Mix.env() == :prod,
elixirc_paths: ["lib", "vendor"],
deps: deps(),
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
source_url: "https://github.com/Farmbot/farmbot_os",
homepage_url: "http://farmbot.io",
docs: [
logo: "../farmbot_os/priv/static/farmbot_logo.png",
extras: Path.wildcard("../docs/**/*.md")
]
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {FarmbotExt, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:amqp, "~> 1.6.0"},
{:ex_doc, "~> 0.23.0", only: [:dev], targets: [:host], runtime: false},
{:excoveralls, "~> 0.13.3", only: [:test], targets: [:host]},
{:extty, "~> 0.1"},
{:farmbot_core, path: "../farmbot_core", env: Mix.env()},
{:farmbot_telemetry, path: "../farmbot_telemetry", env: Mix.env()},
{:hackney, "~> 1.16"},
{:mimic, "~> 1.3.1", only: :test},
{:tesla, "~> 1.3.3"},
{:uuid, "~> 1.1.8"}
]
end
end
| 30.618182 | 95 | 0.56057 |
7940690566efc7b06963cc12b7b0cb4e192cbc06 | 77 | ex | Elixir | testData/org/elixir_lang/parser_definition/heredoc_dot_operation_parsing_test_case/MatchedCallOperation.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 1,668 | 2015-01-03T05:54:27.000Z | 2022-03-25T08:01:20.000Z | testData/org/elixir_lang/parser_definition/heredoc_dot_operation_parsing_test_case/MatchedCallOperation.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 2,018 | 2015-01-01T22:43:39.000Z | 2022-03-31T20:13:08.000Z | testData/org/elixir_lang/parser_definition/heredoc_dot_operation_parsing_test_case/MatchedCallOperation.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | '''
One
'''.two positional, key: value
"""
One
""".two positional, key: value | 12.833333 | 30 | 0.623377 |
7940725973f4f23ed1927c82c610ff3315de5933 | 2,027 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/interconnect_location_list_warning_data.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/interconnect_location_list_warning_data.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/compute/lib/google_api/compute/v1/model/interconnect_location_list_warning_data.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.Compute.V1.Model.InterconnectLocationListWarningData do
@moduledoc """
## Attributes
* `key` (*type:* `String.t`, *default:* `nil`) - [Output Only] A key that provides more detail on the warning being returned. For example, for warnings where there are no results in a list request for a particular zone, this key might be scope and the key value might be the zone name. Other examples might be a key indicating a deprecated resource and a suggested replacement, or a warning about invalid network settings (for example, if an instance attempts to perform IP forwarding but is not enabled for IP forwarding).
* `value` (*type:* `String.t`, *default:* `nil`) - [Output Only] A warning data value corresponding to the key.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:key => String.t(),
:value => String.t()
}
field(:key)
field(:value)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.InterconnectLocationListWarningData do
def decode(value, options) do
GoogleApi.Compute.V1.Model.InterconnectLocationListWarningData.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.InterconnectLocationListWarningData do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.54 | 527 | 0.744943 |
79407dc65c9b7556f9e97f5c2b476b41eac6a874 | 4,372 | ex | Elixir | lib/elixir/lib/kernel/lexical_tracker.ex | sunaku/elixir | 8aa43eaedd76be8ac0d495049eb9ecd56971f4fe | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel/lexical_tracker.ex | sunaku/elixir | 8aa43eaedd76be8ac0d495049eb9ecd56971f4fe | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel/lexical_tracker.ex | sunaku/elixir | 8aa43eaedd76be8ac0d495049eb9ecd56971f4fe | [
"Apache-2.0"
] | null | null | null | # This is a module Elixir responsible for tracking
# the usage of aliases, imports and requires in the Elixir scope.
#
# The implementation simply stores dispatch information in an
# ETS table and then consults this table once compilation is done.
#
# Note that since this is required for bootstrap, we can't use
# any of the `GenServer.Behaviour` conveniences.
defmodule Kernel.LexicalTracker do
@moduledoc false
@timeout 30_000
@behaviour :gen_server
@import 2
@alias 3
@doc """
Returns all remotes linked to in this lexical scope.
"""
def remotes(arg) do
ets = :gen_server.call(to_pid(arg), :ets, @timeout)
:ets.match(ets, {:"$1", :_, :_}) |> List.flatten
end
@doc """
Gets the destination the lexical scope is meant to
compile to.
"""
def dest(arg) do
:gen_server.call(to_pid(arg), :dest, @timeout)
end
defp to_pid(pid) when is_pid(pid), do: pid
defp to_pid(mod) when is_atom(mod) do
table = :elixir_module.data_table(mod)
[{_, val}] = :ets.lookup(table, :__lexical_tracker)
val
end
# Internal API
# Starts the tracker and returns its pid.
@doc false
def start_link(dest) do
:gen_server.start_link(__MODULE__, dest, [])
end
@doc false
def stop(pid) do
:gen_server.cast(pid, :stop)
end
@doc false
def add_import(pid, module, line, warn) do
:gen_server.cast(pid, {:add_import, module, line, warn})
end
@doc false
def add_alias(pid, module, line, warn) do
:gen_server.cast(pid, {:add_alias, module, line, warn})
end
@doc false
def remote_dispatch(pid, module) do
:gen_server.cast(pid, {:remote_dispatch, module})
end
@doc false
def import_dispatch(pid, module) do
:gen_server.cast(pid, {:import_dispatch, module})
end
@doc false
def alias_dispatch(pid, module) do
:gen_server.cast(pid, {:alias_dispatch, module})
end
@doc false
def collect_unused_imports(pid) do
unused(pid, @import)
end
@doc false
def collect_unused_aliases(pid) do
unused(pid, @alias)
end
defp unused(pid, pos) do
ets = :gen_server.call(pid, :ets, @timeout)
:ets.foldl(fn
{module, _, _} = tuple, acc when is_integer(:erlang.element(pos, tuple)) ->
[{module, :erlang.element(pos, tuple)}|acc]
_, acc ->
acc
end, [], ets) |> Enum.sort
end
# Callbacks
def init(dest) do
{:ok, {:ets.new(:lexical, [:protected]), dest}}
end
@doc false
def handle_call(:ets, _from, {d, dest}) do
{:reply, d, {d, dest}}
end
def handle_call(:dest, _from, {d, dest}) do
{:reply, dest, {d, dest}}
end
def handle_call(request, _from, {d, dest}) do
{:stop, {:bad_call, request}, {d, dest}}
end
def handle_cast({:remote_dispatch, module}, {d, dest}) do
add_module(d, module)
{:noreply, {d, dest}}
end
def handle_cast({:import_dispatch, module}, {d, dest}) do
add_dispatch(d, module, @import)
{:noreply, {d, dest}}
end
def handle_cast({:alias_dispatch, module}, {d, dest}) do
add_dispatch(d, module, @alias)
{:noreply, {d, dest}}
end
def handle_cast({:add_import, module, line, warn}, {d, dest}) do
add_directive(d, module, line, warn, @import)
{:noreply, {d, dest}}
end
def handle_cast({:add_alias, module, line, warn}, {d, dest}) do
add_directive(d, module, line, warn, @alias)
{:noreply, {d, dest}}
end
def handle_cast(:stop, {d, dest}) do
{:stop, :normal, {d, dest}}
end
def handle_cast(msg, {d, dest}) do
{:stop, {:bad_cast, msg}, {d, dest}}
end
@doc false
def handle_info(_msg, {d, dest}) do
{:noreply, {d, dest}}
end
@doc false
def terminate(_reason, _state) do
:ok
end
@doc false
def code_change(_old, state, _extra) do
{:ok, state}
end
# Callbacks helpers
# In the table we keep imports and aliases.
# If the value is false, it was not imported/aliased
# If the value is true, it was imported/aliased
# If the value is a line, it was imported/aliased and has a pending warning
defp add_module(d, module) do
:ets.insert_new(d, {module, false, false})
end
defp add_dispatch(d, module, pos) do
:ets.update_element(d, module, {pos, true})
end
defp add_directive(d, module, line, warn, pos) do
add_module(d, module)
marker = if warn, do: line, else: true
:ets.update_element(d, module, {pos, marker})
end
end
| 23.632432 | 81 | 0.648673 |
79408e2198381585fa28209f795576e8c75deda7 | 94 | ex | Elixir | test/support/test_repo.ex | bgentry/ecto_as_state_machine | 068ad13ec60147564f02ab4d0493763dcd758bbd | [
"MIT"
] | null | null | null | test/support/test_repo.ex | bgentry/ecto_as_state_machine | 068ad13ec60147564f02ab4d0493763dcd758bbd | [
"MIT"
] | null | null | null | test/support/test_repo.ex | bgentry/ecto_as_state_machine | 068ad13ec60147564f02ab4d0493763dcd758bbd | [
"MIT"
] | null | null | null | defmodule EctoAsStateMachine.TestRepo do
use Ecto.Repo, otp_app: :ecto_as_state_machine
end
| 23.5 | 48 | 0.840426 |
7940bb738a95a89a5129ff81878b1e44f1a83ccd | 9,772 | ex | Elixir | lib/entice/logic/vitals.ex | entice/logic | e66b753d67f9ffcedf48a3097f2428f60de38d06 | [
"WTFPL"
] | 12 | 2015-02-11T21:50:03.000Z | 2020-12-24T23:05:07.000Z | lib/entice/logic/vitals.ex | entice/logic | e66b753d67f9ffcedf48a3097f2428f60de38d06 | [
"WTFPL"
] | 12 | 2015-09-21T11:19:27.000Z | 2016-09-11T08:13:58.000Z | lib/entice/logic/vitals.ex | entice/logic | e66b753d67f9ffcedf48a3097f2428f60de38d06 | [
"WTFPL"
] | 7 | 2015-09-20T14:37:31.000Z | 2021-07-19T18:10:51.000Z | defmodule Entice.Logic.Vitals do
@moduledoc """
Responsible for the entities vital stats like (health, mana, regen, degen).
If the entity has no explicit level, it is implicitly assumed to be 20.
If and entity dies, a local broadcast will be send that looks like this:
{:entity_dead, %{entity_id: entity_id, attributes: attribs}}
If the entity then gets resurrected, a similar message will be broadcasted:
{:entity_resurrected, %{entity_id: entity_id, attributes: attribs}}
The regeneration of health and energy works in a value-per-second fashion.
Usually, for health we have max/minimum of +-20 HP/s and for energy we have a
max/minimum of +-3 mana/s (both are equal to +-10 pips on the health / energy bars)
Note that the client assumes a standard mana regen of 0.71 mana/s (2 pips),
which is 0.355 * 2, so we think 0.355 is the standard 1 pip regen.
"""
alias Entice.Entity
alias Entice.Entity.Coordination
alias Entice.Logic.Vitals
defmodule Health, do: defstruct(health: 500, max_health: 620, regeneration: 0.0)
defmodule Energy, do: defstruct(mana: 50, max_mana: 70, regeneration: 0.666) # hell yeah
defmodule Morale, do: defstruct(morale: 0)
def register(entity_id),
do: Entity.put_behaviour(entity_id, Vitals.AliveBehaviour, [])
def unregister(entity_id) do
Entity.remove_behaviour(entity_id, Vitals.AliveBehaviour)
Entity.remove_behaviour(entity_id, Vitals.DeadBehaviour)
end
@doc "Damage is dealt till death of the entity. (It then needs to be resurrected)"
def damage(entity, amount),
do: Coordination.notify(entity, {:vitals_entity_damage, amount})
@doc "Heals the entity until `max_health` is reached"
def heal(entity, amount),
do: Coordination.notify(entity, {:vitals_entity_heal, amount})
@doc "Kills an entity, reduces the lifepoints to 0."
def kill(entity),
do: Coordination.notify(entity, :vitals_entity_kill)
@doc "Resurrect with percentage of health and energy. (Entity needs to be dead :P)"
def resurrect(entity, percent_health, percent_energy),
do: Coordination.notify(entity, {:vitals_entity_resurrect, percent_health, percent_energy})
def health_regeneration(entity, value),
do: Coordination.notify(entity, {:vitals_health_regeneration, value})
def energy_regeneration(entity, value),
do: Coordination.notify(entity, {:vitals_energy_regeneration, value})
defmodule AliveBehaviour do
use Entice.Entity.Behaviour
alias Entice.Logic.Vitals.Health
alias Entice.Logic.Vitals.Energy
alias Entice.Logic.Vitals.Morale
alias Entice.Logic.Vitals.DeadBehaviour
alias Entice.Logic.Player.Level
@regeneration_interval 500
@min_accumulated_health 5 # these values need to accumulate over time before
@min_accumulated_energy 1 # the attribute is updated
def init(entity, {:entity_resurrected, percent_health, percent_energy}) do
entity.id |> Coordination.notify_locally({
:entity_resurrected,
%{entity_id: entity.id, attributes: entity.attributes}})
%Health{max_health: max_health} = get_max_health(entity.attributes)
resurrected_health = round(max_health / 100 * percent_health)
%Energy{max_mana: max_mana} = get_max_energy(entity.attributes)
resurrected_mana = round(max_mana / 100 * percent_energy)
self |> Process.send_after({:vitals_regeneration_update, %{
interval: @regeneration_interval,
health_accumulator: 0,
energy_accumulator: 0}}, @regeneration_interval)
{:ok,
entity
|> put_attribute(%Health{health: resurrected_health, max_health: max_health})
|> put_attribute(%Energy{mana: resurrected_mana, max_mana: max_mana})}
end
def init(entity, _args) do
self |> Process.send_after({:vitals_regeneration_update, %{
interval: @regeneration_interval,
health_accumulator: 0,
energy_accumulator: 0}}, @regeneration_interval)
{:ok,
entity
|> put_attribute(%Morale{morale: 0})
|> attribute_transaction(
fn attrs ->
attrs |> Map.merge(%{
Health => get_max_health(attrs),
Energy => get_max_energy(attrs)})
end)}
end
def handle_event(
{:vitals_entity_damage, amount},
%Entity{attributes: %{Health => %Health{health: health}}} = entity) do
new_health = health - amount
cond do
new_health <= 0 -> {:become, DeadBehaviour, :entity_died, entity}
new_health > 0 ->
{:ok, entity |> update_attribute(Health, fn health -> %Health{health | health: new_health} end)}
end
end
def handle_event(
{:vitals_entity_heal, amount},
%Entity{attributes: %{Health => %Health{health: health, max_health: max_health}}} = entity) do
new_health = health + amount
if new_health > max_health, do: new_health = max_health
{:ok, entity |> update_attribute(Health, fn health -> %Health{health | health: new_health} end)}
end
def handle_event(:vitals_entity_kill, entity), do: {:become, DeadBehaviour, :entity_died, entity}
def handle_event({:vitals_health_regeneration, value}, entity) when (-10 <= value) and (value <= 10),
do: {:ok, entity |> update_attribute(Health, fn health -> %Health{health | regeneration: value} end)}
def handle_event({:vitals_energy_regeneration, value}, entity) when (-3 <= value) and (value <= 3),
do: {:ok, entity |> update_attribute(Energy, fn energy -> %Energy{energy | regeneration: value} end)}
def handle_event(
{:vitals_regeneration_update, %{interval: interval, health_accumulator: health_acc, energy_accumulator: energy_acc}},
%Entity{attributes: %{
Health => %Health{regeneration: health_regen} = health,
Energy => %Energy{regeneration: energy_regen} = energy}} = entity) do
health_acc = health_acc + (health_regen * interval/1000)
energy_acc = energy_acc + (energy_regen * interval/1000)
{new_health, new_health_acc} = regenerate_health(health, health_acc)
{new_energy, new_energy_acc} = regenerate_energy(energy, energy_acc)
self |> Process.send_after({:vitals_regeneration_update, %{
interval: @regeneration_interval,
health_accumulator: new_health_acc,
energy_accumulator: new_energy_acc}}, @regeneration_interval)
{:ok, entity |> update_attribute(Health, fn _ -> new_health end)
|> update_attribute(Energy, fn _ -> new_energy end)}
end
def terminate({:become_handler, DeadBehaviour, _}, entity),
do: {:ok, entity}
def terminate(_reason, entity) do
{:ok,
entity
|> remove_attribute(Morale)
|> remove_attribute(Health)
|> remove_attribute(Energy)}
end
# Internal
defp get_max_health(%{Level => %Level{level: level}, Morale => %Morale{morale: morale}}), do: get_max_health(level, morale)
defp get_max_health(%{Morale => %Morale{morale: morale}}), do: get_max_health(20, morale)
defp get_max_health(%{}), do: get_max_health(20, 0)
def get_max_health(level, morale) do
health = calc_life_points_for_level(level)
max_health_with_morale = round(health / 100 * (100 + morale))
%Health{health: max_health_with_morale, max_health: max_health_with_morale}
end
#TODO: Take care of Armor, Runes, Weapons...
defp calc_life_points_for_level(level),
do: 100 + ((level - 1) * 20) # Dont add 20 lifePoints for level1
#TODO: Take care of Armor, Runes, Weapons...
defp get_max_energy(%{Morale => %Morale{morale: morale}}), do: get_max_energy(morale)
defp get_max_energy(%{}), do: get_max_energy(0)
defp get_max_energy(morale) do
inital_mana = 70
mana_with_morale = round(inital_mana / 100 * (100 + morale))
%Energy{mana: mana_with_morale, max_mana: mana_with_morale}
end
defp regenerate_health(health, amount) when amount >= @min_accumulated_health do
health_addition = trunc(amount)
leftover = amount - health_addition
{%Health{health | health: ((health.health + health_addition) |> min(health.max_health))}, leftover}
end
defp regenerate_health(health, amount), do: {health, amount}
defp regenerate_energy(energy, amount) when amount >= @min_accumulated_energy do
energy_addition = trunc(amount)
leftover = amount - energy_addition
{%Energy{energy | mana: ((energy.mana + energy_addition) |> min(energy.max_mana))}, leftover}
end
defp regenerate_energy(energy, amount), do: {energy, amount}
end
defmodule DeadBehaviour do
use Entice.Entity.Behaviour
alias Entice.Logic.Vitals.Morale
alias Entice.Logic.Vitals.AliveBehaviour
def init(%Entity{attributes: %{Morale => %Morale{morale: morale}}} = entity, :entity_died) do
entity.id |> Coordination.notify_locally({
:entity_dead,
%{entity_id: entity.id, attributes: entity.attributes}})
new_morale = morale - 15
if new_morale < -60, #-60 is max negative morale
do: new_morale = -60
{:ok,
entity
|> put_attribute(%Morale{morale: new_morale})
|> update_attribute(Health, fn health -> %Health{health | health: 0} end)}
end
def handle_event({:vitals_entity_resurrect, percent_health, percent_energy}, entity),
do: {:become, AliveBehaviour, {:entity_resurrected, percent_health, percent_energy}, entity}
def terminate({:become_handler, AliveBehaviour, _}, entity),
do: {:ok, entity}
def terminate(_reason, entity) do
{:ok,
entity
|> remove_attribute(Morale)
|> remove_attribute(Health)
|> remove_attribute(Energy)}
end
end
end
| 36.059041 | 127 | 0.685325 |
7940f0c7447968e455e282b49f8c36f93caa0dba | 1,140 | ex | Elixir | lib/hexdocs/utils.ex | hexpm/hexdocs | 808d0b06bbd1a36c639231225ed78cec8c182cae | [
"Apache-2.0"
] | 29 | 2016-10-13T07:32:04.000Z | 2022-03-25T05:59:14.000Z | lib/hexdocs/utils.ex | hexpm/hexdocs | 808d0b06bbd1a36c639231225ed78cec8c182cae | [
"Apache-2.0"
] | 21 | 2016-02-24T03:59:35.000Z | 2021-07-30T08:44:39.000Z | lib/hexdocs/utils.ex | hexpm/hexdocs | 808d0b06bbd1a36c639231225ed78cec8c182cae | [
"Apache-2.0"
] | 12 | 2016-02-28T19:57:36.000Z | 2022-03-18T07:47:39.000Z | defmodule Hexdocs.Utils do
@moduledoc false
def hexdocs_url(repository, path) do
"/" <> _ = path
host = Application.get_env(:hexdocs, :host)
scheme = if host == "hexdocs.pm", do: "https", else: "http"
subdomain = if repository == "hexpm", do: "", else: "#{repository}."
"#{scheme}://#{subdomain}#{host}#{path}"
end
def latest_version(versions) do
Enum.find(versions, &(&1.pre != [])) || List.first(versions)
end
def latest_version?(_version, []) do
true
end
def latest_version?(version, all_versions) do
pre_release? = version.pre != []
first_release? = all_versions == []
all_pre_releases? = Enum.all?(all_versions, &(&1.pre != []))
cond do
first_release? ->
true
all_pre_releases? ->
latest_version = List.first(all_versions)
Version.compare(version, latest_version) in [:eq, :gt]
pre_release? ->
false
true ->
nonpre_versions = Enum.filter(all_versions, &(&1.pre == []))
latest_version = List.first(nonpre_versions)
Version.compare(version, latest_version) in [:eq, :gt]
end
end
end
| 26.511628 | 72 | 0.611404 |
79412bba5968ac471d14e09c908da15721cf2421 | 93 | exs | Elixir | test/flipay/best_rate_finder_test.exs | neofelisho/flipay | 71a03a3f4c859892536faf600b93ff35da82fb88 | [
"MIT"
] | null | null | null | test/flipay/best_rate_finder_test.exs | neofelisho/flipay | 71a03a3f4c859892536faf600b93ff35da82fb88 | [
"MIT"
] | null | null | null | test/flipay/best_rate_finder_test.exs | neofelisho/flipay | 71a03a3f4c859892536faf600b93ff35da82fb88 | [
"MIT"
] | null | null | null | defmodule Flipay.BestRateFinderTest do
use ExUnit.Case
doctest Flipay.BestRateFinder
end
| 18.6 | 38 | 0.83871 |
79412ffa94330563b3eee8a9a174f7354ee3718d | 336 | ex | Elixir | lib/supabase_surface/components/icons/icon_edit.ex | treebee/supabase-surface | 5a184ca92323c085dd81e2fc8aa8c10367f2382e | [
"Apache-2.0"
] | 5 | 2021-06-08T08:02:43.000Z | 2022-02-09T23:13:46.000Z | lib/supabase_surface/components/icons/icon_edit.ex | treebee/supabase-surface | 5a184ca92323c085dd81e2fc8aa8c10367f2382e | [
"Apache-2.0"
] | null | null | null | lib/supabase_surface/components/icons/icon_edit.ex | treebee/supabase-surface | 5a184ca92323c085dd81e2fc8aa8c10367f2382e | [
"Apache-2.0"
] | 1 | 2021-07-14T05:20:31.000Z | 2021-07-14T05:20:31.000Z | defmodule SupabaseSurface.Components.Icons.IconEdit do
use SupabaseSurface.Components.Icon
@impl true
def render(assigns) do
icon_size = IconContainer.get_size(assigns.size)
~F"""
<IconContainer assigns={assigns}>
{Feathericons.edit(width: icon_size, height: icon_size)}
</IconContainer>
"""
end
end
| 22.4 | 62 | 0.714286 |
794150c6c86917cbd024684b78f2ba067eba48c4 | 167 | ex | Elixir | lib/farmbot/celery_script/ast/node/point.ex | pdgonzalez872/farmbot_os | a444248f05ee8f4fe57f6a4865b942131960f76c | [
"MIT"
] | 2 | 2018-08-01T23:07:52.000Z | 2018-10-17T12:49:21.000Z | lib/farmbot/celery_script/ast/node/point.ex | pdgonzalez872/farmbot_os | a444248f05ee8f4fe57f6a4865b942131960f76c | [
"MIT"
] | null | null | null | lib/farmbot/celery_script/ast/node/point.ex | pdgonzalez872/farmbot_os | a444248f05ee8f4fe57f6a4865b942131960f76c | [
"MIT"
] | 1 | 2017-07-22T21:51:14.000Z | 2017-07-22T21:51:14.000Z | defmodule Farmbot.CeleryScript.AST.Node.Point do
@moduledoc false
use Farmbot.CeleryScript.AST.Node
allow_args [:pointer_type, :pointer_id]
return_self()
end
| 20.875 | 48 | 0.784431 |
7941642e79f64bd98965de2f01168a507923b524 | 2,450 | exs | Elixir | test/web/controllers/global_parameter_controller_test.exs | EDENLABLLC/prm.api | 86743f26874f47ce3d48010ccf5d2cd596a3474b | [
"Apache-2.0"
] | 1 | 2017-07-27T16:03:28.000Z | 2017-07-27T16:03:28.000Z | test/web/controllers/global_parameter_controller_test.exs | EDENLABLLC/prm.api | 86743f26874f47ce3d48010ccf5d2cd596a3474b | [
"Apache-2.0"
] | null | null | null | test/web/controllers/global_parameter_controller_test.exs | EDENLABLLC/prm.api | 86743f26874f47ce3d48010ccf5d2cd596a3474b | [
"Apache-2.0"
] | null | null | null | defmodule PRM.Web.GlobalParameterControllerTest do
use PRM.Web.ConnCase
import PRM.SimpleFactory
setup %{conn: conn} do
{:ok, conn: put_req_header(conn, "accept", "application/json")}
end
test "lists all parameters on index", %{conn: conn} do
fixture(:global_parameter, "param1", "value1")
fixture(:global_parameter, "param2", "value2")
fixture(:global_parameter, "param3", "value3")
conn = get conn, global_parameter_path(conn, :index)
resp = json_response(conn, 200)
assert Map.has_key?(resp, "data")
assert Map.has_key?(resp["data"], "param1")
assert "value1" == resp["data"]["param1"]
assert Map.has_key?(resp["data"], "param2")
assert "value2" == resp["data"]["param2"]
assert Map.has_key?(resp["data"], "param3")
assert "value3" == resp["data"]["param3"]
end
describe "put parameters" do
@tag without_consumer_id: true
test "without x-consumer-id header", %{conn: conn} do
params = %{
"param1" => "value1"
}
conn = put conn, global_parameter_path(conn, :create_or_update, params)
resp = json_response(conn, 422)
assert Map.has_key?(resp, "error")
assert Map.has_key?(resp["error"], "type")
assert "validation_failed" == resp["error"]["type"]
assert Map.has_key?(resp["error"], "invalid")
assert 2 == length(resp["error"]["invalid"])
first_error = Enum.at(resp["error"]["invalid"], 0)
assert "$.inserted_by" == first_error["entry"]
assert 1 == length(first_error["rules"])
rule = Enum.at(first_error["rules"], 0)
assert "required" == rule["rule"]
second_error = Enum.at(resp["error"]["invalid"], 1)
assert "$.updated_by" == second_error["entry"]
assert 1 == length(second_error["rules"])
rule = Enum.at(second_error["rules"], 0)
assert "required" == rule["rule"]
end
test "with x-consumer-id header", %{conn: conn} do
fixture(:global_parameter, "param1", "value0")
params = %{
"param1" => "value1",
"param2" => "value2"
}
conn = put conn, global_parameter_path(conn, :create_or_update, params)
resp = json_response(conn, 200)
assert Map.has_key?(resp, "data")
assert Map.has_key?(resp["data"], "param1")
assert "value1" == resp["data"]["param1"]
assert Map.has_key?(resp["data"], "param2")
assert "value2" == resp["data"]["param2"]
end
end
end
| 32.236842 | 77 | 0.617551 |
79416a436dc57888f086adccd3a01e6b180369ed | 115 | ex | Elixir | lib/types/request_download_response.ex | smiyabe/cwmp_ex | 9db322497aa3208b5985ccf496ada5286cde3925 | [
"Artistic-2.0"
] | 3 | 2017-11-29T05:07:35.000Z | 2019-12-18T17:16:41.000Z | lib/types/request_download_response.ex | smiyabe/cwmp_ex | 9db322497aa3208b5985ccf496ada5286cde3925 | [
"Artistic-2.0"
] | 1 | 2021-12-02T19:35:28.000Z | 2022-03-29T09:40:52.000Z | lib/types/request_download_response.ex | smiyabe/cwmp_ex | 9db322497aa3208b5985ccf496ada5286cde3925 | [
"Artistic-2.0"
] | 2 | 2017-11-29T05:07:30.000Z | 2020-11-10T07:10:42.000Z | defmodule CWMP.Protocol.Messages.RequestDownloadResponse do
@derive [Poison.Encoder]
defstruct naught: nil
end
| 23 | 59 | 0.817391 |
79418fee11a9705327f0443f8887c29d0b4fcc4b | 336 | exs | Elixir | apps/tai/test/tai/orders/transitions/rescue_amend_error_test.exs | ccamateur/tai | 41c4b3e09dafc77987fa3f6b300c15461d981e16 | [
"MIT"
] | 276 | 2018-01-16T06:36:06.000Z | 2021-03-20T21:48:01.000Z | apps/tai/test/tai/orders/transitions/rescue_amend_error_test.exs | ccamateur/tai | 41c4b3e09dafc77987fa3f6b300c15461d981e16 | [
"MIT"
] | 73 | 2018-10-05T18:45:06.000Z | 2021-02-08T05:46:33.000Z | apps/tai/test/tai/orders/transitions/rescue_amend_error_test.exs | ccamateur/tai | 41c4b3e09dafc77987fa3f6b300c15461d981e16 | [
"MIT"
] | 43 | 2018-06-09T09:54:51.000Z | 2021-03-07T07:35:17.000Z | defmodule Tai.Orders.Transitions.RescueAmendErrorTest do
use ExUnit.Case, async: false
alias Tai.Orders.Transitions
test ".attrs/1 returns a list of updatable order attributes" do
transition = %Transitions.RescueAmendError{}
attrs = Transitions.RescueAmendError.attrs(transition)
assert Enum.empty?(attrs)
end
end
| 28 | 65 | 0.770833 |
7941a6295bf2f8e13c8447a85ef94cac0dc84fbf | 1,725 | ex | Elixir | lib/changelog/kits/agent_kit.ex | yanokwa/changelog.com | 88093bada9ff294159246b8200b3121cf41666f7 | [
"MIT"
] | null | null | null | lib/changelog/kits/agent_kit.ex | yanokwa/changelog.com | 88093bada9ff294159246b8200b3121cf41666f7 | [
"MIT"
] | null | null | null | lib/changelog/kits/agent_kit.ex | yanokwa/changelog.com | 88093bada9ff294159246b8200b3121cf41666f7 | [
"MIT"
] | null | null | null | defmodule Changelog.AgentKit do
@known_agents ["Overcast", "PlayerFM", "Feedbin", "Feed Wrangler",
"Inoreader", "NewsBlur", "Bloglovin", "NewsGator",
"TheOldReader", "G2Reader", "Feedly", "BazQux"]
@client_regexes [
{"Apple TV", ~r/^AppleCoreMedia\/1\.(.*)Apple TV/},
{"Castro", ~r/^Castro\s/},
{"Apple Watch", ~r/^AppleCoreMedia\/1\.(.*)Apple Watch/},
{"Apple Watch", ~r/(.*)watchOS\//},
{"Google Play", ~r/(.*)Google-Podcast/}
]
# see https://podnews.net/article/podcast-app-useragents
def get_podcast_client(ua) when is_binary(ua) do
ua = URI.decode(ua)
name = case Enum.find(@client_regexes, fn({_, regex}) -> String.match?(ua, regex) end) do
{client, _} -> client
_else -> ua |> String.split("/") |> List.first()
end
case name do
"AppleCoreMedia" -> "Apple Podcasts"
"Mozilla" -> "Browsers"
_else -> name
end
end
def get_podcast_client(_), do: "Unknown"
def get_subscribers(nil), do: {:error, :no_ua_string}
def get_subscribers(ua) do
subscribers = extract_subscribers(ua)
agent = extract_known_agent(ua)
handle(agent, subscribers)
end
defp extract_known_agent(ua) do
Enum.find(@known_agents, fn(x) -> String.match?(ua, ~r/#{x}/i) end)
end
defp extract_subscribers(ua) do
case Regex.named_captures(~r/(?<subs>\d+) subscribers/, ua) do
%{"subs" => count} -> String.to_integer(count)
_else -> 0
end
end
defp handle(_agent, subscribers) when subscribers <= 1, do: {:error, :no_subscribers}
defp handle(agent, _subscribers) when is_nil(agent), do: {:error, :unknown_agent}
defp handle(agent, subscribers), do: {:ok, {agent, subscribers}}
end
| 32.54717 | 93 | 0.627826 |
7941d993a6092b81ea4623e4a009ad93ce4c1e9c | 6,249 | ex | Elixir | lib/sitemapper.ex | tcitworld/sitemapper | ae28d2b642a2e4a4d68c87d9e6d4aff22f97c203 | [
"MIT"
] | 23 | 2019-10-17T22:13:21.000Z | 2021-06-26T05:25:22.000Z | lib/sitemapper.ex | tcitworld/sitemapper | ae28d2b642a2e4a4d68c87d9e6d4aff22f97c203 | [
"MIT"
] | 5 | 2020-07-17T15:20:18.000Z | 2021-06-27T10:20:56.000Z | lib/sitemapper.ex | tcitworld/sitemapper | ae28d2b642a2e4a4d68c87d9e6d4aff22f97c203 | [
"MIT"
] | 6 | 2019-11-25T15:02:12.000Z | 2021-06-26T05:06:59.000Z | defmodule Sitemapper do
@moduledoc """
Sitemapper is an Elixir library for generating [XML Sitemaps](https://www.sitemaps.org).
It's designed to generate large sitemaps while maintaining a low
memory profile. It can persist sitemaps to Amazon S3, disk or any
other adapter you wish to write.
"""
alias Sitemapper.{File, IndexGenerator, SitemapGenerator, SitemapReference}
@doc """
Receives a `Stream` of `Sitemapper.URL` and returns a `Stream` of
`{filename, body}` tuples, representing the individual sitemap XML
files, followed by an index XML file.
Accepts the following `Keyword` options in `opts`:
* `sitemap_url` - The base URL where the generated sitemap
files will live. e.g. `http://example.org`, if your sitemap lives at
`http://example.org/sitemap.xml` (required)
* `gzip` - Sets whether the files are gzipped (default: `true`)
* `name` - An optional suffix for the sitemap filename. e.g. If you
set to `news`, will produce `sitemap-news.xml.gz` and
`sitemap-news-00001.xml.gz` filenames. (default: `nil`)
* `index_lastmod` - An optional Date/DateTime/NaiveDateTime for the lastmod
element in the index. (default: `Date.utc_today()`)
"""
@spec generate(stream :: Enumerable.t(), opts :: keyword) :: Stream.t()
def generate(enum, opts) do
sitemap_url = Keyword.fetch!(opts, :sitemap_url)
gzip_enabled = Keyword.get(opts, :gzip, true)
name = Keyword.get(opts, :name)
index_lastmod = Keyword.get(opts, :index_lastmod, Date.utc_today())
enum
|> Stream.concat([:end])
|> Stream.transform(nil, &reduce_url_to_sitemap/2)
|> Stream.transform(1, &reduce_file_to_name_and_body(&1, &2, name, gzip_enabled))
|> Stream.concat([:end])
|> Stream.transform(
nil,
&reduce_to_index(&1, &2, sitemap_url, name, gzip_enabled, index_lastmod)
)
|> Stream.map(&maybe_gzip_body(&1, gzip_enabled))
end
@doc """
Receives a `Stream` of `{filename, body}` tuples, and persists
those to the `Sitemapper.Store`.
Will raise if persistence fails.
Accepts the following `Keyword` options in `opts`:
* `store` - The module of the desired `Sitemapper.Store`,
such as `Sitemapper.S3Store`. (required)
* `store_config` - A `Keyword` list with options for the
`Sitemapper.Store`. (optional, but usually required)
"""
@spec persist(Enumerable.t(), keyword) :: Stream.t()
def persist(enum, opts) do
store = Keyword.fetch!(opts, :store)
store_config = Keyword.get(opts, :store_config, [])
enum
|> Stream.each(fn {filename, body} ->
:ok = store.write(filename, body, store_config)
end)
end
@doc """
Receives a `Stream` of `{filename, body}` tuples, takes the last
one (the index file), and pings Google and Bing with its URL.
"""
@spec ping(Enumerable.t(), keyword) :: Stream.t()
def ping(enum, opts) do
sitemap_url = Keyword.fetch!(opts, :sitemap_url)
enum
|> Stream.take(-1)
|> Stream.map(fn {filename, _body} ->
index_url =
URI.parse(sitemap_url)
|> join_uri_and_filename(filename)
|> URI.to_string()
Sitemapper.Pinger.ping(index_url)
end)
end
defp reduce_url_to_sitemap(:end, nil) do
{[], nil}
end
defp reduce_url_to_sitemap(:end, progress) do
done = SitemapGenerator.finalize(progress)
{[done], nil}
end
defp reduce_url_to_sitemap(url, nil) do
reduce_url_to_sitemap(url, SitemapGenerator.new())
end
defp reduce_url_to_sitemap(url, progress) do
case SitemapGenerator.add_url(progress, url) do
{:error, reason} when reason in [:over_length, :over_count] ->
done = SitemapGenerator.finalize(progress)
next = SitemapGenerator.new() |> SitemapGenerator.add_url(url)
{[done], next}
new_progress ->
{[], new_progress}
end
end
defp reduce_file_to_name_and_body(%File{body: body}, counter, name, gzip_enabled) do
{[{filename(name, gzip_enabled, counter), body}], counter + 1}
end
defp maybe_gzip_body({filename, body}, true) do
{filename, :zlib.gzip(body)}
end
defp maybe_gzip_body({filename, body}, false) do
{filename, body}
end
defp reduce_to_index(:end, nil, _sitemap_url, _name, _gzip_enabled, _lastmod) do
{[], nil}
end
defp reduce_to_index(:end, index_file, _sitemap_url, name, gzip_enabled, _lastmod) do
done_file = IndexGenerator.finalize(index_file)
{filename, body} = index_file_to_data_and_name(done_file, name, gzip_enabled)
{[{filename, body}], nil}
end
defp reduce_to_index({filename, body}, nil, sitemap_url, name, gzip_enabled, lastmod) do
reduce_to_index(
{filename, body},
IndexGenerator.new(),
sitemap_url,
name,
gzip_enabled,
lastmod
)
end
defp reduce_to_index({filename, body}, index_file, sitemap_url, _name, _gzip_enabled, lastmod) do
reference = filename_to_sitemap_reference(filename, sitemap_url, lastmod)
case IndexGenerator.add_sitemap(index_file, reference) do
{:error, reason} when reason in [:over_length, :over_count] ->
raise "Generated more than 50,000 sitemap indexes"
new_file ->
{[{filename, body}], new_file}
end
end
defp index_file_to_data_and_name(%File{body: body}, name, gzip_enabled) do
{filename(name, gzip_enabled), body}
end
defp filename_to_sitemap_reference(filename, sitemap_url, lastmod) do
loc =
URI.parse(sitemap_url)
|> join_uri_and_filename(filename)
|> URI.to_string()
%SitemapReference{loc: loc, lastmod: lastmod}
end
defp join_uri_and_filename(%URI{path: nil} = uri, filename) do
URI.merge(uri, filename)
end
defp join_uri_and_filename(%URI{path: path} = uri, filename) do
path = Path.join(path, filename)
URI.merge(uri, path)
end
defp filename(name, gzip, count \\ nil) do
prefix = ["sitemap", name] |> Enum.reject(&is_nil/1) |> Enum.join("-")
suffix =
case count do
nil ->
""
c ->
str = Integer.to_string(c)
"-" <> String.pad_leading(str, 5, "0")
end
extension =
case gzip do
true -> ".xml.gz"
false -> ".xml"
end
prefix <> suffix <> extension
end
end
| 30.334951 | 99 | 0.666347 |
7941f2bc55591dbe47af07f4f6b1d8006be83dcc | 1,975 | exs | Elixir | apps/temporario_web/config/dev.exs | achedeuzot/temporar.io | acbec140732614070996924633f254b56e56131f | [
"MIT"
] | 2 | 2019-04-16T18:46:36.000Z | 2020-09-18T12:58:57.000Z | apps/temporario_web/config/dev.exs | achedeuzot/temporar.io | acbec140732614070996924633f254b56e56131f | [
"MIT"
] | 6 | 2019-01-06T11:13:39.000Z | 2022-02-10T15:15:24.000Z | apps/temporario_web/config/dev.exs | achedeuzot/temporar.io | acbec140732614070996924633f254b56e56131f | [
"MIT"
] | null | null | null | # Since configuration is shared in umbrella projects, this file
# should only configure the :temporario_web application itself
# and only for organization purposes. All other config goes to
# the umbrella root.
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 webpack to recompile .js and .css sources.
config :temporario_web, TemporarioWeb.Endpoint,
http: [port: 4000],
https: [
port: 4001,
cipher_suite: :strong,
keyfile: "priv/cert/selfsigned_key.pem",
certfile: "priv/cert/selfsigned.pem"
],
secret_key_base: "Cr4w30hzJx3GOs5+1lkQ5963H3BBbQnxV/iFZVJkjm5xERtFhvJqnBwCNSVrTaSK",
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [
node: [
"node_modules/webpack/bin/webpack.js",
"--mode",
"development",
"--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
# Mix task:
#
# mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.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 :temporario_web, TemporarioWeb.Endpoint,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{priv/gettext/.*(po)$},
~r{lib/temporario_web/views/.*(ex)$},
~r{lib/temporario_web/templates/.*(eex)$}
]
]
| 28.623188 | 86 | 0.684557 |
7941fd0ebf9fe9d238c8403046ca6c4208255cae | 44,319 | ex | Elixir | lib/phoenix_live_view.ex | ohr486/phoenix_live_view | 14a3e5a993de7767e38117852707c6c1feb1d485 | [
"MIT"
] | null | null | null | lib/phoenix_live_view.ex | ohr486/phoenix_live_view | 14a3e5a993de7767e38117852707c6c1feb1d485 | [
"MIT"
] | null | null | null | lib/phoenix_live_view.ex | ohr486/phoenix_live_view | 14a3e5a993de7767e38117852707c6c1feb1d485 | [
"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.
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/2`](`c:Phoenix.LiveComponent.update/2`) on the child component,
`send_update/2` 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/2` 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 send_update(module, assigns) when is_atom(module) do
assigns = Enum.into(assigns, %{})
id =
assigns[:id] ||
raise ArgumentError, "missing required :id in send_update. Got: #{inspect(assigns)}"
Phoenix.LiveView.Channel.send_update(module, id, assigns)
end
@doc """
Similar to `send_update/2` 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 send_update_after(module, assigns, time_in_milliseconds)
when is_atom(module) and is_integer(time_in_milliseconds) 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(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.657568 | 148 | 0.683928 |
79420440e4aca127d8405144a32c5647f0c16959 | 570 | ex | Elixir | lib/club_backend_web/views/changeset_view.ex | ufosc/club-backend-ex | 87b55bc9fcccd9d458ee3277c3153f608f3a8a5e | [
"MIT"
] | null | null | null | lib/club_backend_web/views/changeset_view.ex | ufosc/club-backend-ex | 87b55bc9fcccd9d458ee3277c3153f608f3a8a5e | [
"MIT"
] | 6 | 2020-07-31T23:02:34.000Z | 2021-02-26T21:10:10.000Z | lib/club_backend_web/views/changeset_view.ex | ufosc/club-backend-ex | 87b55bc9fcccd9d458ee3277c3153f608f3a8a5e | [
"MIT"
] | 2 | 2020-08-23T23:04:00.000Z | 2020-10-03T03:18:11.000Z | defmodule ClubBackendWeb.ChangesetView do
use ClubBackendWeb, :view
@doc """
Traverses and translates changeset errors.
See `Ecto.Changeset.traverse_errors/2` and
`ClubBackendWeb.ErrorHelpers.translate_error/1` for more details.
"""
def translate_errors(changeset) do
Ecto.Changeset.traverse_errors(changeset, &translate_error/1)
end
def render("error.json", %{changeset: changeset}) do
# When encoded, the changeset returns its errors
# as a JSON object. So we just pass it forward.
%{errors: translate_errors(changeset)}
end
end
| 28.5 | 67 | 0.74386 |
7942593d320fd7805ae42c23cd410e6fbe7304a9 | 1,455 | exs | Elixir | test/mix/cloak.migrate_test.exs | tizpuppi/cloak | cdeae97c69f7c54aeadf0921db30dc411d7a9938 | [
"MIT"
] | null | null | null | test/mix/cloak.migrate_test.exs | tizpuppi/cloak | cdeae97c69f7c54aeadf0921db30dc411d7a9938 | [
"MIT"
] | null | null | null | test/mix/cloak.migrate_test.exs | tizpuppi/cloak | cdeae97c69f7c54aeadf0921db30dc411d7a9938 | [
"MIT"
] | null | null | null | defmodule Cloak.MigrateTest do
use Cloak.DataCase, async: false
import ExUnit.CaptureIO
import IO.ANSI, only: [yellow: 0, green: 0, reset: 0]
setup do
[user: Factory.create_user("[email protected]")]
end
test "migrates existing rows to new version when command line args given" do
output =
capture_io(fn ->
Mix.Task.rerun("cloak.migrate", [
"-r",
"Cloak.TestRepo",
"-s",
"Cloak.TestUser"
])
end)
assert output == """
Migrating #{yellow()}Cloak.TestUser#{reset()}...
#{green()}Migration complete!#{reset()}
"""
end
test "reads from configuration" do
Application.put_env(:cloak, :cloak_repo, Cloak.TestRepo)
Application.put_env(:cloak, :cloak_schemas, [Cloak.TestUser])
output =
capture_io(fn ->
Mix.Task.rerun("cloak.migrate", [])
end)
assert output == """
Migrating #{yellow()}Cloak.TestUser#{reset()}...
#{green()}Migration complete!#{reset()}
"""
Application.delete_env(:cloak, :cloak_repo)
Application.delete_env(:cloak, :cloak_schemas)
end
test "raises error if called with incorrect arguments" do
bad_args = [
[],
["-r", "Cloak.TestRepo"],
["-s", "Cloak.TestSchema"]
]
for args <- bad_args do
assert_raise Mix.Error, fn ->
Mix.Task.rerun("cloak.migrate", args)
end
end
end
end
| 24.25 | 78 | 0.580756 |
794261ed3f7e815ad4e487140357f24edec4b83e | 947 | ex | Elixir | lib/protobuf/service.ex | hayesgm/protobuf-ex | 9ca03063de265a9690f341fcda77055613f4ff17 | [
"MIT"
] | null | null | null | lib/protobuf/service.ex | hayesgm/protobuf-ex | 9ca03063de265a9690f341fcda77055613f4ff17 | [
"MIT"
] | null | null | null | lib/protobuf/service.ex | hayesgm/protobuf-ex | 9ca03063de265a9690f341fcda77055613f4ff17 | [
"MIT"
] | null | null | null | defmodule Protobuf.Service do
@moduledoc """
Module to be used in Service definitions.
"""
defmodule DSL do
@moduledoc """
DSL to build Service definition.
"""
defmacro rpc(name, request, response, opts \\ []) do
quote do
@rpcs {unquote(name), unquote(request), unquote(response), unquote(opts)}
end
end
defmacro stream(name) do
quote do
{:stream, unquote(name)}
end
end
defmacro __before_compile__(env) do
rpcs_value = env.module
|> Module.get_attribute(:rpcs)
|> Enum.reverse
quote do
def rpcs do
unquote(Macro.escape(rpcs_value))
end
end
end
end
defmacro __using__(_opts) do
quote do
import Protobuf.Service.DSL, only: [rpc: 3, rpc: 4, stream: 1]
Module.register_attribute __MODULE__, :rpcs, accumulate: true
@before_compile Protobuf.Service.DSL
end
end
end
| 20.586957 | 81 | 0.61246 |
794266a507f57d028c9151151007942ecdddd977 | 869 | ex | Elixir | lib/astarte_rpc/protocol/vmq_plugin.ex | Annopaolo/astarte_rpc | cd720004d225631f41d6f4d7f964aecb92b52849 | [
"Apache-2.0"
] | 3 | 2018-02-02T14:07:03.000Z | 2020-02-10T07:12:39.000Z | lib/astarte_rpc/protocol/vmq_plugin.ex | Annopaolo/astarte_rpc | cd720004d225631f41d6f4d7f964aecb92b52849 | [
"Apache-2.0"
] | 49 | 2018-02-02T10:00:30.000Z | 2022-03-22T10:39:10.000Z | lib/astarte_rpc/protocol/vmq_plugin.ex | Annopaolo/astarte_rpc | cd720004d225631f41d6f4d7f964aecb92b52849 | [
"Apache-2.0"
] | 5 | 2018-02-02T09:58:07.000Z | 2021-04-07T08:53:44.000Z | #
# This file is part of Astarte.
#
# Copyright 2018 Ispirata Srl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
defmodule Astarte.RPC.Protocol.VMQ.Plugin do
@external_resource Path.expand("proto/vmq_plugin", __DIR__)
use Protobuf, from: Path.wildcard(Path.expand("proto/vmq_plugin/*.proto", __DIR__))
use Astarte.RPC.Protocol, amqp_queue: "vmq_plugin_rpc"
end
| 34.76 | 85 | 0.761795 |
79426778e303e5873fb1714a54e85fa8f26f0be6 | 288 | ex | Elixir | lib/coxir/gateway/payload/session_start_limit.ex | satom99/coxir | 75bce94dcbe5dfa49e920d2f4ce0de224c315ce4 | [
"Apache-2.0"
] | 178 | 2018-04-08T17:11:56.000Z | 2022-03-25T15:36:41.000Z | lib/coxir/gateway/payload/session_start_limit.ex | satom99/coxir | 75bce94dcbe5dfa49e920d2f4ce0de224c315ce4 | [
"Apache-2.0"
] | 21 | 2018-04-30T21:33:59.000Z | 2019-09-03T17:25:26.000Z | lib/coxir/gateway/payload/session_start_limit.ex | satom99/coxir | 75bce94dcbe5dfa49e920d2f4ce0de224c315ce4 | [
"Apache-2.0"
] | 25 | 2018-04-21T19:41:03.000Z | 2021-07-24T22:40:40.000Z | defmodule Coxir.Gateway.Payload.SessionStartLimit do
@moduledoc """
Work in progress.
"""
use Coxir.Gateway.Payload
embedded_schema do
field(:total, :integer)
field(:remaining, :integer)
field(:reset_after, :integer)
field(:max_concurrency, :integer)
end
end
| 20.571429 | 52 | 0.704861 |
79426de7e61e4389722265a1e0a670f1be20aa98 | 2,276 | exs | Elixir | test/etag/plug/options_test.exs | Zeeker/extag | 7626ac865013d1c379f76cef7fd606ecedb5aa62 | [
"MIT"
] | 13 | 2018-10-28T04:37:21.000Z | 2018-11-30T19:21:35.000Z | test/etag/plug/options_test.exs | Zeeker/extag | 7626ac865013d1c379f76cef7fd606ecedb5aa62 | [
"MIT"
] | 2 | 2019-03-24T18:50:29.000Z | 2019-03-24T21:19:02.000Z | test/etag/plug/options_test.exs | Zeeker/extag | 7626ac865013d1c379f76cef7fd606ecedb5aa62 | [
"MIT"
] | 2 | 2018-10-26T16:29:53.000Z | 2018-10-29T15:09:03.000Z | defmodule ETag.Plug.OptionsTest do
use ExUnit.Case, async: true
import ETag.Plug.Options, only: [sanitize!: 1, defaults: 0]
describe ".sanitize!" do
test "with a bullshit atom, returns the defaults" do
assert_raise ArgumentError, fn -> sanitize!(:bullshit) end
end
test "with empty options, returns the defaults" do
assert_equal(sanitize!([]), defaults())
end
test "with one option applies the remaining defaults but does not override the one value" do
opts = [generator: ETag.Generator.MD5]
expected = Keyword.merge(defaults(), opts)
assert_equal(sanitize!(opts), expected)
end
test "with full options does not care about the defaults" do
opts = [
generator: ETag.Generator.MD5,
methods: ["FOO"],
status_codes: [201]
]
assert_equal(sanitize!(opts), opts)
end
# Methods
test "with an atom method raises an ArgumentError" do
opts = [methods: [:foo_bar]]
assert_raise ArgumentError, fn -> sanitize!(opts) end
end
test "with a empty list for methods raises an ArgumentError" do
opts = [methods: []]
assert_raise ArgumentError, fn -> sanitize!(opts) end
end
test "with lowercase methods casts them to uppercase" do
opts = [methods: ["foo"]]
assert sanitize!(opts)[:methods] == ["FOO"]
end
# Generator
test "with a string as generator raises an ArgumentError" do
opts = [generator: "foo bar"]
assert_raise ArgumentError, fn -> sanitize!(opts) end
end
# Status Codes
test "with atom status_methods tries to resolve them to status code numbers" do
opts = [status_codes: [:ok]]
assert sanitize!(opts)[:status_codes] == [200]
end
test "with a bullshit atom status_methods raises an error" do
opts = [status_codes: [:bullshit]]
assert_raise FunctionClauseError, fn -> sanitize!(opts) end
end
test "with a empty list for status codes raises an ArgumentError" do
opts = [status_codes: []]
assert_raise ArgumentError, fn -> sanitize!(opts) end
end
end
defp assert_equal(expected, actual) do
expected = Enum.sort(expected)
actual = Enum.sort(actual)
assert expected == actual
end
end
| 25.863636 | 96 | 0.653339 |
79426f6b67869293577d71960f9a56d855bf2348 | 1,467 | exs | Elixir | mix.exs | andyleclair/etso | 81ffbb4b23aad4b442954a469e1299cd6d132279 | [
"Apache-2.0"
] | null | null | null | mix.exs | andyleclair/etso | 81ffbb4b23aad4b442954a469e1299cd6d132279 | [
"Apache-2.0"
] | null | null | null | mix.exs | andyleclair/etso | 81ffbb4b23aad4b442954a469e1299cd6d132279 | [
"Apache-2.0"
] | null | null | null | defmodule Etso.MixProject do
use Mix.Project
def project do
[
app: :etso,
version: "0.1.5",
elixir: "~> 1.8",
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
package: package(),
deps: deps(),
dialyzer: dialyzer(),
name: "Etso",
description: "An ETS adapter for Ecto",
source_url: "https://github.com/evadne/etso",
docs: docs()
]
end
def application do
[]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp deps do
[
{:ecto, "~> 3.0"},
{:dialyxir, "~> 1.0.0-rc.6", only: :dev, runtime: false},
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false},
{:jason, "~> 1.1", only: :test, runtime: false},
{:persistent_ets, "~> 0.2.0"}
]
end
defp dialyzer do
[
plt_add_apps: [:mix, :iex, :ex_unit],
flags: ~w(error_handling no_opaque race_conditions underspecs unmatched_returns)a,
ignore_warnings: "dialyzer-ignore-warnings.exs",
list_unused_filters: true
]
end
defp package do
[
maintainers: ["Evadne Wu"],
files: package_files(),
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/evadne/etso"}
]
end
defp docs do
[
main: "readme",
extras: ["README.md"]
]
end
defp package_files do
~w(
lib/etso/*
mix.exs
)
end
end
| 20.957143 | 88 | 0.554192 |
79429fc41be514d5ad1dd7f1638340e2a1682388 | 2,000 | ex | Elixir | test/support/error_projector.ex | kianmeng/commanded-ecto-projections | aa5a99488e969fe338db780898cb8bd22599df15 | [
"MIT"
] | 57 | 2017-11-09T21:18:22.000Z | 2022-02-10T07:58:21.000Z | test/support/error_projector.ex | kianmeng/commanded-ecto-projections | aa5a99488e969fe338db780898cb8bd22599df15 | [
"MIT"
] | 26 | 2018-01-08T13:31:16.000Z | 2022-03-24T20:59:29.000Z | test/support/error_projector.ex | kianmeng/commanded-ecto-projections | aa5a99488e969fe338db780898cb8bd22599df15 | [
"MIT"
] | 25 | 2017-11-03T20:27:10.000Z | 2022-02-23T09:47:11.000Z | defmodule ErrorProjector do
use Commanded.Projections.Ecto, application: TestApplication, name: "ErrorProjector"
alias Commanded.Event.FailureContext
alias Commanded.Projections.Events.{
AnEvent,
ErrorEvent,
RaiseEvent,
ExceptionEvent,
InvalidMultiEvent
}
alias Commanded.Projections.Projection
project %AnEvent{name: name, pid: pid} = event, fn multi ->
send(pid, event)
Ecto.Multi.insert(multi, :projection, %Projection{name: name})
end
project %ErrorEvent{name: name}, fn multi ->
Ecto.Multi.insert(multi, :projection, %Projection{name: name})
{:error, :failed}
end
project %ExceptionEvent{}, fn multi ->
# Attempt an invalid insert due to `name` type mismatch (expects a string).
Ecto.Multi.insert(multi, :projection, %Projection{name: 1})
end
project %RaiseEvent{message: message}, fn _multi ->
raise RuntimeError, message: message
end
project %InvalidMultiEvent{name: name}, fn multi ->
# Attempt to execute an invalid Ecto query (comparison with `nil` is forbidden as it is unsafe).
query = from(p in Projection, where: p.name == ^name)
Ecto.Multi.update_all(multi, :projection, query, set: [name: name])
end
@impl Commanded.Event.Handler
def error({:error, :failed} = error, %ErrorEvent{} = event, %FailureContext{}) do
%ErrorEvent{pid: pid} = event
send(pid, error)
:skip
end
@impl Commanded.Event.Handler
def error({:error, _error} = error, %ExceptionEvent{} = event, %FailureContext{}) do
%ExceptionEvent{pid: pid} = event
send(pid, error)
:skip
end
@impl Commanded.Event.Handler
def error({:error, _error} = error, %RaiseEvent{} = event, %FailureContext{}) do
%RaiseEvent{pid: pid} = event
send(pid, error)
:skip
end
@impl Commanded.Event.Handler
def error({:error, _error} = error, %InvalidMultiEvent{} = event, %FailureContext{}) do
%InvalidMultiEvent{pid: pid} = event
send(pid, error)
:skip
end
end
| 25 | 100 | 0.6815 |
7942a65578c810b2852148b40b52f385949f9a78 | 2,283 | ex | Elixir | clients/classroom/lib/google_api/classroom/v1/model/material.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/classroom/lib/google_api/classroom/v1/model/material.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/classroom/lib/google_api/classroom/v1/model/material.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 "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.Classroom.V1.Model.Material do
@moduledoc """
Material attached to course work. When creating attachments, setting the `form` field is not supported.
## Attributes
- driveFile (SharedDriveFile): Google Drive file material. Defaults to: `null`.
- form (Form): Google Forms material. Defaults to: `null`.
- link (Link): Link material. On creation, will be upgraded to a more appropriate type if possible, and this will be reflected in the response. Defaults to: `null`.
- youtubeVideo (YouTubeVideo): YouTube video material. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:driveFile => GoogleApi.Classroom.V1.Model.SharedDriveFile.t(),
:form => GoogleApi.Classroom.V1.Model.Form.t(),
:link => GoogleApi.Classroom.V1.Model.Link.t(),
:youtubeVideo => GoogleApi.Classroom.V1.Model.YouTubeVideo.t()
}
field(:driveFile, as: GoogleApi.Classroom.V1.Model.SharedDriveFile)
field(:form, as: GoogleApi.Classroom.V1.Model.Form)
field(:link, as: GoogleApi.Classroom.V1.Model.Link)
field(:youtubeVideo, as: GoogleApi.Classroom.V1.Model.YouTubeVideo)
end
defimpl Poison.Decoder, for: GoogleApi.Classroom.V1.Model.Material do
def decode(value, options) do
GoogleApi.Classroom.V1.Model.Material.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Classroom.V1.Model.Material do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.052632 | 166 | 0.737626 |
7942a721f4c1ab4a67fc880fff2a47bfd46a9a86 | 743 | exs | Elixir | examples/hello_world/test/hello_world_test.exs | wojtekmach/twirp | 3f4f6858d4cb3558f3d47f28d8bac1984fa29105 | [
"Apache-2.0"
] | 2 | 2019-08-23T17:26:30.000Z | 2021-01-30T08:08:36.000Z | examples/hello_world/test/hello_world_test.exs | wojtekmach/twirp | 3f4f6858d4cb3558f3d47f28d8bac1984fa29105 | [
"Apache-2.0"
] | 10 | 2019-11-04T12:42:59.000Z | 2020-05-28T11:06:19.000Z | examples/hello_world/test/hello_world_test.exs | wojtekmach/twirp | 3f4f6858d4cb3558f3d47f28d8bac1984fa29105 | [
"Apache-2.0"
] | null | null | null | defmodule HelloWorldTest do
use ExUnit.Case, async: true
alias HelloWorld.RPC.HelloWorldClient
test "protobuf" do
client = HelloWorldClient.new(base_url: "http://localhost:8080")
assert HelloWorldClient.hello(client, %{name: "World"}) == %{message: "Hello World!"}
end
test "json" do
assert post!(
"http://localhost:8080/twirp/example.hello_world.HelloWorld/Hello",
~s({"name": "World"}),
[{"content-type", "application/json"}]
) == ~s({"message":"Hello World!"})
end
defp post!(url, data, headers) do
options = []
{:ok, _status, _headers, ref} = :hackney.request(:post, url, headers, data, options)
{:ok, body} = :hackney.body(ref)
body
end
end
| 29.72 | 89 | 0.617766 |
7942b6862921df81f5a0f2ed254bd38379be6e67 | 2,062 | ex | Elixir | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/sql_scheduled_maintenance.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/sql_scheduled_maintenance.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/sql_scheduled_maintenance.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.SQLAdmin.V1beta4.Model.SqlScheduledMaintenance do
@moduledoc """
Any scheduled maintenance for this instance.
## Attributes
* `canDefer` (*type:* `boolean()`, *default:* `nil`) -
* `canReschedule` (*type:* `boolean()`, *default:* `nil`) - If the scheduled maintenance can be rescheduled.
* `scheduleDeadlineTime` (*type:* `DateTime.t`, *default:* `nil`) - Maintenance cannot be rescheduled to start beyond this deadline.
* `startTime` (*type:* `DateTime.t`, *default:* `nil`) - The start time of any upcoming scheduled maintenance for this instance.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:canDefer => boolean() | nil,
:canReschedule => boolean() | nil,
:scheduleDeadlineTime => DateTime.t() | nil,
:startTime => DateTime.t() | nil
}
field(:canDefer)
field(:canReschedule)
field(:scheduleDeadlineTime, as: DateTime)
field(:startTime, as: DateTime)
end
defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1beta4.Model.SqlScheduledMaintenance do
def decode(value, options) do
GoogleApi.SQLAdmin.V1beta4.Model.SqlScheduledMaintenance.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1beta4.Model.SqlScheduledMaintenance do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.821429 | 136 | 0.71872 |
7942d4975f54545b3a6e10e4df89c88b0073583c | 1,679 | ex | Elixir | apps/service_acquire/lib/acquire/query/where/temporal.ex | rucker/hindsight | 876a5d344c5d8eebbea37684ee07e0a91e4430f0 | [
"Apache-2.0"
] | null | null | null | apps/service_acquire/lib/acquire/query/where/temporal.ex | rucker/hindsight | 876a5d344c5d8eebbea37684ee07e0a91e4430f0 | [
"Apache-2.0"
] | null | null | null | apps/service_acquire/lib/acquire/query/where/temporal.ex | rucker/hindsight | 876a5d344c5d8eebbea37684ee07e0a91e4430f0 | [
"Apache-2.0"
] | null | null | null | defmodule Acquire.Query.Where.Temporal do
@moduledoc false
import Acquire.Query.Where.Functions
@spec to_queryable(
dataset_id :: String.t(),
subset_id :: String.t(),
after_time :: String.t(),
before_time :: String.t()
) :: Acquire.Queryable.t()
def to_queryable(_, _, "", ""), do: nil
def to_queryable(dataset_id, subset_id, after_time, before_time) do
with {:ok, dictionary} <- Acquire.Dictionaries.get_dictionary(dataset_id, subset_id) do
Dictionary.get_by_type(dictionary, Dictionary.Type.Timestamp)
|> Enum.map(&Enum.join(&1, "."))
|> Enum.map(&to_queryable(&1, after_time, before_time))
|> or_clause()
end
end
defp to_queryable(field, after_time, before_time) do
[
after_clause(field, after_time),
before_clause(field, before_time)
]
|> Enum.filter(& &1)
|> and_clause()
end
defp after_clause(_, ""), do: nil
defp after_clause(field, time) do
parsed_timestamp =
time
|> parameter()
|> date_parse(literal("%Y-%m-%dT%H:%i:%S"))
parsed_timestamp
|> date_diff(field(field))
|> gt(literal(0))
end
defp before_clause(_, ""), do: nil
defp before_clause(field, time) do
parsed_timestamp =
time
|> parameter()
|> date_parse(literal("%Y-%m-%dT%H:%i:%S"))
parsed_timestamp
|> date_diff(field(field))
|> lt(literal(0))
end
defp and_clause([item]), do: item
defp and_clause(items) do
Acquire.Query.Where.And.new!(conditions: items)
end
defp or_clause([item]), do: item
defp or_clause(items) do
Acquire.Query.Where.Or.new!(conditions: items)
end
end
| 24.333333 | 91 | 0.628946 |
7942e02efd98f595b2b2fb3cadd8a6d00e290366 | 852 | ex | Elixir | lib/slime/renderer.ex | A-World-For-Us/slime | 0e909776f9022406dd042b20673241dd03224ec9 | [
"MIT"
] | 312 | 2015-12-28T05:25:47.000Z | 2022-02-16T05:18:16.000Z | lib/slime/renderer.ex | A-World-For-Us/slime | 0e909776f9022406dd042b20673241dd03224ec9 | [
"MIT"
] | 105 | 2015-12-27T21:20:58.000Z | 2022-02-24T05:23:38.000Z | lib/slime/renderer.ex | A-World-For-Us/slime | 0e909776f9022406dd042b20673241dd03224ec9 | [
"MIT"
] | 45 | 2016-01-12T04:02:01.000Z | 2021-09-14T16:19:18.000Z | defmodule Slime.Renderer do
@moduledoc """
Transform Slime templates into HTML.
"""
alias Slime.Compiler
alias Slime.Parser
@doc """
Compile Slime template to valid EEx HTML.
## Examples
iex> Slime.Renderer.precompile(~s(input.required type="hidden"))
"<input class=\\"required\\" type=\\"hidden\\">"
"""
def precompile(input) do
input
|> Parser.parse()
|> Compiler.compile()
end
@doc """
Takes a Slime template as a string as well as a set of bindings, and renders
the resulting HTML.
Note that this method of rendering is substantially slower than rendering
precompiled templates created with Slime.function_from_file/5 and
Slime.function_from_string/5.
"""
def render(slime, bindings \\ [], opts \\ []) do
slime
|> precompile
|> EEx.eval_string(bindings, opts)
end
end
| 24.342857 | 78 | 0.676056 |
794337d790625c858d089cba054cd3296a1faa3f | 621 | exs | Elixir | mix.exs | neftalyluis/resortera | 2920e96e05941a678ea2e820ae38465536439160 | [
"MIT"
] | null | null | null | mix.exs | neftalyluis/resortera | 2920e96e05941a678ea2e820ae38465536439160 | [
"MIT"
] | null | null | null | mix.exs | neftalyluis/resortera | 2920e96e05941a678ea2e820ae38465536439160 | [
"MIT"
] | null | null | null | defmodule Resortera.MixProject do
use Mix.Project
def project do
[
app: :resortera,
version: "0.1.0",
elixir: "~> 1.7",
start_permanent: Mix.env() == :prod,
deps: deps(),
escript: [main_module: Resortera.CLI]
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
]
end
end
| 20.7 | 88 | 0.584541 |
79434a6bd2872bd886e2009ea8bb5cb53c1952f6 | 544 | exs | Elixir | test/parser_test.exs | evliang/craigslist-alert | 65de4f3a9070088739c1a1989198ab6b8a22925c | [
"MIT"
] | 2 | 2018-06-27T03:15:46.000Z | 2019-01-26T17:50:17.000Z | test/parser_test.exs | evliang/craigslist-alert | 65de4f3a9070088739c1a1989198ab6b8a22925c | [
"MIT"
] | null | null | null | test/parser_test.exs | evliang/craigslist-alert | 65de4f3a9070088739c1a1989198ab6b8a22925c | [
"MIT"
] | null | null | null | defmodule ClexTest.Parser do
use ExUnit.Case
doctest Clex
test "parser test" do
result = Clex.Parser.read()
result |> is_list |> assert
result
|> Enum.each(fn item ->
item |> is_map |> assert
item |> Map.has_key?("category") |> assert
item |> Map.has_key?("city") |> assert
item |> Map.has_key?("keywords") |> assert
item["keywords"] |> is_list |> assert
item["keywords"] |> Enum.any?() |> assert
end)
end
end
| 27.2 | 54 | 0.512868 |
794368469b9da63235a61097c2f2a86b86282194 | 134 | exs | Elixir | config/config.exs | rschef/ex_azure | 6663914280a693f3332c65c71afdef1255c813fb | [
"MIT"
] | 10 | 2016-07-07T08:55:15.000Z | 2022-01-19T01:47:34.000Z | config/config.exs | rschef/ex_azure | 6663914280a693f3332c65c71afdef1255c813fb | [
"MIT"
] | 5 | 2018-03-06T04:42:02.000Z | 2022-03-16T23:34:42.000Z | config/config.exs | rschef/ex_azure | 6663914280a693f3332c65c71afdef1255c813fb | [
"MIT"
] | 8 | 2016-07-21T16:20:39.000Z | 2021-07-16T02:14:57.000Z | use Mix.Config
config :ex_azure,
account: System.get_env("AZURE_ACCOUNT"),
access_key: System.get_env("AZURE_ACCESS_KEY")
| 22.333333 | 50 | 0.731343 |
79438f23df0671e6275573fe8cf48d7e52b96557 | 1,687 | ex | Elixir | lib/mix/tasks/ecto.rollback.ex | lancehalvorsen/ecto | af1f80f2907c62da8abb6d0e4bdac98269a80339 | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/ecto.rollback.ex | lancehalvorsen/ecto | af1f80f2907c62da8abb6d0e4bdac98269a80339 | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/ecto.rollback.ex | lancehalvorsen/ecto | af1f80f2907c62da8abb6d0e4bdac98269a80339 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Ecto.Rollback do
use Mix.Task
import Mix.Ecto
@shortdoc "Rollback migrations from a repo"
@moduledoc """
Reverts applied migrations in the given repository.
By default, migrations are expected at "priv/YOUR_REPO/migrations"
directory of the current application but it can be configured
by specify the `:priv` key under the repository configuration.
Runs the latest applied migration by default. To roll back to
to a version number, supply `--to version_number`.
To roll back a specific number of times, use `--step n`.
To undo all applied migrations, provide `--all`.
## Examples
mix ecto.rollback
mix ecto.rollback -r Custom.Repo
mix ecto.rollback -n 3
mix ecto.rollback --step 3
mix ecto.rollback -v 20080906120000
mix ecto.rollback --to 20080906120000
## Command line options
* `-r`, `--repo` - the repo to rollback (defaults to `YourApp.Repo`)
* `--all` - revert all applied migrations
* `--step` / `-n` - rever n number of applied migrations
* `--to` / `-v` - revert all migrations down to and including version
* `--no-start` - do not start applications
"""
@doc false
def run(args, migrator \\ &Ecto.Migrator.run/4) do
Mix.Task.run "app.start", args
repo = parse_repo(args)
{opts, _, _} = OptionParser.parse args,
switches: [all: :boolean, step: :integer, to: :integer, start: :boolean],
aliases: [n: :step, v: :to]
ensure_repo(repo)
ensure_started(repo)
unless opts[:to] || opts[:step] || opts[:all] do
opts = Keyword.put(opts, :step, 1)
end
migrator.(repo, migrations_path(repo), :down, opts)
end
end
| 29.086207 | 79 | 0.664493 |
794390a090ad5426a3ede005c67997a09d6218f7 | 1,535 | exs | Elixir | mix.exs | thewidgetsmith/grpc | f718a0d2c906cdfd56300368c3bbe5f1664457fb | [
"Apache-2.0"
] | null | null | null | mix.exs | thewidgetsmith/grpc | f718a0d2c906cdfd56300368c3bbe5f1664457fb | [
"Apache-2.0"
] | null | null | null | mix.exs | thewidgetsmith/grpc | f718a0d2c906cdfd56300368c3bbe5f1664457fb | [
"Apache-2.0"
] | null | null | null | defmodule GRPC.Mixfile do
use Mix.Project
@version "0.5.0-beta.1"
def project do
[
app: :grpc,
version: @version,
elixir: "~> 1.5",
elixirc_paths: elixirc_paths(Mix.env()),
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
deps: deps(),
package: package(),
description: "The Elixir implementation of gRPC",
docs: [
extras: ["README.md"],
main: "readme",
source_ref: "v#{@version}",
source_url: "https://github.com/elixir-grpc/grpc"
],
dialyzer: [
plt_add_apps: [:mix, :iex]
],
xref: [exclude: [IEx]]
]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
[extra_applications: [:logger]]
end
defp deps do
[
{:cowboy, "~> 2.9"},
{:cowlib, "~> 2.11", override: true},
{:gun, "~> 2.0.0-rc.2"},
{:jason, "~> 1.2", override: true},
{:protobuf, "~> 0.8"},
{:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false},
{:ex_doc, "~> 0.23", only: :dev},
{:inch_ex, "~> 2.0", only: [:dev, :test]}
]
end
defp package do
%{
maintainers: ["Bing Han"],
licenses: ["Apache 2"],
links: %{"GitHub" => "https://github.com/elixir-grpc/grpc"},
files: ~w(mix.exs README.md lib src config LICENSE .formatter.exs)
}
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
end
| 24.758065 | 72 | 0.538762 |
79439602cde989ddbff5b86eb3911370192bdde8 | 3,339 | ex | Elixir | apps/snitch_api/lib/snitch_api_web/controllers/line_item_controller.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 456 | 2018-09-20T02:40:59.000Z | 2022-03-07T08:53:48.000Z | apps/snitch_api/lib/snitch_api_web/controllers/line_item_controller.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 273 | 2018-09-19T06:43:43.000Z | 2021-08-07T12:58:26.000Z | apps/snitch_api/lib/snitch_api_web/controllers/line_item_controller.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 122 | 2018-09-26T16:32:46.000Z | 2022-03-13T11:44:19.000Z | defmodule SnitchApiWeb.LineItemController do
use SnitchApiWeb, :controller
alias Snitch.Data.Model.LineItem, as: LineItemModel
alias Snitch.Data.Model.Order, as: OrderModel
alias Snitch.Data.Schema.{LineItem, Variant, Product}
alias Snitch.Core.Tools.MultiTenancy.Repo
import Ecto.Query
alias SnitchApi.Order, as: OrderContext
plug(SnitchApiWeb.Plug.DataToAttributes)
plug(SnitchApiWeb.Plug.LoadUser)
action_fallback(SnitchApiWeb.FallbackController)
def create(conn, %{"product_id" => product_id} = params) do
%{selling_price: selling_price} = Repo.get(Product, product_id)
line_item = Map.put(params, "unit_price", selling_price)
with {:ok, line_item} <- OrderContext.add_to_cart(line_item) do
order = OrderContext.load_order(params["order_id"])
conn
|> put_status(200)
|> put_resp_header("location", line_item_path(conn, :show, line_item.id))
|> render(
SnitchApiWeb.OrderView,
"show.json-api",
data: order,
opts: [
include: "line_items,line_items.product"
]
)
end
end
def guest_line_item(conn, %{"order_id" => order_id} = params) do
with {:ok, line_item} <- add_line_item(params) do
order = OrderContext.load_order(line_item.order_id)
conn
|> put_status(200)
|> put_resp_header("location", line_item_path(conn, :show, line_item.id))
|> render(
SnitchApiWeb.OrderView,
"show.json-api",
data: order,
opts: [
include: "line_items,line_items.product"
]
)
end
end
def guest_line_item(conn, params) do
with {:ok, blank_order} <- OrderModel.create_guest_order(),
params <- Map.put(params, "order_id", blank_order.id),
{:ok, line_item} <- add_line_item(params) do
order = OrderContext.load_order(line_item.order_id)
conn
|> put_status(200)
|> put_resp_header("location", line_item_path(conn, :show, line_item.id))
|> render(
SnitchApiWeb.OrderView,
"show.json-api",
data: order,
opts: [
include: "line_items,line_items.product"
]
)
end
end
def add_line_item(params) do
%{selling_price: selling_price} = Repo.get(Product, params["product_id"])
line_item = Map.put(params, "unit_price", selling_price)
OrderContext.add_to_cart(line_item)
end
def delete(conn, %{"id" => line_item_id}) do
case OrderContext.delete_line_item(line_item_id) do
{:ok, _} ->
conn
|> put_status(204)
|> send_resp(:no_content, "")
end
end
def update(conn, %{"id" => id} = params) do
line_item = Repo.get(LineItem, id)
with {:ok, line_item} <- LineItemModel.update(line_item, params) do
line_item = line_item |> Repo.preload(:product)
conn
|> put_status(200)
|> put_resp_header("location", line_item_path(conn, :show, line_item))
|> render("show.json-api", data: line_item)
end
end
def show(conn, %{"id" => id}) do
case LineItemModel.get(id) do
{:error, :line_item_not_found} ->
conn
|> put_status(204)
|> render("show.json-api", data: [])
{:ok, line_item} ->
conn
|> put_status(200)
|> render("show.json-api", data: line_item)
end
end
end
| 28.538462 | 79 | 0.631626 |
7943b3d236764a19503c91e687f2f2e32ab42e84 | 2,954 | ex | Elixir | clients/analytics/lib/google_api/analytics/v3/api/user_deletion.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/analytics/lib/google_api/analytics/v3/api/user_deletion.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/analytics/lib/google_api/analytics/v3/api/user_deletion.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.Analytics.V3.Api.UserDeletion do
@moduledoc """
API calls for all endpoints tagged `UserDeletion`.
"""
alias GoogleApi.Analytics.V3.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Insert or update a user deletion requests.
## Parameters
- connection (GoogleApi.Analytics.V3.Connection): Connection to server
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (UserDeletionRequest):
## Returns
{:ok, %GoogleApi.Analytics.V3.Model.UserDeletionRequest{}} on success
{:error, info} on failure
"""
@spec analytics_user_deletion_user_deletion_request_upsert(Tesla.Env.client(), keyword()) ::
{:ok, GoogleApi.Analytics.V3.Model.UserDeletionRequest.t()} | {:error, Tesla.Env.t()}
def analytics_user_deletion_user_deletion_request_upsert(
connection,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/analytics/v3/userDeletion/userDeletionRequests:upsert")
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Analytics.V3.Model.UserDeletionRequest{}])
end
end
| 38.363636 | 170 | 0.705146 |
794402788547cd91c5fc84e0efe0c330265e2f3c | 907 | exs | Elixir | elixir/word-count/word_count.exs | macborowy/exercism | c5d45e074e81b946a82a340b2730e0d2732b7e0a | [
"MIT"
] | null | null | null | elixir/word-count/word_count.exs | macborowy/exercism | c5d45e074e81b946a82a340b2730e0d2732b7e0a | [
"MIT"
] | null | null | null | elixir/word-count/word_count.exs | macborowy/exercism | c5d45e074e81b946a82a340b2730e0d2732b7e0a | [
"MIT"
] | null | null | null | defmodule Words do
@doc """
Count the number of words in the sentence.
Words are compared case-insensitively.
"""
@doc """
All known separators
"""
@separators [" ", ",", ":", "_", "!", "&", "@", "$", "%", "^", "&"]
@spec count(String.t) :: map
def count(sentence) do
separators_pattern = :binary.compile_pattern(@separators)
# words are compared case-insensitively.
String.downcase(sentence) |>
# separating
String.split(separators_pattern) |>
# group_by words {word => [all occurences of that word]}
Enum.group_by(&(&1)) |>
# k is single word (key); v is list with all occurrences of that word
# first filter all elements that are empty string
# then map list to number of occurrences (length(v))
Enum.filter_map(fn({k, v}) -> k != "" end, fn({k, v}) -> {k, length(v)} end) |>
# mapping list into dict
Enum.into(%{})
end
end
| 29.258065 | 83 | 0.607497 |
7944364d216d5b745fb3e4d756e5ef8d034feb63 | 1,924 | ex | Elixir | lib/plug_url_redirector_utils.ex | jj1bdx/plug_url_redirector | 80f90020716eef77e9e5f6e6f7655474698557ae | [
"MIT"
] | 2 | 2017-01-21T14:07:43.000Z | 2018-01-09T08:25:20.000Z | lib/plug_url_redirector_utils.ex | jj1bdx/plug_url_redirector | 80f90020716eef77e9e5f6e6f7655474698557ae | [
"MIT"
] | null | null | null | lib/plug_url_redirector_utils.ex | jj1bdx/plug_url_redirector | 80f90020716eef77e9e5f6e6f7655474698557ae | [
"MIT"
] | null | null | null | defmodule PlugUrlRedirector.Utils do
import Plug.Conn
@moduledoc """
This module provides the utility functions as Plug functions.
The functions in this module is derived from the module
`Phoenix.Controller` in the Phoenix Framework,
duplicated under the MIT license.
"""
@doc """
Sends redirect response to the given url.
For security, `:to` only accepts paths. Use the `:external`
option to redirect to any URL.
## Examples
iex> redirect conn, to: "/login"
iex> redirect conn, external: "http://elixir-lang.org"
"""
def redirect(conn, opts) when is_list(opts) do
url = url(opts)
html = Plug.HTML.html_escape(url)
body = "<html><body>You are being <a href=\"#{html}\">redirected</a>.</body></html>"
conn
|> put_resp_header("location", url)
|> send_resp(conn.status || 302, "text/html", body)
end
defp url(opts) do
cond do
to = opts[:to] ->
case to do
"//" <> _ -> raise_invalid_url(to)
"/" <> _ -> to
_ -> raise_invalid_url(to)
end
external = opts[:external] ->
external
true ->
raise ArgumentError, "expected :to or :external option in redirect/2"
end
end
@spec raise_invalid_url(term()) :: no_return()
defp raise_invalid_url(url) do
raise ArgumentError, "the :to option in redirect expects a path but was #{inspect url}"
end
defp send_resp(conn, default_status, default_content_type, body) do
conn
|> ensure_resp_content_type(default_content_type)
|> send_resp(conn.status || default_status, body)
end
defp ensure_resp_content_type(%{resp_headers: resp_headers} = conn, content_type) do
if List.keyfind(resp_headers, "content-type", 0) do
conn
else
content_type = content_type <> "; charset=utf-8"
%{conn | resp_headers: [{"content-type", content_type}|resp_headers]}
end
end
end
| 27.485714 | 91 | 0.647089 |
794439825aa12ef4f460dd0f9602d74005d1b89e | 1,115 | exs | Elixir | config/config.exs | ewildgoose/elixir-sudoku | f0e9403b3d22ff960e74104a555dc145082db101 | [
"Apache-2.0"
] | 7 | 2016-07-07T15:52:18.000Z | 2021-09-14T07:34:13.000Z | config/config.exs | ewildgoose/elixir-sudoku | f0e9403b3d22ff960e74104a555dc145082db101 | [
"Apache-2.0"
] | null | null | null | config/config.exs | ewildgoose/elixir-sudoku | f0e9403b3d22ff960e74104a555dc145082db101 | [
"Apache-2.0"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :sudoku, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:sudoku, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 35.967742 | 73 | 0.750673 |
794480ef317f6811e6483741dcb761e2db7b8a2a | 2,525 | ex | Elixir | lib/rels.ex | kianmeng/microformats2-elixir | 5a48e7bc8bb82ca4b43986f8497a066b23baf6a4 | [
"MIT"
] | 18 | 2016-02-20T12:19:08.000Z | 2021-05-26T07:57:09.000Z | lib/rels.ex | kianmeng/microformats2-elixir | 5a48e7bc8bb82ca4b43986f8497a066b23baf6a4 | [
"MIT"
] | 17 | 2018-07-20T19:10:58.000Z | 2022-02-24T04:07:37.000Z | lib/rels.ex | kianmeng/microformats2-elixir | 5a48e7bc8bb82ca4b43986f8497a066b23baf6a4 | [
"MIT"
] | 7 | 2016-11-06T23:13:55.000Z | 2021-02-20T09:36:49.000Z | defmodule Microformats2.Rels do
@moduledoc false
import Microformats2.Helpers
def parse(doc, base_url, opts) do
link_rels =
Floki.find(doc, "[rel][href]")
|> Enum.filter(fn element ->
rel = Floki.attribute(element, "rel") |> List.first()
href = Floki.attribute(element, "href") |> List.first()
String.trim(to_string(rel)) != "" and String.trim(to_string(href)) != ""
end)
|> Enum.reduce(%{normalized_key("rels", opts) => %{}, normalized_key("rel-urls", opts) => %{}}, fn element, acc ->
rel = attr_list(element, "rel")
url = Floki.attribute(element, "href") |> List.first() |> abs_uri(base_url, doc)
acc
|> save_urls_by_rels(rel, url, opts)
|> save_rels_by_urls(rel, url, opts)
|> save_attributes(element, url, opts)
end)
link_rels
end
defp save_urls_by_rels(map, rel, url, opts) do
Enum.reduce(rel, map, fn rel, nmap ->
key = normalized_key(rel, opts)
if nmap[normalized_key("rels", opts)][key] == nil do
put_in(nmap, [normalized_key("rels", opts), key], [url])
else
put_in(nmap, [normalized_key("rels", opts), key], Enum.uniq(nmap[normalized_key("rels", opts)][key] ++ [url]))
end
end)
end
defp save_rels_by_urls(map, rel, url, opts) do
if map[normalized_key("rel-urls", opts)][url] == nil do
put_in(map, [normalized_key("rel-urls", opts), url], %{normalized_key("rels", opts) => rel})
else
put_in(
map,
[normalized_key("rel-urls", opts), url, normalized_key("rels", opts)],
Enum.uniq(map[normalized_key("rel-urls", opts)][url][normalized_key("rels", opts)] ++ rel)
)
end
end
defp save_text(map, element, url, opts) do
text = Floki.text(element)
if String.trim(to_string(text)) == "" or
map[normalized_key("rel-urls", opts)][url][normalized_key("text", opts)] != nil,
do: map,
else: put_in(map, [normalized_key("rel-urls", opts), url, normalized_key("text", opts)], text)
end
defp save_attributes(map, element, url, opts) do
Enum.reduce(["hreflang", "media", "title", "type"], save_text(map, element, url, opts), fn att, nmap ->
val = Floki.attribute(element, att) |> List.first()
key = normalized_key(att, opts)
if String.trim(to_string(val)) == "" or nmap[normalized_key("rel-urls", opts)][url][key] != nil,
do: nmap,
else: put_in(nmap, [normalized_key("rel-urls", opts), url, key], val)
end)
end
end
| 35.56338 | 120 | 0.605941 |
79449496c14ac6bf8137e7141d348d39e355e83d | 3,043 | ex | Elixir | clients/os_config/lib/google_api/os_config/v1/model/execute_patch_job_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/os_config/lib/google_api/os_config/v1/model/execute_patch_job_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/os_config/lib/google_api/os_config/v1/model/execute_patch_job_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.OSConfig.V1.Model.ExecutePatchJobRequest do
@moduledoc """
A request message to initiate patching across Compute Engine instances.
## Attributes
* `description` (*type:* `String.t`, *default:* `nil`) - Description of the patch job. Length of the description is limited to 1024 characters.
* `displayName` (*type:* `String.t`, *default:* `nil`) - Display name for this patch job. This does not have to be unique.
* `dryRun` (*type:* `boolean()`, *default:* `nil`) - If this patch is a dry-run only, instances are contacted but will do nothing.
* `duration` (*type:* `String.t`, *default:* `nil`) - Duration of the patch job. After the duration ends, the patch job times out.
* `instanceFilter` (*type:* `GoogleApi.OSConfig.V1.Model.PatchInstanceFilter.t`, *default:* `nil`) - Required. Instances to patch, either explicitly or filtered by some criteria such as zone or labels.
* `patchConfig` (*type:* `GoogleApi.OSConfig.V1.Model.PatchConfig.t`, *default:* `nil`) - Patch configuration being applied. If omitted, instances are patched using the default configurations.
* `rollout` (*type:* `GoogleApi.OSConfig.V1.Model.PatchRollout.t`, *default:* `nil`) - Rollout strategy of the patch job.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:description => String.t(),
:displayName => String.t(),
:dryRun => boolean(),
:duration => String.t(),
:instanceFilter => GoogleApi.OSConfig.V1.Model.PatchInstanceFilter.t(),
:patchConfig => GoogleApi.OSConfig.V1.Model.PatchConfig.t(),
:rollout => GoogleApi.OSConfig.V1.Model.PatchRollout.t()
}
field(:description)
field(:displayName)
field(:dryRun)
field(:duration)
field(:instanceFilter, as: GoogleApi.OSConfig.V1.Model.PatchInstanceFilter)
field(:patchConfig, as: GoogleApi.OSConfig.V1.Model.PatchConfig)
field(:rollout, as: GoogleApi.OSConfig.V1.Model.PatchRollout)
end
defimpl Poison.Decoder, for: GoogleApi.OSConfig.V1.Model.ExecutePatchJobRequest do
def decode(value, options) do
GoogleApi.OSConfig.V1.Model.ExecutePatchJobRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.OSConfig.V1.Model.ExecutePatchJobRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 46.815385 | 205 | 0.719685 |
7944bd7c685772d106f7264dfc6b439aea8d561b | 617 | exs | Elixir | apps/idp/priv/repo/migrations/20190919204431_create_users_table.exs | lbrty/idp-backend | 81d5f10ef6177a1e678b994331c5a09abbdca8d6 | [
"Apache-2.0"
] | null | null | null | apps/idp/priv/repo/migrations/20190919204431_create_users_table.exs | lbrty/idp-backend | 81d5f10ef6177a1e678b994331c5a09abbdca8d6 | [
"Apache-2.0"
] | null | null | null | apps/idp/priv/repo/migrations/20190919204431_create_users_table.exs | lbrty/idp-backend | 81d5f10ef6177a1e678b994331c5a09abbdca8d6 | [
"Apache-2.0"
] | null | null | null | defmodule Idp.Repo.Migrations.CreateUsersTable do
use Ecto.Migration
def change do
create table(:users, primary_key: false) do
add :id, :uuid, primary_key: true
add :email, :string
add :avatar, :string
add :full_name, :string
add :password_hash, :string
add :is_active, :boolean, default: false, null: false
add :is_admin, :boolean, default: false, null: false
add :is_consultant, :boolean, default: false, null: false
add :is_guest, :boolean, default: false, null: false
timestamps()
end
create unique_index(:users, [:email])
end
end
| 26.826087 | 63 | 0.659643 |
7944ca9e265cf7a1df23cb6442cd2796f39ffc3a | 211 | exs | Elixir | web_finngen_r8/priv/repo/migrations/20201207155344_alter_phenocodes__remove_h2.exs | vincent-octo/risteys | 5bb1e70b78988770048b91b42fad025faf98d84a | [
"MIT"
] | null | null | null | web_finngen_r8/priv/repo/migrations/20201207155344_alter_phenocodes__remove_h2.exs | vincent-octo/risteys | 5bb1e70b78988770048b91b42fad025faf98d84a | [
"MIT"
] | null | null | null | web_finngen_r8/priv/repo/migrations/20201207155344_alter_phenocodes__remove_h2.exs | vincent-octo/risteys | 5bb1e70b78988770048b91b42fad025faf98d84a | [
"MIT"
] | null | null | null | defmodule Risteys.Repo.Migrations.AlterPhenocodeRemoveH2 do
use Ecto.Migration
def change do
alter table(:phenocodes) do
remove :h2_liab, :float
remove :h2_liab_se, :float
end
end
end
| 19.181818 | 59 | 0.71564 |
7944d6e2423a8efd95c310e0f504a25e9a79f982 | 120 | ex | Elixir | testData/org/elixir_lang/annotator/module_attribute/issue_694.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 1,668 | 2015-01-03T05:54:27.000Z | 2022-03-25T08:01:20.000Z | testData/org/elixir_lang/annotator/module_attribute/issue_694.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 2,018 | 2015-01-01T22:43:39.000Z | 2022-03-31T20:13:08.000Z | testData/org/elixir_lang/annotator/module_attribute/issue_694.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | @typedoc "Result returned from Map functions"
@type result :: {:ok, term} | {:error, term}
@type success(T) :: {:ok, T}
| 30 | 45 | 0.641667 |
7944de868f0d3a75a95daf1c119b9298caec407d | 2,942 | ex | Elixir | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/billing.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/billing.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/billing.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.ServiceConsumerManagement.V1.Model.Billing do
@moduledoc """
Billing related configuration of the service. The following example shows how to configure monitored resources and metrics for billing, `consumer_destinations` is the only supported destination and the monitored resources need at least one label key `cloud.googleapis.com/location` to indicate the location of the billing usage, using different monitored resources between monitoring and billing is recommended so they can be evolved independently: monitored_resources: - type: library.googleapis.com/billing_branch labels: - key: cloud.googleapis.com/location description: | Predefined label to support billing location restriction. - key: city description: | Custom label to define the city where the library branch is located in. - key: name description: Custom label to define the name of the library branch. metrics: - name: library.googleapis.com/book/borrowed_count metric_kind: DELTA value_type: INT64 unit: "1" billing: consumer_destinations: - monitored_resource: library.googleapis.com/billing_branch metrics: - library.googleapis.com/book/borrowed_count
## Attributes
* `consumerDestinations` (*type:* `list(GoogleApi.ServiceConsumerManagement.V1.Model.BillingDestination.t)`, *default:* `nil`) - Billing configurations for sending metrics to the consumer project. There can be multiple consumer destinations per service, each one must have a different monitored resource type. A metric can be used in at most one consumer destination.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:consumerDestinations =>
list(GoogleApi.ServiceConsumerManagement.V1.Model.BillingDestination.t()) | nil
}
field(:consumerDestinations,
as: GoogleApi.ServiceConsumerManagement.V1.Model.BillingDestination,
type: :list
)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.Billing do
def decode(value, options) do
GoogleApi.ServiceConsumerManagement.V1.Model.Billing.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.Billing do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 57.686275 | 1,067 | 0.783821 |
7944e9b7b9113d8a8b7bb46d94a1089ac014c772 | 281 | exs | Elixir | test/lib/spender_web/controllers/page_controller_test.exs | LittleKidogo/Budgetinization | eae6dd62208ec7fb43c8c212f40611f8635205d5 | [
"MIT"
] | 2 | 2018-02-27T06:29:59.000Z | 2018-06-09T16:53:49.000Z | test/lib/spender_web/controllers/page_controller_test.exs | LittleKidogo/Budgetinization | eae6dd62208ec7fb43c8c212f40611f8635205d5 | [
"MIT"
] | 94 | 2018-02-22T06:03:19.000Z | 2018-06-28T14:30:31.000Z | test/lib/spender_web/controllers/page_controller_test.exs | LittleKidogo/Budgetinization | eae6dd62208ec7fb43c8c212f40611f8635205d5 | [
"MIT"
] | 1 | 2020-03-04T19:41:06.000Z | 2020-03-04T19:41:06.000Z | defmodule SpenderWeb.PageControllerTest do
use SpenderWeb.ApiCase
describe "Page Controller" do
test "renders the homepage on the root url", %{conn: conn} do
conn = get conn, "/"
assert html_response(conn, 200) =~ "Welcome to the Mula API."
end
end
end
| 25.545455 | 67 | 0.683274 |
7944f0a01c71379adf9e7a4f8b11963ce057b312 | 1,371 | ex | Elixir | clients/tool_results/lib/google_api/tool_results/v1beta3/model/step_dimension_value_entry.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/tool_results/lib/google_api/tool_results/v1beta3/model/step_dimension_value_entry.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/tool_results/lib/google_api/tool_results/v1beta3/model/step_dimension_value_entry.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.ToolResults.V1beta3.Model.StepDimensionValueEntry do
@moduledoc """
## Attributes
- key (String): Defaults to: `null`.
- value (String): Defaults to: `null`.
"""
defstruct [
:"key",
:"value"
]
end
defimpl Poison.Decoder, for: GoogleApi.ToolResults.V1beta3.Model.StepDimensionValueEntry do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.ToolResults.V1beta3.Model.StepDimensionValueEntry do
def encode(value, options) do
GoogleApi.ToolResults.V1beta3.Deserializer.serialize_non_nil(value, options)
end
end
| 28.5625 | 91 | 0.747629 |
7944f6cfc1f16471b096c43205fdd296ba327242 | 7,001 | ex | Elixir | apps/snitch_core/lib/core/domain/tax.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 456 | 2018-09-20T02:40:59.000Z | 2022-03-07T08:53:48.000Z | apps/snitch_core/lib/core/domain/tax.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 273 | 2018-09-19T06:43:43.000Z | 2021-08-07T12:58:26.000Z | apps/snitch_core/lib/core/domain/tax.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 122 | 2018-09-26T16:32:46.000Z | 2022-03-13T11:44:19.000Z | defmodule Snitch.Domain.Tax do
@moduledoc """
Exposes functions related to Tax Calculation for
product and shipping.
"""
alias Snitch.Core.Tools.MultiTenancy.Repo
alias Snitch.Domain.Calculator.DefaultTaxCalculator, as: TaxCalculator
alias Snitch.Data.Schema.{Order, StockLocation, TaxZone, StateZoneMember, CountryZoneMember}
alias Snitch.Data.Model.{TaxConfig, Product}
alias Snitch.Data.Model.TaxZone, as: TaxZoneModel
import Ecto.Query
@doc """
Returns a map with original price and the tax.
```
%{
original_price: price,
tax: tax_amount
}
```
Calculates tax for a package item or shipping cost associated
with a package.
"""
@spec calculate(atom, any, Order.t(), StockLocation.t()) :: map
def calculate(:package_item, line_item, order, stock_location) do
line_item = Repo.preload(line_item, :product)
tax_class_id = Product.get_tax_class_id(line_item.product)
tax_config = TaxConfig.get_default()
tax_address = get_tax_address(order, stock_location, tax_config)
tax_zone = get_tax_zone!(tax_address)
calculate_item_tax(tax_zone, line_item, tax_config, tax_class_id)
end
def calculate(:shipping, shipping_cost, order, stock_location) do
tax_config = TaxConfig.get_default()
tax_address = get_tax_address(order, stock_location, tax_config)
tax_zone = get_tax_zone!(tax_address)
calculate_shipping_tax(tax_zone, shipping_cost, tax_config)
end
################# package item tax calulation related helpers ###############
defp calculate_item_tax(nil, line_item, tax_config, tax_class_id) do
tax_zone = TaxZoneModel.get_default()
calculate_item_tax(tax_zone, line_item, tax_config, tax_class_id)
end
defp calculate_item_tax(tax_zone, line_item, tax_config, tax_class_id) do
with tax_rates when tax_rates != [] <- tax_zone.tax_rates do
amount_with_taxes =
Enum.map(tax_rates, fn tax_rate ->
tax_by_rate_and_class(tax_rate, tax_class_id, line_item.unit_price, tax_config)
end)
amount_with_tax = List.first(amount_with_taxes)
total_tax =
amount_with_taxes
|> Enum.reduce(Money.new!(line_item.unit_price.currency, 0), fn %{tax: tax}, acc ->
Money.add!(acc, tax)
end)
|> Money.mult!(line_item.quantity)
%{original_amount: amount_with_tax.amount, tax: total_tax}
else
[] ->
%{
original_amount: line_item.unit_price,
tax: Money.new!(line_item.unit_price.currency, 0)
}
end
end
######################## shipping tax helpers ###############################
# If supplied tax_zone is nil then default tax zone is used for
# calculation
defp calculate_shipping_tax(_tax_zone = nil, shipping_cost, tax_config) do
tax_zone = TaxZoneModel.get_default()
calculate_shipping_tax(tax_zone, shipping_cost, tax_config)
end
defp calculate_shipping_tax(tax_zone, shipping_cost, tax_config) do
with tax_rates when tax_rates != [] <- tax_zone.tax_rates do
amount_with_taxes =
Enum.map(tax_rates, fn tax_rate ->
tax_by_rate_and_class(tax_rate, tax_config.shipping_tax_id, shipping_cost, tax_config)
end)
total_tax =
Enum.reduce(amount_with_taxes, Money.new!(shipping_cost.currency, 0), fn %{tax: tax},
acc ->
Money.add!(acc, tax)
end)
amount_with_tax = List.first(amount_with_taxes)
%{original_amount: amount_with_tax.amount, tax: total_tax}
else
[] ->
%{original_amount: shipping_cost, tax: Money.new!(shipping_cost.currency, 0)}
end
end
################# tax calculation helpers ###########################
defp tax_by_rate_and_class(tax_rate, tax_class_id, price, tax_config) do
tax_value =
Enum.find(tax_rate.tax_rate_class_values, fn value ->
value.tax_class.id == tax_class_id
end)
compute_tax(tax_value, price, tax_config)
end
defp compute_tax(nil, price, _tax_config) do
%{amount: price, tax: Money.new!(price.currency, 0)}
end
defp compute_tax(tax_value, price, tax_config) do
TaxCalculator.compute(tax_value.percent_amount, price, tax_config.included_in_price?)
end
################### tax zone related helpers ######################
# Returns tax zone for the supplied country id.
defp get_tax_zone!(%{state_id: nil, country_id: country_id}) do
query =
from(tz in TaxZone,
join: c_z_member in CountryZoneMember,
on: tz.zone_id == c_z_member.zone_id,
where: c_z_member.country_id == ^country_id and tz.is_active? == true,
select: %TaxZone{id: tz.id, name: tz.name, zone_id: tz.zone_id}
)
tax_zone_query_result(query)
end
# Tries to find a tax zone by the state_id if none are found then tries
# to find using the country_id.
defp get_tax_zone!(%{state_id: state_id, country_id: country_id}) do
query =
from(tz in TaxZone,
join: s_z_member in StateZoneMember,
on: tz.zone_id == s_z_member.zone_id,
where: s_z_member.state_id == ^state_id,
select: %TaxZone{id: tz.id, name: tz.name}
)
tax_zone_query_result(query) || get_tax_zone!(%{state_id: nil, country_id: country_id})
end
defp tax_zone_query_result(query) do
case Repo.all(query) do
[] ->
nil
[tax_zone] ->
Repo.preload(tax_zone, tax_rates: [tax_rate_class_values: :tax_class])
end
end
################ address related helpers #########################
# Checks for address type set in tax config, and tries to find if, the address
# set is present in the order or not. In case, order does not have the address
# set, the default address set in tax config is returned.
# Returns in the format {state_id: data, country_id: data}, returns
# nil for values if respective id's are not set.
defp get_tax_address(order, stock_location, tax_config) do
get_address(tax_config.calculation_address_type, order, stock_location, tax_config)
end
defp get_address(:shipping_address, order, _stock_location, tax_config) do
{state_id, country_id} =
if order.shipping_address do
{order.shipping_address.state_id, order.shipping_address.country_id}
else
{tax_config.default_state_id, tax_config.default_country_id}
end
%{state_id: state_id, country_id: country_id}
end
defp get_address(:billing_address, order, _stock_location, tax_config) do
{state_id, country_id} =
if order.billing_address do
{order.billing_address.state_id, order.billing_address.country_id}
else
{tax_config.default_state_id, tax_config.default_country_id}
end
%{state_id: state_id, country_id: country_id}
end
defp get_address(:store_address, _order, stock_location, _tax_config) do
%{state_id: stock_location.state_id, country_id: stock_location.country_id}
end
end
| 34.15122 | 96 | 0.677617 |
79451f86303024d071bf4ed0be2b09b977b774fd | 946 | ex | Elixir | clients/keto/elixir/lib/keto/model/delete_relation_tuples_internal_server_error_body.ex | ory/sdk-generator | 958314d130922ad6f20f439b5230141a832231a5 | [
"Apache-2.0"
] | null | null | null | clients/keto/elixir/lib/keto/model/delete_relation_tuples_internal_server_error_body.ex | ory/sdk-generator | 958314d130922ad6f20f439b5230141a832231a5 | [
"Apache-2.0"
] | null | null | null | clients/keto/elixir/lib/keto/model/delete_relation_tuples_internal_server_error_body.ex | ory/sdk-generator | 958314d130922ad6f20f439b5230141a832231a5 | [
"Apache-2.0"
] | null | null | null | # NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
# https://openapi-generator.tech
# Do not edit the class manually.
defmodule Keto.Model.DeleteRelationTuplesInternalServerErrorBody do
@moduledoc """
DeleteRelationTuplesInternalServerErrorBody DeleteRelationTuplesInternalServerErrorBody DeleteRelationTuplesInternalServerErrorBody delete relation tuples internal server error body
"""
@derive [Poison.Encoder]
defstruct [
:"code",
:"details",
:"message",
:"reason",
:"request",
:"status"
]
@type t :: %__MODULE__{
:"code" => integer() | nil,
:"details" => [map()] | nil,
:"message" => String.t | nil,
:"reason" => String.t | nil,
:"request" => String.t | nil,
:"status" => String.t | nil
}
end
defimpl Poison.Decoder, for: Keto.Model.DeleteRelationTuplesInternalServerErrorBody do
def decode(value, _options) do
value
end
end
| 26.277778 | 183 | 0.690275 |
7945250186b8cd7c7f21526c971103c095925fd0 | 2,517 | ex | Elixir | clients/analytics_reporting/lib/google_api/analytics_reporting/v4/model/segment_dimension_filter.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/analytics_reporting/lib/google_api/analytics_reporting/v4/model/segment_dimension_filter.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/analytics_reporting/lib/google_api/analytics_reporting/v4/model/segment_dimension_filter.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.AnalyticsReporting.V4.Model.SegmentDimensionFilter do
@moduledoc """
Dimension filter specifies the filtering options on a dimension.
## Attributes
* `caseSensitive` (*type:* `boolean()`, *default:* `nil`) - Should the match be case sensitive, ignored for `IN_LIST` operator.
* `dimensionName` (*type:* `String.t`, *default:* `nil`) - Name of the dimension for which the filter is being applied.
* `expressions` (*type:* `list(String.t)`, *default:* `nil`) - The list of expressions, only the first element is used for all operators
* `maxComparisonValue` (*type:* `String.t`, *default:* `nil`) - Maximum comparison values for `BETWEEN` match type.
* `minComparisonValue` (*type:* `String.t`, *default:* `nil`) - Minimum comparison values for `BETWEEN` match type.
* `operator` (*type:* `String.t`, *default:* `nil`) - The operator to use to match the dimension with the expressions.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:caseSensitive => boolean(),
:dimensionName => String.t(),
:expressions => list(String.t()),
:maxComparisonValue => String.t(),
:minComparisonValue => String.t(),
:operator => String.t()
}
field(:caseSensitive)
field(:dimensionName)
field(:expressions, type: :list)
field(:maxComparisonValue)
field(:minComparisonValue)
field(:operator)
end
defimpl Poison.Decoder, for: GoogleApi.AnalyticsReporting.V4.Model.SegmentDimensionFilter do
def decode(value, options) do
GoogleApi.AnalyticsReporting.V4.Model.SegmentDimensionFilter.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AnalyticsReporting.V4.Model.SegmentDimensionFilter do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.596774 | 140 | 0.712753 |
794526bbf2b8f02558a5ea6c9f77a606d4281d3c | 1,303 | ex | Elixir | web/views/tag_view.ex | allen-garvey/artour | fce27b234d11a3e434c897b5fa3178b7c126245f | [
"MIT"
] | 4 | 2019-10-04T16:11:15.000Z | 2021-08-18T21:00:13.000Z | apps/artour/web/views/tag_view.ex | allen-garvey/phoenix-umbrella | 1d444bbd62a5e7b5f51d317ce2be71ee994125d5 | [
"MIT"
] | 5 | 2020-03-16T23:52:25.000Z | 2021-09-03T16:52:17.000Z | apps/artour/web/views/tag_view.ex | allen-garvey/phoenix-umbrella | 1d444bbd62a5e7b5f51d317ce2be71ee994125d5 | [
"MIT"
] | null | null | null | defmodule Artour.TagView do
use Artour.Web, :view
@doc """
How single tag instance should be represented in views
"""
def display_name(tag) do
tag.name
end
@doc """
Renders page to create new tag
"""
def render("new.html", assigns) do
assigns = Map.merge(assigns, %{action: tag_path(assigns[:conn], :create),
heading: Artour.SharedView.form_heading("tag", :new)})
render "form_page.html", assigns
end
@doc """
Renders page to edit tag
"""
def render("edit.html", assigns) do
assigns = Map.merge(assigns, %{action: tag_path(assigns[:conn], :update, assigns[:tag]),
heading: Artour.SharedView.form_heading(display_name(assigns[:tag]), :edit),
show_delete: true})
render "form_page.html", assigns
end
@doc """
Used on index and show pages - returns list of attribute names in the
same order as the attribute_values function
"""
def attribute_names() do
["Name", "Slug"]
end
@doc """
Used on index and show pages - takes tag instance and returns list of
formatted values
"""
def attribute_values(conn, tag) do
[
tag.name,
link(tag.slug, to: Artour.PublicTagView.show_path(conn, tag))
]
end
end
| 25.54902 | 111 | 0.614735 |
794541479cb115c55e817bb750262bfee4f5a1a4 | 2,008 | exs | Elixir | test/passes/translate/forms/map_test.exs | workingjubilee/elixirscript | 2021870d6328a683bdb7c3c9f1a5797cfd08b0fc | [
"MIT"
] | null | null | null | test/passes/translate/forms/map_test.exs | workingjubilee/elixirscript | 2021870d6328a683bdb7c3c9f1a5797cfd08b0fc | [
"MIT"
] | null | null | null | test/passes/translate/forms/map_test.exs | workingjubilee/elixirscript | 2021870d6328a683bdb7c3c9f1a5797cfd08b0fc | [
"MIT"
] | null | null | null | defmodule ElixirScript.Translate.Forms.Map.Test do
use ExUnit.Case
alias ElixirScript.Translate.Form
alias ESTree.Tools.Builder, as: J
use ExUnitProperties
setup_all do
{:ok, pid} = ElixirScript.State.start_link(%{})
state = %{
pid: pid
}
[state: state]
end
property "maps convert to Map objects", %{state: state} do
check all tuple <- StreamData.tuple({
StreamData.one_of([
StreamData.integer(),
StreamData.boolean(),
StreamData.binary(),
StreamData.uniform_float()
]),
StreamData.binary()
}) do
properties = [tuple]
ast = {:%{}, [], properties}
{js_ast, _} = Form.compile(ast, state)
assert js_ast == J.new_expression(
J.identifier("Map"),
[
J.array_expression([
J.array_expression([
J.literal(elem(tuple, 0)),
J.literal(elem(tuple, 1)),
])
])
]
)
end
end
property "maps update converts to new Map objects using old version", %{state: state} do
check all key <- StreamData.binary(),
old_value <- StreamData.integer(),
new_value <- StreamData.integer() do
properties = [{key, old_value}]
map_ast = {:%{}, [], properties}
new_values = [{key, new_value}]
ast = {:%{}, [], [{:|, [], [map_ast, new_values]}]}
map_js_ast = J.new_expression(
J.identifier("Map"),
[
J.array_expression([
J.array_expression([
J.literal(key),
J.literal(old_value),
])
])
]
)
{js_ast, _} = Form.compile(ast, state)
assert js_ast == J.new_expression(
J.identifier("Map"),
[
J.array_expression(
[J.spread_element(map_js_ast)] ++ [J.array_expression([
J.literal(key),
J.literal(new_value)
])]
)
]
)
end
end
end
| 23.623529 | 90 | 0.518924 |
79456f0dd5b90ad987efc623cd038b62069b634f | 1,601 | ex | Elixir | lib/openflow/utils.ex | shun159/tres | 1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f | [
"Beerware"
] | 5 | 2019-05-25T02:25:13.000Z | 2020-10-06T17:00:03.000Z | lib/openflow/utils.ex | shun159/tres | 1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f | [
"Beerware"
] | 5 | 2018-03-29T14:42:10.000Z | 2019-11-19T07:03:09.000Z | lib/openflow/utils.ex | shun159/tres | 1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f | [
"Beerware"
] | 1 | 2019-03-30T20:48:27.000Z | 2019-03-30T20:48:27.000Z | defmodule Openflow.Utils do
import Bitwise
def int_to_flags(acc, int, [{type, flagint} | rest]) when (int &&& flagint) == flagint do
int_to_flags([type | acc], int, rest)
end
def int_to_flags(acc, int, [_h | rest]) do
int_to_flags(acc, int, rest)
end
def int_to_flags(acc, _int, []), do: Enum.reverse(acc)
def flags_to_int(acc, [], _enum), do: acc
def flags_to_int(acc0, [flag | rest], enum) do
acc = acc0 ||| Keyword.get(enum, flag, 0)
flags_to_int(acc, rest, enum)
end
def to_hex_string(binary), do: datapath_id(binary)
def padding(length, padding) do
case padding - rem(length, padding) do
^padding -> 0
pad_len -> pad_len
end
end
def pad_length(length, width) do
rem(width - rem(length, width), width)
end
def decode_string(binary) do
String.trim_trailing(binary, <<0>>)
end
def encode_string(binary, length) do
String.pad_trailing(binary, length, <<0>>)
end
def get_enum(int, type) when is_integer(int) do
try do
Openflow.Enums.to_atom(int, type)
catch
:bad_enum -> int
end
end
def get_enum(int, type) do
try do
Openflow.Enums.to_int(int, type)
catch
:bad_enum -> int
end
end
# private functions
defp datapath_id(binary) do
binary
|> split_to_hex_string
|> Enum.join("")
|> String.downcase()
end
defp split_to_hex_string(binary) do
for <<int <- binary>>, do: integer_to_hex(int)
end
defp integer_to_hex(int) do
case Integer.to_string(int, 16) do
<<d>> -> <<48, d>>
dd -> dd
end
end
end
| 20.525641 | 91 | 0.63148 |
7945782d73b9ef5a217eb54666f5bd1fa1f8e764 | 1,832 | ex | Elixir | lib/koans/10_structs.ex | Kapeusz/Koans | fd9439420633a3e5f6f5d6343ad9bb0eb65d55d4 | [
"MIT"
] | null | null | null | lib/koans/10_structs.ex | Kapeusz/Koans | fd9439420633a3e5f6f5d6343ad9bb0eb65d55d4 | [
"MIT"
] | null | null | null | lib/koans/10_structs.ex | Kapeusz/Koans | fd9439420633a3e5f6f5d6343ad9bb0eb65d55d4 | [
"MIT"
] | null | null | null | defmodule Structs do
use Koans
@intro "Structs"
defmodule Person do
defstruct [:name, :age]
end
koan "Structs are defined and named after a module" do
person = %Person{}
assert person == %Person{}
end
koan "Unless previously defined, fields begin as nil" do
nobody = %Person{}
assert nobody.age == nil
end
koan "You can pass initial values to structs" do
joe = %Person{name: "Joe", age: 23}
assert joe.name == "Joe"
end
koan "Update fields with the cons '|' operator" do
joe = %Person{name: "Joe", age: 23}
older = %{joe | age: joe.age + 10}
assert older.age == 33
end
koan "Struct can be treated like maps" do
silvia = %Person{age: 22, name: "Silvia"}
assert Map.fetch(silvia, :age) == {:ok, 22}
end
defmodule Plane do
defstruct passengers: 0, maker: :boeing
end
defmodule Airline do
defstruct plane: %Plane{}, name: "Southwest"
end
koan "Use the put_in macro to replace a nested value" do
airline = %Airline{}
assert put_in(airline.plane.maker, :airbus) == %Structs.Airline{
name: "Southwest",
plane: %Structs.Plane{maker: :airbus, passengers: 0}
}
end
koan "Use the update_in macro to modify a nested value" do
airline = %Airline{plane: %Plane{passengers: 200}}
assert update_in(airline.plane.passengers, fn x -> x + 2 end) == %Structs.Airline{
name: "Southwest",
plane: %Structs.Plane{maker: :boeing, passengers: 202}
}
end
koan "Use the put_in macro with atoms to replace a nested value in a non-struct" do
airline = %{plane: %{maker: :boeing}, name: "Southwest"}
assert put_in(airline[:plane][:maker], :cessna) == %{
name: "Southwest",
plane: %{maker: :cessna}
}
end
end
| 25.444444 | 86 | 0.614629 |
79457ecf001b887ad0a4a11d586f905e580a8836 | 3,701 | ex | Elixir | clients/display_video/lib/google_api/display_video/v1/model/integral_ad_science.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/display_video/lib/google_api/display_video/v1/model/integral_ad_science.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/display_video/lib/google_api/display_video/v1/model/integral_ad_science.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.DisplayVideo.V1.Model.IntegralAdScience do
@moduledoc """
Details of Integral Ad Science settings.
## Attributes
* `displayViewability` (*type:* `String.t`, *default:* `nil`) - Display Viewability section (applicable to display line items only).
* `excludeUnrateable` (*type:* `boolean()`, *default:* `nil`) - Brand Safety - **Unrateable**.
* `excludedAdFraudRisk` (*type:* `String.t`, *default:* `nil`) - Ad Fraud settings.
* `excludedAdultRisk` (*type:* `String.t`, *default:* `nil`) - Brand Safety - **Adult content**.
* `excludedAlcoholRisk` (*type:* `String.t`, *default:* `nil`) - Brand Safety - **Alcohol**.
* `excludedDrugsRisk` (*type:* `String.t`, *default:* `nil`) - Brand Safety - **Drugs**.
* `excludedGamblingRisk` (*type:* `String.t`, *default:* `nil`) - Brand Safety - **Gambling**.
* `excludedHateSpeechRisk` (*type:* `String.t`, *default:* `nil`) - Brand Safety - **Hate speech**.
* `excludedIllegalDownloadsRisk` (*type:* `String.t`, *default:* `nil`) - Brand Safety - **Illegal downloads**.
* `excludedOffensiveLanguageRisk` (*type:* `String.t`, *default:* `nil`) - Brand Safety - **Offensive language**.
* `excludedViolenceRisk` (*type:* `String.t`, *default:* `nil`) - Brand Safety - **Violence**.
* `traqScoreOption` (*type:* `String.t`, *default:* `nil`) - True advertising quality (applicable to Display line items only).
* `videoViewability` (*type:* `String.t`, *default:* `nil`) - Video Viewability Section (applicable to video line items only).
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:displayViewability => String.t(),
:excludeUnrateable => boolean(),
:excludedAdFraudRisk => String.t(),
:excludedAdultRisk => String.t(),
:excludedAlcoholRisk => String.t(),
:excludedDrugsRisk => String.t(),
:excludedGamblingRisk => String.t(),
:excludedHateSpeechRisk => String.t(),
:excludedIllegalDownloadsRisk => String.t(),
:excludedOffensiveLanguageRisk => String.t(),
:excludedViolenceRisk => String.t(),
:traqScoreOption => String.t(),
:videoViewability => String.t()
}
field(:displayViewability)
field(:excludeUnrateable)
field(:excludedAdFraudRisk)
field(:excludedAdultRisk)
field(:excludedAlcoholRisk)
field(:excludedDrugsRisk)
field(:excludedGamblingRisk)
field(:excludedHateSpeechRisk)
field(:excludedIllegalDownloadsRisk)
field(:excludedOffensiveLanguageRisk)
field(:excludedViolenceRisk)
field(:traqScoreOption)
field(:videoViewability)
end
defimpl Poison.Decoder, for: GoogleApi.DisplayVideo.V1.Model.IntegralAdScience do
def decode(value, options) do
GoogleApi.DisplayVideo.V1.Model.IntegralAdScience.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DisplayVideo.V1.Model.IntegralAdScience do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.590361 | 136 | 0.687112 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.