Elixir Weber Quick start project fails to build

I followed the Weber Quick start, but the command mix deps.get && mix compile --all --force && ./start.sh resulted in the following output: ** (Mix) Could not start application myweber: {:bad_return, {{Myweber, :start, [:normal, []]}, {:EXIT, {:undef, [{Cowboy, :start, 2, []}, {Weber, :start, 2, [file: '/Users/jonas/code/myweber/deps/weber/lib/weber.ex', line: 49]}, {:application_master, :start_it_old, 4, [file: 'application_master.erl', line: 269]}]}}}} Any suggestions on

Does Elixir have a garbage collector?

I've started reading about the Elixir programming language. I understand that: It is Functional It is dynamic but support @spec It is based on Erlang VM My question is: Does it have a sort of GC?

How to Display a single backslash in Elixir string

Can somebody tell me how to add a single backslash in the SQL statement in Elixir iex(1)> sql = "select * from user limit 1 \G;" "select * from user limit 1 G;" iex(2)> sql = "select * from user limit 1 \\G;" "select * from user limit 1 \\G;" I just need '\G' in my sql statement $ elixir -v Elixir 1.1.0-dev In fact, I want to use the mariaex library, but I still cannot make it work defmodule Customer do def main(args) do sql = "SELECT name FROM user limit 3 \\G;"

Step List With Elixir

Can someone please provide a suggestion on how to iterate a list BUT with a batch of x at a time? For example: If the functionality existed: ["1","2","3","4","5","6","7","8","9","10"].step(5)|> IO.puts Would produce in two iterations: 12345 678910 I believe Stream.iterate/2 is the solution but my attempts to do so given an array are not proving profitable.

Elixir Why can't I chain String.replace?

I'm working on a price format function, which takes a float, and represent it properly. ex. 190.5, should be 190,50 This is what i came up with def format_price(price) do price |> to_string |> String.replace ".", "," |> String.replace ~r/,(\d)$/, ",\\1 0" |> String.replace " ", "" end If i run the following. format_price(299.0) # -> 299,0 It looks like it only ran through the first replace. Now if i change this to the following. def format_price(

Elixir Phoenix: using "conn" and "case" in a view

I have some client static jQuery code that I want to replace with server dynamic code that is used on every page of my website and depends on the page that I'm in (the route that was asked). My existing jQuery code (in the template html.eex file) is: if (SOME CONDITION) { $(".page1.firstChild").css({"margin-top": "70px"}); $(".page2.firstChild").css({"margin-top": "70px"}); $(".page3.firstChild").css({"margin-top": "70px"}); $(".page4.firstChild").css({"margi

How to write a list of integers to a file as 16 bit values in Elixir

I have a list of integers with values between [0-65535]. I need to write these to a file as 16 bit integers. How do I do this in Elixir? I have searched, but I am confused about ints and binaries and how to perform the conversion for 16 bit values. I have found how to convert to a 16 bit binary: <<12345 :: size(16)>>

Elixir Making System Calls with Options

I understand that I can do simple things like System.cmd("echo", ["hello"]) but suppose I wanted to do something like run a Ruby process Normally in the shell I could do something like: ruby -e 'puts "hello world" I've tried a bunch of variations of something similar to: System.cmd("ruby", ["-e", "'puts \"hello world\"'"]) without much luck I can call down the the Erlang os module, but that doesn't seem ideal as I need to explicitly split my string into characters and recast it as well as fi

Elixir How to select data from two tables in Ecto

I trying to write Ecto query which will be select data from two tables at the same time. Like Select t1.*,t2.* from table1 t1,table2 t2 where t1.id=1 and t2.id=2 I can't find solution, found only way to write raw SQL and it's looks like not good. Like variant -using preload, but it's spawn additional query. comments_query = from c in Comment, order_by: c.published_at Repo.all from p in Post, preload: [comments: ^comments_query] Thanks for any ideas

Elixir Starting ExIrc supervisor fails

