root
add data
d9f7ff9
Invalid JSON: Unexpected non-whitespace character after JSONat line 2, column 1
{"size":7444,"ext":"ex","lang":"Elixir","max_stars_count":12.0,"content":"#\n# This file is part of Astarte.\n#\n# Copyright 2017 Ispirata Srl\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\ndefmodule Astarte.VMQ.Plugin do\n @moduledoc \"\"\"\n Documentation for Astarte.VMQ.Plugin.\n \"\"\"\n\n alias Astarte.VMQ.Plugin.Config\n alias Astarte.VMQ.Plugin.AMQPClient\n\n @max_rand trunc(:math.pow(2, 32) - 1)\n\n def auth_on_register(_peer, _subscriber_id, :undefined, _password, _cleansession) do\n # If it doesn't have a username we let someone else decide\n :next\n end\n\n def auth_on_register(_peer, {mountpoint, _client_id}, username, _password, _cleansession) do\n if !String.contains?(username, \"\/\") do\n # Not a device, let someone else decide\n :next\n else\n subscriber_id = {mountpoint, username}\n # TODO: we probably want some of these values to be configurable in some way\n {:ok,\n [\n subscriber_id: subscriber_id,\n max_inflight_messages: 100,\n max_message_rate: 10000,\n max_message_size: 65535,\n retry_interval: 20000,\n upgrade_qos: false\n ]}\n end\n end\n\n def auth_on_publish(\n _username,\n {_mountpoint, client_id},\n _qos,\n topic_tokens,\n _payload,\n _isretain\n ) do\n cond do\n # Not a device, let someone else decide\n !String.contains?(client_id, \"\/\") ->\n :next\n\n # Device auth\n String.split(client_id, \"\/\") == Enum.take(topic_tokens, 2) ->\n :ok\n\n true ->\n {:error, :unauthorized}\n end\n end\n\n def auth_on_subscribe(_username, {_mountpoint, client_id}, topics) do\n if !String.contains?(client_id, \"\/\") do\n # Not a device, let someone else decide\n :next\n else\n client_id_tokens = String.split(client_id, \"\/\")\n\n authorized_topics =\n Enum.filter(topics, fn {topic_tokens, _qos} ->\n client_id_tokens == Enum.take(topic_tokens, 2)\n end)\n\n case authorized_topics do\n [] -> {:error, :unauthorized}\n authorized_topics -> {:ok, authorized_topics}\n end\n end\n end\n\n def disconnect_client(client_id, discard_state) do\n opts =\n if discard_state do\n [:do_cleanup]\n else\n []\n end\n\n mountpoint = ''\n subscriber_id = {mountpoint, client_id}\n\n case :vernemq_dev_api.disconnect_by_subscriber_id(subscriber_id, opts) do\n :ok ->\n :ok\n\n :not_found ->\n {:error, :not_found}\n end\n end\n\n def on_client_gone({_mountpoint, client_id}) do\n publish_event(client_id, \"disconnection\", now_us_x10_timestamp())\n end\n\n def on_client_offline({_mountpoint, client_id}) do\n publish_event(client_id, \"disconnection\", now_us_x10_timestamp())\n end\n\n def on_register({ip_addr, _port}, {_mountpoint, client_id}, _username) do\n with [realm, device_id] <- String.split(client_id, \"\/\") do\n # Start the heartbeat\n setup_heartbeat_timer(realm, device_id, self())\n\n timestamp = now_us_x10_timestamp()\n\n ip_string =\n ip_addr\n |> :inet.ntoa()\n |> to_string()\n\n publish_event(client_id, \"connection\", timestamp, x_astarte_remote_ip: ip_string)\n else\n # Not a device, ignoring it\n _ ->\n :ok\n end\n end\n\n def on_publish(_username, {_mountpoint, client_id}, _qos, topic_tokens, payload, _isretain) do\n with [realm, device_id] <- String.split(client_id, \"\/\") do\n timestamp = now_us_x10_timestamp()\n\n case topic_tokens do\n [^realm, ^device_id] ->\n publish_introspection(realm, device_id, payload, timestamp)\n\n [^realm, ^device_id, \"control\" | control_path_tokens] ->\n control_path = \"\/\" <> Enum.join(control_path_tokens, \"\/\")\n publish_control_message(realm, device_id, control_path, payload, timestamp)\n\n [^realm, ^device_id, interface | path_tokens] ->\n path = \"\/\" <> Enum.join(path_tokens, \"\/\")\n publish_data(realm, device_id, interface, path, payload, timestamp)\n end\n else\n # Not a device, ignoring it\n _ ->\n :ok\n end\n end\n\n def handle_heartbeat(realm, device_id, session_pid) do\n if Process.alive?(session_pid) do\n publish_heartbeat(realm, device_id)\n\n setup_heartbeat_timer(realm, device_id, session_pid)\n else\n # The session is not alive anymore, just stop\n :ok\n end\n end\n\n defp setup_heartbeat_timer(realm, device_id, session_pid) do\n args = [realm, device_id, session_pid]\n interval = Config.device_heartbeat_interval_ms() |> randomize_interval(0.25)\n {:ok, _timer} = :timer.apply_after(interval, __MODULE__, :handle_heartbeat, args)\n\n :ok\n end\n\n defp randomize_interval(interval, tolerance) do\n multiplier = 1 + (tolerance * 2 * :random.uniform() - tolerance)\n\n (interval * multiplier)\n |> Float.round()\n |> trunc()\n end\n\n defp publish_introspection(realm, device_id, payload, timestamp) do\n publish(realm, device_id, payload, \"introspection\", timestamp)\n end\n\n defp publish_data(realm, device_id, interface, path, payload, timestamp) do\n additional_headers = [x_astarte_interface: interface, x_astarte_path: path]\n\n publish(realm, device_id, payload, \"data\", timestamp, additional_headers)\n end\n\n defp publish_control_message(realm, device_id, control_path, payload, timestamp) do\n additional_headers = [x_astarte_control_path: control_path]\n\n publish(realm, device_id, payload, \"control\", timestamp, additional_headers)\n end\n\n defp publish_event(client_id, event_string, timestamp, additional_headers \\\\ []) do\n with [realm, device_id] <- String.split(client_id, \"\/\") do\n publish(realm, device_id, \"\", event_string, timestamp, additional_headers)\n else\n # Not a device, ignoring it\n _ ->\n :ok\n end\n end\n\n defp publish_heartbeat(realm, device_id) do\n timestamp = now_us_x10_timestamp()\n\n publish(realm, device_id, \"\", \"heartbeat\", timestamp)\n end\n\n defp publish(realm, device_id, payload, event_string, timestamp, additional_headers \\\\ []) do\n headers =\n [\n x_astarte_vmqamqp_proto_ver: 1,\n x_astarte_realm: realm,\n x_astarte_device_id: device_id,\n x_astarte_msg_type: event_string\n ] ++ additional_headers\n\n message_id = generate_message_id(realm, device_id, timestamp)\n sharding_key = {realm, device_id}\n\n :ok =\n AMQPClient.publish(payload,\n headers: headers,\n message_id: message_id,\n timestamp: timestamp,\n sharding_key: sharding_key\n )\n end\n\n defp now_us_x10_timestamp do\n DateTime.utc_now()\n |> DateTime.to_unix(:microsecond)\n |> Kernel.*(10)\n end\n\n defp generate_message_id(realm, device_id, timestamp) do\n realm_trunc = String.slice(realm, 0..63)\n device_id_trunc = String.slice(device_id, 0..15)\n timestamp_hex_str = Integer.to_string(timestamp, 16)\n rnd = Enum.random(0..@max_rand) |> Integer.to_string(16)\n\n \"#{realm_trunc}-#{device_id_trunc}-#{timestamp_hex_str}-#{rnd}\"\n end\nend\n","avg_line_length":28.6307692308,"max_line_length":96,"alphanum_fraction":0.6656367544}
{"size":1155,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"# This file is responsible for configuring your application\n# and its dependencies with the aid of the Mix.Config module.\nuse Mix.Config\n\n# This configuration is loaded before any dependency and is restricted\n# to this project. If another project depends on this project, this\n# file won't be loaded nor affect the parent project. For this reason,\n# if you want to provide default values for your application for\n# 3rd-party users, it should be done in your \"mix.exs\" file.\n\n# You can configure your application as:\n#\n# config :db_administration_tool, key: :value\n#\n# and access this configuration in your application as:\n#\n# Application.get_env(:db_administration_tool, :key)\n#\n# You can also configure a 3rd-party app:\n#\n# config :logger, level: :info\n#\n\n# It is also possible to import configuration files, relative to this\n# directory. For example, you can emulate configuration per environment\n# by uncommenting the line below and defining dev.exs, test.exs and such.\n# Configuration from the imported file will override the ones defined\n# here (which is why it is important to import them last).\n#\n# import_config \"#{Mix.env()}.exs\"\n","avg_line_length":37.2580645161,"max_line_length":73,"alphanum_fraction":0.7567099567}
{"size":110,"ext":"ex","lang":"Elixir","max_stars_count":16.0,"content":"defmodule Default do\n def go(x \\\\ 42_000), do: x\n\n def gogo(a, x \\\\ 666_000, y \\\\ 1_000), do: a + x + y\nend\n","avg_line_length":18.3333333333,"max_line_length":54,"alphanum_fraction":0.5727272727}
{"size":3698,"ext":"ex","lang":"Elixir","max_stars_count":8.0,"content":"defmodule Core.Validators.Reference do\n @moduledoc \"\"\"\n Validates reference existance\n \"\"\"\n\n alias Core.CapitationContractRequests\n alias Core.ContractRequests.CapitationContractRequest\n alias Core.ContractRequests.ReimbursementContractRequest\n alias Core.Divisions\n alias Core.Divisions.Division\n alias Core.Employees\n alias Core.Employees.Employee\n alias Core.LegalEntities\n alias Core.LegalEntities.LegalEntity\n alias Core.MedicalPrograms\n alias Core.MedicalPrograms.MedicalProgram\n alias Core.Medications\n alias Core.Medications.Medication\n alias Core.Persons\n alias Core.ReimbursementContractRequests\n alias Core.ValidationError\n alias Core.Validators.Error\n\n @ops_api Application.get_env(:core, :api_resolvers)[:ops]\n\n def validate(type, nil) do\n error(type)\n end\n\n def validate(type, id), do: validate(type, id, nil)\n\n def validate(:medication_request = type, id, path) do\n with {:ok, %{\"data\" => [medication_request]}} <- @ops_api.get_medication_requests(%{\"id\" => id}, []) do\n {:ok, medication_request}\n else\n _ -> error(type, path)\n end\n end\n\n def validate(:employee = type, id, path) do\n with %Employee{} = employee <- Employees.get_by_id(id) do\n {:ok, employee}\n else\n _ -> error(type, path)\n end\n end\n\n def validate(:division = type, id, path) do\n with %Division{} = division <- Divisions.get_by_id(id),\n {:status, true} <- {:status, division.status == Division.status(:active)} do\n {:ok, division}\n else\n {:status, _} -> error_status(type, path)\n _ -> error(type, path)\n end\n end\n\n def validate(:medical_program = type, id, path) do\n with %MedicalProgram{} = medical_program <- MedicalPrograms.get_by_id(id) do\n {:ok, medical_program}\n else\n _ -> error(type, path)\n end\n end\n\n def validate(:legal_entity = type, id, path) do\n with %LegalEntity{} = legal_entity <- LegalEntities.get_by_id(id),\n {:status, true} <-\n {:status, legal_entity.status in [LegalEntity.status(:active), LegalEntity.status(:suspended)]} do\n {:ok, legal_entity}\n else\n {:status, _} -> error_status(type, path)\n _ -> error(type, path)\n end\n end\n\n def validate(:person = type, id, path) do\n with {:ok, person} <- Persons.get_by_id(id) do\n {:ok, person}\n else\n _ -> error(type, path)\n end\n end\n\n def validate(:medication = type, id, path) do\n with %Medication{} = medication <- Medications.get_medication_by_id(id) do\n {:ok, medication}\n else\n _ -> error(type, path)\n end\n end\n\n # TODO: rename everywhere\n def validate(:contract_request = type, id, path) do\n with %CapitationContractRequest{} = contract_request <- CapitationContractRequests.get_by_id(id) do\n {:ok, contract_request}\n else\n _ -> error(type, path)\n end\n end\n\n def validate(:reimbursement_contract_request = type, id, path) do\n with %ReimbursementContractRequest{} = contract_request <- ReimbursementContractRequests.get_by_id(id) do\n {:ok, contract_request}\n else\n _ -> error(type, path)\n end\n end\n\n defp error(type, path \\\\ nil) when is_atom(type) do\n description =\n type\n |> to_string()\n |> String.capitalize()\n |> String.replace(\"_\", \" \")\n\n path = path || \"$.#{type}_id\"\n Error.dump(%ValidationError{description: \"#{description} not found\", path: path})\n end\n\n defp error_status(type, path) when is_atom(type) do\n description =\n type\n |> to_string()\n |> String.capitalize()\n |> String.replace(\"_\", \" \")\n\n path = path || \"$.#{type}_id\"\n Error.dump(%ValidationError{description: \"#{description} is not active\", path: path})\n end\nend\n","avg_line_length":28.0151515152,"max_line_length":109,"alphanum_fraction":0.6595457004}
{"size":278,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule Jeff.Reply.KeypadData do\n @moduledoc \"\"\"\n Keypad Data Report\n\n OSDP v2.2 Specification Reference: 7.12\n \"\"\"\n\n defstruct [:reader, :count, :keys]\n\n def decode(<<reader, count, keys::binary>>) do\n %__MODULE__{reader: reader, count: count, keys: keys}\n end\nend\n","avg_line_length":19.8571428571,"max_line_length":57,"alphanum_fraction":0.6798561151}
{"size":1292,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"Logger.configure_backend(:console, colors: [enabled: false])\nExUnit.start(trace: \"--trace\" in System.argv())\n\n# Beam files compiled on demand\npath = Path.expand(\"..\/tmp\/beams\", __DIR__)\nFile.rm_rf!(path)\nFile.mkdir_p!(path)\nCode.prepend_path(path)\n\ndefmodule CabbageTestHelper do\n import ExUnit.CaptureIO\n\n def run(filters \\\\ [], cases \\\\ [])\n\n def run(filters, module) do\n {add_module, load_module, result_fix} = versioned_callbacks()\n\n Enum.each(module, add_module)\n load_module.()\n\n opts =\n ExUnit.configuration()\n |> Keyword.merge(filters)\n |> Keyword.merge(colors: [enabled: false])\n\n output = capture_io(fn -> Process.put(:capture_result, ExUnit.Runner.run(opts, nil)) end)\n {result_fix.(Process.get(:capture_result)), output}\n end\n\n defp versioned_callbacks() do\n System.version()\n |> Version.compare(\"1.6.0\")\n |> case do\n :lt -> {&ExUnit.Server.add_sync_case\/1, &ExUnit.Server.cases_loaded\/0, &fix_13_elixir_test_result\/1}\n _ -> {&ExUnit.Server.add_sync_module\/1, &ExUnit.Server.modules_loaded\/0, &fix_17_elixir_test_result\/1}\n end\n end\n\n defp fix_17_elixir_test_result(result), do: result\n\n defp fix_13_elixir_test_result(result) do\n Map.merge(result, %{excluded: Map.get(result, :skipped, 0), skipped: 0})\n end\nend\n","avg_line_length":28.7111111111,"max_line_length":108,"alphanum_fraction":0.6981424149}
{"size":251,"ext":"exs","lang":"Elixir","max_stars_count":4.0,"content":"Code.require_file \"test_helper.exs\", __DIR__\n\ndefmodule MixTest do\n use MixTest.Case\n\n test :shell do\n assert Mix.shell == Mix.Shell.Process\n end\n\n test :env do\n assert Mix.env == :dev\n Mix.env(:prod)\n assert Mix.env == :prod\n end\nend","avg_line_length":16.7333333333,"max_line_length":44,"alphanum_fraction":0.6693227092}
{"size":141,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule JorbDemoTest do\n use ExUnit.Case\n doctest JorbDemo\n\n test \"greets the world\" do\n assert JorbDemo.hello() == :world\n end\nend\n","avg_line_length":15.6666666667,"max_line_length":37,"alphanum_fraction":0.7163120567}
{"size":1370,"ext":"ex","lang":"Elixir","max_stars_count":17.0,"content":"defmodule SurfaceBootstrap.Form.NumberInput do\n @moduledoc \"\"\"\n The number input element as defined here:\n - https:\/\/hexdocs.pm\/phoenix_html\/Phoenix.HTML.Form.html#number_input\/3\n - https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTML\/Element\/input\/number\n \"\"\"\n\n use Surface.Component\n use SurfaceBootstrap.Form.TextInputBase\n\n alias Surface.Components.Form.NumberInput\n\n @doc \"Largest number allowed, as enforced by client browser. Not validated by Elixir.\"\n prop max, :integer\n\n @doc \"Smallest number allowed, as enforced by client browser. Not validated by Elixir.\"\n prop min, :integer\n\n @doc \"A stepping interval to use when using up and down arrows to adjust the value, as well as for validation\"\n prop step, :integer\n\n def render(assigns) do\n ~F\"\"\"\n <FieldContext name={@field}>\n {raw(optional_div(assigns))}\n <Label :if={@label && !@in_group && !@floating_label} class=\"form-label\">{@label}<\/Label>\n <NumberInput\n class={input_classes(assigns) ++ @class}\n field={@field}\n value={@value}\n :props={default_surface_input_props(assigns)}\n opts={default_core_input_opts(assigns) ++ @opts}\n \/>\n <BootstrapErrorTag has_error={has_error?(assigns)} has_change={has_change?(assigns)} \/>\n {help_text(assigns)}\n <#Raw :if={!@in_group}><\/div><\/#Raw>\n <\/FieldContext>\n \"\"\"\n end\nend\n","avg_line_length":33.4146341463,"max_line_length":112,"alphanum_fraction":0.6846715328}
{"size":323,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule PhxApi.Reports.Source do\n use Ecto.Schema\n import Ecto.Changeset\n\n\n schema \"sources\" do\n field :name, :string\n field :token, :string\n\n timestamps()\n end\n\n @doc false\n def changeset(source, attrs) do\n source\n |> cast(attrs, [:name, :token])\n |> validate_required([:name, :token])\n end\nend\n","avg_line_length":16.15,"max_line_length":41,"alphanum_fraction":0.6501547988}
{"size":1710,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule GenRMQ.Mixfile do\n use Mix.Project\n\n @version \"2.3.0\"\n\n def project do\n [\n app: :gen_rmq,\n version: @version,\n elixir: \"~> 1.7\",\n start_permanent: Mix.env() == :prod,\n elixirc_paths: elixirc_paths(Mix.env()),\n deps: deps(),\n test_coverage: [tool: ExCoveralls],\n description: description(),\n package: package(),\n source_url: \"https:\/\/github.com\/meltwater\/gen_rmq\",\n docs: [\n extras: [\"README.md\"],\n main: \"readme\",\n source_ref: \"v#{@version}\",\n source_url: \"https:\/\/github.com\/meltwater\/gen_rmq\"\n ],\n dialyzer: [\n plt_add_apps: [:mix],\n plt_file: {:no_warn, \"priv\/plts\/dialyzer.plt\"}\n ]\n ]\n end\n\n # Run \"mix help compile.app\" to learn about applications.\n def application do\n [\n extra_applications: [:logger]\n ]\n end\n\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\", \"examples\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n # Run \"mix help deps\" to learn about dependencies.\n defp deps do\n [\n {:amqp, \"~> 1.1\"},\n {:credo, \"~> 1.0\", only: :dev},\n {:excoveralls, \"~> 0.12.0\", only: :test},\n {:jason, \"~> 1.1\", only: [:dev, :test]},\n {:earmark, \"~> 1.2\", only: :dev},\n {:ex_doc, \"~> 0.21.0\", only: :dev},\n {:dialyxir, \"~> 1.0.0-rc.6\", only: [:dev], runtime: false}\n ]\n end\n\n defp description() do\n \"Set of behaviours meant to be used to create RabbitMQ consumers and publishers.\"\n end\n\n defp package() do\n [\n files: [\"lib\", \"mix.exs\", \"README.md\", \"LICENSE\"],\n maintainers: [\"Mateusz Korszun\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/meltwater\/gen_rmq\"}\n ]\n end\nend\n","avg_line_length":25.5223880597,"max_line_length":85,"alphanum_fraction":0.5555555556}
{"size":1229,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule ExVCR.Mixfile do\n use Mix.Project\n\n def project do\n [ app: :exvcr,\n version: \"0.10.3\",\n elixir: \"~> 1.5\",\n deps: deps(),\n description: description(),\n package: package(),\n test_coverage: [tool: ExCoveralls],\n preferred_cli_env: [coveralls: :test]\n ]\n end\n\n # Configuration for the OTP application\n def application do\n [applications: [:meck, :exactor, :exjsx]]\n end\n\n # Returns the list of dependencies in the format:\n # { :foobar, \"~> 0.1\", git: \"https:\/\/github.com\/elixir-lang\/foobar.git\" }\n def deps do\n [\n {:meck, \"~> 0.8\"},\n {:exactor, \"~> 2.2\"},\n {:exjsx, \"~> 4.0\"},\n {:ibrowse, \"~> 4.4\", optional: true},\n {:httpotion, \"~> 3.1\", optional: true},\n {:httpoison, \"~> 1.5\", optional: true},\n {:excoveralls, \"~> 0.8\", only: :test},\n {:http_server, github: \"parroty\/http_server\", only: [:dev, :test]},\n {:ex_doc, \">= 0.0.0\", only: :dev}\n ]\n end\n\n defp description do\n \"\"\"\n HTTP request\/response recording library for elixir, inspired by VCR.\n \"\"\"\n end\n\n defp package do\n [ maintainers: [\"parroty\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/parroty\/exvcr\"} ]\n end\nend\n","avg_line_length":25.0816326531,"max_line_length":75,"alphanum_fraction":0.5606183889}
{"size":1363,"ext":"exs","lang":"Elixir","max_stars_count":3.0,"content":"# This file is responsible for configuring your application\n# and its dependencies with the aid of the Mix.Config module.\n#\n# This configuration file is loaded before any dependency and\n# is restricted to this project.\n\n# General application configuration\nuse Mix.Config\n\nconfig :portishead,\n namespace: Portishead,\n ecto_repos: [Portishead.Repo],\n generators: [binary_id: true],\n mix_env: Mix.env()\n\nconfig :portishead, Portishead.Repo,\n pool_size: String.to_integer(System.get_env(\"POOL_SIZE\", \"10\")),\n migration_primary_key: [name: :uuid, type: :uuid],\n migration_default_prefix: System.get_env(\"DB_SCHEMA\", \"portishead\"),\n migration_source: \"portishead_schema_migrations\"\n\n# Configures the endpoint\nconfig :portishead, PortisheadWeb.Endpoint,\n url: [host: \"localhost\"],\n secret_key_base: \"gIttBcgpBYUp80l7GVqVDG8vBJBIG9+9fw3\/291tQ2xnsmSeRwi3y4wrPGl2uR2+\",\n render_errors: [view: PortisheadWeb.ErrorView, accepts: ~w(html json)],\n pubsub_server: [name: Portishead.PubSub]\n\n# Configures Elixir's Logger\nconfig :logger, :console,\n format: \"$time $metadata[$level] $message\\n\",\n metadata: [:request_id]\n\n# Use Jason for JSON parsing in Phoenix\nconfig :phoenix, :json_library, Jason\n\n# Import environment specific config. This must remain at the bottom\n# of this file so it overrides the configuration defined above.\nimport_config \"#{Mix.env()}.exs\"\n","avg_line_length":34.075,"max_line_length":86,"alphanum_fraction":0.768158474}
{"size":140,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule HelloApi.HelloController do\n use HelloApi.Web, :controller\n\n def index(conn, _params) do\n json conn, \"Hello World\"\n end\nend\n","avg_line_length":17.5,"max_line_length":37,"alphanum_fraction":0.7357142857}
{"size":1944,"ext":"exs","lang":"Elixir","max_stars_count":2.0,"content":"defmodule CodeRunnerTest do\n use ExUnit.Case, async: true\n doctest CodeRunner\n\n test \"executing valid Elixir code should return proper output\" do\n code = \"2+3\"\n assert CodeRunner.run(code) == \"5\\n\"\n end\n\n test \"executing invalid Elixir code returns proper error message\" do\n code = \"IO.puts()\"\n result = CodeRunner.run(code)\n assert String.match?(result, ~r\/(UndefinedFunctionError)\/)\n end\n\n test \"each code should compile and run independent of one another\" do\n code1 =\n \"\"\"\n defmodule Hello do\n def hello() do\n 3+5\n end\n end\n Hello.hello()\n \"\"\"\n assert CodeRunner.run(code1) == \"8\\n\"\n code2 = \"Hello.hello()\"\n result = CodeRunner.run(code2)\n assert String.match?(result, ~r\/(UndefinedFunctionError)\/)\n end\n\n test \"code should result in timeout when it runs longer than the timeout duration set in the configuration\" do\n sleep_duration = Application.fetch_env!(:code_runner, :timeout) + 200\n code = \"Process.sleep(#{sleep_duration})\"\n result = CodeRunner.run(code)\n assert String.match?(result, ~r\/timeout\/)\n end\n\n test \"codes should run concurrently and take less time than they would have taken when run sequentially\" do\n\n concurrent_task_start_time = :os.timestamp()\n\n [1, 2]\n |> Enum.map(fn(_) -> Task.async(fn -> CodeRunner.run(\"Process.sleep(100)\") end) end)\n |> Enum.map(fn(task) -> Task.await(task, :infinity) end)\n\n concurrent_task_end_time = :os.timestamp()\n concurrent_elapsed_time = :timer.now_diff(concurrent_task_end_time, concurrent_task_start_time)\n\n\n sequential_task_start_time = :os.timestamp()\n\n [1, 2]\n |> Enum.each(fn(_) -> CodeRunner.run(\"Process.sleep(100)\") end) \n\n sequential_task_end_time = :os.timestamp()\n sequential_elapsed_time = :timer.now_diff(sequential_task_end_time, sequential_task_start_time)\n\n assert concurrent_elapsed_time < sequential_elapsed_time * 0.75\n end\nend\n","avg_line_length":31.3548387097,"max_line_length":112,"alphanum_fraction":0.691872428}
{"size":2452,"ext":"ex","lang":"Elixir","max_stars_count":1.0,"content":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This file is auto generated by the elixir code generator program.\n# Do not edit this file manually.\n\ndefmodule GoogleApi.Composer.V1beta1.Model.MaintenanceWindow do\n @moduledoc \"\"\"\n The configuration settings for Cloud Composer maintenance window. The following example: { \"startTime\":\"2019-08-01T01:00:00Z\" \"endTime\":\"2019-08-01T07:00:00Z\" \"recurrence\":\"FREQ=WEEKLY;BYDAY=TU,WE\" } would define a maintenance window between 01 and 07 hours UTC during each Tuesday and Wednesday.\n\n ## Attributes\n\n * `endTime` (*type:* `DateTime.t`, *default:* `nil`) - Required. Maintenance window end time. It is used only to calculate the duration of the maintenance window. The value for end_time must be in the future, relative to `start_time`.\n * `recurrence` (*type:* `String.t`, *default:* `nil`) - Required. Maintenance window recurrence. Format is a subset of [RFC-5545](https:\/\/tools.ietf.org\/html\/rfc5545) `RRULE`. The only allowed values for `FREQ` field are `FREQ=DAILY` and `FREQ=WEEKLY;BYDAY=...` Example values: `FREQ=WEEKLY;BYDAY=TU,WE`, `FREQ=DAILY`.\n * `startTime` (*type:* `DateTime.t`, *default:* `nil`) - Required. Start time of the first recurrence of the maintenance window.\n \"\"\"\n\n use GoogleApi.Gax.ModelBase\n\n @type t :: %__MODULE__{\n :endTime => DateTime.t() | nil,\n :recurrence => String.t() | nil,\n :startTime => DateTime.t() | nil\n }\n\n field(:endTime, as: DateTime)\n field(:recurrence)\n field(:startTime, as: DateTime)\nend\n\ndefimpl Poison.Decoder, for: GoogleApi.Composer.V1beta1.Model.MaintenanceWindow do\n def decode(value, options) do\n GoogleApi.Composer.V1beta1.Model.MaintenanceWindow.decode(value, options)\n end\nend\n\ndefimpl Poison.Encoder, for: GoogleApi.Composer.V1beta1.Model.MaintenanceWindow do\n def encode(value, options) do\n GoogleApi.Gax.ModelBase.encode(value, options)\n end\nend\n","avg_line_length":46.2641509434,"max_line_length":322,"alphanum_fraction":0.7287928222}
{"size":77,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"use Mix.Config\n\nconfig :zoho,\n auth_key: \"testkey\",\n domain: \"test.domain\"\n","avg_line_length":12.8333333333,"max_line_length":23,"alphanum_fraction":0.6883116883}
{"size":2230,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"# Copyright 2017 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# NOTE: This class is auto generated by the swagger code generator program.\n# https:\/\/github.com\/swagger-api\/swagger-codegen.git\n# Do not edit the class manually.\n\ndefmodule GoogleApi.Sheets.V4.Model.PivotGroupSortValueBucket do\n @moduledoc \"\"\"\n Information about which values in a pivot group should be used for sorting.\n\n ## Attributes\n\n - buckets (List[ExtendedValue]): Determines the bucket from which values are chosen to sort. For example, in a pivot table with one row group &amp; two column groups, the row group can list up to two values. The first value corresponds to a value within the first column group, and the second value corresponds to a value in the second column group. If no values are listed, this would indicate that the row should be sorted according to the \\&quot;Grand Total\\&quot; over the column groups. If a single value is listed, this would correspond to using the \\&quot;Total\\&quot; of that bucket. Defaults to: `null`.\n - valuesIndex (Integer): The offset in the PivotTable.values list which the values in this grouping should be sorted by. Defaults to: `null`.\n \"\"\"\n\n defstruct [\n :\"buckets\",\n :\"valuesIndex\"\n ]\nend\n\ndefimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.PivotGroupSortValueBucket do\n import GoogleApi.Sheets.V4.Deserializer\n def decode(value, options) do\n value\n |> deserialize(:\"buckets\", :list, GoogleApi.Sheets.V4.Model.ExtendedValue, options)\n end\nend\n\ndefimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.PivotGroupSortValueBucket do\n def encode(value, options) do\n GoogleApi.Sheets.V4.Deserializer.serialize_non_nil(value, options)\n end\nend\n\n","avg_line_length":44.6,"max_line_length":616,"alphanum_fraction":0.7618834081}
{"size":1028,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule NudgeApiWeb.Schema.JsonType do\n @moduledoc \"\"\"\n The Json scalar type allows arbitrary JSON values to be passed in and out.\n Requires `{ :jason, \"~> 1.1\" }` package: https:\/\/github.com\/michalmuskala\/jason\n \"\"\"\n use Absinthe.Schema.Notation\n\n scalar :json, name: \"Json\" do\n description(\"\"\"\n The `Json` scalar type represents arbitrary json string data, represented as UTF-8\n character sequences. The Json type is most often used to represent a free-form\n human-readable json string.\n \"\"\")\n\n serialize(&encode\/1)\n parse(&decode\/1)\n end\n\n @spec decode(Absinthe.Blueprint.Input.String.t()) :: {:ok, term()} | :error\n @spec decode(Absinthe.Blueprint.Input.Null.t()) :: {:ok, nil}\n defp decode(%Absinthe.Blueprint.Input.String{value: value}) do\n case Jason.decode(value) do\n {:ok, result} -> {:ok, result}\n _ -> :error\n end\n end\n\n defp decode(%Absinthe.Blueprint.Input.Null{}) do\n {:ok, nil}\n end\n\n defp decode(_) do\n :error\n end\n\n defp encode(value), do: value\nend\n","avg_line_length":27.0526315789,"max_line_length":86,"alphanum_fraction":0.6653696498}
{"size":6858,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"alias Hightopics.Repo\nalias Hightopics.Themes\nalias Hightopics.Themes.Theme\nalias Hightopics.Topics\nalias Hightopics.Topics.Topic\nalias Hightopics.Users\nalias Hightopics.Users.User\nalias Hightopics.Comments\n\nRepo.delete_all(Theme)\n\ndefmodule Populate do\n def fresh_start! do\n end\n\n def add_user!(list) do\n Users.create_user list_to_map list\n end\n\n def add_theme!(list) do\n Themes.create_theme list_to_map list\n end\n\n def add_topic!(list) do\n Topics.create_topic list_to_map list\n end\n\n def add_comment!(list) do\n Comments.create_comment (list_to_map list)\n end\n\n defp list_to_map(list) do\n Enum.into(list, %{})\n end\nend\n\nRepo.delete_all(User)\nPopulate.add_user! username: \"Maria\", email: \"1@gmail.pt\"\nPopulate.add_user! username: \"bertinho\", email: \"asdsad@protonmail.pt\"\n\nRepo.delete_all(Topic)\nPopulate.add_topic! name: \"Rock\", description: \"Music\", rating: 10\nPopulate.add_topic! name: \"Pop\", description: \"Music\", rating: 10\nPopulate.add_topic! name: \"Indie\", description: \"Music\", rating: 10\nPopulate.add_topic! name: \"Funk\", description: \"Music\", rating: 10\nPopulate.add_topic! name: \"Last Shadow Puppets\", description: \"Music\", rating: 10\n\nPopulate.add_topic! name: \"Submarine\", description: \"Films\", rating: 10\nPopulate.add_topic! name: \"Politics\", description: \"Films\", rating: 10\nPopulate.add_topic! name: \"Saw\", description: \"Films\", rating: 10\nPopulate.add_topic! name: \"HarryPoter\", description: \"Films\", rating: 10\nPopulate.add_topic! name: \"Hobbit\", description: \"Films\", rating: 10\nPopulate.add_topic! name: \"SpiderMan\", description: \"Films\", rating: 10\nPopulate.add_topic! name: \"StarWars\", description: \"Films\", rating: 10\n\nPopulate.add_topic! name: \"PSD\", description: \"Politics\", rating: 10\nPopulate.add_topic! name: \"PS\", description: \"Politics\", rating: 10\nPopulate.add_topic! name: \"Bloco de esquerda\", description: \"Politics\", rating: 10\n\nPopulate.add_topic! name: \"Aristotoles\", description: \"Philosophy\", rating: 10\nPopulate.add_topic! name: \"Socrates\", description: \"Philosophy\", rating: 10\nPopulate.add_topic! name: \"Pitagoras\", description: \"Philosophy\", rating: 10\nPopulate.add_topic! name: \"Aristotoles\", description: \"Philosophy\", rating: 10\n\nPopulate.add_topic! name: \"The Voice\", description: \"TV show\", rating: 10\nPopulate.add_topic! name: \"BGT\", description: \"TV show\", rating: 10\nPopulate.add_topic! name: \"Big Brother\", description: \"TV show\", rating: 10\n\nPopulate.add_topic! name: \"How to make friends and influence people\", description: \"Book\", rating: 10\nPopulate.add_topic! name: \"Harry Potter\", description: \"Book\", rating: 10\nPopulate.add_topic! name: \"Eragon\", description: \"Book\", rating: 10\n\nPopulate.add_topic! name: \"Spaghetti\", description: \"Food\", rating: 10\nPopulate.add_topic! name: \"Hamburger\", description: \"Food\", rating: 10\nPopulate.add_topic! name: \"Pizza\", description: \"Food\", rating: 10\n\nPopulate.add_topic! name: \"Football\", description: \"Sports\", rating: 10\nPopulate.add_topic! name: \"Basketball\", description: \"Sports\", rating: 10\nPopulate.add_topic! name: \"Volleyball\", description: \"Sports\", rating: 10\nPopulate.add_topic! name: \"Handball\", description: \"Sports\", rating: 10\n\nPopulate.add_topic! name: \"SEI\", description: \"Current Events\", rating: 10\nPopulate.add_topic! name: \"Hacktivate\", description: \"Current Events\", rating: 10\nPopulate.add_topic! name: \"WebSummit\", description: \"Current Events\", rating: 10\n\nPopulate.add_topic! name: \"Son\", description: \"Family\", rating: 10\nPopulate.add_topic! name: \"Brother\", description: \"Family\", rating: 10\nPopulate.add_topic! name: \"Sister\", description: \"Family\", rating: 10\n\nRepo.delete_all(Theme)\nPopulate.add_theme! name: \"Music\", description: \"Music is a form of art; an expression of emotions through harmonic frequencies.\"\n\nPopulate.add_theme! name: \"Films\", description: \"a series of still images that when shown on a screen create an illusion of motion images.\"\n\nPopulate.add_theme! name: \"Politics\", description: \"The process of making decisions that apply to members of a group.\"\n\nPopulate.add_theme! name: \"Philosophy\", description: \"Philosophy is the study of general and fundamental problems concerning matters such as existence, knowledge, values, reason, mind, and language\"\n\nPopulate.add_theme! name: \"TV show\", description: \"A m\u00fasica \u00e9 uma forma de arte que se constitui na combina\u00e7\u00e3o de v\u00e1rios sons e ritmos, seguindo uma pr\u00e9-organiza\u00e7\u00e3o ao longo do tempo.\"\n\nPopulate.add_theme! name: \"Book\", description: \"Series of pages assembled for easy portability and reading, as well as the composition contained in it.\"\n\nPopulate.add_theme! name: \"Food\", description: \"Food is what people and animals eat\"\n\nPopulate.add_theme! name: \"Sports\", description: \"All forms of competitive physical activity or games which, through casual or organised participation, aim to use, maintain or improve physical ability and skills while providing enjoyment to participants, and in some cases, entertainment for spectators\"\n\nPopulate.add_theme! name: \"Current Events\", description: \"Information provided through many different media: word of mouth, printing, postal systems, broadcasting, electronic communication, and also on the testimony of observers and witnesses to events. It is also used as a platform to manufacture opinion for the population\"\n\nPopulate.add_theme! name: \"Family\", description: \"Group of people affiliated either by consanguinity (by recognized birth), affinity (by marriage or other relationship), or co-residence \"\n\nfor a <- Repo.all(Topic) do\n Populate.add_comment!(content: \"Pretty Beautiful\", rating: 20)\n Populate.add_comment!(content: \"Things to do\", rating: 20)\n Populate.add_comment!(content: \"WoW!\", rating: 20)\n Populate.add_comment!(content: \"Cool\", rating: 20)\n Populate.add_comment!(content: \"Fomented an incredible discussion!\", rating: 20)\n Populate.add_comment!(content: \"Could not ask for better!\", rating: 20)\n Populate.add_comment!(content: \"Without doubt a great topic and a great WebApp\", rating: 20)\n Populate.add_comment!(content: \"Incredible !!!!!!!\", rating: 20)\nend\n\n#Topics.link_topic_and_comment(Topics.get_topic!(1), Comments.get_comment!(1))\n\nfor a <- Repo.all(Theme) do\n for b <- Enum.filter(Repo.all(Topic), fn(x)-> a.name == x.description end) do\n Topics.link_topic_and_theme(b,a)\n end\nend\n\n\n#for a <- Repo.all(Topic) do\n # for b <- Repo.all(Theme) do\n #Topics.link_topic_and_theme(a,b)\n # end\n #end\n\nfor {a,b} <- Enum.with_index(Repo.all(Topic)) do\n for x <- 0..7, do: Topics.link_topic_and_comment(a, Comments.get_comment!((x+1)+ (b*8)))\nend\n\n#for {a,b} <- Enum.with_index(Repo.all(Topic)) do\n# for x <- 0..7, do: Topics.link_topic_and_comment(a, Comments.get_comment!((x+1)+ (b*8)))\n#end\n#IO.puts Themes.random.name\n\n#for a <- Repo.all(Topic) do\n# x = Repo.preload(a, :themes)\n# for b <- x.themes do\n# IO.puts b.name\n# end\n#end\n","avg_line_length":45.1184210526,"max_line_length":326,"alphanum_fraction":0.7481773112}
{"size":139,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"use Mix.Config\n\nalias Dogma.Rule\n\nconfig :dogma,\n rule_set: Dogma.RuleSet.All,\n override: [\n %Rule.LineLength{ max_length: 120 },\n ]\n","avg_line_length":13.9,"max_line_length":40,"alphanum_fraction":0.6834532374}
{"size":4447,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule MateriaCareerWeb.RecordControllerTest do\n use MateriaCareerWeb.ConnCase\n\n alias MateriaCareer.Projects\n alias MateriaCareer.Projects.Record\n\n @create_attrs %{description: \"some description\", title: \"some title\", score: 10.0, user_id: 1, project_id: nil}\n @update_attrs %{\n description: \"some updated description\",\n title: \"some updated title\",\n score: 12.0,\n user_id: 1,\n project_id: nil\n }\n @invalid_attrs %{description: nil, title: nil, user_id: nil}\n\n def fixture(:record) do\n {:ok, record} = Projects.create_record(@create_attrs)\n record\n end\n\n setup %{conn: conn} do\n %{\"access_token\" => access_token} =\n conn\n |> post(authenticator_path(conn, :sign_in), %{email: \"hogehoge@example.com\", password: \"hogehoge\"})\n |> json_response(201)\n\n conn =\n conn\n |> put_req_header(\"accept\", \"application\/json\")\n |> put_req_header(\"authorization\", \"Bearer \" <> access_token)\n\n {:ok, conn: conn}\n end\n\n describe \"index\" do\n test \"lists all records\", %{conn: conn} do\n conn = get(conn, record_path(conn, :index))\n assert json_response(conn, 200) |> Enum.count() > 0\n end\n end\n\n describe \"create record\" do\n test \"renders record when data is valid\", %{conn: conn} do\n conn = post(conn, record_path(conn, :create), @create_attrs)\n assert %{\"id\" => id} = json_response(conn, 201)\n\n conn = get(conn, record_path(conn, :show, id))\n\n assert json_response(conn, 200) == %{\n \"id\" => id,\n \"description\" => \"some description\",\n \"title\" => \"some title\",\n \"score\" => 10.0,\n \"lock_version\" => 1,\n \"project\" => nil,\n \"tags\" => nil,\n \"user\" => nil\n }\n end\n\n # test \"renders errors when data is invalid\", %{conn: conn} do\n # conn = post(conn, record_path(conn, :create), @invalid_attrs)\n # assert json_response(conn, 422)[\"errors\"] != %{}\n # end\n end\n\n describe \"update record\" do\n setup [:create_record]\n\n test \"renders record when data is valid\", %{conn: conn, record: %Record{id: id} = record} do\n conn = put(conn, record_path(conn, :update, record), @update_attrs)\n assert %{\"id\" => ^id} = json_response(conn, 200)\n\n conn = get(conn, record_path(conn, :show, id))\n\n assert json_response(conn, 200) == %{\n \"id\" => id,\n \"description\" => \"some updated description\",\n \"title\" => \"some updated title\",\n \"score\" => 12.0,\n \"lock_version\" => 2,\n \"project\" => nil,\n \"tags\" => nil,\n \"user\" => nil\n }\n end\n\n # test \"renders errors when data is invalid\", %{conn: conn, record: record} do\n # conn = put(conn, record_path(conn, :update, record), @invalid_attrs)\n # assert json_response(conn, 422)[\"errors\"] != %{}\n # end\n end\n\n describe \"delete record\" do\n setup [:create_record]\n\n test \"deletes chosen record\", %{conn: conn, record: record} do\n conn = delete(conn, record_path(conn, :delete, record))\n assert response(conn, 204)\n\n assert_error_sent(404, fn ->\n get(conn, record_path(conn, :show, record))\n end)\n end\n end\n\n describe \"records API with authentication\" do\n test \"get list-my-records\", %{conn: conn} do\n conn = get(conn, record_path(conn, :list_my_records))\n assert json_response(conn, 200) |> Enum.count() > 0\n end\n\n test \"post create-my-record\", %{conn: conn} do\n req = %{\n title: \"title1\",\n description: \"description1\",\n score: 10,\n project_id: 1\n }\n\n conn = post(conn, record_path(conn, :create_my_record, req))\n assert response(conn, 201)\n end\n\n test \"post update-my-record\", %{conn: conn} do\n req = %{\n title: \"title1\",\n description: \"description1\",\n score: 10,\n project_id: 1\n }\n\n create_conn = post(conn, record_path(conn, :create_my_record, req))\n %{\"id\" => id} = json_response(create_conn, 201)\n\n req = %{\n id: id,\n title: \"updated title1\",\n description: \"updated description1\",\n score: 12,\n project_id: 1\n }\n\n conn = post(conn, record_path(conn, :update_my_record, req))\n assert response(conn, 201)\n end\n end\n\n defp create_record(_) do\n record = fixture(:record)\n {:ok, record: record}\n end\nend\n","avg_line_length":28.6903225806,"max_line_length":113,"alphanum_fraction":0.578142568}
{"size":808,"ext":"ex","lang":"Elixir","max_stars_count":8.0,"content":"defmodule WhistlerNewsReaderWeb.Api.RegistrationController do\n use WhistlerNewsReaderWeb, :controller\n require Logger\n\n alias WhistlerNewsReader.Repo\n alias WhistlerNewsReader.User\n\n plug :scrub_params, \"user\" when action in [:create]\n\n def create(conn, %{\"user\" => user_params}) do\n changeset = User.changeset(%User{}, user_params)\n\n case Repo.insert(changeset) do\n {:ok, user} ->\n {:ok, jwt, _full_claims} = Guardian.encode_and_sign(user, :token)\n\n conn\n |> put_status(:created)\n |> render(WhistlerNewsReaderWeb.Api.SessionView, \"show.json\", jwt: jwt, user: user)\n\n {:error, changeset} ->\n conn\n |> put_status(:unprocessable_entity)\n |> render(WhistlerNewsReaderWeb.Api.ErrorView, \"error.json\", changeset: changeset)\n end\n end\nend\n","avg_line_length":28.8571428571,"max_line_length":91,"alphanum_fraction":0.6806930693}
{"size":1266,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule AbsintheTestAppWeb.UserSocket do\n use Phoenix.Socket\n use Absinthe.Phoenix.Socket,\n schema: AbsintheTestAppWeb.Schema\n\n ## Channels\n # channel \"room:*\", AbsintheTestAppWeb.RoomChannel\n\n ## Transports\n transport :websocket, Phoenix.Transports.WebSocket\n # transport :longpoll, Phoenix.Transports.LongPoll\n\n # Socket params are passed from the client and can\n # be used to verify and authenticate a user. After\n # verification, you can put default assigns into\n # the socket that will be set for all channels, ie\n #\n # {:ok, assign(socket, :user_id, verified_user_id)}\n #\n # To deny connection, return `:error`.\n #\n # See `Phoenix.Token` documentation for examples in\n # performing token verification on connect.\n def connect(_params, socket) do\n {:ok, socket}\n end\n\n # Socket id's are topics that allow you to identify all sockets for a given user:\n #\n # def id(socket), do: \"user_socket:#{socket.assigns.user_id}\"\n #\n # Would allow you to broadcast a \"disconnect\" event and terminate\n # all active sockets and channels for a given user:\n #\n # AbsintheTestAppWeb.Endpoint.broadcast(\"user_socket:#{user.id}\", \"disconnect\", %{})\n #\n # Returning `nil` makes this socket anonymous.\n def id(_socket), do: nil\nend\n","avg_line_length":31.65,"max_line_length":90,"alphanum_fraction":0.7132701422}
{"size":599,"ext":"ex","lang":"Elixir","max_stars_count":30.0,"content":"defmodule Tests.Support.Codecs.ShortStr do\n use EdgeDB.Protocol.Codec\n\n alias EdgeDB.Protocol.{\n Codecs,\n Error\n }\n\n defscalarcodec(\n type_name: \"default::short_str\",\n type: String.t(),\n\n # inherit this from parent codec\n calculate_size: false\n )\n\n @impl EdgeDB.Protocol.Codec\n def encode_instance(str) do\n if String.length(str) <= 5 do\n Codecs.Builtin.Str.encode_instance(str)\n else\n raise Error.invalid_argument_error(\"string is too long\")\n end\n end\n\n @impl EdgeDB.Protocol.Codec\n defdelegate decode_instance(binary_data), to: Codecs.Builtin.Str\nend\n","avg_line_length":20.6551724138,"max_line_length":66,"alphanum_fraction":0.7045075125}
{"size":300,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule ListsAndRecursion do\n def max([]), do: 0\n def max(list) do\n fun = fn num, acc ->\n cond do\n num >= acc -> num\n true -> acc\n end\n end\n\n list\n |> reduce(& fun.(&1, &2))\n end\n\n defp reduce(list, fun) do\n Enum.reduce(list, 0, & fun.(&1, &2))\n end\nend\n","avg_line_length":15.7894736842,"max_line_length":40,"alphanum_fraction":0.5033333333}
{"size":489,"ext":"ex","lang":"Elixir","max_stars_count":8.0,"content":"defmodule HergettoWeb.Components.LogoIcon.Playground do\n use Surface.Catalogue.Playground,\n subject: HergettoWeb.Components.LogoIcon,\n height: \"500px\",\n body: [style: \"padding: 1.5rem;\"]\n\n data props, :map, default: %{\n icon: %{\n type: \"link\",\n value: \"https:\/\/file.coffee\/u\/YQczfq-YZ9dvfq.png\"\n },\n }\n\n def render(assigns) do\n ~F\"\"\"\n <div style=\"height: 400px; width: 400px; display: block;\">\n <LogoIcon {...@props} \/>\n <\/div>\n \"\"\"\n end\nend\n","avg_line_length":22.2272727273,"max_line_length":62,"alphanum_fraction":0.6073619632}
{"size":337,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule KV.BucketTest do\n use ExUnit.Case, async: true\n\n setup do\n {:ok, bucket} = KV.Bucket.start_link\n {:ok, bucket: bucket}\n end\n\n test \"stores values by key\", %{bucket: bucket} do\n assert KV.Bucket.get(bucket, \"milk\") == nil\n\n KV.Bucket.put(bucket, \"milk\", 3)\n assert KV.Bucket.get(bucket, \"milk\") == 3\n end\nend","avg_line_length":22.4666666667,"max_line_length":51,"alphanum_fraction":0.6409495549}
{"size":4800,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This file is auto generated by the elixir code generator program.\n# Do not edit this file manually.\n\ndefmodule GoogleApi.ServiceManagement.V1.Model.AuthProvider do\n @moduledoc \"\"\"\n Configuration for an authentication provider, including support for\n [JSON Web Token\n (JWT)](https:\/\/tools.ietf.org\/html\/draft-ietf-oauth-json-web-token-32).\n\n ## Attributes\n\n * `audiences` (*type:* `String.t`, *default:* `nil`) - The list of JWT\n [audiences](https:\/\/tools.ietf.org\/html\/draft-ietf-oauth-json-web-token-32#section-4.1.3).\n that are allowed to access. A JWT containing any of these audiences will\n be accepted. When this setting is absent, JWTs with audiences:\n - \"https:\/\/[service.name]\/[google.protobuf.Api.name]\"\n - \"https:\/\/[service.name]\/\"\n will be accepted.\n For example, if no audiences are in the setting, LibraryService API will\n accept JWTs with the following audiences:\n -\n https:\/\/library-example.googleapis.com\/google.example.library.v1.LibraryService\n - https:\/\/library-example.googleapis.com\/\n\n Example:\n\n audiences: bookstore_android.apps.googleusercontent.com,\n bookstore_web.apps.googleusercontent.com\n * `authorizationUrl` (*type:* `String.t`, *default:* `nil`) - Redirect URL if JWT token is required but not present or is expired.\n Implement authorizationUrl of securityDefinitions in OpenAPI spec.\n * `id` (*type:* `String.t`, *default:* `nil`) - The unique identifier of the auth provider. It will be referred to by\n `AuthRequirement.provider_id`.\n\n Example: \"bookstore_auth\".\n * `issuer` (*type:* `String.t`, *default:* `nil`) - Identifies the principal that issued the JWT. See\n https:\/\/tools.ietf.org\/html\/draft-ietf-oauth-json-web-token-32#section-4.1.1\n Usually a URL or an email address.\n\n Example: https:\/\/securetoken.google.com\n Example: 1234567-compute@developer.gserviceaccount.com\n * `jwksUri` (*type:* `String.t`, *default:* `nil`) - URL of the provider's public key set to validate signature of the JWT. See\n [OpenID\n Discovery](https:\/\/openid.net\/specs\/openid-connect-discovery-1_0.html#ProviderMetadata).\n Optional if the key set document:\n - can be retrieved from\n [OpenID\n Discovery](https:\/\/openid.net\/specs\/openid-connect-discovery-1_0.html of\n the issuer.\n - can be inferred from the email domain of the issuer (e.g. a Google\n service account).\n\n Example: https:\/\/www.googleapis.com\/oauth2\/v1\/certs\n * `jwtLocations` (*type:* `list(GoogleApi.ServiceManagement.V1.Model.JwtLocation.t)`, *default:* `nil`) - Defines the locations to extract the JWT.\n\n JWT locations can be either from HTTP headers or URL query parameters.\n The rule is that the first match wins. The checking order is: checking\n all headers first, then URL query parameters.\n\n If not specified, default to use following 3 locations:\n 1) Authorization: Bearer\n 2) x-goog-iap-jwt-assertion\n 3) access_token query parameter\n\n Default locations can be specified as followings:\n jwt_locations:\n - header: Authorization\n value_prefix: \"Bearer \"\n - header: x-goog-iap-jwt-assertion\n - query: access_token\n \"\"\"\n\n use GoogleApi.Gax.ModelBase\n\n @type t :: %__MODULE__{\n :audiences => String.t(),\n :authorizationUrl => String.t(),\n :id => String.t(),\n :issuer => String.t(),\n :jwksUri => String.t(),\n :jwtLocations => list(GoogleApi.ServiceManagement.V1.Model.JwtLocation.t())\n }\n\n field(:audiences)\n field(:authorizationUrl)\n field(:id)\n field(:issuer)\n field(:jwksUri)\n field(:jwtLocations, as: GoogleApi.ServiceManagement.V1.Model.JwtLocation, type: :list)\nend\n\ndefimpl Poison.Decoder, for: GoogleApi.ServiceManagement.V1.Model.AuthProvider do\n def decode(value, options) do\n GoogleApi.ServiceManagement.V1.Model.AuthProvider.decode(value, options)\n end\nend\n\ndefimpl Poison.Encoder, for: GoogleApi.ServiceManagement.V1.Model.AuthProvider do\n def encode(value, options) do\n GoogleApi.Gax.ModelBase.encode(value, options)\n end\nend\n","avg_line_length":41.3793103448,"max_line_length":151,"alphanum_fraction":0.6910416667}
{"size":3024,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This file is auto generated by the elixir code generator program.\n# Do not edit this file manually.\n\ndefmodule GoogleApi.SearchConsole.V1.Model.UrlInspectionResult do\n @moduledoc \"\"\"\n URL inspection result, including all inspection results.\n\n ## Attributes\n\n * `ampResult` (*type:* `GoogleApi.SearchConsole.V1.Model.AmpInspectionResult.t`, *default:* `nil`) - Result of the AMP analysis. Absent if the page is not an AMP page.\n * `indexStatusResult` (*type:* `GoogleApi.SearchConsole.V1.Model.IndexStatusInspectionResult.t`, *default:* `nil`) - Result of the index status analysis.\n * `inspectionResultLink` (*type:* `String.t`, *default:* `nil`) - Link to Search Console URL inspection.\n * `mobileUsabilityResult` (*type:* `GoogleApi.SearchConsole.V1.Model.MobileUsabilityInspectionResult.t`, *default:* `nil`) - Result of the Mobile usability analysis.\n * `richResultsResult` (*type:* `GoogleApi.SearchConsole.V1.Model.RichResultsInspectionResult.t`, *default:* `nil`) - Result of the Rich Results analysis. Absent if there are no rich results found.\n \"\"\"\n\n use GoogleApi.Gax.ModelBase\n\n @type t :: %__MODULE__{\n :ampResult => GoogleApi.SearchConsole.V1.Model.AmpInspectionResult.t() | nil,\n :indexStatusResult =>\n GoogleApi.SearchConsole.V1.Model.IndexStatusInspectionResult.t() | nil,\n :inspectionResultLink => String.t() | nil,\n :mobileUsabilityResult =>\n GoogleApi.SearchConsole.V1.Model.MobileUsabilityInspectionResult.t() | nil,\n :richResultsResult =>\n GoogleApi.SearchConsole.V1.Model.RichResultsInspectionResult.t() | nil\n }\n\n field(:ampResult, as: GoogleApi.SearchConsole.V1.Model.AmpInspectionResult)\n field(:indexStatusResult, as: GoogleApi.SearchConsole.V1.Model.IndexStatusInspectionResult)\n field(:inspectionResultLink)\n\n field(:mobileUsabilityResult,\n as: GoogleApi.SearchConsole.V1.Model.MobileUsabilityInspectionResult\n )\n\n field(:richResultsResult, as: GoogleApi.SearchConsole.V1.Model.RichResultsInspectionResult)\nend\n\ndefimpl Poison.Decoder, for: GoogleApi.SearchConsole.V1.Model.UrlInspectionResult do\n def decode(value, options) do\n GoogleApi.SearchConsole.V1.Model.UrlInspectionResult.decode(value, options)\n end\nend\n\ndefimpl Poison.Encoder, for: GoogleApi.SearchConsole.V1.Model.UrlInspectionResult do\n def encode(value, options) do\n GoogleApi.Gax.ModelBase.encode(value, options)\n end\nend\n","avg_line_length":45.8181818182,"max_line_length":200,"alphanum_fraction":0.7476851852}
{"size":1553,"ext":"ex","lang":"Elixir","max_stars_count":61.0,"content":"defmodule Shopifex.DataCase do\n @moduledoc \"\"\"\n This module defines the setup for tests requiring\n access to the application's data layer.\n\n You may define functions here to be used as helpers in\n your tests.\n\n Finally, if the test case interacts with the database,\n we enable the SQL sandbox, so changes done to the database\n are reverted at the end of every test. If you are using\n PostgreSQL, you can even run database tests asynchronously\n by setting `use Shopifex.DataCase, async: true`, although\n this option is not recommended for other databases.\n \"\"\"\n\n use ExUnit.CaseTemplate\n\n using do\n quote do\n alias ShopifexDummy.Repo\n\n import Ecto\n import Ecto.Changeset\n import Ecto.Query\n import Shopifex.DataCase\n end\n end\n\n setup tags do\n :ok = Ecto.Adapters.SQL.Sandbox.checkout(ShopifexDummy.Repo)\n\n unless tags[:async] do\n Ecto.Adapters.SQL.Sandbox.mode(ShopifexDummy.Repo, {:shared, self()})\n end\n\n :ok\n end\n\n @doc \"\"\"\n A helper that transforms changeset errors into a map of messages.\n\n assert {:error, changeset} = Accounts.create_user(%{password: \"short\"})\n assert \"password is too short\" in errors_on(changeset).password\n assert %{password: [\"password is too short\"]} = errors_on(changeset)\n\n \"\"\"\n def errors_on(changeset) do\n Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->\n Regex.replace(~r\"%{(\\w+)}\", message, fn _, key ->\n opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()\n end)\n end)\n end\nend\n","avg_line_length":27.7321428571,"max_line_length":77,"alphanum_fraction":0.6928525435}
{"size":1970,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"use Mix.Config\n\n# For development, we disable any cache and enable\n# debugging and code reloading.\n#\n# The watchers configuration can be used to run external\n# watchers to your application. For example, we use it\n# with webpack to recompile .js and .css sources.\nconfig :school_house, SchoolHouseWeb.Endpoint,\n http: [port: 4000],\n debug_errors: true,\n code_reloader: true,\n check_origin: false,\n watchers: [\n node: [\n \"node_modules\/webpack\/bin\/webpack.js\",\n \"--mode\",\n \"development\",\n \"--watch-stdin\",\n cd: Path.expand(\"..\/assets\", __DIR__)\n ]\n ]\n\n# ## SSL Support\n#\n# In order to use HTTPS in development, a self-signed\n# certificate can be generated by running the following\n# Mix task:\n#\n# mix phx.gen.cert\n#\n# Note that this task requires Erlang\/OTP 20 or later.\n# Run `mix help phx.gen.cert` for more information.\n#\n# The `http:` config above can be replaced with:\n#\n# https: [\n# port: 4001,\n# cipher_suite: :strong,\n# keyfile: \"priv\/cert\/selfsigned_key.pem\",\n# certfile: \"priv\/cert\/selfsigned.pem\"\n# ],\n#\n# If desired, both `http:` and `https:` keys can be\n# configured to run both http and https servers on\n# different ports.\n\n# Watch static and templates for browser reloading.\nconfig :school_house, SchoolHouseWeb.Endpoint,\n live_reload: [\n patterns: [\n ~r\"priv\/static\/.*(js|css|png|jpeg|jpg|gif|svg)$\",\n ~r\"priv\/gettext\/.*(po)$\",\n ~r\"lib\/school_house_web\/(live|views)\/.*(ex)$\",\n ~r\"lib\/school_house_web\/templates\/.*(eex)$\",\n ~r\"lessons\/*\/.*(md)$\"\n ]\n ]\n\n# Do not include metadata nor timestamps in development logs\nconfig :logger, :console, format: \"[$level] $message\\n\"\n\n# Set a higher stacktrace during development. Avoid configuring such\n# in production as building large stacktraces may be expensive.\nconfig :phoenix, :stacktrace_depth, 20\n\n# Initialize plugs at runtime for faster development compilation\nconfig :phoenix, :plug_init_mode, :runtime\n","avg_line_length":28.5507246377,"max_line_length":68,"alphanum_fraction":0.683248731}
{"size":73,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"use Mix.Config\n\n# Start server in OTP\n# config :grpc, start_server: true\n","avg_line_length":14.6,"max_line_length":34,"alphanum_fraction":0.7397260274}
{"size":1824,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule JWTTest do\n use ExUnit.Case\n\n doctest JWT\n\n @hs256_key \"gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9C\"\n @key_id \"test-key\"\n @claims %{\"abc\" => \"def\", \"num\" => 1300819380, \"http:\/\/example.com\/is_root\" => true}\n\n defp sign_does_verify(options, claims \\\\ @claims) do\n jwt = JWT.sign(claims, options)\n {:ok, verified_claims} = JWT.verify(jwt, options)\n assert verified_claims === claims\n end\n\n test \"sign\/2 w 'none' alg (and no key) does verify\/2\" do\n sign_does_verify(%{alg: \"none\"})\n end\n\n test \"sign\/2 w default alg (HS256) does verify\/2\" do\n sign_does_verify(%{key: @hs256_key})\n end\n\n test \"sign\/2 w explicit alg does verify\/2\" do\n sign_does_verify(%{alg: \"HS256\", key: @hs256_key})\n end\n\n test \"sign\/2 w explicit alg and wrong key returns error\" do\n wrong_key = \"gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9Z\"\n options = %{alg: \"HS256\", key: @hs256_key}\n jwt = JWT.sign(@claims, options)\n assert {:error, :invalid_signature} == JWT.verify(jwt, %{alg: \"HS256\", key: wrong_key})\n end\n\n test \"unify_header\/1 w key, w\/o alg returns default alg and filters key\" do\n assert JWT.unify_header(key: @hs256_key) == %{typ: \"JWT\", alg: \"HS256\"}\n end\n\n test \"unify_header\/1 w key, w alg returns alg and filters key\" do\n assert JWT.unify_header(alg: \"RS256\", key: \"rs_256_key\") == %{typ: \"JWT\", alg: \"RS256\"}\n end\n\n test \"unify_header\/1 w\/o key, w alg 'none'\" do\n assert JWT.unify_header(alg: \"none\") == %{typ: \"JWT\", alg: \"none\"}\n end\n\n test \"unify_header\/1 with key and key id includes the key id\" do\n assert JWT.unify_header(key: @hs256_key, kid: @key_id) == %{typ: \"JWT\", alg: \"HS256\", kid: \"test-key\"}\n end\n\n test \"unify_header\/1 excludes header that is not registered\" do\n assert JWT.unify_header(key: @hs256_key, notstandard: \"value\") == %{typ: \"JWT\", alg: \"HS256\"}\n end\nend\n","avg_line_length":33.1636363636,"max_line_length":106,"alphanum_fraction":0.6655701754}
{"size":1255,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"import Config\n\nconfig :postoffice, PostofficeWeb.Endpoint,\n secret_key_base: {:system, \"SECRET_KEY_BASE\", default: \"12121212\"}\n\nconfig :postoffice, pubsub_project_name: {:system, \"GCLOUD_PUBSUB_PROJECT_ID\", default: \"test\"}\n\nconfig :postoffice, Postoffice.Repo,\n username: {:system, \"DB_USERNAME\", default: \"postgres\"},\n hostname: {:system, \"DB_HOST\", default: \"db\"},\n password: {:system, \"DB_PASSWORD\", default: \"postgres\"},\n database: {:system, \"DB_NAME\", default: \"myapp\"},\n port: {:system, \"DB_PORT\", type: :integer, default: 5432},\n pool_size: {:system, \"DB_POOL_SIZE\", type: :integer, default: 20},\n queue_target: {:system, \"DB_QUEUE_TARGET\", type: :integer, default: 3000},\n show_sensitive_data_on_connection_error: false\n\n# If K8S_CLUSTER env_variable is set we'll try to setup a k8s cluster\nif System.get_env(\"K8S_CLUSTER\") do\n config :libcluster,\n topologies: [\n k8s: [\n strategy: Elixir.Cluster.Strategy.Kubernetes,\n config: [\n mode: :ip,\n kubernetes_node_basename: System.get_env(\"K8S_NODE_BASENAME\"),\n kubernetes_selector: System.get_env(\"K8S_SELECTOR\"),\n kubernetes_namespace: System.get_env(\"K8S_NAMESPACE\"),\n polling_interval: 10_000\n ]\n ]\n ]\nend\n","avg_line_length":36.9117647059,"max_line_length":95,"alphanum_fraction":0.6900398406}
{"size":1383,"ext":"ex","lang":"Elixir","max_stars_count":8.0,"content":"defmodule EHealth.Web.V2.LegalEntityController do\n @moduledoc false\n\n use EHealth.Web, :controller\n\n alias Core.V2.LegalEntities, as: API\n alias EHealth.Web.LegalEntityController\n alias Scrivener.Page\n\n action_fallback(EHealth.Web.FallbackController)\n\n def index(conn, params) do\n # Respect MSP token\n legal_entity_id = Map.get(conn.params, \"legal_entity_id\")\n\n params =\n if is_nil(legal_entity_id),\n do: params,\n else: Map.put(params, \"ids\", legal_entity_id)\n\n with %Page{} = paging <- API.list(params) do\n render(conn, \"index.json\", legal_entities: paging.entries, paging: paging)\n end\n end\n\n def show(%Plug.Conn{req_headers: req_headers} = conn, %{\"id\" => id}) do\n with {:ok, legal_entity} <- API.get_by_id(id, req_headers) do\n render(conn, \"show.json\", legal_entity: legal_entity)\n end\n end\n\n def create_or_update(%Plug.Conn{req_headers: req_headers} = conn, legal_entity_params) do\n with {:ok, %{legal_entity: legal_entity, employee_request: employee_request, security: security}} <-\n API.create(legal_entity_params, req_headers) do\n conn\n |> assign_security(security)\n |> assign_employee_request_id(employee_request)\n |> render(\"show.json\", legal_entity: legal_entity)\n end\n end\n\n defdelegate assign_employee_request_id(conn, employee_request_id), to: LegalEntityController\nend\n","avg_line_length":31.4318181818,"max_line_length":104,"alphanum_fraction":0.7114967462}
{"size":1214,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule DrabSpikeWeb.UserSocket do\n use Phoenix.Socket\n use Drab.Socket\n\n ## Channels\n # channel \"room:*\", DrabSpikeWeb.RoomChannel\n\n ## Transports\n transport :websocket, Phoenix.Transports.WebSocket, timeout: 45_000\n # transport :longpoll, Phoenix.Transports.LongPoll\n\n # Socket params are passed from the client and can\n # be used to verify and authenticate a user. After\n # verification, you can put default assigns into\n # the socket that will be set for all channels, ie\n #\n # {:ok, assign(socket, :user_id, verified_user_id)}\n #\n # To deny connection, return `:error`.\n #\n # See `Phoenix.Token` documentation for examples in\n # performing token verification on connect.\n def connect(_params, socket) do\n {:ok, socket}\n end\n\n # Socket id's are topics that allow you to identify all sockets for a given user:\n #\n # def id(socket), do: \"user_socket:#{socket.assigns.user_id}\"\n #\n # Would allow you to broadcast a \"disconnect\" event and terminate\n # all active sockets and channels for a given user:\n #\n # DrabSpikeWeb.Endpoint.broadcast(\"user_socket:#{user.id}\", \"disconnect\", %{})\n #\n # Returning `nil` makes this socket anonymous.\n def id(_socket), do: nil\nend\n","avg_line_length":31.1282051282,"max_line_length":84,"alphanum_fraction":0.7059308072}
{"size":6761,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule Phoenix.Endpoint.Cowboy2Handler do\n @moduledoc false\n\n if Code.ensure_loaded?(:cowboy_websocket) and\n function_exported?(:cowboy_websocket, :behaviour_info, 1) do\n @behaviour :cowboy_websocket\n end\n\n @connection Plug.Cowboy.Conn\n @already_sent {:plug_conn, :sent}\n @adapter :phoenix_cowboy\n\n # Note we keep the websocket state as [handler | state]\n # to avoid conflicts with {endpoint, opts}.\n def init(req, {endpoint, opts}) do\n init(@connection.conn(req), endpoint, opts, true)\n end\n\n defp init(conn, endpoint, opts, retry?) do\n start = System.monotonic_time()\n\n :telemetry.execute(\n [:plug_adapter, :call, :start],\n %{system_time: System.system_time()},\n %{adapter: @adapter, conn: conn, plug: endpoint}\n )\n\n try do\n case endpoint.__handler__(conn, opts) do\n {:websocket, conn, handler, opts} ->\n case Phoenix.Transports.WebSocket.connect(conn, endpoint, handler, opts) do\n {:ok, %Plug.Conn{adapter: {@connection, req}} = conn, state} ->\n cowboy_opts =\n opts\n |> Enum.flat_map(fn\n {:timeout, timeout} -> [idle_timeout: timeout]\n {:compress, _} = opt -> [opt]\n {:max_frame_size, _} = opt -> [opt]\n _other -> []\n end)\n |> Map.new()\n\n :telemetry.execute(\n [:plug_adapter, :call, :stop],\n %{duration: System.monotonic_time() - start},\n %{adapter: @adapter, conn: conn, plug: endpoint}\n )\n\n {:cowboy_websocket, copy_resp_headers(conn, req), [handler | state], cowboy_opts}\n\n {:error, %Plug.Conn{adapter: {@connection, req}} = conn} ->\n :telemetry.execute(\n [:plug_adapter, :call, :stop],\n %{duration: System.monotonic_time() - start},\n %{adapter: @adapter, conn: conn, plug: endpoint}\n )\n\n {:ok, copy_resp_headers(conn, req), {handler, opts}}\n end\n\n {:plug, conn, handler, opts} ->\n %{adapter: {@connection, req}} =\n conn =\n conn\n |> handler.call(opts)\n |> maybe_send(handler)\n\n :telemetry.execute(\n [:plug_adapter, :call, :stop],\n %{duration: System.monotonic_time() - start},\n %{adapter: @adapter, conn: conn, plug: endpoint}\n )\n\n {:ok, req, {handler, opts}}\n end\n catch\n kind, reason ->\n :telemetry.execute(\n [:plug_adapter, :call, :exception],\n %{duration: System.monotonic_time() - start},\n %{\n kind: kind,\n reason: reason,\n stacktrace: __STACKTRACE__,\n adapter: @adapter,\n conn: conn,\n plug: endpoint\n }\n )\n\n case __STACKTRACE__ do\n # Maybe the handler is not available because the code is being recompiled.\n # Sync with the code reloader and retry once.\n [{^endpoint, :__handler__, _, _} | _] when reason == :undef and retry? ->\n Phoenix.CodeReloader.Server.sync()\n init(conn, endpoint, opts, false)\n\n stacktrace ->\n exit_on_error(kind, reason, stacktrace, {endpoint, :call, [conn, opts]})\n end\n after\n receive do\n @already_sent -> :ok\n after\n 0 -> :ok\n end\n end\n end\n\n defp maybe_send(%Plug.Conn{state: :unset}, _plug), do: raise(Plug.Conn.NotSentError)\n defp maybe_send(%Plug.Conn{state: :set} = conn, _plug), do: Plug.Conn.send_resp(conn)\n defp maybe_send(%Plug.Conn{} = conn, _plug), do: conn\n\n defp maybe_send(other, plug) do\n raise \"Cowboy2 adapter expected #{inspect(plug)} to return Plug.Conn but got: \" <>\n inspect(other)\n end\n\n defp exit_on_error(\n :error,\n %Plug.Conn.WrapperError{kind: kind, reason: reason, stack: stack},\n _stack,\n call\n ) do\n exit_on_error(kind, reason, stack, call)\n end\n\n defp exit_on_error(:error, value, stack, call) do\n exception = Exception.normalize(:error, value, stack)\n exit({{exception, stack}, call})\n end\n\n defp exit_on_error(:throw, value, stack, call) do\n exit({{{:nocatch, value}, stack}, call})\n end\n\n defp exit_on_error(:exit, value, _stack, call) do\n exit({value, call})\n end\n\n defp copy_resp_headers(%Plug.Conn{} = conn, req) do\n Enum.reduce(conn.resp_headers, req, fn {key, val}, acc ->\n :cowboy_req.set_resp_header(key, val, acc)\n end)\n end\n\n defp handle_reply(handler, {:ok, state}), do: {:ok, [handler | state]}\n defp handle_reply(handler, {:push, data, state}), do: {:reply, data, [handler | state]}\n\n defp handle_reply(handler, {:reply, _status, data, state}),\n do: {:reply, data, [handler | state]}\n\n defp handle_reply(handler, {:stop, _reason, state}), do: {:stop, [handler | state]}\n\n defp handle_control_frame(payload_with_opts, handler_state) do\n [handler | state] = handler_state\n reply =\n if function_exported?(handler, :handle_control, 2) do\n handler.handle_control(payload_with_opts, state)\n else\n {:ok, state}\n end\n\n handle_reply(handler, reply)\n end\n\n ## Websocket callbacks\n\n def websocket_init([handler | state]) do\n {:ok, state} = handler.init(state)\n {:ok, [handler | state]}\n end\n\n def websocket_handle({opcode, payload}, [handler | state]) when opcode in [:text, :binary] do\n handle_reply(handler, handler.handle_in({payload, opcode: opcode}, state))\n end\n\n def websocket_handle({opcode, payload}, handler_state) when opcode in [:ping, :pong] do\n handle_control_frame({payload, opcode: opcode}, handler_state)\n end\n\n def websocket_handle(opcode, handler_state) when opcode in [:ping, :pong] do\n handle_control_frame({nil, opcode: opcode}, handler_state)\n end\n\n def websocket_handle(_other, handler_state) do\n {:ok, handler_state}\n end\n\n def websocket_info(message, [handler | state]) do\n handle_reply(handler, handler.handle_info(message, state))\n end\n\n def terminate(_reason, _req, {_handler, _state}) do\n :ok\n end\n\n def terminate({:error, :closed}, _req, [handler | state]) do\n handler.terminate(:closed, state)\n end\n\n def terminate({:remote, :closed}, _req, [handler | state]) do\n handler.terminate(:closed, state)\n end\n\n def terminate({:remote, code, _}, _req, [handler | state])\n when code in 1000..1003 or code in 1005..1011 or code == 1015 do\n handler.terminate(:closed, state)\n end\n\n def terminate(:remote, _req, [handler | state]) do\n handler.terminate(:closed, state)\n end\n\n def terminate(reason, _req, [handler | state]) do\n handler.terminate(reason, state)\n end\nend\n","avg_line_length":30.8721461187,"max_line_length":95,"alphanum_fraction":0.5991717202}
{"size":3155,"ext":"ex","lang":"Elixir","max_stars_count":1.0,"content":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This class is auto generated by the elixir code generator program.\n# Do not edit the class manually.\n\ndefmodule GoogleApi.Drive.V3.Model.Channel do\n @moduledoc \"\"\"\n An notification channel used to watch for resource changes.\n\n ## Attributes\n\n * `address` (*type:* `String.t`, *default:* `nil`) - The address where notifications are delivered for this channel.\n * `expiration` (*type:* `String.t`, *default:* `nil`) - Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional.\n * `id` (*type:* `String.t`, *default:* `nil`) - A UUID or similar unique string that identifies this channel.\n * `kind` (*type:* `String.t`, *default:* `api#channel`) - Identifies this as a notification channel used to watch for changes to a resource, which is \"api#channel\".\n * `params` (*type:* `map()`, *default:* `nil`) - Additional parameters controlling delivery channel behavior. Optional.\n * `payload` (*type:* `boolean()`, *default:* `nil`) - A Boolean value to indicate whether payload is wanted. Optional.\n * `resourceId` (*type:* `String.t`, *default:* `nil`) - An opaque ID that identifies the resource being watched on this channel. Stable across different API versions.\n * `resourceUri` (*type:* `String.t`, *default:* `nil`) - A version-specific identifier for the watched resource.\n * `token` (*type:* `String.t`, *default:* `nil`) - An arbitrary string delivered to the target address with each notification delivered over this channel. Optional.\n * `type` (*type:* `String.t`, *default:* `nil`) - The type of delivery mechanism used for this channel.\n \"\"\"\n\n use GoogleApi.Gax.ModelBase\n\n @type t :: %__MODULE__{\n :address => String.t(),\n :expiration => String.t(),\n :id => String.t(),\n :kind => String.t(),\n :params => map(),\n :payload => boolean(),\n :resourceId => String.t(),\n :resourceUri => String.t(),\n :token => String.t(),\n :type => String.t()\n }\n\n field(:address)\n field(:expiration)\n field(:id)\n field(:kind)\n field(:params, type: :map)\n field(:payload)\n field(:resourceId)\n field(:resourceUri)\n field(:token)\n field(:type)\nend\n\ndefimpl Poison.Decoder, for: GoogleApi.Drive.V3.Model.Channel do\n def decode(value, options) do\n GoogleApi.Drive.V3.Model.Channel.decode(value, options)\n end\nend\n\ndefimpl Poison.Encoder, for: GoogleApi.Drive.V3.Model.Channel do\n def encode(value, options) do\n GoogleApi.Gax.ModelBase.encode(value, options)\n end\nend\n","avg_line_length":42.6351351351,"max_line_length":170,"alphanum_fraction":0.6795562599}
{"size":2551,"ext":"ex","lang":"Elixir","max_stars_count":1.0,"content":"defmodule LiveBeats.Accounts.User do\n use Ecto.Schema\n use EdgeDBEcto.Mapper\n\n import Ecto.Changeset\n\n alias LiveBeats.Accounts.{\n Identity,\n User\n }\n\n @primary_key {:id, :binary_id, autogenerate: false}\n\n schema \"default::User\" do\n field :email, :string\n field :name, :string\n field :username, :string\n field :confirmed_at, :naive_datetime\n field :role, :string, default: \"subscriber\"\n field :profile_tagline, :string\n field :avatar_url, :string\n field :external_homepage_url, :string\n field :songs_count, :integer\n\n has_one :active_profile_user, User\n has_many :identities, Identity\n\n timestamps()\n end\n\n @doc \"\"\"\n A user changeset for github registration.\n \"\"\"\n def github_registration_changeset(info, primary_email, emails, token) do\n %{\"login\" => username, \"avatar_url\" => avatar_url, \"html_url\" => external_homepage_url} = info\n\n identity_changeset =\n Identity.github_registration_changeset(info, primary_email, emails, token)\n\n if identity_changeset.valid? do\n params = %{\n \"username\" => username,\n \"email\" => primary_email,\n \"name\" => get_change(identity_changeset, :provider_name),\n \"avatar_url\" => avatar_url,\n \"external_homepage_url\" => external_homepage_url\n }\n\n %User{}\n |> cast(params, [:email, :name, :username, :avatar_url, :external_homepage_url])\n |> validate_required([:email, :name, :username])\n |> validate_username()\n |> validate_email()\n |> put_assoc(:identities, [identity_changeset])\n else\n %User{}\n |> change()\n |> Map.put(:valid?, false)\n |> put_assoc(:identities, [identity_changeset])\n end\n end\n\n def settings_changeset(%User{} = user, params) do\n user\n |> cast(params, [:username, :profile_tagline])\n |> validate_required([:username, :profile_tagline])\n |> validate_username()\n end\n\n defp validate_email(changeset) do\n changeset\n |> validate_required([:email])\n |> validate_format(:email, ~r\/^[^\\s]+@[^\\s]+$\/, message: \"must have the @ sign and no spaces\")\n |> validate_length(:email, max: 160)\n end\n\n def validate_username(changeset) do\n changeset\n |> validate_format(:username, ~r\/^[a-zA-Z0-9_-]{2,32}$\/)\n |> prepare_changes(fn changeset ->\n case fetch_change(changeset, :profile_tagline) do\n {:ok, _} ->\n changeset\n\n :error ->\n username = get_field(changeset, :username)\n put_change(changeset, :profile_tagline, \"#{username}'s beats\")\n end\n end)\n end\nend\n","avg_line_length":27.7282608696,"max_line_length":98,"alphanum_fraction":0.6471971776}
{"size":1888,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This file is auto generated by the elixir code generator program.\n# Do not edit this file manually.\n\ndefmodule GoogleApi.Memcache.Mixfile do\n use Mix.Project\n\n @version \"0.2.0\"\n\n def project() do\n [\n app: :google_api_memcache,\n version: @version,\n elixir: \"~> 1.6\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n description: description(),\n package: package(),\n deps: deps(),\n source_url: \"https:\/\/github.com\/googleapis\/elixir-google-api\/tree\/master\/clients\/memcache\"\n ]\n end\n\n def application() do\n [extra_applications: [:logger]]\n end\n\n defp deps() do\n [\n {:google_gax, \"~> 0.2\"},\n\n {:ex_doc, \"~> 0.16\", only: :dev}\n ]\n end\n\n defp description() do\n \"\"\"\n Cloud Memorystore for Memcached API client library. Google Cloud Memorystore for Memcached API is used for creating and managing Memcached instances in GCP.\n \"\"\"\n end\n\n defp package() do\n [\n files: [\"lib\", \"mix.exs\", \"README*\", \"LICENSE\"],\n maintainers: [\"Jeff Ching\", \"Daniel Azuma\"],\n licenses: [\"Apache 2.0\"],\n links: %{\n \"GitHub\" => \"https:\/\/github.com\/googleapis\/elixir-google-api\/tree\/master\/clients\/memcache\",\n \"Homepage\" => \"https:\/\/cloud.google.com\/memorystore\/\"\n }\n ]\n end\nend\n","avg_line_length":28.1791044776,"max_line_length":160,"alphanum_fraction":0.6604872881}
{"size":2283,"ext":"ex","lang":"Elixir","max_stars_count":1.0,"content":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This class is auto generated by the elixir code generator program.\n# Do not edit the class manually.\n\ndefmodule GoogleApi.Spanner.V1.Model.CreateInstanceMetadata do\n @moduledoc \"\"\"\n Metadata type for the operation returned by\n CreateInstance.\n\n ## Attributes\n\n * `cancelTime` (*type:* `DateTime.t`, *default:* `nil`) - The time at which this operation was cancelled. If set, this operation is\n in the process of undoing itself (which is guaranteed to succeed) and\n cannot be cancelled again.\n * `endTime` (*type:* `DateTime.t`, *default:* `nil`) - The time at which this operation failed or was completed successfully.\n * `instance` (*type:* `GoogleApi.Spanner.V1.Model.Instance.t`, *default:* `nil`) - The instance being created.\n * `startTime` (*type:* `DateTime.t`, *default:* `nil`) - The time at which the\n CreateInstance request was\n received.\n \"\"\"\n\n use GoogleApi.Gax.ModelBase\n\n @type t :: %__MODULE__{\n :cancelTime => DateTime.t(),\n :endTime => DateTime.t(),\n :instance => GoogleApi.Spanner.V1.Model.Instance.t(),\n :startTime => DateTime.t()\n }\n\n field(:cancelTime, as: DateTime)\n field(:endTime, as: DateTime)\n field(:instance, as: GoogleApi.Spanner.V1.Model.Instance)\n field(:startTime, as: DateTime)\nend\n\ndefimpl Poison.Decoder, for: GoogleApi.Spanner.V1.Model.CreateInstanceMetadata do\n def decode(value, options) do\n GoogleApi.Spanner.V1.Model.CreateInstanceMetadata.decode(value, options)\n end\nend\n\ndefimpl Poison.Encoder, for: GoogleApi.Spanner.V1.Model.CreateInstanceMetadata do\n def encode(value, options) do\n GoogleApi.Gax.ModelBase.encode(value, options)\n end\nend\n","avg_line_length":37.4262295082,"max_line_length":135,"alphanum_fraction":0.7152869032}
{"size":1337,"ext":"ex","lang":"Elixir","max_stars_count":1.0,"content":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This file is auto generated by the elixir code generator program.\n# Do not edit this file manually.\n\ndefmodule GoogleApi.HealthCare.V1beta1.Model.ArchiveUserDataMappingResponse do\n @moduledoc \"\"\"\n Archives the specified User data mapping.\n\n ## Attributes\n\n \"\"\"\n\n use GoogleApi.Gax.ModelBase\n\n @type t :: %__MODULE__{}\nend\n\ndefimpl Poison.Decoder, for: GoogleApi.HealthCare.V1beta1.Model.ArchiveUserDataMappingResponse do\n def decode(value, options) do\n GoogleApi.HealthCare.V1beta1.Model.ArchiveUserDataMappingResponse.decode(value, options)\n end\nend\n\ndefimpl Poison.Encoder, for: GoogleApi.HealthCare.V1beta1.Model.ArchiveUserDataMappingResponse do\n def encode(value, options) do\n GoogleApi.Gax.ModelBase.encode(value, options)\n end\nend\n","avg_line_length":31.8333333333,"max_line_length":97,"alphanum_fraction":0.7756170531}
{"size":4146,"ext":"ex","lang":"Elixir","max_stars_count":3.0,"content":"defmodule MishkaHtmlWeb.AdminUserRolesLive do\n use MishkaHtmlWeb, :live_view\n\n alias MishkaUser.Acl.Role\n @section_title MishkaTranslator.Gettext.dgettext(\"html_live\", \"\u0646\u0642\u0634 \u0647\u0627\u06cc \u06a9\u0627\u0631\u0628\u0631\u06cc\")\n\n use MishkaHtml.Helpers.LiveCRUD,\n module: MishkaUser.Acl.Role,\n redirect: __MODULE__,\n router: Routes\n\n\n @impl true\n def render(assigns) do\n ~H\"\"\"\n <.live_component\n module={MishkaHtml.Helpers.ListContainerComponent}\n id={:list_container}\n flash={@flash}\n section_info={section_info(assigns, @socket)}\n filters={@filters}\n list={@roles}\n url={MishkaHtmlWeb.AdminUserRolesLive}\n page_size={@page_size}\n parent_assigns={assigns}\n admin_menu={live_render(@socket, AdminMenu, id: :admin_menu)}\n left_header_side=\"\"\n \/>\n \"\"\"\n end\n\n @impl true\n def mount(_params, session, socket) do\n Process.send_after(self(), :menu, 100)\n socket =\n assign(socket,\n page_size: 10,\n filters: %{},\n page: 1,\n open_modal: false,\n component: nil,\n user_id: Map.get(session, \"user_id\"),\n page_title: @section_title,\n body_color: \"#a29ac3cf\",\n roles: Role.roles(conditions: {1, 10}, filters: %{})\n )\n {:ok, socket, temporary_assigns: [roles: []]}\n end\n\n # Live CRUD\n paginate(:roles, user_id: false)\n\n list_search_and_action()\n\n delete_list_item(:roles, DeleteErrorComponent, false, do: fn data ->\n data\n end, before: fn x -> MishkaUser.Acl.AclTask.delete_role(x) end)\n\n selected_menue(\"MishkaHtmlWeb.AdminUserRolesLive\")\n\n update_list(:roles, false)\n\n def section_fields() do\n [\n ListItemComponent.text_field(\"name\", [1], \"col header1\", MishkaTranslator.Gettext.dgettext(\"html_live\", \"\u0646\u0627\u0645\"),\n {true, false, true}, &MishkaHtml.title_sanitize\/1),\n ListItemComponent.text_field(\"display_name\", [1], \"col header2\", MishkaTranslator.Gettext.dgettext(\"html_live\", \"\u0646\u0627\u0645 \u0646\u0645\u0627\u06cc\u0634\"),\n {true, false, true}, &MishkaHtml.username_sanitize\/1),\n ListItemComponent.time_field(\"inserted_at\", [1], \"col header3\", MishkaTranslator.Gettext.dgettext(\"html_live\", \"\u062b\u0628\u062a\"), false,\n {true, false, false})\n ]\n end\n\n def section_info(assigns, socket) do\n %{\n section_btns: %{\n header: [\n %{\n title: MishkaTranslator.Gettext.dgettext(\"html_live_templates\", \"\u0633\u0627\u062e\u062a \u0646\u0641\u0634\"),\n router: Routes.live_path(socket, MishkaHtmlWeb.AdminUserRoleLive),\n class: \"btn btn-outline-danger\"\n },\n %{\n title: MishkaTranslator.Gettext.dgettext(\"html_live_templates\", \"\u0628\u0631\u06af\u0634\u062a \u0628\u0647 \u06a9\u0627\u0631\u0628\u0631\u0627\u0646\"),\n router: Routes.live_path(socket, MishkaHtmlWeb.AdminUsersLive),\n class: \"btn btn-outline-info\"\n }\n ],\n list_item: [\n %{\n method: :delete,\n router: nil,\n title: MishkaTranslator.Gettext.dgettext(\"html_live\", \"\u062d\u0630\u0641\"),\n class: \"btn btn-outline-danger vazir\"\n },\n %{\n method: :redirect_key,\n router: MishkaHtmlWeb.AdminUserRolePermissionsLive,\n title: MishkaTranslator.Gettext.dgettext(\"html_live\", \"\u0645\u062f\u06cc\u0631\u06cc\u062a \u062f\u0633\u062a\u0631\u0633\u06cc \u0647\u0627\"),\n class: \"btn btn-outline-info vazir\",\n action: :id\n }\n ]\n },\n title: @section_title,\n activities_info: %{\n title: MishkaTranslator.Gettext.dgettext(\"html_live_templates\", \"\u0646\u0642\u0634 \u0647\u0627\"),\n section_type: MishkaTranslator.Gettext.dgettext(\"html_live_component\", \"\u0646\u0642\u0634\"),\n action: :section,\n action_by: :section,\n },\n custom_operations: nil,\n description:\n ~H\"\"\"\n <%= MishkaTranslator.Gettext.dgettext(\"html_live_templates\", \"\u062f\u0631 \u0627\u06cc\u0646 \u0628\u062e\u0634 \u0634\u0645\u0627 \u0645\u06cc \u062a\u0648\u0627\u0646\u06cc\u062f \u0646\u0642\u0634 \u0647\u0627\u06cc \u06a9\u0627\u0631\u0628\u0631\u06cc \u0631\u0627 \u0628\u0633\u0627\u0632\u06cc\u062f \u0648 \u0628\u0647 \u0647\u0631 \u0646\u0642\u0634 \u06cc\u06a9 \u0633\u0631\u06cc \u0633\u0637\u0648\u062d \u062f\u0633\u062a\u0631\u0633\u06cc \u0645\u062e\u0635\u0648\u0635 \u0628\u0647 \u0633\u0627\u06cc\u062a \u0631\u0627 \u062a\u062e\u0635\u06cc\u0635 \u0628\u062f\u0647\u06cc\u062f. \u0644\u0627\u0632\u0645 \u0628\u0647 \u0630\u06a9\u0631 \u0627\u0633\u062a \u0628\u0639\u062f \u0627\u0632 \u0633\u0627\u062e\u062a \u0646\u0642\u0634 \u0648 \u062a\u062e\u0635\u06cc\u0635 \u06cc\u06a9 \u06cc\u0627 \u0686\u0646\u062f \u062f\u0633\u062a\u0631\u0633\u06cc \u0628\u0647 \u0622\u0646 \u062d\u0627\u0644 \u0645\u06cc \u062a\u0648\u0627\u0646\u06cc\u062f \u0648\u0627\u0631\u062f \u0645\u062f\u06cc\u0631\u06cc\u062a \u06a9\u0627\u0631\u0628\u0631\u0627\u0646 \u0634\u062f\u0647 \u0648 \u06cc\u06a9 \u06a9\u0627\u0631\u0628\u0631 \u0631\u0627 \u0628\u0647 \u06cc\u06a9 \u0646\u0642\u0634 \u062e\u0627\u0635 \u062a\u062e\u0635\u06cc\u0635 \u0628\u062f\u0647\u06cc\u062f. \u062f\u0631 \u0632\u0645\u0627\u0646\u06cc \u0634\u0645\u0627 \u0627\u0632 \u0646\u0642\u0634 \u0647\u0627 \u0627\u0633\u062a\u0641\u0627\u062f\u0647 \u0645\u06cc \u06a9\u0646\u06cc\u062f \u06a9\u0647 \u0645\u06cc \u062e\u0648\u0627\u0647\u06cc\u062f \u0628\u0631\u062e\u06cc \u0627\u0632 \u0628\u062e\u0634 \u0647\u0627\u06cc \u0633\u0627\u06cc\u062a \u062e\u0648\u062f \u0631\u0627 \u0628\u0647 \u06af\u0631\u0648\u0647 \u06a9\u0627\u0631\u0628\u0631\u06cc \u062e\u0627\u0635\u06cc \u0627\u062c\u0627\u0632\u0647 \u062f\u0633\u062a\u0631\u0633\u06cc \u0628\u062f\u0647\u06cc\u062f.\") %>\n <div class=\"space30\"><\/div>\n \"\"\"\n }\n end\nend\n","avg_line_length":34.2644628099,"max_line_length":447,"alphanum_fraction":0.6314520019}
{"size":65,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule IMDbDataWeb.PersonView do\n use IMDbDataWeb, :view\nend\n","avg_line_length":16.25,"max_line_length":35,"alphanum_fraction":0.8153846154}
{"size":1040,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule Gruf.DynamicSupervisor do\n use DynamicSupervisor\n\n alias Gruf.Registry\n\n def start_link(args) do\n DynamicSupervisor.start_link(__MODULE__, args, name: __MODULE__)\n end\n\n def init(_args) do\n DynamicSupervisor.init(strategy: :one_for_one)\n end\n\n def create(name) do\n with true <- Registry.name_available?(name)\n do\n {:ok, bin_state} = Registry.get_state(name)\n\n child_spec = %{\n id: Gruf.Server,\n start: {Gruf.Server, :start_link, [bin_state]},\n type: :worker\n }\n\n {:ok, pid} = reply = DynamicSupervisor.start_child(__MODULE__, child_spec)\n Registry.register(name, pid)\n\n reply\n else\n _ -> {:error, \"Name #{name} is already registered\"}\n end\n end\n\n def remove(name) do\n with false <- Registry.name_available?(name)\n do\n {:ok, pid} = Registry.name2pid(name)\n :ok = DynamicSupervisor.terminate_child(__MODULE__, pid)\n Registry.unregister(name, pid)\n else\n _ -> {:error, \"Name #{name} is not registered\"}\n end\n end\nend\n","avg_line_length":23.1111111111,"max_line_length":80,"alphanum_fraction":0.6461538462}
{"size":4206,"ext":"exs","lang":"Elixir","max_stars_count":1.0,"content":"Code.require_file \"..\/..\/test_helper.exs\", __DIR__\n\ndefmodule Mix.Tasks.App.StartTest do\n use MixTest.Case\n\n defmodule AppStartSample do\n def project do\n [app: :app_start_sample, version: \"0.1.0\"]\n end\n end\n\n defmodule WrongElixirProject do\n def project do\n [app: :error, version: \"0.1.0\", elixir: \"~> 0.8.1\"]\n end\n end\n\n defmodule InvalidElixirRequirement do\n def project do\n [app: :error, version: \"0.1.0\", elixir: \"~> ~> 0.8.1\"]\n end\n end\n\n setup config do\n if config[:app] do\n :error_logger.tty(false)\n end\n :ok\n end\n\n teardown config do\n if app = config[:app] do\n :application.stop(app)\n :application.unload(app)\n end\n :ok\n end\n\n teardown do\n :error_logger.tty(true)\n :ok\n end\n\n test \"recompiles project if elixir version changed\" do\n Mix.Project.push MixTest.Case.Sample\n\n in_fixture \"no_mixfile\", fn ->\n Mix.Tasks.Compile.run []\n purge [A, B, C]\n\n assert_received { :mix_shell, :info, [\"Compiled lib\/a.ex\"] }\n assert System.version == Mix.Dep.Lock.elixir_vsn\n\n Mix.Task.clear\n File.write!(\"_build\/dev\/lib\/sample\/.compile.lock\", \"the_past\")\n File.touch!(\"_build\/dev\/lib\/sample\/.compile.lock\", { { 2010, 1, 1 }, { 0, 0, 0 } })\n\n Mix.Tasks.App.Start.run [\"--no-start\"]\n assert System.version == Mix.Dep.Lock.elixir_vsn\n assert File.stat!(\"_build\/dev\/lib\/sample\/.compile.lock\").mtime > { { 2010, 1, 1 }, { 0, 0, 0 } }\n end\n end\n\n test \"compiles and starts the project\" do\n Mix.Project.push AppStartSample\n\n in_fixture \"no_mixfile\", fn ->\n assert_raise Mix.Error, fn ->\n Mix.Tasks.App.Start.run [\"--no-compile\"]\n end\n\n Mix.Tasks.App.Start.run [\"--no-start\"]\n assert File.regular?(\"_build\/dev\/lib\/app_start_sample\/ebin\/Elixir.A.beam\")\n assert File.regular?(\"_build\/dev\/lib\/app_start_sample\/ebin\/app_start_sample.app\")\n refute List.keyfind(:application.loaded_applications, :app_start_sample, 0)\n\n Mix.Tasks.App.Start.run []\n assert List.keyfind(:application.loaded_applications, :app_start_sample, 0)\n end\n end\n\n test \"validates the Elixir version requirement\" do\n Mix.Project.push WrongElixirProject\n\n in_fixture \"no_mixfile\", fn ->\n assert_raise Mix.ElixirVersionError, ~r\/You're trying to run :error on Elixir\/, fn ->\n Mix.Tasks.App.Start.run [\"--no-start\"]\n end\n end\n end\n\n test \"validates invalid Elixir version requirement\" do\n Mix.Project.push InvalidElixirRequirement\n\n in_fixture \"no_mixfile\", fn ->\n assert_raise Mix.Error, ~r\"Invalid Elixir version requirement\", fn ->\n Mix.Tasks.App.Start.run [\"--no-start\"]\n end\n end\n end\n\n test \"does not validate the Elixir version requirement when disabled\" do\n Mix.Project.push WrongElixirProject\n\n in_fixture \"no_mixfile\", fn ->\n Mix.Tasks.App.Start.run [\"--no-start\", \"--no-elixir-version-check\"]\n end\n end\n\n defmodule BadReturnSample do\n def project do\n [app: :bad_return_sample, version: \"0.1.0\"]\n end\n\n def application do\n Process.get(:application_definition)\n end\n end\n\n defmodule BadReturnApp do\n use Application.Behaviour\n\n def start(_type, _args) do\n :bad # Bad return\n end\n end\n\n test \"start does nothing if app is nil\" do\n assert Mix.Tasks.App.Start.start(nil) == :error\n end\n\n @tag app: :bad_return_sample\n test \"start raises on :error\" do\n Mix.Project.push BadReturnSample\n in_fixture \"no_mixfile\", fn ->\n Process.put(:application_definition, applications: [:unknown])\n Mix.Tasks.Compile.run []\n\n assert_raise Mix.Error, ~r\"Could not start application unknown: \", fn ->\n Mix.Tasks.App.Start.start(:bad_return_sample)\n end\n end\n end\n\n @tag app: :bad_return_sample\n test \"start points to report on bad return\" do\n Mix.Project.push BadReturnSample\n in_fixture \"no_mixfile\", fn ->\n Process.put(:application_definition, mod: { BadReturnApp, [] })\n Mix.Tasks.Compile.run []\n\n assert_raise Mix.Error, ~r\"Could not start application bad_return_sample, please see report above\", fn ->\n Mix.Tasks.App.Start.start(:bad_return_sample)\n end\n end\n end\nend\n","avg_line_length":26.6202531646,"max_line_length":111,"alphanum_fraction":0.6581074655}
{"size":3964,"ext":"exs","lang":"Elixir","max_stars_count":21.0,"content":"defmodule ExAlgo.List.LinkedListTest do\n use ExUnit.Case\n use ExUnitProperties\n @moduletag :linked_list\n\n alias ExAlgo.List.LinkedList\n\n doctest ExAlgo.List.LinkedList\n\n setup_all do\n {:ok,\n %{\n empty_list: LinkedList.new(),\n list: LinkedList.from(1..5)\n }}\n end\n\n describe \"new\/0\" do\n test \"creates an empty linked list\" do\n assert %LinkedList{container: []} == LinkedList.new()\n end\n end\n\n describe \"from\/1\" do\n property \"The list that is passed in is the container of the created list\" do\n check all list <- list_of(integer()) do\n %LinkedList{container: container} = LinkedList.from(list)\n assert container == list\n end\n end\n end\n\n describe \"insert\/2\" do\n test \"insert an element in an empty list\", %{empty_list: list} do\n assert %LinkedList{container: [0]} == list |> LinkedList.insert(0)\n end\n\n test \"insert an element at the head of a list\", %{list: list} do\n %LinkedList{container: container} = list |> LinkedList.insert(0)\n assert container == Enum.to_list(0..5)\n end\n end\n\n describe \"remove\/1\" do\n test \"error when trying to remove from an empty list\", %{empty_list: list} do\n assert {:error, :empty_list} == list |> LinkedList.remove()\n end\n\n test \"remove the head of the list\", %{list: list} do\n {value, %LinkedList{container: container}} = list |> LinkedList.remove()\n assert value == hd(list.container)\n assert container == tl(list.container)\n end\n end\n\n describe \"head\/1\" do\n property \"head always returns the head of the underlying list\" do\n check all list <- nonempty(list_of(integer())) do\n linked_list = LinkedList.from(list)\n assert LinkedList.head(linked_list) == hd(list)\n end\n end\n end\n\n describe \"next\/1\" do\n property \"next always returns the tail of the underlying list\" do\n check all list <- nonempty(list_of(integer())) do\n linked_list = LinkedList.from(list)\n assert LinkedList.next(linked_list).container == tl(list)\n end\n end\n end\n\n describe \"at\/2\" do\n test \"cannot index an empty list\", %{empty_list: list} do\n assert {:error, :empty_list} == LinkedList.at(list, 0)\n assert {:error, :empty_list} == LinkedList.at(list, 1)\n end\n\n test \"cannot use negative index\", %{list: list} do\n assert {:error, :negative_index} == LinkedList.at(list, -1)\n end\n\n test \"when querying an empty list with negative index empty error is returned\", %{\n empty_list: list\n } do\n assert {:error, :empty_list} == LinkedList.at(list, -1)\n end\n end\n\n describe \"inspect\" do\n test \"inspect an empty list\", %{empty_list: list} do\n assert inspect(list) == \"#ExAlgo.LinkedList<[]>\"\n end\n\n test \"inspect an non-empty list\", %{list: list} do\n assert inspect(list) == \"#ExAlgo.LinkedList<[1, 2, 3, 4, 5]>\"\n end\n end\n\n describe \"collectable\" do\n test \"convert a List into LinkedList\" do\n list = for i <- 1..10, into: %LinkedList{}, do: i\n assert list.container == 10..1 |> Enum.to_list()\n end\n end\n\n describe \"enumerable\" do\n test \"length of a list\", lists do\n assert lists.empty_list |> Enum.empty?()\n assert Enum.count(lists.list) == 5\n end\n\n test \"map over a list\", %{list: list} do\n assert Enum.map(list, fn elem -> elem ** 2 end) == [1, 4, 9, 16, 25]\n end\n\n test \"filter over a list\", %{list: list} do\n assert Enum.filter(list, fn elem -> elem > 1 end) == [2, 3, 4, 5]\n end\n\n test \"convert a list to a set\", %{list: list} do\n assert Enum.into(list, %MapSet{}) == MapSet.new([1, 2, 3, 4, 5])\n end\n end\n\n property \"linked list from copies the list into container but enum into inserts one by one\" do\n check all list <- nonempty(list_of(integer())) do\n list_1 = LinkedList.from(list)\n list_2 = Enum.into(list, %LinkedList{})\n assert list_1.container == list_2.container |> Enum.reverse()\n end\n end\nend\n","avg_line_length":29.362962963,"max_line_length":96,"alphanum_fraction":0.6326942482}
{"size":1807,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule ExMultipass.MixProject do\n use Mix.Project\n\n def project do\n [\n app: :ex_multipass,\n version: \"0.3.0\",\n elixir: \"~> 1.12\",\n elixirc_paths: elixirc_paths(Mix.env()),\n start_permanent: Mix.env() == :prod,\n description: description(),\n package: package(),\n deps: deps(),\n test_coverage: [tool: ExCoveralls],\n preferred_cli_env: [\n coveralls: :test,\n \"coveralls.detail\": :test,\n \"coveralls.post\": :test,\n \"coveralls.html\": :test,\n \"coveralls.travis\": :test\n ],\n dialyzer: [\n flags: [\n :unmatched_returns,\n :error_handling,\n :race_conditions,\n :no_opaque\n ]\n ],\n\n # Docs\n name: \"ex_multipass\",\n source_url: \"https:\/\/github.com\/activeprospect\/ex_multipass\"\n ]\n end\n\n def application do\n [\n extra_applications: [:logger]\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n defp deps do\n [\n {:jason, \"~> 1.0\"},\n {:credo, \"~> 1.0\", only: [:dev, :test], runtime: false},\n {:dialyxir, \"~> 1.0\", only: [:dev, :test], runtime: false},\n {:excoveralls, \"~> 0.14\", only: :test},\n {:stream_data, \"~> 0.1\", only: :test},\n {:ex_doc, \"~> 0.24\", only: :dev, runtime: false}\n ]\n end\n\n defp description() do\n \"Ruby compatible multipass encryption and decryption\"\n end\n\n defp package() do\n [\n # These are the default files included in the package\n files: [\"lib\", \"test\", \"config\", \"mix.exs\", \"README*\", \"LICENSE*\"],\n maintainers: [\"Frank Kumro\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/activeprospect\/ex_multipass\"}\n ]\n end\nend\n","avg_line_length":25.0972222222,"max_line_length":76,"alphanum_fraction":0.5589374654}
{"size":2001,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This file is auto generated by the elixir code generator program.\n# Do not edit this file manually.\n\ndefmodule GoogleApi.ManagedIdentities.Mixfile do\n use Mix.Project\n\n @version \"0.18.0\"\n\n def project() do\n [\n app: :google_api_managed_identities,\n version: @version,\n elixir: \"~> 1.6\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n description: description(),\n package: package(),\n deps: deps(),\n source_url: \"https:\/\/github.com\/googleapis\/elixir-google-api\/tree\/master\/clients\/managed_identities\"\n ]\n end\n\n def application() do\n [extra_applications: [:logger]]\n end\n\n defp deps() do\n [\n {:google_gax, \"~> 0.4\"},\n\n {:ex_doc, \"~> 0.16\", only: :dev}\n ]\n end\n\n defp description() do\n \"\"\"\n Managed Service for Microsoft Active Directory API client library. The Managed Service for Microsoft Active Directory API is used for managing a highly available, hardened service running Microsoft Active Directory (AD).\n \"\"\"\n end\n\n defp package() do\n [\n files: [\"lib\", \"mix.exs\", \"README*\", \"LICENSE\"],\n maintainers: [\"Jeff Ching\", \"Daniel Azuma\"],\n licenses: [\"Apache 2.0\"],\n links: %{\n \"GitHub\" => \"https:\/\/github.com\/googleapis\/elixir-google-api\/tree\/master\/clients\/managed_identities\",\n \"Homepage\" => \"https:\/\/cloud.google.com\/managed-microsoft-ad\/\"\n }\n ]\n end\nend\n","avg_line_length":29.8656716418,"max_line_length":224,"alphanum_fraction":0.6731634183}
{"size":1492,"ext":"ex","lang":"Elixir","max_stars_count":220.0,"content":"defmodule Fika.Compiler.Parser.Common do\n import NimbleParsec\n\n alias Fika.Compiler.Parser.Helper\n\n horizontal_space =\n choice([\n string(\"\\s\"),\n string(\"\\t\")\n ])\n\n comment =\n string(\"#\")\n |> repeat(utf8_char(not: ?\\n))\n |> string(\"\\n\")\n\n vertical_space =\n choice([\n string(\"\\r\"),\n string(\"\\n\"),\n comment\n ])\n\n space =\n choice([vertical_space, horizontal_space])\n |> label(\"space or newline\")\n\n require_space =\n space\n |> times(min: 1)\n |> ignore()\n\n allow_horizontal_space =\n horizontal_space\n |> repeat()\n |> ignore()\n\n allow_space =\n space\n |> repeat()\n |> ignore()\n\n identifier_str =\n ascii_string([?a..?z], 1)\n |> ascii_string([?a..?z, ?_, ?0..?9], min: 0)\n |> reduce({Enum, :join, [\"\"]})\n |> label(\"snake_case string\")\n\n module_name =\n identifier_str\n |> label(\"module name\")\n |> Helper.to_ast(:module_name)\n\n identifier =\n identifier_str\n |> label(\"identifier\")\n |> Helper.to_ast(:identifier)\n\n atom =\n ignore(string(\":\"))\n |> concat(identifier)\n |> label(\"atom\")\n |> Helper.to_ast(:atom)\n\n defcombinator :allow_space, allow_space\n defcombinator :require_space, require_space\n defcombinator :identifier_str, identifier_str\n defcombinator :identifier, identifier\n defcombinator :module_name, module_name\n defcombinator :allow_horizontal_space, allow_horizontal_space\n defcombinator :vertical_space, vertical_space\n defcombinator :atom, atom\nend\n","avg_line_length":20.1621621622,"max_line_length":63,"alphanum_fraction":0.6300268097}
{"size":815,"ext":"exs","lang":"Elixir","max_stars_count":4.0,"content":"defmodule ZipTest do\n use ExUnit.Case\n alias Observables.{Obs}\n require Logger\n\n @tag :zip\n test \"zip\" do\n Code.load_file(\"test\/util.ex\")\n testproc = self()\n\n Obs.range(1, 5, 500)\n |> Obs.zip(Obs.range(1, 5, 500))\n |> Obs.map(fn x -> send(testproc, x) end)\n\n 1..5\n |> Enum.map(fn x ->\n receive do\n {^x, ^x} -> Logger.debug(\"Got #{inspect({x, x})}\")\n end\n end)\n\n Test.Util.sleep(5000)\n end\n\n @tag :zip\n test \"zip uneven inputs\" do\n Code.load_file(\"test\/util.ex\")\n testproc = self()\n\n Obs.range(1, 5, 500)\n |> Obs.zip(Obs.range(1, 10, 500))\n |> Obs.map(fn x -> send(testproc, x) end)\n\n 1..5\n |> Enum.map(fn x ->\n receive do\n {^x, ^x} -> Logger.debug(\"Got #{inspect({x, x})}\")\n end\n end)\n\n Test.Util.sleep(5000)\n end\nend\n","avg_line_length":18.5227272727,"max_line_length":58,"alphanum_fraction":0.536196319}
{"size":7917,"ext":"exs","lang":"Elixir","max_stars_count":2.0,"content":"System.put_env(\"ENDPOINT_TEST_HOST\", \"example.com\")\n\ndefmodule Phoenix.Endpoint.EndpointTest do\n use ExUnit.Case, async: true\n use RouterHelper\n\n @config [url: [host: {:system, \"ENDPOINT_TEST_HOST\"}, path: \"\/api\"],\n static_url: [host: \"static.example.com\"],\n server: false, http: [port: 80], https: [port: 443],\n force_ssl: [subdomains: true],\n cache_static_manifest: \"..\/..\/..\/..\/test\/fixtures\/cache_manifest.json\",\n pubsub: [adapter: Phoenix.PubSub.PG2, name: :endpoint_pub]]\n Application.put_env(:phoenix, __MODULE__.Endpoint, @config)\n Application.put_env(:phoenix, __MODULE__.NoPubSubNameEndpoint, [])\n\n defmodule Endpoint do\n use Phoenix.Endpoint, otp_app: :phoenix\n\n # Assert endpoint variables\n assert is_list(config)\n assert @otp_app == :phoenix\n assert code_reloading? == false\n end\n\n defmodule NoPubSubNameEndpoint do\n use Phoenix.Endpoint, otp_app: :phoenix\n\n def init(_, config) do\n pubsub = [adapter: Phoenix.PubSub.PG2]\n {:ok, Keyword.put(config, :pubsub, pubsub)}\n end\n end\n\n defmodule NoConfigEndpoint do\n use Phoenix.Endpoint, otp_app: :phoenix\n end\n\n setup_all do\n ExUnit.CaptureLog.capture_log(fn ->\n Endpoint.start_link()\n end)\n on_exit fn -> Application.delete_env(:phoenix, :serve_endpoints) end\n :ok\n end\n\n test \"defines child_spec\/1\" do\n assert Endpoint.child_spec([]) == %{\n id: Endpoint,\n start: {Endpoint, :start_link, [[]]},\n type: :supervisor\n }\n end\n\n @tag :capture_log\n test \"errors if pubsub adapter is set but not a name\" do\n Process.flag(:trap_exit, true)\n {:error, {%ArgumentError{message: message}, _}} = NoPubSubNameEndpoint.start_link()\n assert message =~ \"an adapter was given to :pubsub but no :name\"\n end\n\n test \"warns if there is no configuration for an endpoint\" do\n assert ExUnit.CaptureLog.capture_log(fn ->\n NoConfigEndpoint.start_link()\n end) =~ \"no configuration\"\n end\n\n test \"has reloadable configuration\" do\n assert Endpoint.config(:url) == [host: {:system, \"ENDPOINT_TEST_HOST\"}, path: \"\/api\"]\n assert Endpoint.config(:static_url) == [host: \"static.example.com\"]\n assert Endpoint.url == \"https:\/\/example.com\"\n assert Endpoint.static_url == \"https:\/\/static.example.com\"\n assert Endpoint.struct_url == %URI{scheme: \"https\", host: \"example.com\", port: 443, path: \"\/api\"}\n\n config =\n @config\n |> put_in([:url, :port], 1234)\n |> put_in([:static_url, :port], 456)\n\n assert Endpoint.config_change([{Endpoint, config}], []) == :ok\n assert Enum.sort(Endpoint.config(:url)) ==\n [host: {:system, \"ENDPOINT_TEST_HOST\"}, path: \"\/api\", port: 1234]\n assert Enum.sort(Endpoint.config(:static_url)) ==\n [host: \"static.example.com\", port: 456]\n assert Endpoint.url == \"https:\/\/example.com:1234\"\n assert Endpoint.static_url == \"https:\/\/static.example.com:456\"\n assert Endpoint.struct_url == %URI{scheme: \"https\", host: \"example.com\", port: 1234, path: \"\/api\"}\n end\n\n test \"sets script name when using path\" do\n conn = conn(:get, \"https:\/\/example.com\/\")\n assert Endpoint.call(conn, []).script_name == ~w\"api\"\n\n conn = put_in conn.script_name, ~w(foo)\n assert Endpoint.call(conn, []).script_name == ~w\"api\"\n end\n\n @tag :capture_log\n test \"redirects http requests to https on force_ssl\" do\n conn = Endpoint.call(conn(:get, \"\/\"), [])\n assert get_resp_header(conn, \"location\") == [\"https:\/\/example.com\/\"]\n assert conn.halted\n end\n\n test \"sends hsts on https requests on force_ssl\" do\n conn = Endpoint.call(conn(:get, \"https:\/\/example.com\/\"), [])\n assert get_resp_header(conn, \"strict-transport-security\") ==\n [\"max-age=31536000; includeSubDomains\"]\n end\n\n test \"warms up caches on load and config change\" do\n assert Endpoint.static_path(\"\/foo.css\") == \"\/foo-d978852bea6530fcd197b5445ed008fd.css?vsn=d\"\n\n # Trigger a config change and the cache should be warmed up again\n config = put_in(@config[:cache_static_manifest], \"..\/..\/..\/..\/test\/fixtures\/cache_manifest_upgrade.json\")\n\n assert Endpoint.config_change([{Endpoint, config}], []) == :ok\n assert Endpoint.static_path(\"\/foo.css\") == \"\/foo-ghijkl.css?vsn=d\"\n end\n\n @tag :capture_log\n test \"invokes init\/2 callback\" do\n Application.put_env(:phoenix, __MODULE__.InitEndpoint, parent: self())\n\n defmodule InitEndpoint do\n use Phoenix.Endpoint, otp_app: :phoenix\n\n def init(:supervisor, opts) do\n send opts[:parent], {self(), :sample}\n {:ok, opts}\n end\n end\n\n {:ok, pid} = InitEndpoint.start_link()\n assert_receive {^pid, :sample}\n end\n\n @tag :capture_log\n test \"uses url configuration for static path\" do\n Application.put_env(:phoenix, __MODULE__.UrlEndpoint, url: [path: \"\/api\"])\n defmodule UrlEndpoint do\n use Phoenix.Endpoint, otp_app: :phoenix\n end\n UrlEndpoint.start_link()\n assert UrlEndpoint.path(\"\/phoenix.png\") =~ \"\/api\/phoenix.png\"\n assert UrlEndpoint.static_path(\"\/phoenix.png\") =~ \"\/api\/phoenix.png\"\n end\n\n @tag :capture_log\n test \"uses static_url configuration for static path\" do\n Application.put_env(:phoenix, __MODULE__.StaticEndpoint, static_url: [path: \"\/static\"])\n defmodule StaticEndpoint do\n use Phoenix.Endpoint, otp_app: :phoenix\n end\n StaticEndpoint.start_link()\n assert StaticEndpoint.path(\"\/phoenix.png\") =~ \"\/phoenix.png\"\n assert StaticEndpoint.static_path(\"\/phoenix.png\") =~ \"\/static\/phoenix.png\"\n end\n\n test \"injects pubsub broadcast with configured server\" do\n Endpoint.subscribe(\"sometopic\")\n some = spawn fn -> :ok end\n\n Endpoint.broadcast_from(some, \"sometopic\", \"event1\", %{key: :val})\n assert_receive %Phoenix.Socket.Broadcast{\n event: \"event1\", payload: %{key: :val}, topic: \"sometopic\"}\n\n Endpoint.broadcast_from!(some, \"sometopic\", \"event2\", %{key: :val})\n assert_receive %Phoenix.Socket.Broadcast{\n event: \"event2\", payload: %{key: :val}, topic: \"sometopic\"}\n\n Endpoint.broadcast(\"sometopic\", \"event3\", %{key: :val})\n assert_receive %Phoenix.Socket.Broadcast{\n event: \"event3\", payload: %{key: :val}, topic: \"sometopic\"}\n\n Endpoint.broadcast!(\"sometopic\", \"event4\", %{key: :val})\n assert_receive %Phoenix.Socket.Broadcast{\n event: \"event4\", payload: %{key: :val}, topic: \"sometopic\"}\n end\n\n test \"server?\/2 returns true for explicitly true server\", config do\n endpoint = Module.concat(__MODULE__, config.test)\n Application.put_env(:phoenix, endpoint, server: true)\n assert Phoenix.Endpoint.server?(:phoenix, endpoint)\n end\n\n test \"server?\/2 returns false for explicitly false server\", config do\n Application.put_env(:phoenix, :serve_endpoints, true)\n endpoint = Module.concat(__MODULE__, config.test)\n Application.put_env(:phoenix, endpoint, server: false)\n refute Phoenix.Endpoint.server?(:phoenix, endpoint)\n end\n\n test \"server?\/2 returns true for global serve_endpoints as true\", config do\n Application.put_env(:phoenix, :serve_endpoints, true)\n endpoint = Module.concat(__MODULE__, config.test)\n Application.put_env(:phoenix, endpoint, [])\n assert Phoenix.Endpoint.server?(:phoenix, endpoint)\n end\n\n test \"server?\/2 returns false for no global serve_endpoints config\", config do\n Application.delete_env(:phoenix, :serve_endpoints)\n endpoint = Module.concat(__MODULE__, config.test)\n Application.put_env(:phoenix, endpoint, [])\n refute Phoenix.Endpoint.server?(:phoenix, endpoint)\n end\n\n test \"static_path\/1 validates paths are local\/safe\" do\n safe_path = \"\/some_safe_path\"\n assert Endpoint.static_path(safe_path) == safe_path\n\n assert_raise ArgumentError, ~r\/unsafe characters\/, fn ->\n Endpoint.static_path(\"\/\\\\unsafe_path\")\n end\n\n assert_raise ArgumentError, ~r\/expected a path starting with a single\/, fn ->\n Endpoint.static_path(\"\/\/invalid_path\")\n end\n end\nend\n","avg_line_length":35.9863636364,"max_line_length":109,"alphanum_fraction":0.6800555766}
{"size":649,"ext":"exs","lang":"Elixir","max_stars_count":1.0,"content":"defmodule PrimeFinder do\n def search(primes_list, limit) do\n next_primes_list = calculate_next_prime(primes_list, List.first(primes_list))\n\n if Kernel.length(next_primes_list) == limit do\n List.first(next_primes_list)\n else\n search(next_primes_list, limit)\n end\n end\n\n defp calculate_next_prime(my_list, max) do\n new_max = max + 1\n\n if prime?(new_max) == true do\n [new_max | my_list]\n else\n calculate_next_prime(my_list, new_max)\n end\n end\n\n defp prime?(n) do\n floored_sqrt =\n :math.sqrt(n)\n |> Float.floor()\n |> round\n\n !Enum.any?(2..floored_sqrt, &(rem(n, &1) == 0))\n end\nend\n","avg_line_length":20.935483871,"max_line_length":81,"alphanum_fraction":0.6471494607}
{"size":2018,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This file is auto generated by the elixir code generator program.\n# Do not edit this file manually.\n\ndefmodule GoogleApi.CloudTrace.V2.Model.TruncatableString do\n @moduledoc \"\"\"\n Represents a string that might be shortened to a specified length.\n\n ## Attributes\n\n * `truncatedByteCount` (*type:* `integer()`, *default:* `nil`) - The number of bytes removed from the original string. If this value is 0, then the string was not shortened.\n * `value` (*type:* `String.t`, *default:* `nil`) - The shortened string. For example, if the original string is 500 bytes long and the limit of the string is 128 bytes, then `value` contains the first 128 bytes of the 500-byte string. Truncation always happens on a UTF8 character boundary. If there are multi-byte characters in the string, then the length of the shortened string might be less than the size limit.\n \"\"\"\n\n use GoogleApi.Gax.ModelBase\n\n @type t :: %__MODULE__{\n :truncatedByteCount => integer(),\n :value => String.t()\n }\n\n field(:truncatedByteCount)\n field(:value)\nend\n\ndefimpl Poison.Decoder, for: GoogleApi.CloudTrace.V2.Model.TruncatableString do\n def decode(value, options) do\n GoogleApi.CloudTrace.V2.Model.TruncatableString.decode(value, options)\n end\nend\n\ndefimpl Poison.Encoder, for: GoogleApi.CloudTrace.V2.Model.TruncatableString do\n def encode(value, options) do\n GoogleApi.Gax.ModelBase.encode(value, options)\n end\nend\n","avg_line_length":40.36,"max_line_length":419,"alphanum_fraction":0.7418235877}
{"size":6393,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"# Copyright 2017 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# NOTE: This class is auto generated by the swagger code generator program.\n# https:\/\/github.com\/swagger-api\/swagger-codegen.git\n# Do not edit the class manually.\n\ndefmodule GoogleApi.Plus.V1.Model.Person do\n @moduledoc \"\"\"\n \n\n ## Attributes\n\n - aboutMe (String): A short biography for this person. Defaults to: `null`.\n - ageRange (PersonAgeRange): Defaults to: `null`.\n - birthday (String): The person&#39;s date of birth, represented as YYYY-MM-DD. Defaults to: `null`.\n - braggingRights (String): The \\&quot;bragging rights\\&quot; line of this person. Defaults to: `null`.\n - circledByCount (Integer): For followers who are visible, the number of people who have added this person or page to a circle. Defaults to: `null`.\n - cover (PersonCover): Defaults to: `null`.\n - currentLocation (String): (this field is not currently used) Defaults to: `null`.\n - displayName (String): The name of this person, which is suitable for display. Defaults to: `null`.\n - domain (String): The hosted domain name for the user&#39;s Google Apps account. For instance, example.com. The plus.profile.emails.read or email scope is needed to get this domain name. Defaults to: `null`.\n - emails (List[PersonEmails]): A list of email addresses that this person has, including their Google account email address, and the public verified email addresses on their Google+ profile. The plus.profile.emails.read scope is needed to retrieve these email addresses, or the email scope can be used to retrieve just the Google account email address. Defaults to: `null`.\n - etag (String): ETag of this response for caching purposes. Defaults to: `null`.\n - gender (String): The person&#39;s gender. Possible values include, but are not limited to, the following values: - \\&quot;male\\&quot; - Male gender. - \\&quot;female\\&quot; - Female gender. - \\&quot;other\\&quot; - Other. Defaults to: `null`.\n - id (String): The ID of this person. Defaults to: `null`.\n - image (PersonImage): Defaults to: `null`.\n - isPlusUser (Boolean): Whether this user has signed up for Google+. Defaults to: `null`.\n - kind (String): Identifies this resource as a person. Value: \\&quot;plus#person\\&quot;. Defaults to: `null`.\n - language (String): The user&#39;s preferred language for rendering. Defaults to: `null`.\n - name (PersonName): Defaults to: `null`.\n - nickname (String): The nickname of this person. Defaults to: `null`.\n - objectType (String): Type of person within Google+. Possible values include, but are not limited to, the following values: - \\&quot;person\\&quot; - represents an actual person. - \\&quot;page\\&quot; - represents a page. Defaults to: `null`.\n - occupation (String): The occupation of this person. Defaults to: `null`.\n - organizations (List[PersonOrganizations]): A list of current or past organizations with which this person is associated. Defaults to: `null`.\n - placesLived (List[PersonPlacesLived]): A list of places where this person has lived. Defaults to: `null`.\n - plusOneCount (Integer): If a Google+ Page, the number of people who have +1&#39;d this page. Defaults to: `null`.\n - relationshipStatus (String): The person&#39;s relationship status. Possible values include, but are not limited to, the following values: - \\&quot;single\\&quot; - Person is single. - \\&quot;in_a_relationship\\&quot; - Person is in a relationship. - \\&quot;engaged\\&quot; - Person is engaged. - \\&quot;married\\&quot; - Person is married. - \\&quot;its_complicated\\&quot; - The relationship is complicated. - \\&quot;open_relationship\\&quot; - Person is in an open relationship. - \\&quot;widowed\\&quot; - Person is widowed. - \\&quot;in_domestic_partnership\\&quot; - Person is in a domestic partnership. - \\&quot;in_civil_union\\&quot; - Person is in a civil union. Defaults to: `null`.\n - skills (String): The person&#39;s skills. Defaults to: `null`.\n - tagline (String): The brief description (tagline) of this person. Defaults to: `null`.\n - url (String): The URL of this person&#39;s profile. Defaults to: `null`.\n - urls (List[PersonUrls]): A list of URLs for this person. Defaults to: `null`.\n - verified (Boolean): Whether the person or Google+ Page has been verified. Defaults to: `null`.\n \"\"\"\n\n defstruct [\n :\"aboutMe\",\n :\"ageRange\",\n :\"birthday\",\n :\"braggingRights\",\n :\"circledByCount\",\n :\"cover\",\n :\"currentLocation\",\n :\"displayName\",\n :\"domain\",\n :\"emails\",\n :\"etag\",\n :\"gender\",\n :\"id\",\n :\"image\",\n :\"isPlusUser\",\n :\"kind\",\n :\"language\",\n :\"name\",\n :\"nickname\",\n :\"objectType\",\n :\"occupation\",\n :\"organizations\",\n :\"placesLived\",\n :\"plusOneCount\",\n :\"relationshipStatus\",\n :\"skills\",\n :\"tagline\",\n :\"url\",\n :\"urls\",\n :\"verified\"\n ]\nend\n\ndefimpl Poison.Decoder, for: GoogleApi.Plus.V1.Model.Person do\n import GoogleApi.Plus.V1.Deserializer\n def decode(value, options) do\n value\n |> deserialize(:\"ageRange\", :struct, GoogleApi.Plus.V1.Model.PersonAgeRange, options)\n |> deserialize(:\"cover\", :struct, GoogleApi.Plus.V1.Model.PersonCover, options)\n |> deserialize(:\"emails\", :list, GoogleApi.Plus.V1.Model.PersonEmails, options)\n |> deserialize(:\"image\", :struct, GoogleApi.Plus.V1.Model.PersonImage, options)\n |> deserialize(:\"name\", :struct, GoogleApi.Plus.V1.Model.PersonName, options)\n |> deserialize(:\"organizations\", :list, GoogleApi.Plus.V1.Model.PersonOrganizations, options)\n |> deserialize(:\"placesLived\", :list, GoogleApi.Plus.V1.Model.PersonPlacesLived, options)\n |> deserialize(:\"urls\", :list, GoogleApi.Plus.V1.Model.PersonUrls, options)\n end\nend\n\ndefimpl Poison.Encoder, for: GoogleApi.Plus.V1.Model.Person do\n def encode(value, options) do\n GoogleApi.Plus.V1.Deserializer.serialize_non_nil(value, options)\n end\nend\n\n","avg_line_length":56.5752212389,"max_line_length":693,"alphanum_fraction":0.7057719381}
{"size":984,"ext":"ex","lang":"Elixir","max_stars_count":1.0,"content":"defmodule Fuschia.Queries.Pesquisadores do\n @moduledoc \"\"\"\n Queries para interagir com `Pesquisadores`\n \"\"\"\n\n import Ecto.Query, only: [from: 2, where: 3, order_by: 3]\n\n alias Fuschia.Entities.Pesquisador\n\n @behaviour Fuschia.Query\n\n @impl true\n def query do\n from p in Pesquisador,\n left_join: campus in assoc(p, :campus),\n left_join: orientador in assoc(p, :orientador),\n order_by: [desc: p.created_at]\n end\n\n @spec query_by_orientador(binary) :: Ecto.Query.t()\n def query_by_orientador(orientador_cpf) do\n query()\n |> where([p], p.orientador_cpf == ^orientador_cpf)\n |> order_by([p], desc: p.created_at)\n end\n\n @spec query_exists(binary) :: Ecto.Query.t()\n def query_exists(usuario_cpf) do\n where(Pesquisador, [p], p.usuario_cpf == ^usuario_cpf)\n end\n\n @impl true\n def relationships do\n [\n orientador: [usuario: :contato],\n orientandos: [usuario: :contato],\n usuario: :contato,\n campus: :cidade\n ]\n end\nend\n","avg_line_length":23.4285714286,"max_line_length":59,"alphanum_fraction":0.6666666667}
{"size":7087,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This file is auto generated by the elixir code generator program.\n# Do not edit this file manually.\n\ndefmodule GoogleApi.DFAReporting.V34.Api.Conversions do\n @moduledoc \"\"\"\n API calls for all endpoints tagged `Conversions`.\n \"\"\"\n\n alias GoogleApi.DFAReporting.V34.Connection\n alias GoogleApi.Gax.{Request, Response}\n\n @library_version Mix.Project.config() |> Keyword.get(:version, \"\")\n\n @doc \"\"\"\n Inserts conversions.\n\n ## Parameters\n\n * `connection` (*type:* `GoogleApi.DFAReporting.V34.Connection.t`) - Connection to server\n * `profile_id` (*type:* `String.t`) - User profile ID associated with this request.\n * `optional_params` (*type:* `keyword()`) - Optional parameters\n * `:\"$.xgafv\"` (*type:* `String.t`) - V1 error format.\n * `:access_token` (*type:* `String.t`) - OAuth access token.\n * `:alt` (*type:* `String.t`) - Data format for response.\n * `:callback` (*type:* `String.t`) - JSONP\n * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.\n * `: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.\n * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.\n * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.\n * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.\n * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. \"media\", \"multipart\").\n * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. \"raw\", \"multipart\").\n * `:body` (*type:* `GoogleApi.DFAReporting.V34.Model.ConversionsBatchInsertRequest.t`) - \n * `opts` (*type:* `keyword()`) - Call options\n\n ## Returns\n\n * `{:ok, %GoogleApi.DFAReporting.V34.Model.ConversionsBatchInsertResponse{}}` on success\n * `{:error, info}` on failure\n \"\"\"\n @spec dfareporting_conversions_batchinsert(Tesla.Env.client(), String.t(), keyword(), keyword()) ::\n {:ok, GoogleApi.DFAReporting.V34.Model.ConversionsBatchInsertResponse.t()}\n | {:ok, Tesla.Env.t()}\n | {:error, any()}\n def dfareporting_conversions_batchinsert(\n connection,\n profile_id,\n optional_params \\\\ [],\n opts \\\\ []\n ) do\n optional_params_config = %{\n :\"$.xgafv\" => :query,\n :access_token => :query,\n :alt => :query,\n :callback => :query,\n :fields => :query,\n :key => :query,\n :oauth_token => :query,\n :prettyPrint => :query,\n :quotaUser => :query,\n :uploadType => :query,\n :upload_protocol => :query,\n :body => :body\n }\n\n request =\n Request.new()\n |> Request.method(:post)\n |> Request.url(\"\/dfareporting\/v3.4\/userprofiles\/{profileId}\/conversions\/batchinsert\", %{\n \"profileId\" => URI.encode(profile_id, &URI.char_unreserved?\/1)\n })\n |> Request.add_optional_params(optional_params_config, optional_params)\n |> Request.library_version(@library_version)\n\n connection\n |> Connection.execute(request)\n |> Response.decode(\n opts ++ [struct: %GoogleApi.DFAReporting.V34.Model.ConversionsBatchInsertResponse{}]\n )\n end\n\n @doc \"\"\"\n Updates existing conversions.\n\n ## Parameters\n\n * `connection` (*type:* `GoogleApi.DFAReporting.V34.Connection.t`) - Connection to server\n * `profile_id` (*type:* `String.t`) - User profile ID associated with this request.\n * `optional_params` (*type:* `keyword()`) - Optional parameters\n * `:\"$.xgafv\"` (*type:* `String.t`) - V1 error format.\n * `:access_token` (*type:* `String.t`) - OAuth access token.\n * `:alt` (*type:* `String.t`) - Data format for response.\n * `:callback` (*type:* `String.t`) - JSONP\n * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.\n * `: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.\n * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.\n * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.\n * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.\n * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. \"media\", \"multipart\").\n * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. \"raw\", \"multipart\").\n * `:body` (*type:* `GoogleApi.DFAReporting.V34.Model.ConversionsBatchUpdateRequest.t`) - \n * `opts` (*type:* `keyword()`) - Call options\n\n ## Returns\n\n * `{:ok, %GoogleApi.DFAReporting.V34.Model.ConversionsBatchUpdateResponse{}}` on success\n * `{:error, info}` on failure\n \"\"\"\n @spec dfareporting_conversions_batchupdate(Tesla.Env.client(), String.t(), keyword(), keyword()) ::\n {:ok, GoogleApi.DFAReporting.V34.Model.ConversionsBatchUpdateResponse.t()}\n | {:ok, Tesla.Env.t()}\n | {:error, any()}\n def dfareporting_conversions_batchupdate(\n connection,\n profile_id,\n optional_params \\\\ [],\n opts \\\\ []\n ) do\n optional_params_config = %{\n :\"$.xgafv\" => :query,\n :access_token => :query,\n :alt => :query,\n :callback => :query,\n :fields => :query,\n :key => :query,\n :oauth_token => :query,\n :prettyPrint => :query,\n :quotaUser => :query,\n :uploadType => :query,\n :upload_protocol => :query,\n :body => :body\n }\n\n request =\n Request.new()\n |> Request.method(:post)\n |> Request.url(\"\/dfareporting\/v3.4\/userprofiles\/{profileId}\/conversions\/batchupdate\", %{\n \"profileId\" => URI.encode(profile_id, &URI.char_unreserved?\/1)\n })\n |> Request.add_optional_params(optional_params_config, optional_params)\n |> Request.library_version(@library_version)\n\n connection\n |> Connection.execute(request)\n |> Response.decode(\n opts ++ [struct: %GoogleApi.DFAReporting.V34.Model.ConversionsBatchUpdateResponse{}]\n )\n end\nend\n","avg_line_length":43.2134146341,"max_line_length":196,"alphanum_fraction":0.6390574291}
{"size":315,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule Kepler.UserIdentities.UserIdentity do\n use Ecto.Schema\n use PowAssent.Ecto.UserIdentities.Schema, user: Kepler.Users.User\n\n @primary_key {:id, :binary_id, autogenerate: true}\n @foreign_key_type :binary_id\n schema \"user_identities\" do\n pow_assent_user_identity_fields()\n\n timestamps()\n end\nend\n","avg_line_length":24.2307692308,"max_line_length":67,"alphanum_fraction":0.7746031746}
{"size":9255,"ext":"exs","lang":"Elixir","max_stars_count":1.0,"content":"Code.require_file(\"test_helper.exs\", __DIR__)\n\ndefmodule ListTest do\n use ExUnit.Case, async: true\n\n doctest List\n\n test \"cons cell precedence\" do\n assert [1 | List.flatten([2, 3])] == [1, 2, 3]\n end\n\n test \"optional comma\" do\n assert Code.eval_string(\"[1,]\") == {[1], []}\n assert Code.eval_string(\"[1, 2, 3,]\") == {[1, 2, 3], []}\n end\n\n test \"partial application\" do\n assert (&[&1, 2]).(1) == [1, 2]\n assert (&[&1, &2]).(1, 2) == [1, 2]\n assert (&[&2, &1]).(2, 1) == [1, 2]\n assert (&[&1 | &2]).(1, 2) == [1 | 2]\n assert (&[&1, &2 | &3]).(1, 2, 3) == [1, 2 | 3]\n end\n\n test \"wrap\/1\" do\n assert List.wrap([1, 2, 3]) == [1, 2, 3]\n assert List.wrap(1) == [1]\n assert List.wrap(nil) == []\n end\n\n test \"flatten\/1\" do\n assert List.flatten([1, 2, 3]) == [1, 2, 3]\n assert List.flatten([1, [2], 3]) == [1, 2, 3]\n assert List.flatten([[1, [2], 3]]) == [1, 2, 3]\n\n assert List.flatten([]) == []\n assert List.flatten([[]]) == []\n end\n\n test \"flatten\/2\" do\n assert List.flatten([1, 2, 3], [4, 5]) == [1, 2, 3, 4, 5]\n assert List.flatten([1, [2], 3], [4, 5]) == [1, 2, 3, 4, 5]\n assert List.flatten([[1, [2], 3]], [4, 5]) == [1, 2, 3, 4, 5]\n end\n\n test \"foldl\/3\" do\n assert List.foldl([1, 2, 3], 0, fn x, y -> x + y end) == 6\n assert List.foldl([1, 2, 3], 10, fn x, y -> x + y end) == 16\n assert List.foldl([1, 2, 3, 4], 0, fn x, y -> x - y end) == 2\n end\n\n test \"foldr\/3\" do\n assert List.foldr([1, 2, 3], 0, fn x, y -> x + y end) == 6\n assert List.foldr([1, 2, 3], 10, fn x, y -> x + y end) == 16\n assert List.foldr([1, 2, 3, 4], 0, fn x, y -> x - y end) == -2\n end\n\n test \"duplicate\/2\" do\n assert List.duplicate(1, 3) == [1, 1, 1]\n assert List.duplicate([1], 1) == [[1]]\n end\n\n test \"last\/1\" do\n assert List.last([]) == nil\n assert List.last([1]) == 1\n assert List.last([1, 2, 3]) == 3\n end\n\n test \"zip\/1\" do\n assert List.zip([[1, 4], [2, 5], [3, 6]]) == [{1, 2, 3}, {4, 5, 6}]\n assert List.zip([[1, 4], [2, 5, 0], [3, 6]]) == [{1, 2, 3}, {4, 5, 6}]\n assert List.zip([[1], [2, 5], [3, 6]]) == [{1, 2, 3}]\n assert List.zip([[1, 4], [2, 5], []]) == []\n end\n\n test \"keyfind\/4\" do\n assert List.keyfind([a: 1, b: 2], :a, 0) == {:a, 1}\n assert List.keyfind([a: 1, b: 2], 2, 1) == {:b, 2}\n assert List.keyfind([a: 1, b: 2], :c, 0) == nil\n end\n\n test \"keyreplace\/4\" do\n assert List.keyreplace([a: 1, b: 2], :a, 0, {:a, 3}) == [a: 3, b: 2]\n assert List.keyreplace([a: 1], :b, 0, {:b, 2}) == [a: 1]\n end\n\n test \"keysort\/2\" do\n assert List.keysort([a: 4, b: 3, c: 5], 1) == [b: 3, a: 4, c: 5]\n assert List.keysort([a: 4, c: 1, b: 2], 0) == [a: 4, b: 2, c: 1]\n end\n\n test \"keystore\/4\" do\n assert List.keystore([a: 1, b: 2], :a, 0, {:a, 3}) == [a: 3, b: 2]\n assert List.keystore([a: 1], :b, 0, {:b, 2}) == [a: 1, b: 2]\n end\n\n test \"keymember?\/3\" do\n assert List.keymember?([a: 1, b: 2], :a, 0) == true\n assert List.keymember?([a: 1, b: 2], 2, 1) == true\n assert List.keymember?([a: 1, b: 2], :c, 0) == false\n end\n\n test \"keydelete\/3\" do\n assert List.keydelete([a: 1, b: 2], :a, 0) == [{:b, 2}]\n assert List.keydelete([a: 1, b: 2], 2, 1) == [{:a, 1}]\n assert List.keydelete([a: 1, b: 2], :c, 0) == [{:a, 1}, {:b, 2}]\n end\n\n test \"insert_at\/3\" do\n assert List.insert_at([1, 2, 3], 0, 0) == [0, 1, 2, 3]\n assert List.insert_at([1, 2, 3], 3, 0) == [1, 2, 3, 0]\n assert List.insert_at([1, 2, 3], 2, 0) == [1, 2, 0, 3]\n assert List.insert_at([1, 2, 3], 10, 0) == [1, 2, 3, 0]\n assert List.insert_at([1, 2, 3], -1, 0) == [1, 2, 3, 0]\n assert List.insert_at([1, 2, 3], -4, 0) == [0, 1, 2, 3]\n assert List.insert_at([1, 2, 3], -10, 0) == [0, 1, 2, 3]\n end\n\n test \"replace_at\/3\" do\n assert List.replace_at([1, 2, 3], 0, 0) == [0, 2, 3]\n assert List.replace_at([1, 2, 3], 1, 0) == [1, 0, 3]\n assert List.replace_at([1, 2, 3], 2, 0) == [1, 2, 0]\n assert List.replace_at([1, 2, 3], 3, 0) == [1, 2, 3]\n assert List.replace_at([1, 2, 3], -1, 0) == [1, 2, 0]\n assert List.replace_at([1, 2, 3], -4, 0) == [1, 2, 3]\n end\n\n test \"update_at\/3\" do\n assert List.update_at([1, 2, 3], 0, &(&1 + 1)) == [2, 2, 3]\n assert List.update_at([1, 2, 3], 1, &(&1 + 1)) == [1, 3, 3]\n assert List.update_at([1, 2, 3], 2, &(&1 + 1)) == [1, 2, 4]\n assert List.update_at([1, 2, 3], 3, &(&1 + 1)) == [1, 2, 3]\n assert List.update_at([1, 2, 3], -1, &(&1 + 1)) == [1, 2, 4]\n assert List.update_at([1, 2, 3], -4, &(&1 + 1)) == [1, 2, 3]\n end\n\n test \"delete_at\/2\" do\n for index <- [-1, 0, 1] do\n assert List.delete_at([], index) == []\n end\n\n assert List.delete_at([1, 2, 3], 0) == [2, 3]\n assert List.delete_at([1, 2, 3], 2) == [1, 2]\n assert List.delete_at([1, 2, 3], 3) == [1, 2, 3]\n assert List.delete_at([1, 2, 3], -1) == [1, 2]\n assert List.delete_at([1, 2, 3], -3) == [2, 3]\n assert List.delete_at([1, 2, 3], -4) == [1, 2, 3]\n end\n\n test \"pop_at\/3\" do\n for index <- [-1, 0, 1] do\n assert List.pop_at([], index) == {nil, []}\n end\n\n assert List.pop_at([1], 1, 2) == {2, [1]}\n assert List.pop_at([1, 2, 3], 0) == {1, [2, 3]}\n assert List.pop_at([1, 2, 3], 2) == {3, [1, 2]}\n assert List.pop_at([1, 2, 3], 3) == {nil, [1, 2, 3]}\n assert List.pop_at([1, 2, 3], -1) == {3, [1, 2]}\n assert List.pop_at([1, 2, 3], -3) == {1, [2, 3]}\n assert List.pop_at([1, 2, 3], -4) == {nil, [1, 2, 3]}\n end\n\n describe \"starts_with?\/2\" do\n test \"list and prefix are equal\" do\n assert List.starts_with?([], [])\n assert List.starts_with?([1], [1])\n assert List.starts_with?([1, 2, 3], [1, 2, 3])\n end\n\n test \"proper lists\" do\n refute List.starts_with?([1], [1, 2])\n assert List.starts_with?([1, 2, 3], [1, 2])\n refute List.starts_with?([1, 2, 3], [1, 2, 3, 4])\n end\n\n test \"list is empty\" do\n refute List.starts_with?([], [1])\n refute List.starts_with?([], [1, 2])\n end\n\n test \"prefix is empty\" do\n assert List.starts_with?([1], [])\n assert List.starts_with?([1, 2], [])\n assert List.starts_with?([1, 2, 3], [])\n end\n\n test \"only accepts proper lists\" do\n message = \"no function clause matching in List.starts_with?\/2\"\n\n assert_raise FunctionClauseError, message, fn ->\n List.starts_with?([1 | 2], [1 | 2])\n end\n\n message = \"no function clause matching in List.starts_with?\/2\"\n\n assert_raise FunctionClauseError, message, fn ->\n List.starts_with?([1, 2], 1)\n end\n end\n end\n\n test \"to_string\/1\" do\n assert List.to_string([?\u00e6, ?\u00df]) == \"\u00e6\u00df\"\n assert List.to_string([?a, ?b, ?c]) == \"abc\"\n\n assert_raise UnicodeConversionError, \"invalid code point 57343\", fn ->\n List.to_string([0xDFFF])\n end\n\n assert_raise UnicodeConversionError, \"invalid encoding starting at <<216, 0>>\", fn ->\n List.to_string([\"a\", \"b\", <<0xD800::size(16)>>])\n end\n\n assert_raise ArgumentError, ~r\"cannot convert the given list to a string\", fn ->\n List.to_string([:a, :b])\n end\n end\n\n describe \"myers_difference\/2\" do\n test \"follows paper implementation\" do\n assert List.myers_difference([], []) == []\n assert List.myers_difference([], [1, 2, 3]) == [ins: [1, 2, 3]]\n assert List.myers_difference([1, 2, 3], []) == [del: [1, 2, 3]]\n assert List.myers_difference([1, 2, 3], [1, 2, 3]) == [eq: [1, 2, 3]]\n assert List.myers_difference([1, 2, 3], [1, 4, 2, 3]) == [eq: [1], ins: [4], eq: [2, 3]]\n assert List.myers_difference([1, 4, 2, 3], [1, 2, 3]) == [eq: [1], del: [4], eq: [2, 3]]\n assert List.myers_difference([1], [[1]]) == [del: [1], ins: [[1]]]\n assert List.myers_difference([[1]], [1]) == [del: [[1]], ins: [1]]\n end\n\n test \"rearranges inserts and equals for smaller diffs\" do\n assert List.myers_difference([3, 2, 0, 2], [2, 2, 0, 2]) ==\n [del: [3], ins: [2], eq: [2, 0, 2]]\n\n assert List.myers_difference([3, 2, 1, 0, 2], [2, 1, 2, 1, 0, 2]) ==\n [del: [3], ins: [2, 1], eq: [2, 1, 0, 2]]\n\n assert List.myers_difference([3, 2, 2, 1, 0, 2], [2, 2, 1, 2, 1, 0, 2]) ==\n [del: [3], eq: [2, 2, 1], ins: [2, 1], eq: [0, 2]]\n\n assert List.myers_difference([3, 2, 0, 2], [2, 2, 1, 0, 2]) ==\n [del: [3], eq: [2], ins: [2, 1], eq: [0, 2]]\n end\n end\n\n test \"improper?\/1\" do\n assert List.improper?([1 | 2])\n assert List.improper?([1, 2, 3 | 4])\n refute List.improper?([])\n refute List.improper?([1])\n refute List.improper?([[1]])\n refute List.improper?([1, 2])\n refute List.improper?([1, 2, 3])\n\n assert_raise FunctionClauseError, fn ->\n List.improper?(%{})\n end\n end\n\n describe \"ascii_printable?\/1\" do\n test \"proper lists without limit\" do\n assert List.ascii_printable?([])\n assert List.ascii_printable?('abc')\n refute(List.ascii_printable?('abc' ++ [0]))\n assert List.ascii_printable?('abc \\a\\b\\e\\f\\n\\r\\t\\v def')\n refute List.ascii_printable?('ma\u00f1ana')\n end\n\n test \"proper lists with limit\" do\n assert List.ascii_printable?([], 100)\n assert List.ascii_printable?('abc' ++ [0], 2)\n end\n\n test \"improper lists\" do\n refute List.ascii_printable?('abc' ++ ?d)\n end\n end\nend\n","avg_line_length":33.0535714286,"max_line_length":94,"alphanum_fraction":0.5092382496}
{"size":1798,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule ExAws.Mixfile do\n use Mix.Project\n\n @source_url \"https:\/\/github.com\/ex-aws\/ex_aws\"\n @version \"2.1.7\"\n\n def project do\n [\n app: :ex_aws,\n version: @version,\n elixir: \"~> 1.7\",\n elixirc_paths: elixirc_paths(Mix.env()),\n description: \"Generic AWS client\",\n name: \"ExAws\",\n source_url: @source_url,\n package: package(),\n dialyzer: [flags: \"--fullpath\"],\n deps: deps(),\n docs: docs()\n ]\n end\n\n def application do\n [extra_applications: [:logger, :crypto], mod: {ExAws, []}]\n end\n\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n defp deps() do\n [\n {:bypass, \"~> 1.0\", only: :test},\n {:configparser_ex, \"~> 4.0\", optional: true},\n {:dialyze, \"~> 0.2.0\", only: [:dev, :test]},\n {:ex_doc, \"~> 0.16\", only: [:dev, :test]},\n {:finch, \"~> 0.6\", optional: true},\n {:hackney, \"~> 1.9\", optional: true},\n {:jason, \"~> 1.1\", optional: true},\n {:jsx, \"~> 2.8\", optional: true},\n {:mox, \"~> 0.3\", only: :test},\n {:sweet_xml, \"~> 0.6\", optional: true}\n ]\n end\n\n defp package do\n [\n description: description(),\n files: [\"priv\", \"lib\", \"config\", \"mix.exs\", \"README*\"],\n maintainers: [\"Bernard Duggan\", \"Ben Wilson\"],\n licenses: [\"MIT\"],\n links: %{\n Changelog: \"#{@source_url}\/blob\/master\/CHANGELOG.md\",\n GitHub: @source_url\n }\n ]\n end\n\n defp description do\n \"\"\"\n AWS client for Elixir. Currently supports Dynamo, DynamoStreams, EC2,\n Firehose, Kinesis, KMS, Lambda, RRDS, Route53, S3, SES, SNS, SQS, STS\n \"\"\"\n end\n\n defp docs do\n [\n main: \"readme\",\n source_ref: \"v#{@version}\",\n source_url: @source_url,\n extras: [\"README.md\"]\n ]\n end\nend\n","avg_line_length":24.2972972973,"max_line_length":73,"alphanum_fraction":0.5400444939}
{"size":598,"ext":"exs","lang":"Elixir","max_stars_count":37.0,"content":"# Script for populating the database. You can run it as:\n#\n# mix run priv\/repo\/seeds.exs\n#\n# Inside the script, you can read and write to any of your\n# repositories directly:\n#\n# Videologue.Repo.insert!(%Videologue.SomeSchema{})\n#\n# We recommend using the bang functions (`insert!`, `update!`\n# and so on) as they will fail if something goes wrong.\nalias Videologue.Multimedia\n\ndefmodule Seeds.Multimedia.Category do\n def add_default do\n for category <- ~w(erlang elixir phoenix) do\n Multimedia.create_category!(category)\n end\n end\nend\n\nSeeds.Multimedia.Category.add_default()\n","avg_line_length":26.0,"max_line_length":61,"alphanum_fraction":0.7324414716}
{"size":14898,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule Record do\n @moduledoc \"\"\"\n Module to work with, define, and import records.\n\n Records are simply tuples where the first element is an atom:\n\n iex> Record.is_record {User, \"john\", 27}\n true\n\n This module provides conveniences for working with records at\n compilation time, where compile-time field names are used to\n manipulate the tuples, providing fast operations on top of\n the tuples' compact structure.\n\n In Elixir, records are used mostly in two situations:\n\n 1. to work with short, internal data\n 2. to interface with Erlang records\n\n The macros `defrecord\/3` and `defrecordp\/3` can be used to create records\n while `extract\/2` and `extract_all\/1` can be used to extract records from\n Erlang files.\n\n ## Types\n\n Types can be defined for tuples with the `record\/2` macro (only available in\n typespecs). This macro will expand to a tuple as seen in the example below:\n\n defmodule MyModule do\n require Record\n Record.defrecord :user, name: \"john\", age: 25\n\n @type user :: record(:user, name: String.t, age: integer)\n # expands to: \"@type user :: {:user, String.t, integer}\"\n end\n\n \"\"\"\n\n @doc \"\"\"\n Extracts record information from an Erlang file.\n\n Returns a quoted expression containing the fields as a list\n of tuples.\n\n `name`, which is the name of the extracted record, is expected to be an atom\n *at compile time*.\n\n ## Options\n\n This function accepts the following options, which are exclusive to each other\n (i.e., only one of them can be used in the same call):\n\n * `:from` - (binary representing a path to a file) path to the Erlang file\n that contains the record definition to extract; with this option, this\n function uses the same path lookup used by the `-include` attribute used in\n Erlang modules.\n\n * `:from_lib` - (binary representing a path to a file) path to the Erlang\n file that contains the record definition to extract; with this option,\n this function uses the same path lookup used by the `-include_lib`\n attribute used in Erlang modules.\n\n * `:includes` - (a list of directories as binaries) if the record being\n extracted depends on relative includes, this option allows developers\n to specify the directory those relative includes exist\n\n * `:macros` - (keyword list of macro names and values) if the record\n being extract depends on the values of macros, this option allows\n the value of those macros to be set\n\n These options are expected to be literals (including the binary values) at\n compile time.\n\n ## Examples\n\n iex> Record.extract(:file_info, from_lib: \"kernel\/include\/file.hrl\")\n [size: :undefined, type: :undefined, access: :undefined, atime: :undefined,\n mtime: :undefined, ctime: :undefined, mode: :undefined, links: :undefined,\n major_device: :undefined, minor_device: :undefined, inode: :undefined,\n uid: :undefined, gid: :undefined]\n\n \"\"\"\n @spec extract(name :: atom, keyword) :: keyword\n def extract(name, opts) when is_atom(name) and is_list(opts) do\n Record.Extractor.extract(name, opts)\n end\n\n @doc \"\"\"\n Extracts all records information from an Erlang file.\n\n Returns a keyword list of `{record_name, fields}` tuples where `record_name`\n is the name of an extracted record and `fields` is a list of `{field, value}`\n tuples representing the fields for that record.\n\n ## Options\n\n This function accepts the following options, which are exclusive to each other\n (i.e., only one of them can be used in the same call):\n\n * `:from` - (binary representing a path to a file) path to the Erlang file\n that contains the record definitions to extract; with this option, this\n function uses the same path lookup used by the `-include` attribute used in\n Erlang modules.\n * `:from_lib` - (binary representing a path to a file) path to the Erlang\n file that contains the record definitions to extract; with this option,\n this function uses the same path lookup used by the `-include_lib`\n attribute used in Erlang modules.\n\n These options are expected to be literals (including the binary values) at\n compile time.\n \"\"\"\n @spec extract_all(keyword) :: [{name :: atom, keyword}]\n def extract_all(opts) when is_list(opts) do\n Record.Extractor.extract_all(opts)\n end\n\n @doc \"\"\"\n Checks if the given `data` is a record of kind `kind`.\n\n This is implemented as a macro so it can be used in guard clauses.\n\n ## Examples\n\n iex> record = {User, \"john\", 27}\n iex> Record.is_record(record, User)\n true\n\n \"\"\"\n defguard is_record(data, kind)\n when is_atom(kind) and is_tuple(data) and tuple_size(data) > 0 and\n elem(data, 0) == kind\n\n @doc \"\"\"\n Checks if the given `data` is a record.\n\n This is implemented as a macro so it can be used in guard clauses.\n\n ## Examples\n\n iex> record = {User, \"john\", 27}\n iex> Record.is_record(record)\n true\n iex> tuple = {}\n iex> Record.is_record(tuple)\n false\n\n \"\"\"\n defguard is_record(data)\n when is_tuple(data) and tuple_size(data) > 0 and is_atom(elem(data, 0))\n\n @doc \"\"\"\n Defines a set of macros to create, access, and pattern match\n on a record.\n\n The name of the generated macros will be `name` (which has to be an\n atom). `tag` is also an atom and is used as the \"tag\" for the record (i.e.,\n the first element of the record tuple); by default (if `nil`), it's the same\n as `name`. `kv` is a keyword list of `name: default_value` fields for the\n new record.\n\n The following macros are generated:\n\n * `name\/0` to create a new record with default values for all fields\n * `name\/1` to create a new record with the given fields and values,\n to get the zero-based index of the given field in a record or to\n convert the given record to a keyword list\n * `name\/2` to update an existing record with the given fields and values\n or to access a given field in a given record\n\n All these macros are public macros (as defined by `defmacro`).\n\n See the \"Examples\" section for examples on how to use these macros.\n\n ## Examples\n\n defmodule User do\n require Record\n Record.defrecord :user, [name: \"meg\", age: \"25\"]\n end\n\n In the example above, a set of macros named `user` but with different\n arities will be defined to manipulate the underlying record.\n\n # Import the module to make the user macros locally available\n import User\n\n # To create records\n record = user() #=> {:user, \"meg\", 25}\n record = user(age: 26) #=> {:user, \"meg\", 26}\n\n # To get a field from the record\n user(record, :name) #=> \"meg\"\n\n # To update the record\n user(record, age: 26) #=> {:user, \"meg\", 26}\n\n # To get the zero-based index of the field in record tuple\n # (index 0 is occupied by the record \"tag\")\n user(:name) #=> 1\n\n # Convert a record to a keyword list\n user(record) #=> [name: \"meg\", age: 26]\n\n The generated macros can also be used in order to pattern match on records and\n to bind variables during the match:\n\n record = user() #=> {:user, \"meg\", 25}\n\n user(name: name) = record\n name #=> \"meg\"\n\n By default, Elixir uses the record name as the first element of the tuple (the \"tag\").\n However, a different tag can be specified when defining a record,\n as in the following example, in which we use `Customer` as the second argument of `defrecord\/3`:\n\n defmodule User do\n require Record\n Record.defrecord :user, Customer, name: nil\n end\n\n require User\n User.user() #=> {Customer, nil}\n\n ## Defining extracted records with anonymous functions in the values\n\n If a record defines an anonymous function in the default values, an\n `ArgumentError` will be raised. This can happen unintentionally when defining\n a record after extracting it from an Erlang library that uses anonymous\n functions for defaults.\n\n Record.defrecord :my_rec, Record.extract(...)\n #=> ** (ArgumentError) invalid value for record field fun_field,\n #=> cannot escape #Function<12.90072148\/2 in :erl_eval.expr\/5>.\n\n To work around this error, redefine the field with your own &M.f\/a function,\n like so:\n\n defmodule MyRec do\n require Record\n Record.defrecord :my_rec, Record.extract(...) |> Keyword.merge(fun_field: &__MODULE__.foo\/2)\n def foo(bar, baz), do: IO.inspect({bar, baz})\n end\n\n \"\"\"\n defmacro defrecord(name, tag \\\\ nil, kv) do\n quote bind_quoted: [name: name, tag: tag, kv: kv] do\n tag = tag || name\n fields = Record.__fields__(:defrecord, kv)\n\n defmacro unquote(name)(args \\\\ []) do\n Record.__access__(unquote(tag), unquote(fields), args, __CALLER__)\n end\n\n defmacro unquote(name)(record, args) do\n Record.__access__(unquote(tag), unquote(fields), record, args, __CALLER__)\n end\n end\n end\n\n @doc \"\"\"\n Same as `defrecord\/3` but generates private macros.\n \"\"\"\n defmacro defrecordp(name, tag \\\\ nil, kv) do\n quote bind_quoted: [name: name, tag: tag, kv: kv] do\n tag = tag || name\n fields = Record.__fields__(:defrecordp, kv)\n\n defmacrop unquote(name)(args \\\\ []) do\n Record.__access__(unquote(tag), unquote(fields), args, __CALLER__)\n end\n\n defmacrop unquote(name)(record, args) do\n Record.__access__(unquote(tag), unquote(fields), record, args, __CALLER__)\n end\n end\n end\n\n # Normalizes of record fields to have default values.\n @doc false\n def __fields__(type, fields) do\n normalizer_fun = fn\n {key, value} when is_atom(key) ->\n try do\n Macro.escape(value)\n rescue\n e in [ArgumentError] ->\n raise ArgumentError, \"invalid value for record field #{key}, \" <> Exception.message(e)\n else\n value -> {key, value}\n end\n\n key when is_atom(key) ->\n {key, nil}\n\n other ->\n raise ArgumentError, \"#{type} fields must be atoms, got: #{inspect(other)}\"\n end\n\n :lists.map(normalizer_fun, fields)\n end\n\n # Callback invoked from record\/0 and record\/1 macros.\n @doc false\n def __access__(tag, fields, args, caller) do\n cond do\n is_atom(args) ->\n index(tag, fields, args)\n\n Keyword.keyword?(args) ->\n create(tag, fields, args, caller)\n\n true ->\n fields = Macro.escape(fields)\n\n case Macro.expand(args, caller) do\n {:{}, _, [^tag | list]} when length(list) == length(fields) ->\n record = List.to_tuple([tag | list])\n Record.__keyword__(tag, fields, record)\n\n {^tag, arg} when length(fields) == 1 ->\n Record.__keyword__(tag, fields, {tag, arg})\n\n _ ->\n quote(do: Record.__keyword__(unquote(tag), unquote(fields), unquote(args)))\n end\n end\n end\n\n # Callback invoked from the record\/2 macro.\n @doc false\n def __access__(tag, fields, record, args, caller) do\n cond do\n is_atom(args) ->\n get(tag, fields, record, args)\n\n Keyword.keyword?(args) ->\n update(tag, fields, record, args, caller)\n\n true ->\n raise ArgumentError,\n \"expected arguments to be a compile time atom or a keyword list, got: \" <>\n Macro.to_string(args)\n end\n end\n\n # Gets the index of field.\n defp index(tag, fields, field) do\n if index = find_index(fields, field, 0) do\n # Convert to Elixir index\n index - 1\n else\n raise ArgumentError, \"record #{inspect(tag)} does not have the key: #{inspect(field)}\"\n end\n end\n\n # Creates a new record with the given default fields and keyword values.\n defp create(tag, fields, keyword, caller) do\n in_match = Macro.Env.in_match?(caller)\n keyword = apply_underscore(fields, keyword)\n\n {match, remaining} =\n Enum.map_reduce(fields, keyword, fn {field, default}, each_keyword ->\n new_fields =\n case Keyword.fetch(each_keyword, field) do\n {:ok, value} -> value\n :error when in_match -> {:_, [], nil}\n :error -> Macro.escape(default)\n end\n\n {new_fields, Keyword.delete(each_keyword, field)}\n end)\n\n case remaining do\n [] ->\n {:{}, [], [tag | match]}\n\n _ ->\n keys = for {key, _} <- remaining, do: key\n raise ArgumentError, \"record #{inspect(tag)} does not have the key: #{inspect(hd(keys))}\"\n end\n end\n\n # Updates a record given by var with the given keyword.\n defp update(tag, fields, var, keyword, caller) do\n if Macro.Env.in_match?(caller) do\n raise ArgumentError, \"cannot invoke update style macro inside match\"\n end\n\n keyword = apply_underscore(fields, keyword)\n\n Enum.reduce(keyword, var, fn {key, value}, acc ->\n index = find_index(fields, key, 0)\n\n if index do\n quote do\n :erlang.setelement(unquote(index), unquote(acc), unquote(value))\n end\n else\n raise ArgumentError, \"record #{inspect(tag)} does not have the key: #{inspect(key)}\"\n end\n end)\n end\n\n # Gets a record key from the given var.\n defp get(tag, fields, var, key) do\n index = find_index(fields, key, 0)\n\n if index do\n quote do\n :erlang.element(unquote(index), unquote(var))\n end\n else\n raise ArgumentError, \"record #{inspect(tag)} does not have the key: #{inspect(key)}\"\n end\n end\n\n defp find_index([{k, _} | _], k, i), do: i + 2\n defp find_index([{_, _} | t], k, i), do: find_index(t, k, i + 1)\n defp find_index([], _k, _i), do: nil\n\n # Returns a keyword list of the record\n @doc false\n def __keyword__(tag, fields, record) do\n if is_record(record, tag) do\n [_tag | values] = Tuple.to_list(record)\n\n case join_keyword(fields, values, []) do\n kv when is_list(kv) ->\n kv\n\n expected_fields ->\n raise ArgumentError,\n \"expected argument to be a #{inspect(tag)} record with \" <>\n \"#{expected_fields} fields, got: \" <> inspect(record)\n end\n else\n raise ArgumentError,\n \"expected argument to be a literal atom, literal keyword or \" <>\n \"a #{inspect(tag)} record, got runtime: \" <> inspect(record)\n end\n end\n\n # Returns a keyword list, or expected number of fields on size mismatch\n defp join_keyword([{field, _default} | fields], [value | values], acc),\n do: join_keyword(fields, values, [{field, value} | acc])\n\n defp join_keyword([], [], acc), do: :lists.reverse(acc)\n defp join_keyword(rest_fields, _rest_values, acc), do: length(acc) + length(rest_fields)\n\n defp apply_underscore(fields, keyword) do\n case Keyword.fetch(keyword, :_) do\n {:ok, default} ->\n fields\n |> Enum.map(fn {k, _} -> {k, default} end)\n |> Keyword.merge(keyword)\n |> Keyword.delete(:_)\n\n :error ->\n keyword\n end\n end\nend\n","avg_line_length":32.1771058315,"max_line_length":100,"alphanum_fraction":0.6441133038}
{"size":956,"ext":"ex","lang":"Elixir","max_stars_count":47.0,"content":"defmodule Krihelinator.Repo do\n use Ecto.Repo, otp_app: :krihelinator\n\n @doc \"\"\"\n Given a model and an keyword list get or create a row in the DB. Return\n signature is the same as Repo.insert.\n Note that the the keyword list passes through the model changeset.\n \"\"\"\n def get_or_create_by(model, keywords) do\n case get_by(model, keywords) do\n nil ->\n model\n |> struct\n |> model.changeset(Enum.into(keywords, %{}))\n |> insert\n struct -> {:ok, struct}\n end\n end\n\n @doc \"\"\"\n Update existing struct or create new one using data map. Return signature\n is the same as Repo.insert_or_update.\n Note that the the map passes through the model changeset.\n \"\"\"\n def update_or_create_from_data(model, data, by: by) do\n model\n |> get_by([{by, Map.fetch!(data, by)}])\n |> case do\n :nil -> struct(model)\n struct -> struct\n end\n |> model.changeset(data)\n |> insert_or_update()\n end\n\nend\n","avg_line_length":25.8378378378,"max_line_length":75,"alphanum_fraction":0.6453974895}
{"size":423,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule Hermes.Repo.Migrations.CreateMessages do\n use Ecto.Migration\n\n def change do\n create table(:messages) do\n add :text, :string, null: false\n add :room_id, references(:rooms, on_delete: :nothing), null: false\n add :user_id, references(:users, on_delete: :nothing), null: false\n\n timestamps()\n end\n\n create index(:messages, [:room_id])\n create index(:messages, [:user_id])\n end\nend\n","avg_line_length":24.8823529412,"max_line_length":72,"alphanum_fraction":0.6761229314}
{"size":2523,"ext":"exs","lang":"Elixir","max_stars_count":38.0,"content":"defmodule CoursePlanner.OfferedCourseTest do\n use CoursePlannerWeb.ModelCase\n\n alias CoursePlanner.{Courses.Course, Courses.OfferedCourse, Repo, Terms.Term}\n\n test \"changeset with valid attributes\" do\n changeset =\n OfferedCourse.changeset(\n %OfferedCourse{},\n %{term_id: new_term().id, course_id: new_course().id, number_of_sessions: 2, syllabus: \"some content\"}\n )\n\n assert changeset.valid?\n end\n\n test \"changeset without required associations\" do\n changeset = OfferedCourse.changeset(%OfferedCourse{}, %{})\n\n refute changeset.valid?\n assert changeset.errors[:term_id] == {\"can't be blank\", [validation: :required]}\n assert changeset.errors[:course_id] == {\"can't be blank\", [validation: :required]}\n end\n\n test \"changeset with nonexistent term\" do\n {:error, changeset} =\n OfferedCourse.changeset(%OfferedCourse{}, %{course_id: new_course().id, term_id: -1, number_of_sessions: 42, syllabus: \"some content\"})\n |> Repo.insert\n\n refute changeset.valid?\n assert changeset.errors[:term] == {\"does not exist\", []}\n end\n\n test \"changeset with nonexistent course\" do\n {:error, changeset} =\n OfferedCourse.changeset(%OfferedCourse{}, %{course_id: -1, term_id: new_term().id, number_of_sessions: 42, syllabus: \"some content\"})\n |> Repo.insert\n\n refute changeset.valid?\n assert changeset.errors[:course] == {\"does not exist\", []}\n end\n\n test \"changeset with number_of_sessions equal zero\" do\n changeset = OfferedCourse.changeset(%OfferedCourse{}, %{course_id: -1, term_id: new_term().id, number_of_sessions: 0, syllabus: \"some content\"})\n refute changeset.valid?\n end\n\n test \"changeset with negative number_of_sessions\" do\n changeset = OfferedCourse.changeset(%OfferedCourse{}, %{course_id: -1, term_id: new_term().id, number_of_sessions: -1, syllabus: \"some content\"})\n refute changeset.valid?\n end\n\n test \"changeset with too big number_of_sessions\" do\n changeset = OfferedCourse.changeset(%OfferedCourse{}, %{course_id: -1, term_id: new_term().id, number_of_sessions: 100_000_000, syllabus: \"some content\"})\n refute changeset.valid?\n end\n\n defp new_term do\n Repo.insert!(\n %Term{\n name: \"Fall\",\n start_date: %Ecto.Date{day: 1, month: 1, year: 2017},\n end_date: %Ecto.Date{day: 1, month: 6, year: 2017},\n minimum_teaching_days: 5\n })\n end\n\n defp new_course do\n Repo.insert!(\n %Course{\n name: \"Course\",\n description: \"Description\"\n })\n end\nend\n","avg_line_length":33.64,"max_line_length":158,"alphanum_fraction":0.6817281015}
{"size":720,"ext":"ex","lang":"Elixir","max_stars_count":1.0,"content":"defmodule Coherence.Invitation do\n @moduledoc \"\"\"\n Schema to support inviting a someone to create an account.\n \"\"\"\n use Coherence.Web, :model\n\n schema \"invitations\" do\n field :name, :string\n field :email, :string\n field :token, :string\n\n timestamps()\n end\n\n @doc \"\"\"\n Creates a changeset based on the `model` and `params`.\n\n If no params are provided, an invalid changeset is returned\n with no validation performed.\n \"\"\"\n @spec changeset(Ecto.Schema.t, Map.t) :: Ecto.Changeset.t\n def changeset(model, params \\\\ %{}) do\n model\n |> cast(params, ~w(name email token))\n |> validate_required([:name, :email])\n |> unique_constraint(:email)\n |> validate_format(:email, ~r\/@\/)\n end\nend\n","avg_line_length":24.0,"max_line_length":61,"alphanum_fraction":0.6611111111}
{"size":3296,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule LiveSup.Test.Core.ProjectsTest do\n use ExUnit.Case, async: true\n use LiveSup.DataCase\n\n alias LiveSup.Core.Projects\n import LiveSup.Test.Setups\n\n describe \"projects\" do\n @describetag :projects\n\n alias LiveSup.Schemas.Project\n\n @valid_attrs %{internal: true, labels: [], name: \"some name\", settings: %{}}\n @valid_public_attrs %{internal: false, labels: [], name: \"public project\", settings: %{}}\n @update_attrs %{internal: false, labels: [], name: \"some updated name\", settings: %{}}\n @invalid_attrs %{internal: nil, labels: nil, name: nil, settings: nil}\n\n def project_fixture(attrs \\\\ %{}) do\n {:ok, project} =\n attrs\n |> Enum.into(@valid_attrs)\n |> Projects.create()\n\n project\n end\n\n test \"list_projects\/0 returns all projects\" do\n project = project_fixture()\n assert Projects.all() == [project]\n end\n\n test \"get!\/1 returns the project with given id\" do\n project = project_fixture()\n assert Projects.get!(project.id) == project\n end\n\n test \"get!\/1 returns the project with given id and the associated dashboards\" do\n project = project_fixture()\n\n # Creates a dashboard for the project\n %{project: project}\n |> setup_dashboard()\n\n found_project = Projects.get_with_dashboards!(project.id)\n\n assert %{\n name: \"some name\",\n dashboards: [%{name: \"Cool Dashboard\"}]\n } = found_project\n end\n\n test \"create\/1 with valid data creates a project\" do\n assert {:ok, %Project{} = project} = Projects.create(@valid_attrs)\n assert project.internal == true\n assert project.labels == []\n assert project.name == \"some name\"\n assert project.settings == %{}\n end\n\n test \"create\/1 with invalid data returns error changeset\" do\n assert {:error, %Ecto.Changeset{}} = Projects.create(@invalid_attrs)\n end\n\n test \"update\/2 with valid data updates the project\" do\n project = project_fixture()\n assert {:ok, %Project{} = project} = Projects.update(project, @update_attrs)\n assert project.internal == false\n assert project.labels == []\n assert project.name == \"some updated name\"\n assert project.settings == %{}\n end\n\n test \"update\/2 with invalid data returns error changeset\" do\n project = project_fixture()\n assert {:error, %Ecto.Changeset{}} = Projects.update(project, @invalid_attrs)\n assert project == Projects.get!(project.id)\n end\n\n test \"delete\/1 deletes the project\" do\n project = project_fixture()\n assert {:ok, %Project{}} = Projects.delete(project)\n assert_raise Ecto.NoResultsError, fn -> Projects.get!(project.id) end\n end\n\n test \"change\/1 returns a project changeset\" do\n project = project_fixture()\n assert %Ecto.Changeset{} = Projects.change(project)\n end\n\n @tag :create_public_project\n test \"create_public_project\/1 create public project\" do\n user =\n %{}\n |> setup_groups()\n |> setup_user_with_groups()\n |> Map.get(:user)\n\n {:ok, project} =\n @valid_public_attrs\n |> Projects.create_public_project()\n\n assert @valid_public_attrs = project\n\n assert [%{name: \"public project\"}] = user |> Projects.by_user()\n end\n end\nend\n","avg_line_length":30.5185185185,"max_line_length":93,"alphanum_fraction":0.6380461165}
{"size":5664,"ext":"exs","lang":"Elixir","max_stars_count":1.0,"content":"defmodule Phoenix.MixProject do\n use Mix.Project\n\n @version \"1.5.0-dev\"\n\n # If the elixir requirement is updated, we need to make the installer\n # use at least the minimum requirement used here. Although often the\n # installer is ahead of Phoenix itself.\n @elixir_requirement \"~> 1.7\"\n\n def project do\n [\n app: :phoenix,\n version: @version,\n elixir: @elixir_requirement,\n deps: deps(),\n package: package(),\n lockfile: lockfile(),\n preferred_cli_env: [docs: :docs],\n consolidate_protocols: Mix.env() != :test,\n xref: [\n exclude: [\n {IEx, :started?, 0},\n Ecto.Type,\n :ranch,\n :cowboy_req,\n Plug.Adapters.Cowboy.Conn,\n Plug.Cowboy.Conn,\n Plug.Cowboy\n ]\n ],\n elixirc_paths: elixirc_paths(Mix.env()),\n name: \"Phoenix\",\n docs: docs(),\n aliases: aliases(),\n source_url: \"https:\/\/github.com\/phoenixframework\/phoenix\",\n homepage_url: \"http:\/\/www.phoenixframework.org\",\n description: \"\"\"\n Productive. Reliable. Fast. A productive web framework that\n does not compromise speed or maintainability.\n \"\"\"\n ]\n end\n\n defp elixirc_paths(:docs), do: [\"lib\", \"installer\/lib\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n def application do\n [\n mod: {Phoenix, []},\n extra_applications: [:logger, :eex, :crypto],\n env: [\n logger: true,\n stacktrace_depth: nil,\n template_engines: [],\n format_encoders: [],\n filter_parameters: [\"password\"],\n serve_endpoints: false,\n gzippable_exts: ~w(.js .css .txt .text .html .json .svg .eot .ttf),\n trim_on_html_eex_engine: true\n ]\n ]\n end\n\n defp deps do\n [\n {:plug, \"~> 1.10\"},\n {:plug_crypto, \"~> 1.1.2 or ~> 1.2\"},\n {:telemetry, \"~> 0.4\"},\n {:phoenix_pubsub, \"~> 2.0-dev\", github: \"phoenixframework\/phoenix_pubsub\"},\n\n # Optional deps\n {:plug_cowboy, \"~> 1.0 or ~> 2.1\", optional: true},\n {:jason, \"~> 1.0\", optional: true},\n {:phoenix_html, \"~> 2.13\", optional: true},\n\n # Docs dependencies\n {:ex_doc, \"~> 0.20\", only: :docs},\n {:inch_ex, \"~> 0.2\", only: :docs},\n\n # Test dependencies\n {:gettext, \"~> 0.15.0\", only: :test},\n {:telemetry_poller, \"~> 0.4\", only: :test},\n {:telemetry_metrics, \"~> 0.4\", only: :test},\n {:websocket_client, git: \"https:\/\/github.com\/jeremyong\/websocket_client.git\", only: :test}\n ]\n end\n\n defp lockfile() do\n case System.get_env(\"COWBOY_VERSION\") do\n \"1\" <> _ -> \"mix-cowboy1.lock\"\n _ -> \"mix.lock\"\n end\n end\n\n defp package do\n [\n maintainers: [\"Chris McCord\", \"Jos\u00e9 Valim\", \"Gary Rennie\", \"Jason Stiebs\"],\n licenses: [\"MIT\"],\n links: %{github: \"https:\/\/github.com\/phoenixframework\/phoenix\"},\n files: ~w(assets\/js lib priv CHANGELOG.md LICENSE.md mix.exs package.json README.md .formatter.exs)\n ]\n end\n\n defp docs do\n [\n source_ref: \"v#{@version}\",\n main: \"overview\",\n logo: \"logo.png\",\n extra_section: \"GUIDES\",\n assets: \"guides\/assets\",\n formatters: [\"html\", \"epub\"],\n groups_for_modules: groups_for_modules(),\n extras: extras(),\n groups_for_extras: groups_for_extras()\n ]\n end\n\n defp extras do\n [\n \"guides\/introduction\/overview.md\",\n \"guides\/introduction\/installation.md\",\n \"guides\/introduction\/up_and_running.md\",\n \"guides\/introduction\/community.md\",\n\n \"guides\/directory_structure.md\",\n \"guides\/request_lifecycle.md\",\n \"guides\/plug.md\",\n \"guides\/routing.md\",\n \"guides\/controllers.md\",\n \"guides\/views.md\",\n \"guides\/ecto.md\",\n \"guides\/contexts.md\",\n \"guides\/mix_tasks.md\",\n\n \"guides\/realtime\/channels.md\",\n \"guides\/realtime\/presence.md\",\n\n \"guides\/testing\/testing.md\",\n \"guides\/testing\/testing_contexts.md\",\n \"guides\/testing\/testing_controllers.md\",\n \"guides\/testing\/testing_channels.md\",\n\n \"guides\/deployment\/deployment.md\",\n \"guides\/deployment\/releases.md\",\n \"guides\/deployment\/heroku.md\",\n\n \"guides\/howto\/custom_error_pages.md\",\n \"guides\/howto\/using_ssl.md\",\n ]\n end\n\n defp groups_for_extras do\n [\n \"Introduction\": ~r\/guides\\\/introduction\\\/.?\/,\n \"Guides\": ~r\/guides\\\/[^\\\/]+\\.md\/,\n \"Real-time components\": ~r\/guides\\\/realtime\\\/.?\/,\n \"Testing\": ~r\/guides\\\/testing\\\/.?\/,\n \"Deployment\": ~r\/guides\\\/deployment\\\/.?\/,\n \"How-to's\": ~r\/guides\\\/howto\\\/.?\/\n ]\n end\n\n defp groups_for_modules do\n # Ungrouped Modules:\n #\n # Phoenix\n # Phoenix.Channel\n # Phoenix.Controller\n # Phoenix.Endpoint\n # Phoenix.Naming\n # Phoenix.Logger\n # Phoenix.Param\n # Phoenix.Presence\n # Phoenix.Router\n # Phoenix.Token\n # Phoenix.View\n\n [\n \"Testing\": [\n Phoenix.ChannelTest,\n Phoenix.ConnTest,\n ],\n\n \"Adapters and Plugs\": [\n Phoenix.CodeReloader,\n Phoenix.Endpoint.CowboyAdapter,\n Phoenix.Endpoint.Cowboy2Adapter\n ],\n\n \"Socket and Transport\": [\n Phoenix.Socket,\n Phoenix.Socket.Broadcast,\n Phoenix.Socket.Message,\n Phoenix.Socket.Reply,\n Phoenix.Socket.Serializer,\n Phoenix.Socket.Transport\n ],\n\n \"Templating\": [\n Phoenix.Template,\n Phoenix.Template.EExEngine,\n Phoenix.Template.Engine,\n Phoenix.Template.ExsEngine,\n ],\n ]\n end\n\n defp aliases do\n [\n docs: [\"docs\", &generate_js_docs\/1]\n ]\n end\n\n def generate_js_docs(_) do\n Mix.Task.run \"app.start\"\n System.cmd(\"npm\", [\"run\", \"docs\"], cd: \"assets\")\n end\nend\n","avg_line_length":25.7454545455,"max_line_length":105,"alphanum_fraction":0.584039548}
{"size":1707,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule BackendWeb.Endpoint do\n use Phoenix.Endpoint, otp_app: :backend\n\n socket \"\/socket\", BackendWeb.UserSocket\n\n # Serve at \"\/\" the static files from \"priv\/static\" directory.\n #\n # You should set gzip to true if you are running phoenix.digest\n # when deploying your static files in production.\n plug Plug.Static,\n at: \"\/\", from: :backend, gzip: false,\n only: ~w(css fonts images js favicon.ico robots.txt)\n plug Plug.Static, at: \"\/files\", from: Path.join([\"media\"])\n\n # Code reloading can be explicitly enabled under the\n # :code_reloader configuration of your endpoint.\n if code_reloading? do\n socket \"\/phoenix\/live_reload\/socket\", Phoenix.LiveReloader.Socket\n plug Phoenix.LiveReloader\n plug Phoenix.CodeReloader\n end\n\n plug Plug.Logger\n\n plug Plug.Parsers,\n parsers: [:urlencoded, :multipart, :json],\n pass: [\"*\/*\"],\n json_decoder: Poison\n\n plug Plug.MethodOverride\n plug Plug.Head\n\n # The session will be stored in the cookie and signed,\n # this means its contents can be read but not tampered with.\n # Set :encryption_salt if you would also like to encrypt it.\n plug Plug.Session,\n store: :cookie,\n key: \"_backend_key\",\n signing_salt: \"rztM\/enU\"\n\n plug BackendWeb.Router\n\n @doc \"\"\"\n Callback invoked for dynamically configuring the endpoint.\n\n It receives the endpoint configuration and checks if\n configuration should be loaded from the system environment.\n \"\"\"\n def init(_key, config) do\n if config[:load_from_system_env] do\n port = System.get_env(\"PORT\") || raise \"expected the PORT environment variable to be set\"\n {:ok, Keyword.put(config, :http, [:inet6, port: port])}\n else\n {:ok, config}\n end\n end\nend\n","avg_line_length":29.4310344828,"max_line_length":95,"alphanum_fraction":0.7024018746}
{"size":1218,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"# This file is responsible for configuring your application\n# and its dependencies with the aid of the Mix.Config module.\n#\n# This configuration file is loaded before any dependency and\n# is restricted to this project.\nuse Mix.Config\n\n# General application configuration\nconfig :javex,\n ecto_repos: [Javex.Repo]\n\n# Configures the endpoint\nconfig :javex, Javex.Endpoint,\n url: [host: \"localhost\"],\n secret_key_base: \"+IV\/t+gf75FUwMNpL61hhILFvKWSACK30kpEgHdB181eorO+ZAcNdS807U4refqm\",\n render_errors: [view: Javex.ErrorView, accepts: ~w(html json)],\n pubsub: [name: Javex.PubSub,\n adapter: Phoenix.PubSub.PG2]\n\n# Configures Elixir's Logger\nconfig :logger, :console,\n format: \"$time $metadata[$level] $message\\n\",\n metadata: [:request_id]\n\nconfig :ex_aws,\n access_key_id: System.get_env(\"AWS_ACCESS_KEY_ID\"),\n secret_access_key: System.get_env(\"AWS_SECRET_ACCESS_KEY\"),\n region: \"ap-southeast-1\"\n # s3: [\n # scheme: \"https:\/\/\", \n # host: \"#{System.get_env(\"BUCKET_NAME\")}.s3.amazonaws.com\", \n # region: \"ap-southeast-1\"\n # ]\n\n# Import environment specific config. This must remain at the bottom\n# of this file so it overrides the configuration defined above.\nimport_config \"#{Mix.env}.exs\"\n","avg_line_length":32.0526315789,"max_line_length":86,"alphanum_fraction":0.7315270936}
{"size":1370,"ext":"ex","lang":"Elixir","max_stars_count":1.0,"content":"defmodule TextBasedFPS.Text do\n @type color_t :: :success | :info | :danger\n\n @spec all_colors() :: list(color_t)\n def all_colors, do: [:success, :info, :danger]\n\n @spec highlight(String.t()) :: String.t()\n def highlight(text), do: paint(text, :info)\n\n @spec danger(String.t()) :: String.t()\n def danger(text), do: paint(text, :danger)\n\n @spec success(String.t()) :: String.t()\n def success(text), do: paint(text, :success)\n\n @spec paint(String.t(), color_t) :: String.t()\n def paint(text, color) do\n ansi_color = ansi_color(color)\n ansi_color <> String.replace(text, IO.ANSI.reset(), ansi_color) <> IO.ANSI.reset()\n end\n\n @spec unpaint(String.t()) :: String.t()\n def unpaint(text) do\n Enum.reduce(\n all_colors(),\n text,\n fn color, text -> String.replace(text, ansi_color(color), \"\") end\n )\n |> String.replace(IO.ANSI.reset(), \"\")\n end\n\n @spec find_painted_text(String.t(), color_t) :: any\n def find_painted_text(text, color) do\n escaped_ansi_color = Regex.escape(ansi_color(color))\n escaped_reset = Regex.escape(IO.ANSI.reset())\n regex = Regex.compile!(\"#{escaped_ansi_color}([^\\e]+)#{escaped_reset}\")\n\n Regex.scan(regex, text) |> Enum.map(&Enum.at(&1, 1))\n end\n\n defp ansi_color(:success), do: IO.ANSI.green()\n defp ansi_color(:info), do: IO.ANSI.yellow()\n defp ansi_color(:danger), do: IO.ANSI.red()\nend\n","avg_line_length":30.4444444444,"max_line_length":86,"alphanum_fraction":0.6481751825}
{"size":718,"ext":"exs","lang":"Elixir","max_stars_count":2.0,"content":"defmodule GlowServerTest do\n use ExUnit.Case, async: true\n\n setup do\n glow = start_supervised!(ExampleGlowServer)\n %{glow: glow}\n end\n\n test \"ExampleGlowServer\", %{glow: _} do\n assert \"initial-state\" == ExampleGlowServer.read()\n assert \"the initial-state\" == ExampleGlowServer.concat(\"the \")\n ExampleGlowServer.clear()\n assert \"\" == ExampleGlowServer.read()\n ExampleGlowServer.set(\"new-state\")\n assert \"new-state\" == ExampleGlowServer.read()\n ExampleGlowServer.reverse()\n assert \"etats-wen\" == ExampleGlowServer.read()\n ExampleGlowServer.reverse()\n assert \"new-state\" == ExampleGlowServer.read()\n ExampleGlowServer.clear()\n assert \"\" == ExampleGlowServer.read()\n end\nend\n","avg_line_length":29.9166666667,"max_line_length":66,"alphanum_fraction":0.6977715877}
{"size":513,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule Web.Socket.RequestTest do\n use ExUnit.Case\n\n alias Web.Socket.Request\n alias Web.Socket.State\n\n describe \"checks for supports\" do\n test \"support flag is present\" do\n state = %State{supports: [\"channels\"]}\n assert {:ok, :support_present} = Request.check_support_flag(state, \"channels\")\n end\n\n test \"support flag is not present\" do\n state = %State{supports: [\"channels\"]}\n assert {:error, :support_missing} = Request.check_support_flag(state, \"players\")\n end\n end\nend\n","avg_line_length":27.0,"max_line_length":86,"alphanum_fraction":0.6900584795}
{"size":638,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule VoidElementsTest do\n use ExUnit.Case\n import ExUnit.CaptureIO\n\n [\n {~s[<img src=\"whatevs.png\">], nil},\n {~s[<area alt=\"alt\" href=\"http:\/\/some.image.com\/image\">], nil},\n {~s[<br>], nil},\n {~s[<hr \/>], ~s[<hr \/>]},\n {~s[<wbr>], nil},\n ] |> Enum.each( fn {inp, out} ->\n test \"#{inp} is transformed to #{out} without errors\" do\n stderr_out = capture_io(:stderr, fn ->\n result = Earmark.as_html!(unquote(inp))\n expected = unquote(out||inp)\n assert result == expected\n end)\n assert stderr_out == \"\"\n end\n end)\nend\n\n# SPDX-License-Identifier: Apache-2.0\n","avg_line_length":26.5833333333,"max_line_length":67,"alphanum_fraction":0.5501567398}
{"size":608,"ext":"exs","lang":"Elixir","max_stars_count":100.0,"content":"defmodule Exfile.ConfigTest do\n use ExUnit.Case, async: false\n\n test \"get_backend\/1 with an invalid backend name works\" do\n assert_raise RuntimeError, \"The backend aoeu couldn't be initialized: backend_not_found\", fn ->\n Exfile.Config.get_backend(\"aoeu\")\n end\n end\n\n test \"refresh_backend_config\/0 works\" do\n assert %Exfile.Backend{\n backend_mod: Exfile.Backend.FileSystem\n } = Exfile.Config.get_backend(\"store\")\n\n Exfile.Config.refresh_backend_config\n\n assert %Exfile.Backend{\n backend_mod: Exfile.Backend.FileSystem\n } = Exfile.Config.get_backend(\"store\")\n end\nend\n","avg_line_length":27.6363636364,"max_line_length":99,"alphanum_fraction":0.7286184211}
{"size":3020,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule KafkaEx.ConsumerGroup.Heartbeat do\n @moduledoc false\n\n # GenServer to send heartbeats to the broker\n #\n # A `HeartbeatRequest` is sent periodically by each active group member (after\n # completing the join\/sync phase) to inform the broker that the member is\n # still alive and participating in the group. If a group member fails to send\n # a heartbeat before the group's session timeout expires, the coordinator\n # removes that member from the group and initiates a rebalance.\n #\n # `HeartbeatResponse` allows the coordinating broker to communicate the\n # group's status to each member:\n #\n # * `:no_error` indicates that the group is up to date and no action is\n # needed.\n # * `:rebalance_in_progress` a rebalance has been initiated, so each member\n # should re-join.\n # * `:unknown_member_id` means that this heartbeat was from a previous dead\n # generation.\n #\n # For either of the error conditions, the heartbeat process exits, which is\n # trapped by the KafkaEx.ConsumerGroup.Manager and handled by re-joining the\n # consumer group. (see KafkaEx.ConsumerGroup.Manager.join\/1)\n\n use GenServer\n alias KafkaEx.Protocol.Heartbeat.Request, as: HeartbeatRequest\n alias KafkaEx.Protocol.Heartbeat.Response, as: HeartbeatResponse\n alias KafkaEx.Utils.Logger\n\n defmodule State do\n @moduledoc false\n defstruct [:worker_name, :heartbeat_request, :heartbeat_interval]\n end\n\n def start_link(options) do\n GenServer.start_link(__MODULE__, options)\n end\n\n def init(%{\n group_name: group_name,\n member_id: member_id,\n generation_id: generation_id,\n worker_name: worker_name,\n heartbeat_interval: heartbeat_interval\n }) do\n heartbeat_request = %HeartbeatRequest{\n group_name: group_name,\n member_id: member_id,\n generation_id: generation_id\n }\n\n state = %State{\n worker_name: worker_name,\n heartbeat_request: heartbeat_request,\n heartbeat_interval: heartbeat_interval\n }\n\n {:ok, state, state.heartbeat_interval}\n end\n\n def handle_info(\n :timeout,\n %State{\n worker_name: worker_name,\n heartbeat_request: heartbeat_request,\n heartbeat_interval: heartbeat_interval\n } = state\n ) do\n case KafkaEx.heartbeat(heartbeat_request, worker_name: worker_name) do\n %HeartbeatResponse{error_code: :no_error} ->\n {:noreply, state, heartbeat_interval}\n\n %HeartbeatResponse{error_code: :rebalance_in_progress} ->\n {:stop, {:shutdown, :rebalance}, state}\n\n %HeartbeatResponse{error_code: :unknown_member_id} ->\n {:stop, {:shutdown, :rebalance}, state}\n\n %HeartbeatResponse{error_code: error_code} ->\n Logger.warn(\"Heartbeat failed, got error code #{error_code}\")\n {:stop, {:shutdown, {:error, error_code}}, state}\n\n {:error, reason} ->\n Logger.warn(\"Heartbeat failed, got error reason #{inspect(reason)}\")\n {:stop, {:shutdown, {:error, reason}}, state}\n end\n end\nend\n","avg_line_length":33.5555555556,"max_line_length":80,"alphanum_fraction":0.6966887417}
{"size":7061,"ext":"ex","lang":"Elixir","max_stars_count":2.0,"content":"defmodule Fastfwd do\n @moduledoc \"\"\"\n Toolkit for quickly building simple module proxies, adapters, plugins, facades, and so on.\n\n Fastfwd can be used to provide functionality similar to Rails' ActiveRecord type column,\n or to allow third party libraries or applications to extend the functionality of your code.\n\n Please read the Readme.md file for an introduction.\n\n ## Usage\n\n ### 1) Using the Sender and Receiver modules\n\n The easiest way to use Fastfwd is to `use` the included `Fastfwd.Sender` and `Fastfwd.Receiver` modules to extend your own modules. If you\n want more control then the Fastfwd module provides some utility functions that you can use to extend or replace\n the bundled `Fastfwd.Sender` and `Fastfwd.Receiver`.\n\n Read the `Fastfwd.Sender` and `Fastfwd.Receiver` docs for more information.\n\n ### 2) Writing your own Sender and Receiver modules\n\n When you `use` the `Fastfwd.Sender` it will by default search for modules\n that implement the `Fastfwd.Behaviours.Receiver` behaviour, like `Fastfwd.Sender`. If\n you need different behaviour you can write your own implementations of\n `Fastfwd.Behaviours.Receiver` or `Fastfwd.Behaviours.Sender` behaviour or\n specify different behaviours.\n\n Read the `Fastfwd.Behaviours.Sender` and `Fastfwd.Behaviours.Receiver` docs for more information.\n\n ### 3) Using the utility functions\n\n Fastfwd works by building a list of suitable modules, then collecting the tags of those modules,\n then providing an alternative to `Kernel.apply` that uses a tag to select a module. The supplied\n `Fastfwd.Sender` makes this process faster by caching the module list and tag lookup table using\n [Discord's FastGlobal library](https:\/\/github.com\/discordapp\/fastglobal).\n\n The top level `Fastfwd` module contains some useful functions for listing modules and\n extracting tags, while `Fastfwd.Modules` and `Fastfwd.Module` have some lower-level\n utilities for filtering lists of modules.\n\n These utilities can be used to validating or process tags before using them\n to call functions, such as when read and writing to a database or accepting\n user input.\n\n This top-level module, `Fastfwd`, contains the most useful utilties for (2) and (3).\n\n \"\"\"\n\n def fwd(modules, tag, function_name, params) do\n modules\n |> Fastfwd.find(tag)\n |> apply(function_name, params)\n end\n\n\n @doc \"\"\"\n Returns a list of all modules within a module namespace\n\n This will include *any* module with within the namespace, including those that lack a required behaviour.\n\n ## Examples\n\n iex> Fastfwd.modules(Icecream) |> Enum.sort()\n [Icecream.Chocolate, Icecream.DoubleChocolate, Icecream.Pistachio, Icecream.ShavedIce, Icecream.Spoon, Icecream.Strawberry]\n\n In this example Icecream.Spoon is not a receiver, and has no receiver tags.\n\n \"\"\"\n @spec modules(module) :: [module]\n def modules(namespace) do\n Fastfwd.Modules.all()\n |> Fastfwd.Modules.in_namespace(namespace)\n end\n\n @doc \"\"\"\n Returns a list of all modules within a module namespace, filtered by behaviour.\n\n ## Examples\n\n iex> Fastfwd.modules(Icecream, Fastfwd.Behaviours.Receiver) |> Enum.sort()\n [Icecream.Chocolate, Icecream.DoubleChocolate, Icecream.Pistachio, Icecream.ShavedIce, Icecream.Strawberry]\n\n Icecream.Spoon lacks receiver behaviour so it has been excluded.\n\n \"\"\"\n @spec modules(module, module) :: [module]\n def modules(namespace, behaviour) do\n Fastfwd.Modules.all()\n |> Fastfwd.Modules.in_namespace(namespace)\n |> Fastfwd.Modules.with_behaviour(behaviour)\n end\n\n @doc \"\"\"\n Returns a list of all modules implementing a Sender behaviour (Fastfwd.Behaviours.Sender)\n\n ## Examples\n\n iex> Fastfwd.senders()\n [Icecream]\n\n \"\"\"\n @spec senders() :: [module]\n def senders() do\n Fastfwd.Modules.all()\n |> Fastfwd.Modules.with_behaviour(Fastfwd.Behaviours.Sender)\n end\n\n @doc \"\"\"\n Finds the first appropriate module from a list of modules for the supplied tag\n\n Returns the module\n\n ## Examples\n\n iex> modules = Fastfwd.modules(Icecream)\n iex> Fastfwd.find(modules, :chocolate)\n Icecream.Chocolate\n\n \"\"\"\n @spec find([module(), ...], atom()) :: module()\n def find(modules, tag) do\n Fastfwd.Modules.find(modules, tag)\n end\n\n @doc \"\"\"\n Finds all tags used by receivers in a list of modules\n\n Returns a list of tags as atoms\n\n ## Examples\n\n iex> modules = Fastfwd.modules(Icecream)\n iex> Fastfwd.tags(modules) |> Enum.sort()\n [:chocolate, :chocolate, :double_chocolate, :pistachio, :strawberry]\n\n \"\"\"\n @spec tags([module]) :: [atom]\n def tags(modules) do\n modules\n |> Fastfwd.Modules.tags()\n end\n\n @doc \"\"\"\n Returns a map of tags and modules\n\n ## Examples\n\n iex> Fastfwd.modules(Icecream) |> Fastfwd.routes()\n %{chocolate: Icecream.DoubleChocolate, double_chocolate: Icecream.DoubleChocolate, pistachio: Icecream.Pistachio, strawberry: Icecream.Strawberry}\n\n \"\"\"\n @spec routes([module]) :: map\n def routes(modules) do\n modules\n |> Fastfwd.Modules.routes()\n end\n\n @doc \"\"\"\n Finds all modules for the first application and preloads them, making them visible to Fastfwd.\n\n If a module has not been loaded it might not be detected as a Fastfwd sender - in some environments Elixir will only load a module\n when it first accessed, and so modules designed to be accessed by Fastfwd may not be ready.\n\n Modules using the Fastfwd.Sender module will auto-load their receiver modules, but you may want to manually preload modules if you\n are using Fastfwd to build something more bespoke.\n\n If no applications are specified then Fastfwd will attempt to search the first application found, assuming it to be the current project.\n\n ## Examples\n\n iex> Fastfwd.preload()\n {:ok, [:my_app]}\n\n\n \"\"\"\n @spec preload() :: {:ok, [atom]} | {:error, String.t()}\n defdelegate preload(), to: Fastfwd.Loader, as: :run\n\n @doc \"\"\"\n Finds all modules for listed applications and preloads them, making them visible to Fastfwd.\n\n If a module has not been loaded it might not be detected as a Fastfwd sender - in some environments Elixir will only load a module\n when it first accessed, and so modules designed to be accessed by Fastfwd may not be ready.\n\n Modules using the Fastfwd.Sender module will auto-load their receiver modules, but you may want to manually preload modules if you\n are using Fastfwd to build something more bespoke.\n\n If `:all` is specified then Fastfwd will attempt to search all applications.\n\n ## Examples\n\n iex> Fastfwd.preload(:my_app)\n {:ok, [:my_app]}\n\n iex> Fastfwd.preload([:my_app, :my_app_ee, :extra_plugins])\n {:ok, [:my_app, :my_app_ee, :extra_plugins]}\n\n iex> Fastfwd.preload(:all)\n {:ok, [:my_app, :fastfwd, :fastglobal, :syntax_tools, :benchee, :deep_merge, :logger, :hex, :inets, :ssl, :public_key, :asn1, :crypto, :mix, :iex, :elixir, :compiler, :stdlib, :kernel]}\n\n \"\"\"\n @spec preload([atom]) :: {:ok, [atom]} | {:error, String.t()}\n defdelegate preload(list_of_applications), to: Fastfwd.Loader, as: :run\n\nend\n\n","avg_line_length":34.1111111111,"max_line_length":191,"alphanum_fraction":0.7202945758}
{"size":909,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule Orga.Application do\n # See https:\/\/hexdocs.pm\/elixir\/Application.html\n # for more information on OTP Applications\n @moduledoc false\n\n use Application\n\n def start(_type, _args) do\n # List all child processes to be supervised\n children = [\n # Start the Ecto repository\n Orga.Repo,\n # Start the endpoint when the application starts\n OrgaWeb.Endpoint\n # Starts a worker by calling: Orga.Worker.start_link(arg)\n # {Orga.Worker, arg},\n ]\n\n # See https:\/\/hexdocs.pm\/elixir\/Supervisor.html\n # for other strategies and supported options\n opts = [strategy: :one_for_one, name: Orga.Supervisor]\n Supervisor.start_link(children, opts)\n end\n\n # Tell Phoenix to update the endpoint configuration\n # whenever the application is updated.\n def config_change(changed, _new, removed) do\n OrgaWeb.Endpoint.config_change(changed, removed)\n :ok\n end\nend\n","avg_line_length":28.40625,"max_line_length":63,"alphanum_fraction":0.7073707371}
{"size":1804,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"# Copyright 2017 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This class is auto generated by the swagger code generator program.\n# https:\/\/github.com\/swagger-api\/swagger-codegen.git\n# Do not edit the class manually.\n\ndefmodule GoogleApi.PubSub.V1.Model.PullResponse do\n @moduledoc \"\"\"\n Response for the &#x60;Pull&#x60; method.\n\n ## Attributes\n\n - receivedMessages ([ReceivedMessage]): Received Pub\/Sub messages. The Pub\/Sub system will return zero messages if there are no more available in the backlog. The Pub\/Sub system may return fewer than the &#x60;maxMessages&#x60; requested even if there are more messages available in the backlog. Defaults to: `null`.\n \"\"\"\n\n use GoogleApi.Gax.ModelBase\n\n @type t :: %__MODULE__{\n :receivedMessages => list(GoogleApi.PubSub.V1.Model.ReceivedMessage.t())\n }\n\n field(:receivedMessages, as: GoogleApi.PubSub.V1.Model.ReceivedMessage, type: :list)\nend\n\ndefimpl Poison.Decoder, for: GoogleApi.PubSub.V1.Model.PullResponse do\n def decode(value, options) do\n GoogleApi.PubSub.V1.Model.PullResponse.decode(value, options)\n end\nend\n\ndefimpl Poison.Encoder, for: GoogleApi.PubSub.V1.Model.PullResponse do\n def encode(value, options) do\n GoogleApi.Gax.ModelBase.encode(value, options)\n end\nend\n","avg_line_length":37.5833333333,"max_line_length":318,"alphanum_fraction":0.7533259424}
{"size":2646,"ext":"ex","lang":"Elixir","max_stars_count":6.0,"content":"defmodule Teiserver.Telemetry.UnauthEventLib do\n use CentralWeb, :library\n alias Teiserver.Telemetry.UnauthEvent\n\n # Functions\n @spec colours :: {String.t(), String.t(), String.t()}\n def colours(), do: Central.Helpers.StylingHelper.colours(:info2)\n\n @spec icon() :: String.t()\n def icon(), do: \"far fa-sliders-up\"\n\n # Queries\n @spec query_unauth_events() :: Ecto.Query.t\n def query_unauth_events do\n from unauth_events in UnauthEvent\n end\n\n @spec search(Ecto.Query.t, Map.t | nil) :: Ecto.Query.t\n def search(query, nil), do: query\n def search(query, params) do\n params\n |> Enum.reduce(query, fn ({key, value}, query_acc) ->\n _search(query_acc, key, value)\n end)\n end\n\n @spec _search(Ecto.Query.t, Atom.t(), any()) :: Ecto.Query.t\n def _search(query, _, \"\"), do: query\n def _search(query, _, nil), do: query\n\n def _search(query, :id, id) do\n from unauth_events in query,\n where: unauth_events.id == ^id\n end\n\n def _search(query, :id_list, id_list) do\n from unauth_events in query,\n where: unauth_events.id in ^id_list\n end\n\n def _search(query, :simple_search, ref) do\n ref_like = \"%\" <> String.replace(ref, \"*\", \"%\") <> \"%\"\n\n from unauth_events in query,\n where: (\n ilike(unauth_events.name, ^ref_like)\n )\n end\n\n def _search(query, :event_type_id, event_type_id) do\n from unauth_events in query,\n where: unauth_events.event_type_id == ^event_type_id\n end\n\n def _search(query, :between, {start_date, end_date}) do\n from unauth_events in query,\n where: between(unauth_events.timestamp, ^start_date, ^end_date)\n end\n\n @spec order_by(Ecto.Query.t, String.t | nil) :: Ecto.Query.t\n def order_by(query, nil), do: query\n def order_by(query, \"Name (A-Z)\") do\n from unauth_events in query,\n order_by: [asc: unauth_events.name]\n end\n\n def order_by(query, \"Name (Z-A)\") do\n from unauth_events in query,\n order_by: [desc: unauth_events.name]\n end\n\n def order_by(query, \"Newest first\") do\n from unauth_events in query,\n order_by: [desc: unauth_events.inserted_at]\n end\n\n def order_by(query, \"Oldest first\") do\n from unauth_events in query,\n order_by: [asc: unauth_events.inserted_at]\n end\n\n @spec preload(Ecto.Query.t, List.t | nil) :: Ecto.Query.t\n def preload(query, nil), do: query\n def preload(query, preloads) do\n query = if :event_type in preloads, do: _preload_event_types(query), else: query\n query\n end\n\n def _preload_event_types(query) do\n from unauth_events in query,\n left_join: event_types in assoc(unauth_events, :event_type),\n preload: [event_type: event_types]\n end\nend\n","avg_line_length":27.8526315789,"max_line_length":84,"alphanum_fraction":0.6742252457}
{"size":41994,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"import Ecto.Query, only: [from: 2, join: 4, distinct: 3]\n\ndefmodule Ecto.Association.NotLoaded do\n @moduledoc \"\"\"\n Struct returned by associations when they are not loaded.\n\n The fields are:\n\n * `__field__` - the association field in `owner`\n * `__owner__` - the schema that owns the association\n * `__cardinality__` - the cardinality of the association\n \"\"\"\n\n @type t :: %__MODULE__{\n __field__: atom(),\n __owner__: any(),\n __cardinality__: atom()\n }\n\n defstruct [:__field__, :__owner__, :__cardinality__]\n\n defimpl Inspect do\n def inspect(not_loaded, _opts) do\n msg = \"association #{inspect not_loaded.__field__} is not loaded\"\n ~s(#Ecto.Association.NotLoaded<#{msg}>)\n end\n end\nend\n\ndefmodule Ecto.Association do\n @moduledoc false\n\n @type t :: %{__struct__: atom,\n on_cast: nil | fun,\n cardinality: :one | :many,\n relationship: :parent | :child,\n owner: atom,\n owner_key: atom,\n field: atom,\n unique: boolean,\n where: mfa | Ecto.Query.dynamic() | Keyword.t()}\n\n alias Ecto.Query.{BooleanExpr, QueryExpr, FromExpr}\n\n @doc \"\"\"\n Builds the association struct.\n\n The struct must be defined in the module that implements the\n callback and it must contain at least the following keys:\n\n * `:cardinality` - tells if the association is one to one\n or one\/many to many\n\n * `:field` - tells the field in the owner struct where the\n association should be stored\n\n * `:owner` - the owner module of the association\n\n * `:owner_key` - the key in the owner with the association value\n\n * `:relationship` - if the relationship to the specified schema is\n of a `:child` or a `:parent`\n\n \"\"\"\n @callback struct(module, field :: atom, opts :: Keyword.t) :: t\n\n @doc \"\"\"\n Invoked after the schema is compiled to validate associations.\n\n Useful for checking if associated modules exist without running\n into deadlocks.\n \"\"\"\n @callback after_compile_validation(t, Macro.Env.t) :: :ok | {:error, String.t}\n\n @doc \"\"\"\n Builds a struct for the given association.\n\n The struct to build from is given as argument in case default values\n should be set in the struct.\n\n Invoked by `Ecto.build_assoc\/3`.\n \"\"\"\n @callback build(t, Ecto.Schema.t, %{atom => term} | [Keyword.t]) :: Ecto.Schema.t\n\n @doc \"\"\"\n Returns an association join query.\n\n This callback receives the association struct and it must return\n a query that retrieves all associated entries using joins up to\n the owner association.\n\n For example, a `has_many :comments` inside a `Post` module would\n return:\n\n from c in Comment, join: p in Post, on: c.post_id == p.id\n\n Note all the logic must be expressed inside joins, as fields like\n `where` and `order_by` won't be used by the caller.\n\n This callback is invoked when `join: assoc(p, :comments)` is used\n inside queries.\n \"\"\"\n @callback joins_query(t) :: Ecto.Query.t\n\n @doc \"\"\"\n Returns the association query on top of the given query.\n\n If the query is `nil`, the association target must be used.\n\n This callback receives the association struct and it must return\n a query that retrieves all associated entries with the given\n values for the owner key.\n\n This callback is used by `Ecto.assoc\/2` and when preloading.\n \"\"\"\n @callback assoc_query(t, Ecto.Query.t | nil, values :: [term]) :: Ecto.Query.t\n\n @doc \"\"\"\n Returns information used by the preloader.\n \"\"\"\n @callback preload_info(t) ::\n {:assoc, t, {integer, atom}} | {:through, t, [atom]}\n\n @doc \"\"\"\n Performs the repository change on the association.\n\n Receives the parent changeset, the current changesets\n and the repository action options. Must return the\n persisted struct (or nil) or the changeset error.\n \"\"\"\n @callback on_repo_change(t, parent :: Ecto.Changeset.t, changeset :: Ecto.Changeset.t, Ecto.Adapter.t, Keyword.t) ::\n {:ok, Ecto.Schema.t | nil} | {:error, Ecto.Changeset.t}\n\n @doc \"\"\"\n Retrieves the association from the given schema.\n \"\"\"\n def association_from_schema!(schema, assoc) do\n schema.__schema__(:association, assoc) ||\n raise ArgumentError, \"schema #{inspect schema} does not have association #{inspect assoc}\"\n end\n\n @doc \"\"\"\n Returns the association key for the given module with the given suffix.\n\n ## Examples\n\n iex> Ecto.Association.association_key(Hello.World, :id)\n :world_id\n\n iex> Ecto.Association.association_key(Hello.HTTP, :id)\n :http_id\n\n iex> Ecto.Association.association_key(Hello.HTTPServer, :id)\n :http_server_id\n\n \"\"\"\n def association_key(module, suffix) do\n prefix = module |> Module.split |> List.last |> Macro.underscore\n :\"#{prefix}_#{suffix}\"\n end\n\n @doc \"\"\"\n Build an association query through with starting the given reflection\n and through the given associations.\n \"\"\"\n def assoc_query(refl, through, query, values)\n\n def assoc_query(%{owner: owner, through: [h|t], field: field}, extra, query, values) do\n refl = owner.__schema__(:association, h) ||\n raise \"unknown association `#{h}` for `#{inspect owner}` (used by through association `#{field}`)\"\n assoc_query refl, t ++ extra, query, values\n end\n\n def assoc_query(%module{} = refl, [], query, values) do\n module.assoc_query(refl, query, values)\n end\n\n def assoc_query(refl, t, query, values) do\n query =\n query ||\n %Ecto.Query{\n from: %FromExpr{\n source: {\"join expression\", nil},\n prefix: refl.queryable.__schema__(:prefix)\n }\n }\n\n # Find the position for upcoming joins\n position = length(query.joins) + 1\n\n # The first association must become a join,\n # so we convert its where (that comes from assoc_query)\n # to a join expression.\n #\n # Note we are being restrictive on the format\n # expected from assoc_query.\n assoc_query = refl.__struct__.assoc_query(refl, nil, values)\n %{from: %{source: assoc_source}} = assoc_query\n joins = Ecto.Query.Planner.query_to_joins(:inner, assoc_source, assoc_query, position)\n\n # Add the new join to the query and traverse the remaining\n # joins that will start counting from the added join position.\n query =\n %{query | joins: query.joins ++ joins}\n |> joins_query(t, position + length(joins) - 1)\n |> Ecto.Query.Planner.plan_sources(:adapter_wont_be_needed)\n\n # Our source is going to be the last join after\n # traversing them all.\n {joins, [assoc]} = Enum.split(query.joins, -1)\n\n # Update the mapping and start rewriting expressions\n # to make the last join point to the new from source.\n rewrite_ix = assoc.ix\n [assoc | joins] = Enum.map([assoc | joins], &rewrite_join(&1, rewrite_ix))\n\n query = %{\n query\n | wheres: [assoc_to_where(assoc) | query.wheres],\n joins: joins,\n from: merge_from(query.from, assoc.source),\n sources: nil\n }\n\n distinct(query, [x], true)\n end\n\n @doc \"\"\"\n Add the default assoc query where clauses a provided query\n \"\"\"\n def combine_assoc_query(%{queryable: queryable} = assoc, nil),\n do: combine_assoc_query(assoc, queryable)\n\n def combine_assoc_query(%{where: nil}, queryable), do: queryable\n def combine_assoc_query(%{where: []}, queryable), do: queryable\n\n def combine_assoc_query(%{where: {module, function, args}}, queryable) do\n where = apply(module, function, args)\n Ecto.Query.where(queryable, _, ^where)\n end\n\n def combine_assoc_query(%{where: where}, queryable) do\n Ecto.Query.where(queryable, _, ^where)\n end\n\n defp assoc_to_where(%{on: %QueryExpr{} = on}) do\n on\n |> Map.put(:__struct__, BooleanExpr)\n |> Map.put(:op, :and)\n end\n\n defp merge_from(%FromExpr{source: {\"join expression\", _}} = from, assoc_source),\n do: %{from | source: assoc_source}\n defp merge_from(from, _assoc_source),\n do: from\n\n # Rewrite all later joins\n defp rewrite_join(%{on: on, ix: ix} = join, mapping) when ix >= mapping do\n on = Ecto.Query.Planner.rewrite_sources(on, &rewrite_ix(mapping, &1))\n %{join | on: on, ix: rewrite_ix(mapping, ix)}\n end\n\n # Previous joins are kept intact\n defp rewrite_join(join, _mapping) do\n join\n end\n\n defp rewrite_ix(mapping, ix) when ix > mapping, do: ix - 1\n defp rewrite_ix(ix, ix), do: 0\n defp rewrite_ix(_mapping, ix), do: ix\n\n @doc \"\"\"\n Build a join query with the given `through` associations starting at `counter`.\n \"\"\"\n def joins_query(query, through, counter) do\n Enum.reduce(through, {query, counter}, fn current, {acc, counter} ->\n query = join(acc, :inner, [{x, counter}], assoc(x, ^current))\n {query, counter + 1}\n end) |> elem(0)\n end\n\n @doc \"\"\"\n Retrieves related module from queryable.\n\n ## Examples\n\n iex> Ecto.Association.related_from_query({\"custom_source\", Schema}, :comments_v1)\n Schema\n\n iex> Ecto.Association.related_from_query(Schema, :comments_v1)\n Schema\n\n iex> Ecto.Association.related_from_query(\"wrong\", :comments_v1)\n ** (ArgumentError) association :comments_v1 queryable must be a schema or a {source, schema}. got: \"wrong\"\n \"\"\"\n def related_from_query(atom, _name) when is_atom(atom), do: atom\n def related_from_query({source, schema}, _name) when is_binary(source) and is_atom(schema), do: schema\n def related_from_query(queryable, name) do\n raise ArgumentError, \"association #{inspect name} queryable must be a schema or \" <>\n \"a {source, schema}. got: #{inspect queryable}\"\n end\n\n @doc \"\"\"\n Merges source from query into to the given schema.\n\n In case the query does not have a source, returns\n the schema unchanged.\n \"\"\"\n def merge_source(schema, query)\n\n def merge_source(%{__meta__: %{source: source}} = struct, {source, _}) do\n struct\n end\n\n def merge_source(struct, {source, _}) do\n Ecto.put_meta(struct, source: source)\n end\n\n def merge_source(struct, _query) do\n struct\n end\n\n @doc false\n def update_parent_prefix(\n %{data: %{__meta__: %{prefix: prefix}}} = changeset,\n %{__meta__: %{prefix: prefix}}\n ),\n do: changeset\n\n def update_parent_prefix(changeset, %{__meta__: %{prefix: prefix}}),\n do: update_in(changeset.data, &Ecto.put_meta(&1, prefix: prefix))\n\n def update_parent_prefix(changeset, _),\n do: changeset\n\n @doc \"\"\"\n Performs the repository action in the related changeset,\n returning `{:ok, data}` or `{:error, changes}`.\n \"\"\"\n def on_repo_change(%{data: struct}, [], _adapter, _opts) do\n {:ok, struct}\n end\n\n def on_repo_change(changeset, assocs, adapter, opts) do\n %{data: struct, changes: changes, action: action} = changeset\n\n {struct, changes, _halt, valid?} =\n Enum.reduce(assocs, {struct, changes, false, true}, fn {refl, value}, acc ->\n on_repo_change(refl, value, changeset, action, adapter, opts, acc)\n end)\n\n case valid? do\n true -> {:ok, struct}\n false -> {:error, changes}\n end\n end\n\n defp on_repo_change(%{cardinality: :one, field: field} = meta, nil, parent_changeset,\n _repo_action, adapter, opts, {parent, changes, halt, valid?}) do\n if not halt, do: maybe_replace_one!(meta, nil, parent, parent_changeset, adapter, opts)\n {Map.put(parent, field, nil), Map.put(changes, field, nil), halt, valid?}\n end\n\n defp on_repo_change(%{cardinality: :one, field: field, __struct__: mod} = meta,\n %{action: action} = changeset, parent_changeset,\n repo_action, adapter, opts, {parent, changes, halt, valid?}) do\n check_action!(meta, action, repo_action)\n\n case on_repo_change_unless_halted(halt, mod, meta, parent_changeset, changeset, adapter, opts) do\n {:ok, struct} ->\n struct && maybe_replace_one!(meta, struct, parent, parent_changeset, adapter, opts)\n {Map.put(parent, field, struct), Map.put(changes, field, changeset), halt, valid?}\n\n {:error, error_changeset} ->\n {parent, Map.put(changes, field, error_changeset),\n halted?(halt, changeset, error_changeset), false}\n end\n end\n\n defp on_repo_change(%{cardinality: :many, field: field, __struct__: mod} = meta,\n changesets, parent_changeset, repo_action, adapter, opts,\n {parent, changes, halt, all_valid?}) do\n {changesets, structs, halt, valid?} =\n Enum.reduce(changesets, {[], [], halt, true}, fn\n %{action: action} = changeset, {changesets, structs, halt, valid?} ->\n check_action!(meta, action, repo_action)\n\n case on_repo_change_unless_halted(halt, mod, meta, parent_changeset, changeset, adapter, opts) do\n {:ok, nil} ->\n {[changeset | changesets], structs, halt, valid?}\n\n {:ok, struct} ->\n {[changeset | changesets], [struct | structs], halt, valid?}\n\n {:error, error_changeset} ->\n {[error_changeset | changesets], structs, halted?(halt, changeset, error_changeset), false}\n end\n end)\n\n if valid? do\n {Map.put(parent, field, Enum.reverse(structs)),\n Map.put(changes, field, Enum.reverse(changesets)),\n halt, all_valid?}\n else\n {parent,\n Map.put(changes, field, Enum.reverse(changesets)),\n halt, false}\n end\n end\n\n defp check_action!(%{related: schema}, :delete, :insert),\n do: raise(ArgumentError, \"got action :delete in changeset for associated #{inspect schema} while inserting\")\n defp check_action!(_, _, _), do: :ok\n\n defp halted?(true, _, _), do: true\n defp halted?(_, %{valid?: true}, %{valid?: false}), do: true\n defp halted?(_, _, _), do: false\n\n defp on_repo_change_unless_halted(true, _mod, _meta, _parent, changeset, _adapter, _opts) do\n {:error, changeset}\n end\n defp on_repo_change_unless_halted(false, mod, meta, parent, changeset, adapter, opts) do\n mod.on_repo_change(meta, parent, changeset, adapter, opts)\n end\n\n defp maybe_replace_one!(%{field: field, __struct__: mod} = meta, current, parent,\n parent_changeset, adapter, opts) do\n previous = Map.get(parent, field)\n if replaceable?(previous) and primary_key!(previous) != primary_key!(current) do\n changeset = %{Ecto.Changeset.change(previous) | action: :replace}\n\n case mod.on_repo_change(meta, parent_changeset, changeset, adapter, opts) do\n {:ok, _} ->\n :ok\n {:error, changeset} ->\n raise Ecto.InvalidChangesetError,\n action: changeset.action, changeset: changeset\n end\n end\n end\n\n defp maybe_replace_one!(_, _, _, _, _, _), do: :ok\n\n defp replaceable?(nil), do: false\n defp replaceable?(%Ecto.Association.NotLoaded{}), do: false\n defp replaceable?(%{__meta__: %{state: :built}}), do: false\n defp replaceable?(_), do: true\n\n defp primary_key!(nil), do: []\n defp primary_key!(struct), do: Ecto.primary_key!(struct)\nend\n\ndefmodule Ecto.Association.Has do\n @moduledoc \"\"\"\n The association struct for `has_one` and `has_many` associations.\n\n Its fields are:\n\n * `cardinality` - The association cardinality\n * `field` - The name of the association field on the schema\n * `owner` - The schema where the association was defined\n * `related` - The schema that is associated\n * `owner_key` - The key on the `owner` schema used for the association\n * `related_key` - The key on the `related` schema used for the association\n * `queryable` - The real query to use for querying association\n * `on_delete` - The action taken on associations when schema is deleted\n * `on_replace` - The action taken on associations when schema is replaced\n * `defaults` - Default fields used when building the association\n * `relationship` - The relationship to the specified schema, default is `:child`\n \"\"\"\n\n @behaviour Ecto.Association\n @on_delete_opts [:nothing, :nilify_all, :delete_all]\n @on_replace_opts [:raise, :mark_as_invalid, :delete, :nilify]\n @has_one_on_replace_opts @on_replace_opts ++ [:update]\n defstruct [:cardinality, :field, :owner, :related, :owner_key, :related_key, :on_cast,\n :queryable, :on_delete, :on_replace, :where, unique: true, defaults: [], relationship: :child]\n\n @doc false\n def after_compile_validation(%{queryable: queryable, related_key: related_key}, env) do\n cond do\n not is_atom(queryable) or queryable in env.context_modules ->\n :ok\n not Code.ensure_compiled?(queryable) ->\n {:error, \"associated schema #{inspect queryable} does not exist\"}\n not function_exported?(queryable, :__schema__, 2) ->\n {:error, \"associated module #{inspect queryable} is not an Ecto schema\"}\n is_nil queryable.__schema__(:type, related_key) ->\n {:error, \"associated schema #{inspect queryable} does not have field `#{related_key}`\"}\n true ->\n :ok\n end\n end\n\n @doc false\n def struct(module, name, opts) do\n ref =\n module\n |> Module.get_attribute(:primary_key)\n |> get_ref(opts[:references], name)\n\n unless Module.get_attribute(module, :ecto_fields)[ref] do\n raise ArgumentError, \"schema does not have the field #{inspect ref} used by \" <>\n \"association #{inspect name}, please set the :references option accordingly\"\n end\n\n queryable = Keyword.fetch!(opts, :queryable)\n cardinality = Keyword.fetch!(opts, :cardinality)\n related = Ecto.Association.related_from_query(queryable, name)\n\n if opts[:through] do\n raise ArgumentError, \"invalid association #{inspect name}. When using the :through \" <>\n \"option, the schema should not be passed as second argument\"\n end\n\n on_delete = Keyword.get(opts, :on_delete, :nothing)\n unless on_delete in @on_delete_opts do\n raise ArgumentError, \"invalid :on_delete option for #{inspect name}. \" <>\n \"The only valid options are: \" <>\n Enum.map_join(@on_delete_opts, \", \", &\"`#{inspect &1}`\")\n end\n\n on_replace = Keyword.get(opts, :on_replace, :raise)\n on_replace_opts = if cardinality == :one, do: @has_one_on_replace_opts, else: @on_replace_opts\n\n unless on_replace in on_replace_opts do\n raise ArgumentError, \"invalid `:on_replace` option for #{inspect name}. \" <>\n \"The only valid options are: \" <>\n Enum.map_join(@on_replace_opts, \", \", &\"`#{inspect &1}`\")\n end\n\n %__MODULE__{\n field: name,\n cardinality: cardinality,\n owner: module,\n related: related,\n owner_key: ref,\n related_key: opts[:foreign_key] || Ecto.Association.association_key(module, ref),\n queryable: queryable,\n on_delete: on_delete,\n on_replace: on_replace,\n defaults: opts[:defaults] || [],\n where: opts[:where]\n }\n end\n\n defp get_ref(primary_key, nil, name) when primary_key in [nil, false] do\n raise ArgumentError, \"need to set :references option for \" <>\n \"association #{inspect name} when schema has no primary key\"\n end\n defp get_ref(primary_key, nil, _name), do: elem(primary_key, 0)\n defp get_ref(_primary_key, references, _name), do: references\n\n @doc false\n def build(%{owner_key: owner_key, related_key: related_key} = refl, struct, attributes) do\n %{refl |> build() |> struct(attributes) | related_key => Map.get(struct, owner_key)}\n end\n\n @doc false\n def joins_query(%{related_key: related_key, owner: owner, owner_key: owner_key} = assoc) do\n from o in owner,\n join: q in ^Ecto.Association.combine_assoc_query(assoc, nil),\n on: field(q, ^related_key) == field(o, ^owner_key)\n end\n\n @doc false\n def assoc_query(%{related_key: related_key} = assoc, query, [value]) do\n from x in Ecto.Association.combine_assoc_query(assoc, query),\n where: field(x, ^related_key) == ^value\n end\n\n @doc false\n def assoc_query(%{related_key: related_key} = assoc, query, values) do\n from x in Ecto.Association.combine_assoc_query(assoc, query),\n where: field(x, ^related_key) in ^values\n end\n\n @doc false\n def preload_info(%{related_key: related_key} = refl) do\n {:assoc, refl, {0, related_key}}\n end\n\n @doc false\n def on_repo_change(%{on_replace: on_replace} = refl, %{data: parent} = parent_changeset,\n %{action: :replace} = changeset, adapter, opts) do\n changeset = case on_replace do\n :nilify -> %{changeset | action: :update}\n :update -> %{changeset | action: :update}\n :delete -> %{changeset | action: :delete}\n end\n\n changeset = Ecto.Association.update_parent_prefix(changeset, parent)\n\n case on_repo_change(refl, %{parent_changeset | data: nil}, changeset, adapter, opts) do\n {:ok, _} -> {:ok, nil}\n {:error, changeset} -> {:error, changeset}\n end\n end\n\n def on_repo_change(assoc, parent_changeset, changeset, _adapter, opts) do\n %{data: parent, repo: repo} = parent_changeset\n %{action: action, changes: changes} = changeset\n\n {key, value} = parent_key(assoc, parent)\n changeset = update_parent_key(changeset, action, key, value)\n changeset = Ecto.Association.update_parent_prefix(changeset, parent)\n\n case apply(Ecto.Repo.Schema, action, [repo, changeset, opts]) do\n {:ok, _} = ok ->\n if action == :delete, do: {:ok, nil}, else: ok\n {:error, changeset} ->\n original = Map.get(changes, key)\n {:error, put_in(changeset.changes[key], original)}\n end\n end\n\n defp update_parent_key(changeset, :delete, _key, _value),\n do: changeset\n defp update_parent_key(changeset, _action, key, value),\n do: Ecto.Changeset.put_change(changeset, key, value)\n\n defp parent_key(%{related_key: related_key}, nil) do\n {related_key, nil}\n end\n defp parent_key(%{owner_key: owner_key, related_key: related_key}, owner) do\n {related_key, Map.get(owner, owner_key)}\n end\n\n ## Relation callbacks\n @behaviour Ecto.Changeset.Relation\n\n @doc false\n def build(%{related: related, queryable: queryable, defaults: defaults}) do\n related\n |> struct(defaults)\n |> Ecto.Association.merge_source(queryable)\n end\n\n ## On delete callbacks\n\n @doc false\n def delete_all(refl, parent, repo_name, opts) do\n if query = on_delete_query(refl, parent) do\n Ecto.Repo.Queryable.delete_all repo_name, query, opts\n end\n end\n\n @doc false\n def nilify_all(%{related_key: related_key} = refl, parent, repo_name, opts) do\n if query = on_delete_query(refl, parent) do\n Ecto.Repo.Queryable.update_all repo_name, query, [set: [{related_key, nil}]], opts\n end\n end\n\n defp on_delete_query(%{owner_key: owner_key, related_key: related_key,\n queryable: queryable}, parent) do\n if value = Map.get(parent, owner_key) do\n from x in queryable, where: field(x, ^related_key) == ^value\n end\n end\nend\n\ndefmodule Ecto.Association.HasThrough do\n @moduledoc \"\"\"\n The association struct for `has_one` and `has_many` through associations.\n\n Its fields are:\n\n * `cardinality` - The association cardinality\n * `field` - The name of the association field on the schema\n * `owner` - The schema where the association was defined\n * `owner_key` - The key on the `owner` schema used for the association\n * `through` - The through associations\n * `relationship` - The relationship to the specified schema, default `:child`\n \"\"\"\n\n @behaviour Ecto.Association\n defstruct [:cardinality, :field, :owner, :owner_key, :through, :on_cast, :where,\n relationship: :child, unique: true]\n\n @doc false\n def after_compile_validation(_, _) do\n :ok\n end\n\n @doc false\n def struct(module, name, opts) do\n through = Keyword.fetch!(opts, :through)\n\n refl =\n case through do\n [h,_|_] ->\n Module.get_attribute(module, :ecto_assocs)[h]\n _ ->\n raise ArgumentError, \":through expects a list with at least two entries: \" <>\n \"the association in the current module and one step through, got: #{inspect through}\"\n end\n\n unless refl do\n raise ArgumentError, \"schema does not have the association #{inspect hd(through)} \" <>\n \"used by association #{inspect name}, please ensure the association exists and \" <>\n \"is defined before the :through one\"\n end\n\n %__MODULE__{\n field: name,\n cardinality: Keyword.fetch!(opts, :cardinality),\n through: through,\n owner: module,\n owner_key: refl.owner_key,\n where: opts[:where]\n }\n end\n\n @doc false\n def build(%{field: name}, %{__struct__: struct}, _attributes) do\n raise ArgumentError,\n \"cannot build through association `#{inspect name}` for #{inspect struct}. \" <>\n \"Instead build the intermediate steps explicitly.\"\n end\n\n @doc false\n def preload_info(%{through: through} = refl) do\n {:through, refl, through}\n end\n\n def on_repo_change(%{field: name}, _, _, _, _) do\n raise ArgumentError,\n \"cannot insert\/update\/delete through associations `#{inspect name}` via the repository. \" <>\n \"Instead build the intermediate steps explicitly.\"\n end\n\n @doc false\n def joins_query(%{owner: owner, through: through}) do\n Ecto.Association.joins_query(owner, through, 0)\n end\n\n @doc false\n def assoc_query(refl, query, values) do\n Ecto.Association.assoc_query(refl, [], query, values)\n end\nend\n\ndefmodule Ecto.Association.BelongsTo do\n @moduledoc \"\"\"\n The association struct for a `belongs_to` association.\n\n Its fields are:\n\n * `cardinality` - The association cardinality\n * `field` - The name of the association field on the schema\n * `owner` - The schema where the association was defined\n * `owner_key` - The key on the `owner` schema used for the association\n * `related` - The schema that is associated\n * `related_key` - The key on the `related` schema used for the association\n * `queryable` - The real query to use for querying association\n * `defaults` - Default fields used when building the association\n * `relationship` - The relationship to the specified schema, default `:parent`\n * `on_replace` - The action taken on associations when schema is replaced\n \"\"\"\n\n @behaviour Ecto.Association\n @on_replace_opts [:raise, :mark_as_invalid, :delete, :nilify, :update]\n defstruct [:field, :owner, :related, :owner_key, :related_key, :queryable, :on_cast, :where,\n :on_replace, defaults: [], cardinality: :one, relationship: :parent, unique: true]\n\n @doc false\n def after_compile_validation(%{queryable: queryable, related_key: related_key}, env) do\n cond do\n not is_atom(queryable) or queryable in env.context_modules ->\n :ok\n not Code.ensure_compiled?(queryable) ->\n {:error, \"associated schema #{inspect queryable} does not exist\"}\n not function_exported?(queryable, :__schema__, 2) ->\n {:error, \"associated module #{inspect queryable} is not an Ecto schema\"}\n is_nil queryable.__schema__(:type, related_key) ->\n {:error, \"associated schema #{inspect queryable} does not have field `#{related_key}`\"}\n true ->\n :ok\n end\n end\n\n @doc false\n def struct(module, name, opts) do\n ref = if ref = opts[:references], do: ref, else: :id\n queryable = Keyword.fetch!(opts, :queryable)\n related = Ecto.Association.related_from_query(queryable, name)\n\n unless is_atom(related) do\n raise ArgumentError, \"association queryable must be a schema, got: #{inspect related}\"\n end\n\n on_replace = Keyword.get(opts, :on_replace, :raise)\n\n unless on_replace in @on_replace_opts do\n raise ArgumentError, \"invalid `:on_replace` option for #{inspect name}. \" <>\n \"The only valid options are: \" <>\n Enum.map_join(@on_replace_opts, \", \", &\"`#{inspect &1}`\")\n end\n\n %__MODULE__{\n field: name,\n owner: module,\n related: related,\n owner_key: Keyword.fetch!(opts, :foreign_key),\n related_key: ref,\n queryable: queryable,\n on_replace: on_replace,\n defaults: opts[:defaults] || [],\n where: opts[:where]\n }\n end\n\n @doc false\n def build(refl, _, attributes) do\n refl\n |> build()\n |> struct(attributes)\n end\n\n @doc false\n def joins_query(%{related_key: related_key,\n owner: owner, owner_key: owner_key} = assoc) do\n from o in owner,\n join: q in ^Ecto.Association.combine_assoc_query(assoc, nil),\n on: field(q, ^related_key) == field(o, ^owner_key)\n end\n\n @doc false\n def assoc_query(%{related_key: related_key} = assoc, query, [value]) do\n from x in Ecto.Association.combine_assoc_query(assoc, query),\n where: field(x, ^related_key) == ^value\n end\n\n @doc false\n def assoc_query(%{related_key: related_key} = assoc, query, values) do\n from x in Ecto.Association.combine_assoc_query(assoc, query),\n where: field(x, ^related_key) in ^values\n end\n\n @doc false\n def preload_info(%{related_key: related_key} = refl) do\n {:assoc, refl, {0, related_key}}\n end\n\n @doc false\n def on_repo_change(%{on_replace: :nilify}, _parent_changeset, %{action: :replace}, _adapter, _opts) do\n {:ok, nil}\n end\n\n def on_repo_change(%{on_replace: on_replace} = refl, parent_changeset,\n %{action: :replace} = changeset, adapter, opts) do\n changeset =\n case on_replace do\n :delete -> %{changeset | action: :delete}\n :update -> %{changeset | action: :update}\n end\n\n on_repo_change(refl, parent_changeset, changeset, adapter, opts)\n end\n\n def on_repo_change(_refl, %{data: parent, repo: repo}, %{action: action} = changeset, _adapter, opts) do\n changeset = Ecto.Association.update_parent_prefix(changeset, parent)\n\n case apply(Ecto.Repo.Schema, action, [repo, changeset, opts]) do\n {:ok, _} = ok ->\n if action == :delete, do: {:ok, nil}, else: ok\n {:error, changeset} ->\n {:error, changeset}\n end\n end\n\n ## Relation callbacks\n @behaviour Ecto.Changeset.Relation\n\n @doc false\n def build(%{related: related, queryable: queryable, defaults: defaults}) do\n related\n |> struct(defaults)\n |> Ecto.Association.merge_source(queryable)\n end\nend\n\ndefmodule Ecto.Association.ManyToMany do\n @moduledoc \"\"\"\n The association struct for `many_to_many` associations.\n\n Its fields are:\n\n * `cardinality` - The association cardinality\n * `field` - The name of the association field on the schema\n * `owner` - The schema where the association was defined\n * `related` - The schema that is associated\n * `owner_key` - The key on the `owner` schema used for the association\n * `queryable` - The real query to use for querying association\n * `on_delete` - The action taken on associations when schema is deleted\n * `on_replace` - The action taken on associations when schema is replaced\n * `defaults` - Default fields used when building the association\n * `relationship` - The relationship to the specified schema, default `:child`\n * `join_keys` - The keyword list with many to many join keys\n * `join_through` - Atom (representing a schema) or a string (representing a table)\n for many to many associations\n \"\"\"\n\n @behaviour Ecto.Association\n @on_delete_opts [:nothing, :delete_all]\n @on_replace_opts [:raise, :mark_as_invalid, :delete]\n defstruct [:field, :owner, :related, :owner_key, :queryable, :on_delete,\n :on_replace, :join_keys, :join_through, :join_through_where, :on_cast, :where,\n defaults: [], relationship: :child, cardinality: :many, unique: false]\n\n @doc false\n def after_compile_validation(%{queryable: queryable, join_through: join_through}, env) do\n cond do\n not is_atom(queryable) or queryable in env.context_modules ->\n :ok\n not Code.ensure_compiled?(queryable) ->\n {:error, \"associated schema #{inspect queryable} does not exist\"}\n not function_exported?(queryable, :__schema__, 2) ->\n {:error, \"associated module #{inspect queryable} is not an Ecto schema\"}\n not is_atom(join_through) ->\n :ok\n not Code.ensure_compiled?(join_through) ->\n {:error, \":join_through schema #{inspect join_through} does not exist\"}\n not function_exported?(join_through, :__schema__, 2) ->\n {:error, \":join_through module #{inspect join_through} is not an Ecto schema\"}\n true ->\n :ok\n end\n end\n\n @doc false\n def struct(module, name, opts) do\n join_through = opts[:join_through]\n\n validate_join_through(name, join_through)\n\n join_keys = opts[:join_keys]\n queryable = Keyword.fetch!(opts, :queryable)\n related = Ecto.Association.related_from_query(queryable, name)\n\n {owner_key, join_keys} =\n case join_keys do\n [{join_owner_key, owner_key}, {join_related_key, related_key}]\n when is_atom(join_owner_key) and is_atom(owner_key) and\n is_atom(join_related_key) and is_atom(related_key) ->\n {owner_key, join_keys}\n nil ->\n {:id, default_join_keys(module, related)}\n _ ->\n raise ArgumentError,\n \"many_to_many #{inspect name} expect :join_keys to be a keyword list \" <>\n \"with two entries, the first being how the join table should reach \" <>\n \"the current schema and the second how the join table should reach \" <>\n \"the associated schema. For example: #{inspect default_join_keys(module, related)}\"\n end\n\n unless Module.get_attribute(module, :ecto_fields)[owner_key] do\n raise ArgumentError, \"schema does not have the field #{inspect owner_key} used by \" <>\n \"association #{inspect name}, please set the :join_keys option accordingly\"\n end\n\n on_delete = Keyword.get(opts, :on_delete, :nothing)\n on_replace = Keyword.get(opts, :on_replace, :raise)\n\n unless on_delete in @on_delete_opts do\n raise ArgumentError, \"invalid :on_delete option for #{inspect name}. \" <>\n \"The only valid options are: \" <>\n Enum.map_join(@on_delete_opts, \", \", &\"`#{inspect &1}`\")\n end\n\n unless on_replace in @on_replace_opts do\n raise ArgumentError, \"invalid `:on_replace` option for #{inspect name}. \" <>\n \"The only valid options are: \" <>\n Enum.map_join(@on_replace_opts, \", \", &\"`#{inspect &1}`\")\n end\n\n %__MODULE__{\n field: name,\n cardinality: Keyword.fetch!(opts, :cardinality),\n owner: module,\n related: related,\n owner_key: owner_key,\n join_keys: join_keys,\n join_through: join_through,\n join_through_where: opts[:join_through_where],\n queryable: queryable,\n on_delete: on_delete,\n on_replace: on_replace,\n defaults: opts[:defaults] || [],\n unique: Keyword.get(opts, :unique, false),\n where: opts[:where]\n }\n end\n\n defp default_join_keys(module, related) do\n [{Ecto.Association.association_key(module, :id), :id},\n {Ecto.Association.association_key(related, :id), :id}]\n end\n\n @doc false\n def joins_query(%{owner: owner, join_through_where: join_through_where,\n join_through: join_through, join_keys: join_keys} = assoc) do\n [{join_owner_key, owner_key}, {join_related_key, related_key}] = join_keys\n join_through_query = join_through_query(join_through, join_through_where)\n\n from o in owner,\n join: j in ^join_through_query, on: field(j, ^join_owner_key) == field(o, ^owner_key),\n join: q in ^Ecto.Association.combine_assoc_query(assoc, nil), on: field(j, ^join_related_key) == field(q, ^related_key)\n end\n\n defp join_through_query(queryable, []), do: queryable\n defp join_through_query(queryable, nil), do: queryable\n defp join_through_query(queryable, {module, function, args}) do\n where = apply(module, function, args)\n Ecto.Query.where(queryable, _, ^where)\n end\n defp join_through_query(queryable, where) do\n Ecto.Query.where(queryable, _, ^where)\n end\n\n @doc false\n def assoc_query(%{queryable: queryable} = refl, values) do\n assoc_query(refl, queryable, values)\n end\n\n @doc false\n def assoc_query(%{join_through: join_through, join_keys: join_keys,\n owner: owner, join_through_where: join_through_where} = assoc, query, values) do\n [{join_owner_key, owner_key}, {join_related_key, related_key}] = join_keys\n\n join_through_query = join_through_query(join_through, join_through_where)\n # We need to go all the way using owner and query so\n # Ecto has all the information necessary to cast fields.\n # This also helps validate the associated schema exists all the way.\n from q in Ecto.Association.combine_assoc_query(assoc, query),\n join: o in ^owner, on: field(o, ^owner_key) in ^values,\n join: j in ^join_through_query, on: field(j, ^join_owner_key) == field(o, ^owner_key),\n where: field(j, ^join_related_key) == field(q, ^related_key)\n end\n\n @doc false\n def build(refl, _, attributes) do\n refl\n |> build()\n |> struct(attributes)\n end\n\n @doc false\n def preload_info(%{join_keys: [{_, owner_key}, {_, _}]} = refl) do\n {:assoc, refl, {-2, owner_key}}\n end\n\n @doc false\n def on_repo_change(%{on_replace: :delete} = refl, parent_changeset,\n %{action: :replace} = changeset, adapter, opts) do\n on_repo_change(refl, parent_changeset, %{changeset | action: :delete}, adapter, opts)\n end\n\n def on_repo_change(%{join_keys: join_keys, join_through: join_through},\n %{repo: repo, data: owner}, %{action: :delete, data: related}, adapter, opts) do\n [{join_owner_key, owner_key}, {join_related_key, related_key}] = join_keys\n owner_value = dump! :delete, join_through, owner, owner_key, adapter\n related_value = dump! :delete, join_through, related, related_key, adapter\n\n query =\n from j in join_through,\n where: field(j, ^join_owner_key) == ^owner_value and\n field(j, ^join_related_key) == ^related_value\n\n query = Map.put(query, :prefix, owner.__meta__.prefix)\n Ecto.Repo.Queryable.delete_all repo, query, opts\n {:ok, nil}\n end\n\n def on_repo_change(%{field: field, join_through: join_through, join_keys: join_keys},\n %{repo: repo, data: owner, constraints: constraints} = parent_changeset,\n %{action: action} = changeset, adapter, opts) do\n changeset = Ecto.Association.update_parent_prefix(changeset, owner)\n\n case apply(repo, action, [changeset, opts]) do\n {:ok, related} ->\n [{join_owner_key, owner_key}, {join_related_key, related_key}] = join_keys\n\n if insert_join?(parent_changeset, changeset, field, related_key) do\n owner_value = dump! :insert, join_through, owner, owner_key, adapter\n related_value = dump! :insert, join_through, related, related_key, adapter\n data = [{join_owner_key, owner_value}, {join_related_key, related_value}]\n\n case insert_join(repo, join_through, data, opts, constraints) do\n {:error, join_changeset} ->\n {:error, %{changeset | errors: join_changeset.errors ++ changeset.errors,\n valid?: join_changeset.valid? and changeset.valid?}}\n _ ->\n {:ok, related}\n end\n else\n {:ok, related}\n end\n\n {:error, changeset} ->\n {:error, changeset}\n end\n end\n\n defp validate_join_through(name, nil) do\n raise ArgumentError, \"many_to_many #{inspect name} associations require the :join_through option to be given\"\n end\n defp validate_join_through(_, join_through) when is_atom(join_through) or is_binary(join_through) do\n :ok\n end\n defp validate_join_through(name, _join_through) do\n raise ArgumentError,\n \"many_to_many #{inspect name} associations require the :join_through option to be \" <>\n \"an atom (representing a schema) or a string (representing a table)\"\n end\n\n defp insert_join?(%{action: :insert}, _, _field, _related_key), do: true\n defp insert_join?(_, %{action: :insert}, _field, _related_key), do: true\n defp insert_join?(%{data: owner}, %{data: related}, field, related_key) do\n current_key = Map.fetch!(related, related_key)\n not Enum.any? Map.fetch!(owner, field), fn child ->\n Map.get(child, related_key) == current_key\n end\n end\n\n defp insert_join(repo, join_through, data, opts, _constraints) when is_binary(join_through) do\n Ecto.Repo.Schema.insert_all(repo, join_through, [data], opts)\n end\n\n defp insert_join(repo, join_through, data, opts, constraints) when is_atom(join_through) do\n changeset =\n struct(join_through, data)\n |> Ecto.Changeset.change\n |> Map.put(:constraints, constraints)\n\n Ecto.Repo.Schema.insert(repo, changeset, opts)\n end\n\n defp field!(op, struct, field) do\n Map.get(struct, field) || raise \"could not #{op} join entry because `#{field}` is nil in #{inspect struct}\"\n end\n\n defp dump!(action, join_through, struct, field, adapter) when is_binary(join_through) do\n value = field!(action, struct, field)\n type = struct.__struct__.__schema__(:type, field)\n\n case Ecto.Type.adapter_dump(adapter, type, value) do\n {:ok, value} ->\n value\n :error ->\n raise Ecto.ChangeError,\n \"value `#{inspect value}` for `#{inspect struct.__struct__}.#{field}` \" <>\n \"in `#{action}` does not match type #{inspect type}\"\n end\n end\n\n defp dump!(action, join_through, struct, field, _) when is_atom(join_through) do\n field!(action, struct, field)\n end\n\n ## Relation callbacks\n @behaviour Ecto.Changeset.Relation\n\n @doc false\n def build(%{related: related, queryable: queryable, defaults: defaults}) do\n related\n |> struct(defaults)\n |> Ecto.Association.merge_source(queryable)\n end\n\n ## On delete callbacks\n\n @doc false\n def delete_all(refl, parent, repo_name, opts) do\n %{join_through: join_through, join_keys: join_keys, owner: owner} = refl\n [{join_owner_key, owner_key}, {_, _}] = join_keys\n\n if value = Map.get(parent, owner_key) do\n owner_type = owner.__schema__(:type, owner_key)\n query = from j in join_through, where: field(j, ^join_owner_key) == type(^value, ^owner_type)\n Ecto.Repo.Queryable.delete_all repo_name, query, opts\n end\n end\nend\n","avg_line_length":35.4080944351,"max_line_length":125,"alphanum_fraction":0.6650235748}
{"size":376,"ext":"ex","lang":"Elixir","max_stars_count":528.0,"content":"defmodule Ash.Registry.ResourceValidations do\n @moduledoc \"\"\"\n Adds some top level validations of resources present in a registry\n \"\"\"\n @transformers [\n Ash.Registry.ResourceValidations.Transformers.EnsureResourcesCompiled,\n Ash.Registry.ResourceValidations.Transformers.ValidateRelatedResourceInclusion\n ]\n\n use Ash.Dsl.Extension, transformers: @transformers\nend\n","avg_line_length":31.3333333333,"max_line_length":82,"alphanum_fraction":0.8031914894}
{"size":850,"ext":"ex","lang":"Elixir","max_stars_count":2.0,"content":"defmodule MangaEx.MangaProviders.ProvidersBehaviour do\n @callback find_mangas(String.t()) ::\n [{manga_name :: String.t(), manga_url :: String.t()}]\n | {:error, :client_error | :server_error}\n | {:ok, :manga_not_found}\n\n @callback get_chapters(String.t(), pos_integer()) ::\n :ok\n | {:error, :manga_not_found}\n | %{:chapters => [integer()], :special_chapters => [String.t()]}\n\n @callback download_pages(\n pages_url :: [String.t()],\n manga_name :: String.t(),\n chapter :: String.t() | integer(),\n sleep :: integer()\n ) :: list()\n\n @callback get_pages(chapter_url :: String.t(), manga_name :: String.t(), pos_integer()) ::\n [{String.t(), integer()}] | {:error, :client_error | :server_error}\nend\n","avg_line_length":38.6363636364,"max_line_length":92,"alphanum_fraction":0.5341176471}
{"size":3436,"ext":"ex","lang":"Elixir","max_stars_count":449.0,"content":"defmodule GitGud.DataFactory do\n @moduledoc \"\"\"\n This module provides functions to generate all kind of test data.\n \"\"\"\n\n alias GitGud.User\n\n import Faker.Person, only: [name: 0]\n import Faker.Company, only: [catch_phrase: 0]\n import Faker.Internet, only: [user_name: 0]\n import Faker.Lorem, only: [sentence: 1, paragraph: 1]\n import Faker.Nato, only: [callsign: 0]\n\n @doc \"\"\"\n Returns a map representing `GitGud.User` registration changeset params.\n \"\"\"\n def user do\n %{\n name: name(),\n login: String.replace(user_name(), ~r\/[^a-zA-Z0-9_-]\/, \"-\", global: true),\n account: account(),\n emails: [email()]\n }\n end\n\n @doc \"\"\"\n Returns a map representing `GitGud.Repo` changeset params.\n \"\"\"\n def repo do\n %{name: String.downcase(callsign()), description: sentence(2..8), pushed_at: NaiveDateTime.utc_now()}\n end\n\n @doc \"\"\"\n Returns a map representing `GitGud.Account` changeset params.\n \"\"\"\n def account do\n %{password: \"qwertz\"}\n end\n\n @doc \"\"\"\n Returns a map representing `GitGud.Email` changeset params.\n \"\"\"\n def email do\n %{address: String.replace(Faker.Internet.email(), \"'\", \"\")}\n end\n\n @doc \"\"\"\n Returns a map representing `GitGud.SSHKey` changeset params.\n \"\"\"\n def ssh_key do\n {rsa_pub, rsa_priv} = make_ssh_pair(512)\n %{name: callsign(), data: rsa_pub, __priv__: rsa_priv}\n end\n\n @doc \"\"\"\n Returns a map representing `GitGud.SSHKey` changeset params.\n \"\"\"\n def ssh_key_strong do\n {rsa_pub, rsa_priv} = make_ssh_pair(2048)\n %{name: callsign(), data: rsa_pub, __priv__: rsa_priv}\n end\n\n @doc \"\"\"\n Returns a map representing `GitGud.SSHKey` changeset params.\n \"\"\"\n def ssh_key_strong(%User{id: user_id}), do: ssh_key_strong(user_id)\n def ssh_key_strong(user_id) when is_integer(user_id) do\n Map.put(ssh_key_strong(), :user_id, user_id)\n end\n\n @doc \"\"\"\n Returns a map representing `GitGud.GPGKey` changeset params.\n \"\"\"\n def gpg_key(%User{name: name, emails: emails}) do\n gpg_key(name, Enum.map(emails, &(&1.address)))\n end\n\n @doc \"\"\"\n Returns a map representing `GitGud.GPGKey` changeset params.\n \"\"\"\n def gpg_key(name, emails) do\n %{data: make_gpg_key(name, emails)}\n end\n\n @doc \"\"\"\n Returns a map representing `GitGud.Issue` changeset params.\n \"\"\"\n def issue() do\n %{title: catch_phrase(), comment: comment()}\n end\n\n @doc \"\"\"\n Returns a map representing `GitGud.Comment` changeset params.\n \"\"\"\n def comment do\n %{body: paragraph(2..5)}\n end\n\n @doc false\n defmacro __using__(_opts) do\n quote do\n def factory(name, params \\\\ []) do\n apply(unquote(__MODULE__), name, List.wrap(params))\n end\n end\n end\n\n #\n # Helpers\n #\n\n defp make_ssh_pair(bit_size) do\n {rsa_priv, 0} = System.cmd(\"sh\", [\"-c\", \"openssl genrsa #{bit_size} 2>\/dev\/null\"])\n {rsa_pubk, 0} = System.cmd(\"sh\", [\"-c\", \"echo \\\"#{rsa_priv}\\\" | openssl pkey -pubout | ssh-keygen -i -f \/dev\/stdin -m PKCS8\"])\n {rsa_pubk, rsa_priv}\n end\n\n defp make_gpg_key(name, emails) do\n gen_key =\n Enum.reduce(emails, \"%no-protection\\n%pubring -\\nKey-Type: eddsa\\nKey-Curve: Ed25519\\nSubkey-Type: ecdh\\nSubkey-Curve: Curve25519\", fn email, acc ->\n acc <> \"\\nName-Real: #{name}\\nName-Email: #{email}\"\n end)\n\n case System.cmd(\"sh\", [\"-c\", \"echo \\\"#{gen_key}\\\" | gpg --batch --gen-key --armor\"]) do\n {armor, 0} -> armor\n {error, 1} -> raise \"failed to generate GPG key: #{error}\"\n end\n end\nend\n","avg_line_length":26.4307692308,"max_line_length":152,"alphanum_fraction":0.6408614668}
{"size":1153,"ext":"exs","lang":"Elixir","max_stars_count":4.0,"content":"defmodule AgentCheck.Mixfile do\n use Mix.Project\n\n def project do\n [\n app: :agent_check,\n version: \"0.2.8\",\n elixir: \"~> 1.5\",\n build_embedded: Mix.env() == :prod,\n start_permanent: Mix.env() == :prod,\n description: description(),\n package: package(),\n deps: deps()\n ]\n end\n\n # Run \"mix help compile.app\" to learn about applications.\n def application do\n [\n extra_applications: [:logger],\n mod: {AgentCheck.Application, []}\n ]\n end\n\n # Run \"mix help deps\" to learn about dependencies.\n defp deps do\n [\n {:ex_doc, \"~> 0.18\", only: :dev},\n {:credo, \"~> 0.9.0-rc1\", only: [:dev, :test], runtime: false}\n ]\n end\n\n defp description do\n \"\"\"\n HAProxy Agent Check protocol implementation for Elixir\/Phoenix apps. Allows for easy rolling restarts and dynamic backpressure to your HAProxy loadbalancer.\n \"\"\"\n end\n\n defp package do\n [\n files: [\"lib\", \"mix.exs\", \"README*\", \"LICENSE*\"],\n maintainers: [\"Bart ten Brinke\", \"Beta Corp\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/betacooperation\/agent_check\"}\n ]\n end\nend\n","avg_line_length":24.0208333333,"max_line_length":160,"alphanum_fraction":0.5958369471}
{"size":438,"ext":"ex","lang":"Elixir","max_stars_count":4.0,"content":"defmodule InstituteWeb.PageView do\n use InstituteWeb, :view\n\n alias Institute.Meetings\n\n def next_meeting do\n Meetings.next_meeting()\n end\n\n def fmt_mtg_content(%{content: content, type: \"html\"}) do\n raw(content)\n end\n\n def fmt_mtg_content(%{content: content, type: _type}) do\n content\n end\n\n @doc \"\"\"\n Guards agains a nil stored in the DB.\n\n Returns blank as a last resort.\n \"\"\"\n def fmt_mtg_content(_), do: \"\"\nend\n","avg_line_length":17.52,"max_line_length":59,"alphanum_fraction":0.6872146119}
{"size":2402,"ext":"exs","lang":"Elixir","max_stars_count":7.0,"content":"defmodule Txpost.Plug.EnvelopeRequiredTest do\n use ExUnit.Case, async: true\n use Plug.Test\n\n @rawtx <<1, 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 >>\n @cbor_payload <<\n 161, 100, 100, 97, 116, 97, 161, 101, 114, 97, 119, 116, 120, 106, 1, 0, 0,\n 0, 0, 0, 0, 0, 0, 0>>\n @cbor_envelope <<\n 162, 103, 112, 97, 121, 108, 111, 97, 100, 120, 24, 161, 100, 100, 97, 116,\n 97, 161, 101, 114, 97, 119, 116, 120, 106, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 102, 112, 117, 98, 107, 101, 121, 99, 97, 98, 99>>\n @cbor_envelope_signed <<\n 163, 103, 112, 97, 121, 108, 111, 97, 100, 120, 24, 161, 100, 100, 97, 116,\n 97, 161, 101, 114, 97, 119, 116, 120, 106, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 102, 112, 117, 98, 107, 101, 121, 120, 33, 2, 170, 75, 142, 232, 142, 111,\n 76, 138, 31, 212, 197, 4, 20, 227, 157, 8, 252, 150, 79, 61, 83, 205, 99,\n 54, 225, 193, 254, 122, 200, 147, 51, 180, 105, 115, 105, 103, 110, 97, 116,\n 117, 114, 101, 120, 70, 48, 68, 2, 32, 24, 134, 241, 47, 243, 122, 86, 199,\n 199, 220, 173, 209, 38, 189, 238, 84, 197, 20, 218, 193, 190, 35, 88, 95,\n 214, 137, 204, 206, 156, 21, 223, 5, 2, 32, 67, 243, 10, 255, 17, 52, 68,\n 176, 250, 253, 199, 208, 16, 167, 132, 183, 206, 49, 147, 241, 61, 117, 231,\n 254, 197, 52, 109, 45, 247, 78, 210, 62>>\n\n\n def cbor_conn(body, content_type \\\\ \"application\/cbor\") do\n put_req_header(conn(:post, \"\/\", body), \"content-type\", content_type)\n end\n\n def parse(conn, opts \\\\ []) do\n opts = Keyword.put_new(opts, :parsers, [Txpost.Parsers.CBOR])\n conn\n |> plug(Plug.Parsers, opts)\n |> plug(Txpost.Plug.EnvelopeRequired, opts)\n end\n\n def plug(conn, mod, opts \\\\ []) do\n apply(mod, :call, [conn, apply(mod, :init, [opts])])\n end\n\n test \"should parse the CBOR envelope\" do\n conn = cbor_conn(@cbor_envelope) |> parse\n assert get_in(conn.params, [\"data\", \"rawtx\"]) == @rawtx\n end\n\n test \"should parse a signed CBOR envelope\" do\n conn = cbor_conn(@cbor_envelope_signed) |> parse(ensure_signed: true)\n assert get_in(conn.params, [\"data\", \"rawtx\"]) == @rawtx\n end\n\n test \"should raise requires signature\" do\n assert_raise Txpost.Envelope.InvalidSignatureError, fn ->\n cbor_conn(@cbor_envelope) |> parse(ensure_signed: true)\n end\n end\n\n test \"should raise when invalid CBOR envelope\" do\n assert_raise Plug.BadRequestError, fn ->\n cbor_conn(@cbor_payload) |> parse\n end\n end\n\nend\n","avg_line_length":37.53125,"max_line_length":80,"alphanum_fraction":0.5986677769}
{"size":4948,"ext":"exs","lang":"Elixir","max_stars_count":29.0,"content":"defmodule TelemetryMetricsPrometheus.Core.AggregatorTest do\n use ExUnit.Case\n\n defstruct error: nil\n\n import ExUnit.CaptureLog\n\n alias TelemetryMetricsPrometheus.Core.{Aggregator, Counter, Distribution}\n\n setup do\n tid = :ets.new(:test_table, [:named_table, :public, :set, {:write_concurrency, true}])\n\n dist_tid =\n :ets.new(:test_dist_table, [\n :named_table,\n :public,\n :duplicate_bag,\n {:write_concurrency, true}\n ])\n\n %{tid: tid, dist_tid: dist_tid}\n end\n\n describe \"bucket_measurements\/2\" do\n test \"measurements are properly bucketed\" do\n [\n {[1, 2, 3, \"+Inf\"], [], {[{\"1\", 0}, {\"2\", 0}, {\"3\", 0}, {\"+Inf\", 0}], 0, 0},\n \"with no measurements\"},\n {[1, 2, 3, \"+Inf\"], [0.1], {[{\"1\", 1}, {\"2\", 1}, {\"3\", 1}, {\"+Inf\", 1}], 1, 0.1},\n \"with one measurement\"},\n {[1, 2, 3, \"+Inf\"], [2, 3.1], {[{\"1\", 0}, {\"2\", 1}, {\"3\", 1}, {\"+Inf\", 2}], 2, 5.1},\n \"compares measurement to bucket limit correctly\"},\n {[1, 2, 3, \"+Inf\"], [4, 5], {[{\"1\", 0}, {\"2\", 0}, {\"3\", 0}, {\"+Inf\", 2}], 2, 9},\n \"with measurements over the bucket limits\"}\n ]\n |> Enum.each(fn {buckets, measurements, expected_buckets, message} ->\n result = Aggregator.bucket_measurements(measurements, buckets)\n assert(result == expected_buckets, message)\n end)\n end\n end\n\n describe \"get_time_series\/1\" do\n test \"aggregations with bad tag values are filtered and deleted\",\n %{tid: tid} do\n metric =\n Telemetry.Metrics.counter(\"http.request.error\",\n event_name: [:plug, :call, :exception],\n tags: [:kind, :reason]\n )\n\n {:ok, _handler_id} = Counter.register(metric, tid, self())\n\n :telemetry.execute([:plug, :call, :exception], %{duration: 120}, %{\n kind: :error,\n reason: \"Oops\"\n })\n\n :telemetry.execute([:plug, :call, :exception], %{duration: 120}, %{\n kind: :error,\n reason: %__MODULE__{}\n })\n\n expected = %{\n [:http, :request, :error] => [\n {{[:http, :request, :error], %{kind: :error, reason: \"Oops\"}}, 1}\n ]\n }\n\n capture_log(fn ->\n assert Aggregator.get_time_series(tid) == expected\n end) =~\n \"Dropping aggregation for bad tag value. metric:=[:http, :request, :error] tag: :reason\"\n\n cleanup(tid)\n end\n end\n\n describe \"aggregate\/3\" do\n test \"stores an aggregation in the aggregates table and combines on subsequent aggregations\",\n %{tid: tid, dist_tid: dist_tid} do\n buckets = [\n 1,\n 2,\n 3\n ]\n\n metric =\n Telemetry.Metrics.distribution(\"some.plug.call.duration\",\n description: \"Plug call duration\",\n event_name: [:some, :plug, :call, :stop],\n measurement: :duration,\n unit: {:native, :second},\n tags: [:method, :path_root],\n reporter_options: [\n buckets: buckets\n ],\n tag_values: fn %{conn: conn} ->\n %{\n method: conn.method,\n path_root: List.first(conn.path_info) || \"\"\n }\n end\n )\n\n metric = %{metric | reporter_options: [buckets: buckets ++ [\"+Inf\"]]}\n\n {:ok, _handler_id} = Distribution.register(metric, dist_tid, self())\n\n :telemetry.execute([:some, :plug, :call, :stop], %{duration: 3_000_000_000}, %{\n conn: %{method: \"GET\", path_info: [\"users\", \"123\"]}\n })\n\n :telemetry.execute([:some, :plug, :call, :stop], %{duration: 3_000_000_000}, %{\n conn: %{method: \"GET\", path_info: [\"users\", \"123\"]}\n })\n\n :ok = Aggregator.aggregate([metric], tid, dist_tid)\n\n [\n {{[:some, :plug, :call, :duration], %{method: \"GET\", path_root: \"users\"}},\n {bucketed, count, sum}}\n ] = :ets.tab2list(tid)\n\n assert bucketed == [{\"1\", 0}, {\"2\", 0}, {\"3\", 2}, {\"+Inf\", 2}]\n assert count == 2\n assert sum == 6.0\n\n :telemetry.execute([:some, :plug, :call, :stop], %{duration: 1_500_000_000}, %{\n conn: %{method: \"GET\", path_info: [\"users\", \"123\"]}\n })\n\n :telemetry.execute([:some, :plug, :call, :stop], %{duration: 0_800_000_000}, %{\n conn: %{method: \"GET\", path_info: [\"users\", \"123\"]}\n })\n\n :ok = Aggregator.aggregate([metric], tid, dist_tid)\n\n [\n {{[:some, :plug, :call, :duration], %{method: \"GET\", path_root: \"users\"}},\n {bucketed_2, count_2, sum_2}}\n ] = :ets.tab2list(tid)\n\n assert bucketed_2 == [{\"1\", 1}, {\"2\", 2}, {\"3\", 4}, {\"+Inf\", 4}]\n assert count_2 == 4\n assert sum_2 == 8.3\n\n cleanup(tid)\n cleanup(dist_tid)\n end\n end\n\n def cleanup(tid) do\n :ets.delete_all_objects(tid)\n\n :telemetry.list_handlers([])\n |> Enum.each(&:telemetry.detach(&1.id))\n end\n\n def fetch_metric(table_id, key) do\n case :ets.lookup(table_id, key) do\n [result] -> result\n _ -> :error\n end\n end\nend\n","avg_line_length":29.628742515,"max_line_length":97,"alphanum_fraction":0.5351657235}
{"size":1712,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule Mojito.MixProject do\n use Mix.Project\n\n @version \"0.7.9\"\n @repo_url \"https:\/\/github.com\/appcues\/mojito\"\n\n def project do\n [\n app: :mojito,\n version: @version,\n elixir: \"~> 1.7\",\n elixirc_paths: elixirc_paths(Mix.env()),\n start_permanent: Mix.env() == :prod,\n dialyzer: [\n plt_add_apps: [:mix]\n ],\n deps: deps(),\n package: package(),\n docs: docs()\n ]\n end\n\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n defp package do\n [\n description: \"Fast, easy to use HTTP client based on Mint\",\n licenses: [\"MIT\"],\n maintainers: [\"pete gamache <pete@appcues.com>\"],\n links: %{\n Changelog: \"https:\/\/hexdocs.pm\/mojito\/changelog.html\",\n GitHub: @repo_url\n }\n ]\n end\n\n def application do\n [\n extra_applications: [:logger],\n mod: {Mojito.Application, []}\n ]\n end\n\n defp deps do\n [\n {:mint, \"~> 1.1\"},\n {:castore, \"~> 0.1\"},\n {:poolboy, \"~> 1.5\"},\n {:telemetry, \"~> 0.4\"},\n {:ex_spec, \"~> 2.0\", only: :test},\n {:jason, \"~> 1.0\", only: :test},\n {:cowboy, \"~> 2.0\", only: :test},\n {:plug, \"~> 1.3\", only: :test},\n {:plug_cowboy, \"~> 2.0\", only: :test},\n {:ex_doc, \">= 0.0.0\", only: :dev, runtime: false},\n {:dialyxir, \"~> 1.0\", only: :dev, runtime: false}\n ]\n end\n\n defp docs do\n [\n extras: [\n \"CHANGELOG.md\": [title: \"Changelog\"],\n \"LICENSE.md\": [title: \"License\"]\n ],\n assets: \"assets\",\n logo: \"assets\/mojito.png\",\n main: \"Mojito\",\n source_url: @repo_url,\n source_ref: @version,\n formatters: [\"html\"]\n ]\n end\nend\n","avg_line_length":22.5263157895,"max_line_length":65,"alphanum_fraction":0.5134345794}
{"size":9705,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule Integer do\n @moduledoc \"\"\"\n Functions for working with integers.\n \"\"\"\n\n import Bitwise\n\n @doc \"\"\"\n Determines if `integer` is odd.\n\n Returns `true` if the given `integer` is an odd number,\n otherwise it returns `false`.\n\n Allowed in guard clauses.\n\n ## Examples\n\n iex> Integer.is_odd(5)\n true\n\n iex> Integer.is_odd(6)\n false\n\n iex> Integer.is_odd(-5)\n true\n\n iex> Integer.is_odd(0)\n false\n\n \"\"\"\n defmacro is_odd(integer) do\n quote do: (unquote(integer) &&& 1) == 1\n end\n\n @doc \"\"\"\n Determines if an `integer` is even.\n\n Returns `true` if the given `integer` is an even number,\n otherwise it returns `false`.\n\n Allowed in guard clauses.\n\n ## Examples\n\n iex> Integer.is_even(10)\n true\n\n iex> Integer.is_even(5)\n false\n\n iex> Integer.is_even(-10)\n true\n\n iex> Integer.is_even(0)\n true\n\n \"\"\"\n defmacro is_even(integer) do\n quote do: (unquote(integer) &&& 1) == 0\n end\n\n @doc \"\"\"\n Computes the modulo remainder of an integer division.\n\n `Integer.mod\/2` uses floored division, which means that\n the result will always have the sign of the `divisor`.\n\n Raises an `ArithmeticError` exception if one of the arguments is not an\n integer, or when the `divisor` is `0`.\n\n ## Examples\n\n iex> Integer.mod(5, 2)\n 1\n iex> Integer.mod(6, -4)\n -2\n\n \"\"\"\n @spec mod(integer, neg_integer | pos_integer) :: integer\n def mod(dividend, divisor) do\n remainder = rem(dividend, divisor)\n if remainder * divisor < 0 do\n remainder + divisor\n else\n remainder\n end\n end\n\n @doc \"\"\"\n Performs a floored integer division.\n\n Raises an `ArithmeticError` exception if one of the arguments is not an\n integer, or when the `divisor` is `0`.\n\n `Integer.floor_div\/2` performs *floored* integer division. This means that\n the result is always rounded towards negative infinity.\n\n If you want to perform truncated integer division (rounding towards zero),\n use `Kernel.div\/2` instead.\n\n ## Examples\n\n iex> Integer.floor_div(5, 2)\n 2\n iex> Integer.floor_div(6, -4)\n -2\n iex> Integer.floor_div(-99, 2)\n -50\n\n \"\"\"\n @spec floor_div(integer, neg_integer | pos_integer) :: integer\n def floor_div(dividend, divisor) do\n if (dividend * divisor < 0) and rem(dividend, divisor) != 0 do\n div(dividend, divisor) - 1\n else\n div(dividend, divisor)\n end\n end\n\n @doc \"\"\"\n Returns the ordered digits for the given `integer`.\n\n An optional `base` value may be provided representing the radix for the returned\n digits. This one must be an integer >= 2.\n\n ## Examples\n\n iex> Integer.digits(123)\n [1, 2, 3]\n\n iex> Integer.digits(170, 2)\n [1, 0, 1, 0, 1, 0, 1, 0]\n\n iex> Integer.digits(-170, 2)\n [-1, 0, -1, 0, -1, 0, -1, 0]\n\n \"\"\"\n @spec digits(integer, pos_integer) :: [integer, ...]\n def digits(integer, base \\\\ 10)\n when is_integer(integer) and is_integer(base) and base >= 2 do\n do_digits(integer, base, [])\n end\n\n defp do_digits(digit, base, []) when abs(digit) < base,\n do: [digit]\n defp do_digits(digit, base, []) when digit == -base,\n do: [-1, 0]\n defp do_digits(base, base, []),\n do: [1, 0]\n defp do_digits(0, _base, acc),\n do: acc\n defp do_digits(integer, base, acc),\n do: do_digits(div(integer, base), base, [rem(integer, base) | acc])\n\n @doc \"\"\"\n Returns the integer represented by the ordered `digits`.\n\n An optional `base` value may be provided representing the radix for the `digits`.\n This one can be an integer >= 2.\n\n ## Examples\n\n iex> Integer.undigits([1, 2, 3])\n 123\n\n iex> Integer.undigits([1, 4], 16)\n 20\n\n iex> Integer.undigits([])\n 0\n\n \"\"\"\n @spec undigits([integer], integer) :: integer\n def undigits(digits, base \\\\ 10) when is_list(digits) and is_integer(base) and base >= 2 do\n do_undigits(digits, base, 0)\n end\n\n defp do_undigits([], _base, 0),\n do: 0\n defp do_undigits([digit], base, 0) when is_integer(digit) and digit < base,\n do: digit\n defp do_undigits([1, 0], base, 0),\n do: base\n defp do_undigits([0 | tail], base, 0),\n do: do_undigits(tail, base, 0)\n\n defp do_undigits([], _base, acc),\n do: acc\n defp do_undigits([digit | _], base, _) when is_integer(digit) and digit >= base,\n do: raise ArgumentError, \"invalid digit #{digit} in base #{base}\"\n defp do_undigits([digit | tail], base, acc) when is_integer(digit),\n do: do_undigits(tail, base, acc * base + digit)\n\n @doc \"\"\"\n Parses a text representation of an integer.\n\n An optional `base` to the corresponding integer can be provided.\n If `base` is not given, 10 will be used.\n\n If successful, returns a tuple in the form of `{integer, remainder_of_binary}`.\n Otherwise `:error`.\n\n Raises an error if `base` is less than 2 or more than 36.\n\n If you want to convert a string-formatted integer directly to a integer,\n `String.to_integer\/1` or `String.to_integer\/2` can be used instead.\n\n ## Examples\n\n iex> Integer.parse(\"34\")\n {34, \"\"}\n\n iex> Integer.parse(\"34.5\")\n {34, \".5\"}\n\n iex> Integer.parse(\"three\")\n :error\n\n iex> Integer.parse(\"34\", 10)\n {34, \"\"}\n\n iex> Integer.parse(\"f4\", 16)\n {244, \"\"}\n\n iex> Integer.parse(\"Awww++\", 36)\n {509216, \"++\"}\n\n iex> Integer.parse(\"fab\", 10)\n :error\n\n iex> Integer.parse(\"a2\", 38)\n ** (ArgumentError) invalid base 38\n\n \"\"\"\n @spec parse(binary, 2..36) :: {integer, binary} | :error\n def parse(binary, base \\\\ 10)\n\n def parse(_binary, base) when not base in 2..36 do\n raise ArgumentError, \"invalid base #{inspect base}\"\n end\n\n def parse(binary, base) do\n case count_digits(binary, base) do\n 0 ->\n :error\n count ->\n {digits, rem} = :erlang.split_binary(binary, count)\n {:erlang.binary_to_integer(digits, base), rem}\n end\n end\n\n defp count_digits(<<sign, rest::binary>>, base) when sign in '+-' do\n case count_digits_nosign(rest, base, 1) do\n 1 -> 0\n count -> count\n end\n end\n\n defp count_digits(<<rest::binary>>, base) do\n count_digits_nosign(rest, base, 0)\n end\n\n digits = [{?0..?9, -?0}, {?A..?Z, 10 - ?A}, {?a..?z, 10 - ?a}]\n\n for {chars, diff} <- digits, char <- chars do\n digit = char + diff\n\n defp count_digits_nosign(<<unquote(char), rest::binary>>, base, count)\n when base > unquote(digit) do\n count_digits_nosign(rest, base, count + 1)\n end\n end\n\n defp count_digits_nosign(<<_::binary>>, _, count), do: count\n\n @doc \"\"\"\n Returns a binary which corresponds to the text representation\n of `integer`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Integer.to_string(123)\n \"123\"\n\n iex> Integer.to_string(+456)\n \"456\"\n\n iex> Integer.to_string(-789)\n \"-789\"\n\n iex> Integer.to_string(0123)\n \"123\"\n\n \"\"\"\n @spec to_string(integer) :: String.t\n def to_string(integer) do\n :erlang.integer_to_binary(integer)\n end\n\n @doc \"\"\"\n Returns a binary which corresponds to the text representation\n of `integer` in the given `base`.\n\n `base` can be an integer between 2 and 36.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Integer.to_string(100, 16)\n \"64\"\n\n iex> Integer.to_string(-100, 16)\n \"-64\"\n\n iex> Integer.to_string(882681651, 36)\n \"ELIXIR\"\n\n \"\"\"\n @spec to_string(integer, 2..36) :: String.t\n def to_string(integer, base) do\n :erlang.integer_to_binary(integer, base)\n end\n\n @doc \"\"\"\n Returns a charlist which corresponds to the text representation of the given `integer`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Integer.to_charlist(123)\n '123'\n\n iex> Integer.to_charlist(+456)\n '456'\n\n iex> Integer.to_charlist(-789)\n '-789'\n\n iex> Integer.to_charlist(0123)\n '123'\n\n \"\"\"\n @spec to_charlist(integer) :: charlist\n def to_charlist(integer) do\n :erlang.integer_to_list(integer)\n end\n\n @doc \"\"\"\n Returns a charlist which corresponds to the text representation of `integer` in the given `base`.\n\n `base` can be an integer between 2 and 36.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Integer.to_charlist(100, 16)\n '64'\n\n iex> Integer.to_charlist(-100, 16)\n '-64'\n\n iex> Integer.to_charlist(882681651, 36)\n 'ELIXIR'\n\n \"\"\"\n @spec to_charlist(integer, 2..36) :: charlist\n def to_charlist(integer, base) do\n :erlang.integer_to_list(integer, base)\n end\n\n @doc \"\"\"\n Returns the greatest common divisor of the two given numbers.\n\n The greatest common divisor (GCD) of `int1` and `int2` is the largest positive\n integer that divides both `int1` and `int2` without leaving a remainder.\n\n By convention, `gcd(0, 0)` returns `0`.\n\n ## Examples\n\n iex> Integer.gcd(2, 3)\n 1\n\n iex> Integer.gcd(8, 12)\n 4\n\n iex> Integer.gcd(8, -12)\n 4\n\n iex> Integer.gcd(10, 0)\n 10\n\n iex> Integer.gcd(7, 7)\n 7\n\n iex> Integer.gcd(0, 0)\n 0\n\n \"\"\"\n @spec gcd(0, 0) :: 0\n @spec gcd(integer, integer) :: pos_integer\n def gcd(int1, int2) when is_integer(int1) and is_integer(int2) do\n gcd_positive(abs(int1), abs(int2))\n end\n\n defp gcd_positive(0, int2), do: int2\n defp gcd_positive(int1, 0), do: int1\n defp gcd_positive(int1, int2), do: gcd_positive(int2, rem(int1, int2))\n\n # TODO: Remove by 2.0\n # (hard-deprecated in elixir_dispatch)\n @doc false\n @spec to_char_list(integer) :: charlist\n def to_char_list(integer), do: Integer.to_charlist(integer)\n\n # TODO: Remove by 2.0\n # (hard-deprecated in elixir_dispatch)\n @doc false\n @spec to_char_list(integer, 2..36) :: charlist\n def to_char_list(integer, base), do: Integer.to_charlist(integer, base)\nend\n","avg_line_length":22.7283372365,"max_line_length":99,"alphanum_fraction":0.6251416795}
{"size":1856,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This file is auto generated by the elixir code generator program.\n# Do not edit this file manually.\n\ndefmodule GoogleApi.StreetViewPublish.V1.Model.Level do\n @moduledoc \"\"\"\n Level information containing level number and its corresponding name.\n\n ## Attributes\n\n * `name` (*type:* `String.t`, *default:* `nil`) - Required. A name assigned to this Level, restricted to 3 characters.\n Consider how the elevator buttons would be labeled for this level if there\n was an elevator.\n * `number` (*type:* `float()`, *default:* `nil`) - Floor number, used for ordering. 0 indicates the ground level, 1 indicates\n the first level above ground level, -1 indicates the first level under\n ground level. Non-integer values are OK.\n \"\"\"\n\n use GoogleApi.Gax.ModelBase\n\n @type t :: %__MODULE__{\n :name => String.t(),\n :number => float()\n }\n\n field(:name)\n field(:number)\nend\n\ndefimpl Poison.Decoder, for: GoogleApi.StreetViewPublish.V1.Model.Level do\n def decode(value, options) do\n GoogleApi.StreetViewPublish.V1.Model.Level.decode(value, options)\n end\nend\n\ndefimpl Poison.Encoder, for: GoogleApi.StreetViewPublish.V1.Model.Level do\n def encode(value, options) do\n GoogleApi.Gax.ModelBase.encode(value, options)\n end\nend\n","avg_line_length":34.3703703704,"max_line_length":129,"alphanum_fraction":0.7225215517}
{"size":411,"ext":"ex","lang":"Elixir","max_stars_count":1.0,"content":"defmodule FreeFallWeb.Live.Components.Shape do\n use Surface.LiveComponent\n alias FreeFallWeb.Live.Components.Point\n\n prop(points, :list, required: true)\n\n def update(assigns, socket) do\n {:ok, assign(socket, points: assigns.points)}\n end\n\n def render(assigns) do\n ~F\"\"\"\n {#for {x, y, color} <- @points}\n <Point x={x} y={y} color={color} id={Ecto.UUID.generate} \/>\n {\/for}\n \"\"\"\n end\nend\n","avg_line_length":21.6315789474,"max_line_length":63,"alphanum_fraction":0.6472019465}
{"size":8000,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule Draft6.TypeTest do\n use ExUnit.Case, async: true\n\n import Xema, only: [valid?: 2]\n\n describe \"integer type matches integers\" do\n setup do\n %{schema: Xema.new(:integer)}\n end\n\n test \"an integer is an integer\", %{schema: schema} do\n data = 1\n assert valid?(schema, data)\n end\n\n test \"a float is not an integer\", %{schema: schema} do\n data = 1.1\n refute valid?(schema, data)\n end\n\n test \"a string is not an integer\", %{schema: schema} do\n data = \"foo\"\n refute valid?(schema, data)\n end\n\n test \"a string is still not an integer, even if it looks like one\", %{\n schema: schema\n } do\n data = \"1\"\n refute valid?(schema, data)\n end\n\n test \"an object is not an integer\", %{schema: schema} do\n data = %{}\n refute valid?(schema, data)\n end\n\n test \"an array is not an integer\", %{schema: schema} do\n data = []\n refute valid?(schema, data)\n end\n\n test \"a boolean is not an integer\", %{schema: schema} do\n data = true\n refute valid?(schema, data)\n end\n\n test \"null is not an integer\", %{schema: schema} do\n data = nil\n refute valid?(schema, data)\n end\n end\n\n describe \"number type matches numbers\" do\n setup do\n %{schema: Xema.new(:number)}\n end\n\n test \"an integer is a number\", %{schema: schema} do\n data = 1\n assert valid?(schema, data)\n end\n\n test \"a float is a number\", %{schema: schema} do\n data = 1.1\n assert valid?(schema, data)\n end\n\n test \"a string is not a number\", %{schema: schema} do\n data = \"foo\"\n refute valid?(schema, data)\n end\n\n test \"a string is still not a number, even if it looks like one\", %{\n schema: schema\n } do\n data = \"1\"\n refute valid?(schema, data)\n end\n\n test \"an object is not a number\", %{schema: schema} do\n data = %{}\n refute valid?(schema, data)\n end\n\n test \"an array is not a number\", %{schema: schema} do\n data = []\n refute valid?(schema, data)\n end\n\n test \"a boolean is not a number\", %{schema: schema} do\n data = true\n refute valid?(schema, data)\n end\n\n test \"null is not a number\", %{schema: schema} do\n data = nil\n refute valid?(schema, data)\n end\n end\n\n describe \"string type matches strings\" do\n setup do\n %{schema: Xema.new(:string)}\n end\n\n test \"1 is not a string\", %{schema: schema} do\n data = 1\n refute valid?(schema, data)\n end\n\n test \"a float is not a string\", %{schema: schema} do\n data = 1.1\n refute valid?(schema, data)\n end\n\n test \"a string is a string\", %{schema: schema} do\n data = \"foo\"\n assert valid?(schema, data)\n end\n\n test \"a string is still a string, even if it looks like a number\", %{\n schema: schema\n } do\n data = \"1\"\n assert valid?(schema, data)\n end\n\n test \"an object is not a string\", %{schema: schema} do\n data = %{}\n refute valid?(schema, data)\n end\n\n test \"an array is not a string\", %{schema: schema} do\n data = []\n refute valid?(schema, data)\n end\n\n test \"a boolean is not a string\", %{schema: schema} do\n data = true\n refute valid?(schema, data)\n end\n\n test \"null is not a string\", %{schema: schema} do\n data = nil\n refute valid?(schema, data)\n end\n end\n\n describe \"object type matches objects\" do\n setup do\n %{schema: Xema.new(:map)}\n end\n\n test \"an integer is not an object\", %{schema: schema} do\n data = 1\n refute valid?(schema, data)\n end\n\n test \"a float is not an object\", %{schema: schema} do\n data = 1.1\n refute valid?(schema, data)\n end\n\n test \"a string is not an object\", %{schema: schema} do\n data = \"foo\"\n refute valid?(schema, data)\n end\n\n test \"an object is an object\", %{schema: schema} do\n data = %{}\n assert valid?(schema, data)\n end\n\n test \"an array is not an object\", %{schema: schema} do\n data = []\n refute valid?(schema, data)\n end\n\n test \"a boolean is not an object\", %{schema: schema} do\n data = true\n refute valid?(schema, data)\n end\n\n test \"null is not an object\", %{schema: schema} do\n data = nil\n refute valid?(schema, data)\n end\n end\n\n describe \"array type matches arrays\" do\n setup do\n %{schema: Xema.new(:list)}\n end\n\n test \"an integer is not an array\", %{schema: schema} do\n data = 1\n refute valid?(schema, data)\n end\n\n test \"a float is not an array\", %{schema: schema} do\n data = 1.1\n refute valid?(schema, data)\n end\n\n test \"a string is not an array\", %{schema: schema} do\n data = \"foo\"\n refute valid?(schema, data)\n end\n\n test \"an object is not an array\", %{schema: schema} do\n data = %{}\n refute valid?(schema, data)\n end\n\n test \"an array is an array\", %{schema: schema} do\n data = []\n assert valid?(schema, data)\n end\n\n test \"a boolean is not an array\", %{schema: schema} do\n data = true\n refute valid?(schema, data)\n end\n\n test \"null is not an array\", %{schema: schema} do\n data = nil\n refute valid?(schema, data)\n end\n end\n\n describe \"boolean type matches booleans\" do\n setup do\n %{schema: Xema.new(:boolean)}\n end\n\n test \"an integer is not a boolean\", %{schema: schema} do\n data = 1\n refute valid?(schema, data)\n end\n\n test \"a float is not a boolean\", %{schema: schema} do\n data = 1.1\n refute valid?(schema, data)\n end\n\n test \"a string is not a boolean\", %{schema: schema} do\n data = \"foo\"\n refute valid?(schema, data)\n end\n\n test \"an object is not a boolean\", %{schema: schema} do\n data = %{}\n refute valid?(schema, data)\n end\n\n test \"an array is not a boolean\", %{schema: schema} do\n data = []\n refute valid?(schema, data)\n end\n\n test \"a boolean is a boolean\", %{schema: schema} do\n data = true\n assert valid?(schema, data)\n end\n\n test \"null is not a boolean\", %{schema: schema} do\n data = nil\n refute valid?(schema, data)\n end\n end\n\n describe \"null type matches only the null object\" do\n setup do\n %{schema: Xema.new(nil)}\n end\n\n test \"an integer is not null\", %{schema: schema} do\n data = 1\n refute valid?(schema, data)\n end\n\n test \"a float is not null\", %{schema: schema} do\n data = 1.1\n refute valid?(schema, data)\n end\n\n test \"a string is not null\", %{schema: schema} do\n data = \"foo\"\n refute valid?(schema, data)\n end\n\n test \"an object is not null\", %{schema: schema} do\n data = %{}\n refute valid?(schema, data)\n end\n\n test \"an array is not null\", %{schema: schema} do\n data = []\n refute valid?(schema, data)\n end\n\n test \"a boolean is not null\", %{schema: schema} do\n data = true\n refute valid?(schema, data)\n end\n\n test \"null is null\", %{schema: schema} do\n data = nil\n assert valid?(schema, data)\n end\n end\n\n describe \"multiple types can be specified in an array\" do\n setup do\n %{schema: Xema.new([:integer, :string])}\n end\n\n test \"an integer is valid\", %{schema: schema} do\n data = 1\n assert valid?(schema, data)\n end\n\n test \"a string is valid\", %{schema: schema} do\n data = \"foo\"\n assert valid?(schema, data)\n end\n\n test \"a float is invalid\", %{schema: schema} do\n data = 1.1\n refute valid?(schema, data)\n end\n\n test \"an object is invalid\", %{schema: schema} do\n data = %{}\n refute valid?(schema, data)\n end\n\n test \"an array is invalid\", %{schema: schema} do\n data = []\n refute valid?(schema, data)\n end\n\n test \"a boolean is invalid\", %{schema: schema} do\n data = true\n refute valid?(schema, data)\n end\n\n test \"null is invalid\", %{schema: schema} do\n data = nil\n refute valid?(schema, data)\n end\n end\nend\n","avg_line_length":22.5352112676,"max_line_length":74,"alphanum_fraction":0.573875}
{"size":277,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule PhoenixApiToolkit.Ecto.GenericQueriesTest do\n use ExUnit.Case, async: true\n\n import PhoenixApiToolkit.Ecto.GenericQueries\n require Ecto.Query\n\n def base_query(), do: Ecto.Query.from(user in \"users\", as: :user)\n\n doctest PhoenixApiToolkit.Ecto.GenericQueries\nend\n","avg_line_length":25.1818181818,"max_line_length":67,"alphanum_fraction":0.7906137184}
{"size":70,"ext":"exs","lang":"Elixir","max_stars_count":518.0,"content":"# Used by \"mix format\"\n[\n inputs: [\"mix.exs\", \"lib\/**\/*.{ex,exs}\"]\n]\n","avg_line_length":14.0,"max_line_length":42,"alphanum_fraction":0.5}
{"size":1464,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"ExUnit.configure(exclude: [pending: true], capture_log: true)\nExUnit.start()\n\ndefmodule ThriftTestHelpers do\n\n defmacro __using__(_) do\n quote do\n require ThriftTestHelpers\n import ThriftTestHelpers\n end\n end\n\n def build_thrift_file(base_dir, {file_name, contents}) do\n file_relative_path = Atom.to_string(file_name)\n file_path = Path.join(base_dir, file_relative_path)\n\n file_path\n |> Path.dirname\n |> File.mkdir_p!\n\n File.write!(file_path, contents)\n file_relative_path\n end\n\n def tmp_dir do\n tmp_path = Path.join(System.tmp_dir!, Integer.to_string(System.unique_integer))\n\n File.mkdir(tmp_path)\n tmp_path\n end\n\n def parse(_root_dir, nil) do\n nil\n end\n\n def parse(file_path) do\n alias Thrift.Parser\n Parser.parse_file(file_path)\n end\n\n @spec with_thrift_files(Keyword.t, String.t) :: nil\n defmacro with_thrift_files(opts, do: block) do\n {var_name, opts_1} = Keyword.pop(opts, :as, :file_group)\n {parsed_file, specs} = Keyword.pop(opts_1, :parse, nil)\n\n thrift_var = Macro.var(var_name, nil)\n\n quote location: :keep do\n root_dir = ThriftTestHelpers.tmp_dir\n full_path = Path.join(root_dir, unquote(parsed_file))\n\n files = Enum.map(unquote(specs), &ThriftTestHelpers.build_thrift_file(root_dir, &1))\n unquote(thrift_var) = ThriftTestHelpers.parse(full_path)\n try do\n unquote(block)\n after\n File.rm_rf!(root_dir)\n end\n end\n end\n\nend\n","avg_line_length":23.2380952381,"max_line_length":90,"alphanum_fraction":0.6953551913}
{"size":5604,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTE: This file is auto generated by the elixir code generator program.\n# Do not edit this file manually.\n\ndefmodule GoogleApi.CloudAsset.V1.Model.Asset do\n @moduledoc \"\"\"\n An asset in Google Cloud. An asset can be any resource in the Google Cloud\n [resource\n hierarchy](https:\/\/cloud.google.com\/resource-manager\/docs\/cloud-platform-resource-hierarchy),\n a resource outside the Google Cloud resource hierarchy (such as Google\n Kubernetes Engine clusters and objects), or a Cloud IAM policy.\n\n ## Attributes\n\n * `accessLevel` (*type:* `GoogleApi.CloudAsset.V1.Model.GoogleIdentityAccesscontextmanagerV1AccessLevel.t`, *default:* `nil`) - \n * `accessPolicy` (*type:* `GoogleApi.CloudAsset.V1.Model.GoogleIdentityAccesscontextmanagerV1AccessPolicy.t`, *default:* `nil`) - \n * `ancestors` (*type:* `list(String.t)`, *default:* `nil`) - The ancestry path of an asset in Google Cloud [resource\n hierarchy](https:\/\/cloud.google.com\/resource-manager\/docs\/cloud-platform-resource-hierarchy),\n represented as a list of relative resource names. An ancestry path starts\n with the closest ancestor in the hierarchy and ends at root. If the asset\n is a project, folder, or organization, the ancestry path starts from the\n asset itself.\n\n For example: `[\"projects\/123456789\", \"folders\/5432\", \"organizations\/1234\"]`\n * `assetType` (*type:* `String.t`, *default:* `nil`) - The type of the asset. For example: \"compute.googleapis.com\/Disk\"\n\n See [Supported asset\n types](https:\/\/cloud.google.com\/asset-inventory\/docs\/supported-asset-types)\n for more information.\n * `iamPolicy` (*type:* `GoogleApi.CloudAsset.V1.Model.Policy.t`, *default:* `nil`) - A representation of the Cloud IAM policy set on a Google Cloud resource.\n There can be a maximum of one Cloud IAM policy set on any given resource.\n In addition, Cloud IAM policies inherit their granted access scope from any\n policies set on parent resources in the resource hierarchy. Therefore, the\n effectively policy is the union of both the policy set on this resource\n and each policy set on all of the resource's ancestry resource levels in\n the hierarchy. See\n [this topic](https:\/\/cloud.google.com\/iam\/docs\/policies#inheritance) for\n more information.\n * `name` (*type:* `String.t`, *default:* `nil`) - The full name of the asset. For example:\n \"\/\/compute.googleapis.com\/projects\/my_project_123\/zones\/zone1\/instances\/instance1\"\n\n See [Resource\n names](https:\/\/cloud.google.com\/apis\/design\/resource_names#full_resource_name)\n for more information.\n * `orgPolicy` (*type:* `list(GoogleApi.CloudAsset.V1.Model.GoogleCloudOrgpolicyV1Policy.t)`, *default:* `nil`) - A representation of an [organization\n policy](https:\/\/cloud.google.com\/resource-manager\/docs\/organization-policy\/overview#organization_policy).\n There can be more than one organization policy with different constraints\n set on a given resource.\n * `resource` (*type:* `GoogleApi.CloudAsset.V1.Model.Resource.t`, *default:* `nil`) - A representation of the resource.\n * `servicePerimeter` (*type:* `GoogleApi.CloudAsset.V1.Model.GoogleIdentityAccesscontextmanagerV1ServicePerimeter.t`, *default:* `nil`) - \n \"\"\"\n\n use GoogleApi.Gax.ModelBase\n\n @type t :: %__MODULE__{\n :accessLevel =>\n GoogleApi.CloudAsset.V1.Model.GoogleIdentityAccesscontextmanagerV1AccessLevel.t(),\n :accessPolicy =>\n GoogleApi.CloudAsset.V1.Model.GoogleIdentityAccesscontextmanagerV1AccessPolicy.t(),\n :ancestors => list(String.t()),\n :assetType => String.t(),\n :iamPolicy => GoogleApi.CloudAsset.V1.Model.Policy.t(),\n :name => String.t(),\n :orgPolicy => list(GoogleApi.CloudAsset.V1.Model.GoogleCloudOrgpolicyV1Policy.t()),\n :resource => GoogleApi.CloudAsset.V1.Model.Resource.t(),\n :servicePerimeter =>\n GoogleApi.CloudAsset.V1.Model.GoogleIdentityAccesscontextmanagerV1ServicePerimeter.t()\n }\n\n field(:accessLevel,\n as: GoogleApi.CloudAsset.V1.Model.GoogleIdentityAccesscontextmanagerV1AccessLevel\n )\n\n field(:accessPolicy,\n as: GoogleApi.CloudAsset.V1.Model.GoogleIdentityAccesscontextmanagerV1AccessPolicy\n )\n\n field(:ancestors, type: :list)\n field(:assetType)\n field(:iamPolicy, as: GoogleApi.CloudAsset.V1.Model.Policy)\n field(:name)\n field(:orgPolicy, as: GoogleApi.CloudAsset.V1.Model.GoogleCloudOrgpolicyV1Policy, type: :list)\n field(:resource, as: GoogleApi.CloudAsset.V1.Model.Resource)\n\n field(:servicePerimeter,\n as: GoogleApi.CloudAsset.V1.Model.GoogleIdentityAccesscontextmanagerV1ServicePerimeter\n )\nend\n\ndefimpl Poison.Decoder, for: GoogleApi.CloudAsset.V1.Model.Asset do\n def decode(value, options) do\n GoogleApi.CloudAsset.V1.Model.Asset.decode(value, options)\n end\nend\n\ndefimpl Poison.Encoder, for: GoogleApi.CloudAsset.V1.Model.Asset do\n def encode(value, options) do\n GoogleApi.Gax.ModelBase.encode(value, options)\n end\nend\n","avg_line_length":49.1578947368,"max_line_length":161,"alphanum_fraction":0.7293004996}
{"size":3084,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule ExOkex.Futures.Private do\n @moduledoc \"\"\"\n Futures account client.\n\n [API docs](https:\/\/www.okex.com\/docs\/en\/#futures-README)\n \"\"\"\n\n import ExOkex.Api.Private\n\n @type params :: map\n @type config :: map | nil\n @type response :: ExOkex.Api.response()\n\n @prefix \"\/api\/futures\/v3\"\n\n @doc \"\"\"\n Place a new order.\n\n ## Examples\n\n iex> ExOkex.Futures.create_order(%{\n client_oid: \"y12233456\",\n order_type: \"1\",\n instrument_id: \"BTC-USD-180213\",\n type: \"1\",\n price: \"432.11\",\n size: \"2\",\n match_price: \"0\",\n \"leverage\":\"10\"\n })\n\n {:ok, %{{\n \"client_oid\" => \"y12233456\",\n \"error_code\" => \"0\",\n \"error_message\" => \"\",\n \"order_id\" => \"3422539729641472\",\n \"result\" => true\n }}}\n \"\"\"\n @spec create_order(params, config) :: response\n def create_order(params, config \\\\ nil) do\n post(\"#{@prefix}\/order\", params, config)\n end\n\n @doc \"\"\"\n Place multiple orders for specific trading pairs (up to 4 trading pairs, maximum 4 orders each)\n\n https:\/\/www.okex.com\/docs\/en\/#futures-batch\n\n ## Examples\n\n iex> ExOkex.Futures.create_bulk_orders([\n %{\"instrument_id\":\"BTC-USD-180213\",\n \"type\":\"1\",\n \"price\":\"432.11\",\n \"size\":\"2\",\n \"match_price\":\"0\",\n \"leverage\":\"10\" },\n ])\n\n # TODO: Add response sample\n\n \"\"\"\n @spec create_bulk_orders(params, config) :: response\n def create_bulk_orders(params, config \\\\ nil) do\n post(\"#{@prefix}\/orders\", params, config)\n end\n\n defdelegate create_batch_orders(params, config \\\\ nil), to: __MODULE__, as: :create_bulk_orders\n\n @doc \"\"\"\n Cancelling an unfilled order.\n\n https:\/\/www.okex.com\/docs\/en\/#futures-repeal\n\n ## Example\n\n iex> ExOkex.Futures.cancel_orders(\"BTC-USD-180309\", [1600593327162368,1600593327162369])\n\n # TODO: Add response\n \"\"\"\n def cancel_orders(instrument_id, order_ids \\\\ [], params \\\\ %{}, config \\\\ nil) do\n new_params = Map.merge(params, %{order_ids: order_ids})\n post(\"#{@prefix}\/cancel_batch_orders\/#{instrument_id}\", new_params, config)\n end\n\n @doc \"\"\"\n Get the futures account info of all token.\n\n https:\/\/www.okex.com\/docs\/en\/#futures-singleness\n\n ## Examples\n\n iex(3)> ExOkex.Futures.list_accounts()\n\n # TODO: Add Response\n \"\"\"\n def list_accounts(config \\\\ nil) do\n get(\"#{@prefix}\/accounts\", %{}, config)\n end\n\n @doc \"\"\"\n Get the information of holding positions of a contract.\n\n https:\/\/www.okex.com\/docs\/en\/#futures-hold_information\n\n ## Examples\n\n iex(3)> ExOkex.Futures.get_position(\"BTC-USD-190329\")\n\n \"\"\"\n def get_position(instrument_id, config \\\\ nil) do\n get(\"#{@prefix}\/#{instrument_id}\/position\", %{}, config)\n end\n\n def get_positions(config \\\\ nil) do\n get(\"#{@prefix}\/position\", %{}, config)\n end\n\n @doc \"\"\"\n Get the leverage of the futures account.\n\n https:\/\/www.okex.com\/docs\/en\/#futures-huo-qu-he-yue-bi-zhong-gang-gan-bei-shu\n\n ## Examples\n\n iex(3)> ExOkex.Futures.Private.get_futures_leverage(\"BTC\")\n\n \"\"\"\n def get_futures_leverage(currency, config \\\\ nil) do\n get(\"#{@prefix}\/accounts\/#{currency}\/leverage\", %{}, config)\n end\nend\n","avg_line_length":23.0149253731,"max_line_length":97,"alphanum_fraction":0.6361867704}
{"size":4013,"ext":"ex","lang":"Elixir","max_stars_count":60.0,"content":"defmodule UcxChat.SharedView do\n use UcxChat.Utils\n alias UcxChat.{User, Repo, Permission}\n require Logger\n\n def markdown(text), do: text\n\n def get_all_users do\n Repo.all User\n end\n\n def get_status(user) do\n UcxChat.PresenceAgent.get(user.id)\n end\n\n def get_room_icon(chatd), do: chatd.room_map[chatd.channel.id][:room_icon]\n def get_room_status(chatd) do\n # Logger.error \"get room status room_map: #{inspect chatd.room_map[chatd.channel.id]}\"\n chatd.room_map[chatd.channel.id][:user_status]\n end\n def get_room_display_name(chatd), do: chatd.room_map[chatd.channel.id][:display_name]\n\n def hidden_on_nil(test, prefix \\\\ \"\")\n def hidden_on_nil(_test, \"\"), do: \" hidden\"\n def hidden_on_nil(test, prefix) when is_falsy(test), do: \" #{prefix}hidden\"\n def hidden_on_nil(_, _), do: \"\"\n\n def map_field(map, field, default \\\\ \"\")\n def map_field(%{} = map, field, default), do: Map.get(map, field, default)\n def map_field(_, _, default), do: default\n\n def get_ftab_open_class(nil), do: \"\"\n def get_ftab_open_class(_), do: \"opened\"\n\n def get_room_notification_sounds do\n [None: \"none\", \"Use system preferences (Default)\": \"system_default\", \"Door (Default)\": \"door\", Beep: \"beep\", Chelle: \"chelle\", Ding: \"ding\",\n Droplet: \"droplet\", Highbell: \"highbell\", Seasons: \"seasons\"]\n end\n def get_message_notification_sounds do\n [None: \"none\", \"Use room and system preferences (Default)\": \"system_default\", \"Chime (Default)\": \"chime\", Beep: \"beep\", Chelle: \"chelle\", Ding: \"ding\",\n Droplet: \"droplet\", Highbell: \"highbell\", Seasons: \"seasons\"]\n end\n\n @regex1 ~r\/^(.*?)(`(.*?)`)(.*?)$\/\n @regex2 ~r\/\\A(```(.*)```)\\z\/Ums\n\n def format_quoted_code(string, _, true), do: string\n def format_quoted_code(string, true, _) do\n do_format_multi_line_quoted_code(string)\n end\n def format_quoted_code(string, _, _) do\n do_format_quoted_code(string, \"\")\n end\n\n def do_format_quoted_code(string, acc \\\\ \"\")\n def do_format_quoted_code(\"\", acc), do: acc\n def do_format_quoted_code(nil, acc), do: acc\n def do_format_quoted_code(string, acc) do\n case Regex.run(@regex1, string) do\n nil -> acc <> string\n [_, head, _, quoted, tail] ->\n acc = acc <> head <> \" \" <> single_quote_code(quoted)\n do_format_quoted_code(tail, acc)\n end\n end\n\n def do_format_multi_line_quoted_code(string) do\n case Regex.run(@regex2, string) do\n nil -> string\n [_, _, quoted] ->\n multi_quote_code quoted\n end\n end\n\n # def multi_quote_code(quoted) do\n # \"\"\"\n # <pre>\n # <code class='code-colors'>\n # #{quoted}\n # <\/code>\n # <\/pre>\n # \"\"\"\n # end\n def multi_quote_code(quoted) do\n \"<pre><code class='code-colors'>#{quoted}<\/code><\/pre>\"\n end\n\n def single_quote_code(quoted) do\n \"\"\"\n <span class=\"copyonly\">`<\/span>\n <span>\n <code class=\"code-colors inline\">#{quoted}<\/code>\n <\/span>\n <span class=\"copyonly\">`<\/span>\n \"\"\"\n end\n\n def get_avatar_img(username, size \\\\ \"40x40\") do\n # Logger.warn \"get_avatar #{inspect msg}\"\n # \"\"\n Phoenix.HTML.Tag.tag :img, src: \"https:\/\/robohash.org\/#{username}.png?set=any&bgset=any&size=#{size}\"\n end\n def get_avatar(msg) do\n # Logger.warn \"get_avatar #{inspect msg}\"\n # \"\"\n # Phoenix.HTML.Tag.tag :img, src: \"https:\/\/robohash.org\/#{msg}.png?size=40x40\"\n \"https:\/\/robohash.org\/#{msg}.png?set=any&bgset=any&size=40x40\"\n end\n def get_large_avatar(username) do\n # Phoenix.HTML.Tag.tag :img, src: \"https:\/\/robohash.org\/#{username}.png?size=350x310\"\n \"https:\/\/robohash.org\/#{username}.png?set=any&bgset=any&size=350x310\"\n end\n\n def has_permission?(user, permission, scope \\\\ nil), do: Permission.has_permission?(user, permission, scope)\n def has_role?(user, role, scope \\\\ nil), do: User.has_role?(user, role, scope)\n\n def user_muted?(%{} = user, channel_id), do: UcxChat.ChannelService.user_muted?(user.id, channel_id)\n\n defmacro gt(text, opts \\\\ []) do\n quote do\n gettext(unquote(text), unquote(opts))\n end\n end\nend\n","avg_line_length":32.104,"max_line_length":155,"alphanum_fraction":0.6551208572}