I'm tinkering with ExIrc to make a simple bot, but i can't make it work. I'm getting this Error: ** (Mix) Could not start application streamingutils: TwitchSniper.start(:normal, []) returned an error: shutdown: failed to start child: TwitchSniper.Bot ** (EXIT) an exception was raised: ** (ArgumentError) argument error :erlang.apply([%TwitchSniper.Bot.State{client: nil, handlers: [], host: "irc.chat.twitch.tv", name: "Paul Schoenfelder", nick: "hajtosek", pass: "my pass

Elixir How to raise an exception in render

I have this following exception handler in my controller def call(conn, opts) do try do super(conn, opts) rescue e in Ecto.CastError -> conn |> put_status(:not_found) |> render(ErrorView, "404.html") e in ArgumentError -> conn |> put_status(:not_found) |> render(ErrorView, "404.html") end end Instead of Ecto.CastError to raise a 400 I want it to raise 404. However I can't satisfy my following test condition test "

Elixir pipes invalid syntax

I'm having trouble understanding why this works: 1..1000 |> Stream.map(&(3 * &1)) |> Enum.sum While this doesnt: 1..1000 |> Stream.map (&(3 * &1)) |> Enum.sum The only difference is the space after .map To my understanding, Elixir should not care about white-space in this case. Running the above code in iex yields the following error: warning: you are piping into a function call without parentheses, which may be ambiguous. Please wrap the function you are pipi

Elixir Ecto validate required *change* instead of field

I've got an Ecto Model with a changeset that will change a state property in a model: def next_state_changeset(model, params) do model |> cast(params, ~w(state)) |> validate_required(:state) end However I'd like to reject a changeset if the state submitted is the same as in the model (there is no change in the state) But this code will still return a valid changeset if there is no state submitted, because if it doesn't exists in a changeset it still does in the model. I know I

How to use defdelegate in elixir?

Could somebody provide a simple example for defdelegate. I couldn't find any, making it hard to understand. defmodule Dummy do def hello, do: "hello from dummy" end I get undefined function world/0 for the below: defmodule Other do defdelegate hello, to: Dummy, as: world end I would like to delegate Other.world to Dummy.hello

Elixir How can I convert a map with array values to the list of strings in elegant way?

I have a map (errors of Ecto.Changeset) like that: %{ field_a: ["error 1", "error 2"], field_b: ["something here"] } I want it to be a [ "field_a error 1", "field_a error 2", "field_b something here" ] I tried to implement it with Enum.map(map, fn({ key, errors }) -> # another anonymous function which generates strings end) but got a compilation error since elixir doesn't support nested anonymous functions right now. How can I implement this convertation?

Using drop_while in Elixir?

Elixir's documentation states drop_while(enumerable, fun) Drops items at the beginning of the enumerable while fun returns a truthy value But I am confused with the below output. Does it mean once it gets !truthy everything else is treated as false? iex> Enum.drop_while([0,1,2,3,4,5], fn(x) -> rem(x,2) == 0 end) [1,2,3,4,5] I expected an output of [1,3,5] because iex> Enum.map([0,1,2,3,4,5], fn(x) -> rem(x,2) == 0 end) [true,false,true,false,true,false] I am trying to u

Elixir Ecto query where string field contains other string

I'm building a simple search feature and I want to find all the records that have a string within a string field. Here's what I've attempted. term = "Moby" MyApp.Book |> where([p], String.contains?(p, term)) |> order_by(desc: :inserted_at) This would return the following books: Moby Dick Sandich Moby Lean My Mobyand Example But I get: `String.contains?(p, term)` is not a valid query expression

Elixir Difference between spawn/1 and spawn/3

I believe I have read somewhere that there is a difference between using spawn/1 and spawn/3 when it comes to hot reloading but I can't find any complete info on the subject. So I wonder if there is actually a difference and if there is, then what is it? Some example would be great. Thank you.

Elixir Flatten/merge nested map

Say we have map like: %{"a": %{"b": 2, "c":5}, "d": 1} Is there anything similar to this function(js answer to same question) built in elixr? End result should be: %{"a.b": 4, "a.c":5, "d": 1}

How can I write my own stream functions in Elixir?

I have written a simple Stream.unfold function, which works fine when I call it like this: a = Stream.unfold({1,2,3}, &my_unfold_func) |> Stream.take(5) However, I don't seem able to find a way of implementing a wrapper that would allow me to call my function directly, e.g. like this: a = my_unfold_wrapper() |> Stream.take(5) What I've tried is: def my_unfold_wrapper(), do: Stream.unfold({1,2,3}, &my_unfold_func) When I run this code, I get the error: #Stream<[enum: #

How to write to a file in RAM in elixir?

So if I open a file in RAM memory (see below code 2) with Elixir, how do I write to that file in RAM and then retrieve its contents once the writing is done? The pattern match returns "#Port<0.11114>", which is not the same as a file handle PID apparently as IO.write #Port<0.11114>, "hello" returns an error such as: Code 1 ** (CaseClauseError) no case clause matching: {#Port<0.11114>} (elixir) lib/io.ex:495: IO.write/2 Code 2 File.open("text.txt", [:ram]) # => {:ok, {:fi

Elixir Ecto: Include join schema field in many_to_many query

I have a many_to_many association with an explicit join_schema that references the same model on both ends (kind of like the classic Follower (is a user) <-> Followee (is a user) thing). To stick with the example if I query for the followers of a user I want to include the time when the followed the user. This data obviously is located on the join schema (let's call is Subscription). If would just want the followers I would do it like this: followers = User |> Repo.get!(user_id) |> a

Elixir Phoenix: Interpolate function in string in template

I have a link I want to show in a set of breadcrumbs (using Slime for markup). = link(@project.name, to: project_path(@conn, :show, @project)) This renders fine. But I want to show it in context, with other links. # by concatenation = link("Projects > ", to: project_path(@conn, :index)) <> link(@project.name, to: project_path(@conn, :show, @project)) # or by interpolation #{link("Projects", to: project_path(@conn, :index))} > #{link(@project.name, to: project_path(@conn, :show,

Elixir What's the need for function heads in multiple clauses?

I'm new to Elixir and quite frankly, can't understand why function heads are needed when we have multiple clauses with default values. From the official docs: If a function with default values has multiple clauses, it is required to create a function head (without an actual body) for declaring defaults: defmodule Concat do def join(a, b \\ nil, sep \\ " ") def join(a, b, _sep) when is_nil(b) do a end def join(a, b, sep) do a <> sep <> b end end IO.puts C

Elixir GenStage scaling depending on load

I'm trying to build a following pipeline: [A] -> [B] -> [C] A takes entries from database which have timestamp older than one day. B performs some heavy task using external node. C stores result of computation back to DB. Each B-node can perform more than one task concurrently, and we can set the level of concurrency on node spawn. What I want is to spawn as many B-nodes as needed depending on how many tasks are waiting in DB. Is GenStage a good fit for that task or better to build s

Elixir How to test or serialize struct in Phoenix.Socket.Broadcast payload?

How to automatically serialize ecto struct to json response in channel test? As I can see in documentation The event’s message must be a serializable map, I found in answer and in tutorial that when I use Poison.Encoder in model then any message passed via Transport (as I understand) layer should be encoded. Example model: use PhoenixTrello.Web, :model # ... @derive {Poison.Encoder, only: [:id, :first_name, :last_name, :email]} # ... end broadcast from one of channel functions: broa

Elixir Duplicated modules in phoenix mix release

I'm trying to run the mix release task to create a production phoenix server. I was having an issue with poison so added the workaround from here. However now when I run the release task I get the following error: Errors generating release Duplicated modules: 'Elixir.Poison.Encoder.Any' specified in poison and myappname I tried adding the following line in lib/myappname.ex based on instructions from elixir getting started. But it didn't have any effect. defmodule Myappname do

Elixir & Phoenix - ArgumentError at GET /users/new

I am trying to implement user authentication with the Phoenix web framework on Elixir but stumped by this error. If I run changeset = Blog.User.changeset(%Blog.User{}) inside iex I get the following error: ** (ArgumentError) unknown field "email" for changeset on %Blog.User{__meta__: #Ecto.Schema.Metadata<:built, "users">, email: nil, id: nil, inserted_at: nil, is_admin: false, name: nil, password: nil, password_hash: nil, posts: #Ecto.Association.NotLoaded<association :posts is no

Elixir deployment issues for phoenix app using gatling and distillery to deploy to a VPS

I'm using the below command on my VPS to deploy an app I recently put together. sudo -E mix gatling.deploy kegcopr_api However, the deployment errors out when it tries to start the app as a service. $ mix release --warnings-as-errors --env=prod (/home/deploy/kegcopr_api) ==> Assembling release.. ==> Building release kegcopr_api:0.0.1 using environment prod ==> Including ERTS 8.3 from /home/deploy/.asdf/installs/erlang/19.3/lib/erlang/erts-8.3 ==> Packaging release.. ==> Releas

Elixir Erlang package failing to load

I'm trying to use an Erlang package (this one : https://github.com/komone/qrcode) inside my Phoenix project, so I'm simply trying to get it from my mix file : defp deps do [{:phoenix, "~> 1.3.0-rc"}, {:phoenix_pubsub, "~> 1.0"}, {:phoenix_ecto, "~> 3.2"}, {:postgrex, ">= 0.0.0"}, {:gettext, "~> 0.11"}, {:cowboy, "~> 1.0"}, {:comeonin, "~> 3.0"}, {:uuid, "~> 1.1"}, {:timex, "~> 3.1"}, {:timex_ecto, "~> 3.1"}, {

Elixir Update Map based on another nested Map iteration

Immutability in Elixir is really blowing my mind and makes the languages so confusing to use. I need to iterate a nested map and simple update some counts based on the iteration, but Enum.reduce just makes it difficult for me. Say I have: defmodule Predictor do def past_matches() do [ team1: %{team2: %{f: 0, a: 1}, team3: %{f: 1, a: 3}}, team2: %{team1: %{f: 3, a: 0}, team3: %{f: 2, a: 0}}, team3: %{team1: %{f: 1, a: 0}, team2: %{f: 0, a: 1}},

Understanding folds in Elixir

I was going through the elixir documentation and I came across this code: List.foldl([1, 2, 3, 4], 0, fn(x, acc) -> x - acc end) # 2 I tried for awhile to understand what it is doing but for the life of me I don't understand why this returns 2? If someone can take the time to explain this to me I appreciate that. I totally understand that the second arg is an accumulator. with that being set to 0 shouldn't this return 10?

Generate a running-sum or row-sum in Elixir

Given: data = [[1,2,3, ..., n],[1,2,3, ..., n],[1,2,3, ..., n], ...] # List with N rows of equal length How may we get a row sum: [3,6,9, ..., x] It is not immediately obvious which of the Enum functions to use, or how to hold a running sum using list comprehension

Elixir Ecto after_create callback or similar

Is there any callback in Ecto that runs after database is created, i.e. after ecto.create? I am using Cassandra with Ecto using ecto-cassandra, and I need to change some keyspace options. The best place is to it after create. Although, it is possible to do it in a migration, preferably in the first one, but having an after_create callback makes the intention more clear.

Elixir Create lists of list while creating a map

I wrote Enum.reduce(list, map, fn elem, map -> key=hd(elem) Map.put(map, key, List.wrap(Map.get(map, key)) ++ tl(elem)) end) The list looks like this ['B2', ['B1', 'B2', 'B3']], ['B2', ['A1', 'A2', 'A3']], and the desired result looks like B2 => [['B1', 'B2', 'B3'], ['A1', 'A2', 'A3']] The above code does produce this result but it feels like exceptionally ugly. I feel Enum.into could work for a much nicer variant but it seems I can't get hold of the values meanwhile. I have

Elixir Guardian let the user to get to the controller even when current_user is nil?

If user sends a token which is not expired however that specific user is no longer exist, Guardian still let user to get to the controller. I have added {:ok, nil} in the current_user.ex and it simply kill the connection which I don't think is the correct approach as I need to give something back to the user like an error. I am not sure what should I use there? Here is my router: pipeline :authed_api do plug :accepts, ["json"] plug Guardian.Plug.VerifyHeader, realm: "Bearer" plu

elixir/phoenix ecto how to judge return condition?

Given the code def getbno() do query = from u in GodowentryForAcceptance, select: max(u.bno) Repo.one(query) end I want to judge return condition such as case GodownentryForAcceptanceService.getbno() do empty-> do something notempty -> dosomething end What is judge condition(empty/not empty)?

Elixir How to restart a crashed supervised process after a certain amount of time?

I have a simple GenServer based app that parses a webpage and plays with the data that it got from it. The code looks roughly like this: def start_link do GenServer.start_link(__MODULE__, %{}) end def init(state) do schedule_work(1) {:ok, state} end def handle_info(:work, state) do // Request webpage using HTTPoisson // Parse data using Floki // Use it schedule_work(10 * 60) # Reschedule after 10 minutes {:noreply, state} end defp schedule_work(timeout) do Process.send_aft

Best approach to do auto versioning of an elixir application phoenix

I am doing hot code upgrade using distillery for a phoenix application. I used this to create the version of the application. def project do {result, _exit_code} = System.cmd("git", ["rev-parse", "HEAD"]) git_sha = String.slice(result, 0, 7) [app: :evercam_media, version: "1.0.1-a#{git_sha}", elixir: "~> 1.7", elixirc_paths: elixirc_paths(Mix.env), build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, compilers: [:phoenix] ++ Mix.co

Elixir How to redirect back to current page after delete form request in phoenix framework using scrivener

I am using scrivener_ecto and scrivener_html in phoenix framework. I have a contact list that has 300 contact in it. When I click delete a contact in for page 6, after submit deletion, I redirect to first page of contact list. I want to stay in current page(like page 6) after a deletion. How can I do this? I tried to get params info from delete controller, but it has no page information(query params) I tried IO.inspect conn.query_string but it returns "" here is delete action in person_cont

Elixir How to conditionally reduce a changeset with Enum rather than If statements

I am encrypting a changeset with a bunch of optional fields, but I am currently using a ton of If statements to see if a changeset contains a field before trying to encrypt it. I have a feeling there is an Enum function (like reduce) that would do this in a way that is idiomatically more Elixir, but none of what I have come up with is more performant than a ton of ugly If statements. def encrypt(changeset) do if changeset.changes["address"] do {:ok, encrypted_address} = EncryptedFi

Elixir How do I translate a Where clause subquery into an Ecto join?

I currently have two tables that have a hasMany relationship: customers [hasMany] items Within items there are some belongsTo relationships: providers [belongsTo] items statuses [belongsTo] items types [belongsTo] items My goal is to have an Ecto query that returns a list of customers that have at least one items record with a status_id of 2 AND any other items that this customers record has. I also need to preload items, providers, statuses and a types I have replicated this in SQL as f

Are there some drawbacks by allowing subfolders templates in Elixir Phoenix Framework projects?

By default one can’t use subfolders to render partial templates in Elixir Phoenix framework but it can be changed in the web_app module view definition. That is one of the changes I always make when starting a new Phoenix project. def view do quote do use Phoenix.View, root: "lib/demo_web/templates", namespace: DemoWeb, # for template subfolders usage pattern: "**/*" ..... end end So I was wondering that if it is no

Elixir How to write link tag without Undefined function Error with phx.routes

I'm trying to write link tag to next page xxx_path in phoenix template. <%= link to: xxx_path(@conn, :main, id) do %> <% end %> However I have following error. ** (CompileError) lib/xxx_web/templates/layout/header.html.eex:5: undefined function xxx_path/3 I tell you the phx.routes C:\Works>mix phx.routes xxx_path GET / xxxWeb.XxxController :index xxx_path GET /:id xxxWeb.XxxController :main What is wro

Elixir's use with function name

Recently I've stumbled upon this code defmodule MyAppWeb.PageLive do use MyAppWeb, :live_view It's part of default app generated with Phoenix Live View (mix phx.new --live). It's first time when I see the use construct with a function name as a second argument. I've tried to search the web on some docs about it but couldn't find a proper naming for this. Can you help me understand what happens when this executes? It doesn't call __using__ macro but calls a function instead, and I'm not sure w

Why accessing size of tuple in Elixir is fast?

I've read in many places that finding the size of a tuple in Elixir is really fast because tuples are stored in contiguous memory cells. However, for lists is more expensive to do because one needs to traverse the whole list to know the length of the list. I don't understand how by being in contiguous memory cells, finding out the size of a tuple will be faster. Don't you have to go through each cell too?

  1    2   3   4   5   6  ... 下一页 最后一页 共 21 页