FAQ Database Discussion Community


Erlang: strange output formatting

xml,file,formatting,erlang,output
Windows 7 x64, Erlang-OTP 17. I wrote simple module like this: -module (somequery). -export ([fbquery/2]). fbquery(P1,P2) -> inets:start(), ssl:start(), token = "78a8shd67tyajsndweiu03hr83h19j", Encoded = {"Authorization","Basic " ++ base64:encode_to_string(lists:append([token,":",""]))}, ContentType = "application/xml", Headers = [Encoded, {"Content-Type",ContentType}], Options = [{body_format,binary}], {ok, File}=file:read_file(P1), Res = httpc:request(post, {"https://datapi.com/api/xml4-8", Headers, ContentType, File}, [], Options),...

Integrate aerospike client in erlang environment as global module

erlang,aerospike
I want to integrate the aerospike erlang client to the erlang environment as a global module in Fedora 21. I achieve to make the client nif and module but I have to always copy the files in every project. Now I want to use the aerospike module like the erlang...

:rpc.call fails with global registered node alias

erlang,elixir
I have an Elixir project that globally registers a node using the Erlang global module: :global.register_name(:my_node, self) From another node in the cluster I can get the pid of the registered node using the global alias: :global.whereis_name :my_node However I'm unable to issue an rpc call using the global alias....

What does these compile time warning means?

erlang,.app,chicagoboss
I am newbie to erlang chicagoboss. I have just created a small project in erlang, and now wanted to update CB. Since I am updating only ChicagoBoss to its latest version i.e. 0.8.14. But While compiling/ running ./rebar get-deps getting following warnings. I'm not getting what does it mean? WARN:...

“init terminating in do_boot” is thrown when executing Erlang script

erlang,erlang-shell
Here's my code in 'factorial.erl': -module(factorial). -author("jasonzhu"). %% API -export([fac/1]). fac(0) -> 1; fac(N) -> N * fac(N-1). When interacting this code in prompt, it works fine: 1> c(factorial). {ok,factorial} 2> factorial:fac(20). 2432902008176640000 But if I compile and execute it from command line, some errors occurred. Jasons-MacBook-Pro:src jasonzhu$ erlc factorial.erl...

Find the minimum value in a map

erlang
I have a map organized as follows.Key is a simple term lets say an integer but the value is complex tuple {BB,CC,DD}. What is the best way to find the minimum CC in the map ? So far I have the following -module(test). -author("andre"). %% API -export([init/0]). init() -> TheMap...

Convert bitstring to tuple

binary,erlang
I'm trying to find out how to convert an Erlang bitstring to a tuple, but so far without any luck. What I want is to get from for example <<"{1,2}">> the tuple {1,2}....

erlang processes and message passing architecture

concurrency,process,erlang,messages
The task I have in hand is to read the lines of large file, process them, and return ordered results. My algorithm is: start with master process that will evaluate the workload (written in the first line of the file) spawn worker processes: each worker will read part of the...

How to read and write id3v1 and id3v2 tags in Elixir

erlang,mp4,elixir,id3
I would like to scan music files and read/write metadata using Elixir (this whole project is about learning Elixir - so please don't tell me to use Python!). As I understand it, I have two choices: call a system utility or (as no libraries exist in Erlang or Elixir that...

Erlang pass-by-reference nuances

erlang,pass-by-reference
9> A = lists:seq(1,10). [1,2,3,4,5,6,7,8,9,10] 13> Fn = fun (L) -> [0|L] end. #Fun<erl_eval.6.90072148> 14> Fn(A). [0,1,2,3,4,5,6,7,8,9,10] 15> A. [1,2,3,4,5,6,7,8,9,10] If erlang internally passes by reference (see this), why does the value of A not reflect the change? What fundamental am I missing about passing-by-reference or erlang?...

how to reload all otp code when developing an otp application?

erlang,erlang-shell
While I'm learning OTP I've been making a lot of changes to the .app and .erl files and re-running my application to see the effect of the changes. I've tried the following sequence of commands to pick up all my new changes, but it doesn't seem to work: Compile src...

erlang processes communication (code error)

process,erlang,spawn
I am new to Erlang. In my code I try to give each of my 2 processes a list of numbers. The process oid should send all even numbers in its list to the process eid, which should send all odd numbers in its process to oid. When a process...

How to perform actions periodically in Erlang

timer,erlang,periodic-task,periodic-processing
-define(INTERVAL, 1000). init([]) -> Timer = erlang:send_after(?INTERVAL, self(), tick), {ok, Timer}. handle_info(tick, OldTimer) -> erlang:cancel_timer(OldTimer), io:format("Tick ~w~n", [OldTimer]), Timer = erlang:send_after(?INTERVAL, self(), tick). {noreplay, Timer}. start_clock() -> {_, Timer} = init([]), spawn(clock, handle_info, [tick, Timer]). My codes is as above, but the output is not what I want. How can...

ctrl+G in erl doesn't work

unicode,encoding,utf-8,erlang,docker
I'm trying to interconnect erlang nodes, but entering ctrl+G doesn not work: Eshell V6.4.1 (abort with ^G) 1> ^G Eshell V6.4.1 (abort with ^G) 1> ^G Eshell V6.4.1 (abort with ^G) 1> ^G Eshell V6.4.1 (abort with ^G) any idea why this can happen? I was thinking about locale settings,...

How to list all the bucket types in riak?

erlang,riak
Using Riak Client(erlang), I can list all the buckets of the default bucket type. But how can I list all the bucket types? Or If I can't do this by the client, how can I find out about this?

Adding to an existing value in Erlang

erlang,record,erl
I am attempting to create a function that stores a number into a record and then adds value X to that number every time the function runs. Value: 5 Run Function (Add One): 1 Value should be: 6 Run Function (Add One): 1 value should be 7 I tried to...

Erlang C port - serial or parallel execution?

erlang,erlang-ports
Erlang ports and thread safety "With ports, however, the "controlling process" acts as a serialization (as in arranged in a series) layer, meaning requests are handled one after the other and not all at once. Moreover, I believe (but do not know for certain) that the communication protocol ports use...

erlang os:cmd() command with UTF8 binary

unicode,encoding,erlang,utf
I'm trying to get an Erlang function to execute a bash command containing unicode characters. For example, I want to execute the equivalent of: touch /home/jani/ჟანიweł I put that command in variable D, for example: io:fwrite("~ts", [list_to_binary(D)]). touch /home/jani/ჟანიwełok but after I execute: os:cmd(D) I get file called á??á??á??á??weÅ?. How...

Why are the programming languages limits precision of 22/7 equally?

python,ruby,haskell,floating-point,erlang
I tried Erlang $ erl 1> Pi = 22/7. 3.142857142857143 Haskell $ ghci Prelude> 22/7 3.142857142857143 Python $ python >>> 22/7.0 3.142857142857143 Ruby $ irb 2.1.6 :001 > 22 / 7.0 => 3.142857142857143 The result is the same. Why?...

Why doesn't spawn link cause the calling process to die?

erlang,erlang-shell
From the example given here, Erlang and process_flag(trap_exit, true) -module(play). -compile(export_all). start() -> process_flag(trap_exit, true), spawn_link(?MODULE, inverse, [***0***]), loop(). loop() -> receive Msg -> io:format("~p~n", [Msg]) end, loop(). inverse(N) -> 1/N. If I run it as, A = spawn(play, start, []). The spawned process <0.40.0> dies as it is suppose...

What is the difference between .app and .app.src files in Erlang?

erlang
I found these description in the Erlang doc and learnyousomeerlang.com, but not sure which one is the "Application Resource File". When should I use .app and .app.src? 7.3 Application Resource File http://www.erlang.org/doc/design_principles/applications.html The Application Resource File http://learnyousomeerlang.com/building-otp-applications...

passing arrays to a function in erlang

arrays,function,erlang,arguments
I am new to erlang programming and as a matter of fact no very experienced programmer. I need to pass an array to a function and then manipulate it.. however I have so far not be this what I found. module(easy). export([myfunction/1]). myfunction([myarray]) -> %% mycode.. hier I will need...

How to upgrade from R16B to 17? list_to_binary breaks if there are Chinese characters inside

erlang
We are using R16B03-1 and trying to upgrade to R17. iolist_to_binary and list_to_binary breaks if there are Chinese characters inside. I googled and found following links to explain the problem. http://www.erlang.org/news/71 The default encoding of Erlang files has been changed from ISO-8859-1 to UTF-8. The encoding of XML files has...

Erlang translation of golang walk trees

design-patterns,concurrency,erlang
I am trying to implement the Walk function from here which is implemented in golang into erlang. Here is the result: -module(tree). -export([walk/1,test/0]). walk({Left, Value, Right}) -> spawn(tree,walk,[Left]), io:format(Value), spawn(tree,walk,[Right]); walk({}) -> continue. test() -> B = {{}, alina, {}}, D = {{},vlad,{}}, C = {D, tea, {}}, A =...

Exception handling in Erlang to Continue execution

exception,error-handling,exception-handling,erlang,ejabberd
What I am trying to do is mochijson2:decode(Ccode) generates any exception or error, program execution should not stop and case branch {error, Reason} should get executed. But when I am trying to get it implemented, it generates error at first line while checking and code doesn't continue execution for lines...

Erlang gen_tcp:recv http_request abs_path

erlang,gen-tcp
I'm writing code in Erlang that accepts HTTP requests. I have working code which is shown below. The problem I have is that I'm unsure about the returned result of gen_tcp:recv. I create a listening socket and accept sockets using {ok, ListenSock}=gen_tcp:listen(Port, [list,{active, false},{packet,http}]) {ok, Sock}=gen_tcp:accept(ListenSock), I accept a GET...

How to read a key value after decoding json in erlang

json,erlang,jiffy
Here is a short query In Erlang I parsed json using Ccode = jiffy:decode(<<"{\"foo\": \"bar\"}">>). it returns {[{<<"foo">>,<<"bar">>}]} Now target is to get value of 'foo' and it should return 'bar' any help is appreciated....

Erlang spawning large amounts of C processes

c,multithreading,lua,erlang,ffi
I've been looking into how I could embed languages (let's use Lua as an example) in Erlang. This of course isn't a new idea and there are many libraries out there that can do this. However I was wondering if it was possible to start a Genserver with state which...

Getting SSL related error against my request to Ejabberd

android,sockets,ssl,erlang,ejabberd
Following is the code snippet where i open a socket to write APNS notifications on: get_socket()-> %%Options Options = [{certfile, ?Cert}, {keyfile, ?Key}, {mode, binary}], %%ssl connection ssl:connect(?Address, ?Port, Options, infinity) . close_socket(Socket)-> ssl:close(Socket). I am getting the following crash in my ejabberd.log file 2015-06-05 12:33:17.112 [error] <0.3134.0> gen_fsm <0.3134.0>...

Reliable way to convert javascript timestamp into a date tuple

javascript,date,erlang
I want to convert javascript time stamps to erlang dates. I am using the qdate library to help me do that since it also provides functions for date arithmetic. Calling it's to_date function first before midnight and then after midnight results in time displacement of 24 hrs. For example:- qdate:to_date(Timestamp...

How to run queries from MongooseIM module

erlang,mongoose-im
I am trying to make MongooseIM module, that will trigger with offline_message_hook, count number of pending messages in offline storage for the user and send it to an URL through GET method. Below is my code. send_notice(From, To, Packet) -> Type = xml:get_tag_attr_s(list_to_binary("type"), Packet), Body = xml:get_path_s(Packet, [{elem, list_to_binary("body")}, cdata]),...

Value from binding in LFE interpreter using Erlang

erlang,lisp,lfe
I'd like to use Lisp Flavored Erlang as a scripting extension language for an Erlang application. If you want, in a similar way GNU Emacs is configured and extended via Emacs Lisp. I know that the argument is wide and structured; but in the specific case of this question I'd...

Webmachine {not_started,mochiweb}

osx,erlang,webmachine
I'm new to Erlang's Webmachine, and I'm having a bit of trouble even getting a basic "hello world" going. Whenever I run ./start.sh, I get a big error like this: ➜ webmachine git:(master) ./start.sh Erlang/OTP 17 [erts-6.3.1] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace] =PROGRESS REPORT==== 4-Mar-2015::17:27:09 === supervisor: {local,sasl_safe_sup}...

Erlang port example

c,erlang
I'am actually reading the interoperability tutorial in Erlang C and Erlang: Erlang Port example i want to know how the c program works: The function read_exact(byte *buf, int len) reads exactly len Bytes from stdin and puts them in buf, but i don't undrestand what read_cmd do read_cmd(byte *buf) {...

Communication between Erlang and c program

erlang,port
When erlang module communicates with a c program via a port it sends a packet to the c program my question is when i create a port using this configuration Port = open_port({spawn, ExtPrg}, [{packet, 2}]). what are the parameters sent in the packet ? what is the length of...

Elixir exrm release crashes on eredis start_link

erlang,elixir,exrm
I'm fairly new to Elixir and this is the first app that I'm attempting to release using exrm. My app interacts with a Redis database for consuming jobs from a queue (using exq), and also stores results of processed jobs in Redis using eredis. My app works perfectly when I...

Erlang based chat (load balancing and notifications distribution)

erlang
We are going to develop a backend for our messenger, so I have one idea which I want describe here, maybe someone can give me an advice. 1) Idea: Nginx - redirects request to random node (round robin) -> Erlang cluster - redirects to actual node (we choose node with...

gen_server handle_info/2 clarification

syntax,erlang,gen-server
While reading through Erlang and OTP in action, I ran across some weird syntax regarding records that I'm having trouble wrapping my head around. I'm hoping someone can clarify what's going on in the handle_info for timeouts here: handle_info({tcp, Socket, RawData}, State) -> do_rpc(Socket, RawData), RequestCount = State#state.request_count, {noreply, State#state{request_count...

Erlang/Elixir guards and arity

erlang,elixir,arity,pattern-guards
Is there a way to see a function's guards without seeing the source code? Given an example function (in Elixir): def divide(x, y) when y != 0 do x / y end How would one figure out that there is a guard on divide/2 without access to the source code,...

eheap allocated in erlang

memory,erlang
I use recon_alloc:memory(allocated_types) and get info like below. 34> recon_alloc:memory(allocated_types). [{binary_alloc,1546650440}, {driver_alloc,21504840}, {eheap_alloc,28704768840}, {ets_alloc,526938952}, {fix_alloc,145359688}, {ll_alloc,403701800}, {sl_alloc,688968}, {std_alloc,67633992}, {temp_alloc,21504840}] The eheap_alloc is using 28G. But sum up with heap_size of all process >lists:sum([begin {_, X}=process_info(P, heap_size), X end || P <- processes()]). 683197586 Only 683M !Any idea where is the...

Pattern matching the fields of a map in erlang

erlang,erlang-shell
I'm currently reading book << Programming Erlang, 2nd edition >>. When I looked through the pattern matching of Map's field, the code snippet in the book complains some error on my Erlang prompt. %% Book's version 1> Henry8 = #{ class => king, born => 1491, died => 1547 }....

How to verify if Erlang runtime and loader is indeed running native code

erlang,erl,hipe
I am trying to explore performance improvements by switching to native compilation for my Erlang code (native option and {hipe, [verbose]}). How can I make sure that the Erlang loader is indeed using the native code from the beam file? Is there some verbose logging option for the loader to...

Executing concurrent example in Erlang code from command line

erlang,erlang-shell
I'm testing the code in Getting Started with Erlang User's Guide Concurrent Programming Section. In tut17.erl, I started a process with erl -sname ping, and another process with al -sname pong as the guide described. -module(tut17). -export([start_ping/1, start_pong/0, ping/2, pong/0]). ping(0, Pong_Node) -> {pong, Pong_Node} ! finished, io:format("ping finished~n", []);...

Erlang converting timestamp to Year-Month-DayTHour:Min:SecZ format

erlang
Hi I want to convert erlang:now(). timestamp output : > erlang:now(). {1425,589373,955614} into Year-Month-DayTHour:Min:SecZ format. Whats the fastes way to do it?...

Passing map type argument in function in Erlang complains error

erlang,erlang-shell
Here's my code snippet. %% test.erl -export([count_characters/1]). count_characters(Str) -> count_characters(Str, #{}). count_characters([H|T], #{H := N} = X) -> count_characters(T, X#{H := N+1}); count_characters([H|T], X) -> count_characters(T, X#{H => 1}); count_characters([], X) -> X. %% ErShell 1> c(test). test.erl:19: illegal use of variable 'H' in map test.erl:20: illegal use of variable...

How to rewrite Erlang combinations algorithm in Elixir?

functional-programming,erlang,elixir
I've been tinkering with Elixir for the last few weeks. I just came across this succinct combinations algorithm in Erlang, which I tried rewriting in Elixir but got stuck. Erlang version: comb(0,_) -> [[]]; comb(_,[]) -> []; comb(N,[H|T]) -> [[H|L] || L <- comb(N-1,T)]++comb(N,T). Elixir version I came up with...

Erlang: Returning a function from a function

erlang
I know Erlang supports anonymous functions. My question is, can I return a function from a function then call that returned function from outside? If so, how do I do it? I know this is possible in many languages such as C and Python. Here is what I tried to...

concatenating string with variable in erlang

string,erlang,string-concatenation
I have below string in erlang which I get from Msg#archive_message.body {\"message\":\"tttfdfdfdfdddtt\",\"customid\":\"454dddfdfdfd\"} I need to make it <<"{\"message\":\"tttfdfdfdfdddtt\",\"customid\":\"454dddfdfdfd\"}">> and pass into a function. any help is appreciated....

Is there a nightly build for Erlang/OTP? [closed]

github,erlang,common-test
I am able to build Erlang from source, and also ran the tests shipped with the source followed the instructions documented at https://github.com/erlang/otp/wiki/Running-tests. I am seeing about 900 failures out of a total of 11000 test cases, however, the failures are not very appealing to me in terms of: Is...

Manipulating XML element to get value from Sub-element in Erlang

xml,erlang,ejabberd
I have this in Packet: {xmlelement,"message", [{"from", "[email protected]/26526129921433241378891365"}, {"to", "[email protected]/30014432481433242528199830"}], [{xmlelement,"received", [{"xmlns", "urn:xmpp:receipts"}, {"id", "018A12FB-0718-4304-87FD-430C59EDB4F9"}], []}]} I just need to get the value of the id attribute under the received XML element....

Get packet type in module (ejabberd 15.02)

module,erlang,xmpp,ejabberd
I have this code for an ejabberd module. I am trying to filter messages in order to add meta-tags inside some of them but I am getting an error when I try to get the type of the Packet to filter only 'message' packets. This is my code so far:...

How to make a gen_server reply with a message?

erlang
I have the gen_server shown below. It works for the most part. However when I start it from the shell the replies come right back to the shell prompt. I would have expected them to be sent as messages back to the shells pid and then I would use flush()...

Can someone explain me why the following algorithm for LIS is not O(n)?

algorithm,erlang,dynamic-programming,combinatorics,lis
The following code traverses the list once and finds the LIS. I don't see why the DP algorithm should take O(n2). //C int lis(int *a, int l){ if(l == 0) return 1; else if(a[l] > a[l - 1]) return 1 + lis(a, l - 1); else return lis(a, l -...

Recursive function call hanging, Erlang

windows,memory,erlang,erlang-shell
I am currently teaching my self Erlang. Everything is going well until I found a problem with this function. -module(chapter). -compile(export_all). list_length([]) -> 0; list_length([_|Xs]) -> 1+list_length([Xs]). This was taken out of an textbook. When I run this code using OTP 17, it just hangs, meaning it just sits as...

Is there benefit to tagging errors in Erlang?

error-handling,erlang
In Erlang there is a benefit to tagging successful return values (e.g. as shown in the Erlang Programming Rules and Conventions), but is there a benefit to tagging failure values? Specifically, is there benefit to the style of tagging used in the file package, where errors are tagged with the...

erlang suppressing output from mnesia

erlang,mnesia
I want to suppress the "informational" output from mnesia. I.e. when I do mnesia:load_textfile("foo.txt"). I get, on stdout: New table foo New table bar I still want to keep all warnings and error on stdout. This is the only thing I want to redirect or disable....

Riak mapReduce fails with > 15 records

mapreduce,erlang,riak
Problem I've been learning Riak and ran into an issue with mapReduce. My mapReduce functions work fine when there's 15 records, but after that, it throws a stack trace error. I'm new to Riak and Erlang, so I'm unsure whether it's my code or it's Riak. Any advice on how...

Where does Elixir/erlang fit into the microservices approach? [closed]

architecture,erlang,docker,elixir,microservices
Lately I've been doing some experiments with docker compose in order to deploy multiple collaborating microservices. I can see the many benefits that microservices provide, and now that there is a good toolset for managing them, I think that it's not extremely hard to jump into the microservices wagon. But,...

Using ets function to read mnesia table (erlang)

erlang,mnesia,ets
working on an erlang project using mnesia (some tables ram copies, some tables disk copies, some tables both). in an attempt to optimize a certain read (ram table), i used the ets lookup rather than the mnesia dirty_read i had been using, and timed both versions of the routine. the...

Error with not totally inclusive if statement

erlang
I wrote a program in erlang (Just for learning it). This is a part of my code: test(X, Y) -> if X == 0 -> -1; Y == 0 -> -2 end, 2 * Y. I don't receive compile error. But when X and Y (both of them) are nonzero,...

What is the standard build tool in Erlang?

build,erlang,make,rebar
I am very new to Erlang programming language. Is there a standard build tool in Erlang? I have googled out these, not sure which one I should use. Erlang Make http://www.erlang.org/doc/man/make.html Rebar Erlang.mk ...

Broken utf8 conversion?

erlang
I am trying to force UTF-8 like this: to_utf8(X) when is_list(X) -> unicode:characters_to_binary(X, utf8); to_utf8(X) when is_binary(X) -> to_utf8(binary_to_list(X)); to_utf8(X) -> X. And testing it like this: <<"é"/utf8>> = to_utf8(<<"é">>), <<"Ø"/utf8>> = to_utf8(<<"Ø">>), <<"œ"/utf8>> = to_utf8(<<"œ">>), When using R16B03 everything works fine. However after upgrading to Erlang 17.5, the function...

How to print a message within a process when it gets the right from another process in erlang?

process,erlang,send,alarm,spawn
I'm all new to erlang, and i got this task: Write a function "setalarm(T,Message)" what starts two processes at the same time. After T miliseconds the first process sends a message to the second process, and that message will be the Message arg. It's forbidden to use function library, only...

How to check chicagoboss version

erlang,chicagoboss
We have more time to release our a Chicagoboss framework project. Since we're thinking to update it to its latest version. But I don't know what's the way to find its current version. Since - How can I find the version of ChicagoBoss?...

Elixir File.read returns empty data when accessing /proc/cpuinfo

erlang,elixir
When running any thing like File.read "/proc/cpuinfo" >> {:ok, ""} Same for equivalent erlang function. Is there some reason for this pattern?...

Wait for Node.connect before using :global.whereis_name

erlang,elixir
I have the following function: def join(id) do if Node.connect(:"[email protected]") do send :global.whereis_name(id), {:join, id} end end I receive the error: (ArgumentError) argument error :erlang.send(:undefined, ... which I assume is because Node.connect does some gathering of information and when I call :global.whereis_name it has not finished yet. If I throw...

How to delete the whole directory which is not empty?

erlang
I want to clean the temporary for collecting resource. The file module only has del_dir/1 which require the directory is empty. But there is not function the get the all files in the directory (with absolute path") The source code is as follows, how to correct it? delete_path(X)-> {ok,List} =...

Getting a sibling process in Elixir

erlang,elixir,otp
I have an Elixir/Erlang process tree: parent (Supervisor) ├── child1 (GenServer) └── child2 (GenServer) child1 (a DB client) has information that child2 needs to use. What's a good way to pass a reference from the Supervisor process to child2 so that child2 will always have a valid reference to child1?...

Does the pattern [_|_] in Erlang mean anything specific?

erlang
I am learning Erlang from Learn You Some Erlang and I've seen the pattern [_|_] twice already but couldn't find any info on it. This usage seems superfluous because omitting it from (1) and subsituting it with _ in (2) yields the same result without degrading readability. It is my...

What's the terminology for when a boolean/tagged union determines whether the current execution of a recursive function is at its first iteration?

haskell,recursion,erlang
I remember seeing in Erlang, that a wrapper function of a recursive function will sometimes pass an atom that determines whether the recursion is at the first iteration (n = 1) or some successive iterations (n > 1). This is useful when a recursive function needs to change its behaviour...

How can I build an Elixir escript that does not halt the Erlang VM after execution (like elixir --no-halt)

erlang,elixir,erlang-escript
I have a program that starts the application and then adds (children) workers to a supervisor. Obviously after doing only that it has nothing more left to do and it halts (exits). So making it not halt the VM would allow the workers to work. The only solution I have...

First word of binary string erlang

functional-programming,erlang,pattern-matching
I need to do something like this <<"Some text in binary">>, and it should return <<"Some">. How can i do it without split function, only by pattern matching and select/if cases with Erlang. Thank you.

Fast mutable objects in Erlang

erlang
What is the best approach to store and manage high-performance mutable objects in Erlang? Assume that I want to write really simple online game server with realtime gameplay. Somehow I need to represent player's state in Erlang memory. For example, it could be just a simple tuple like {name, "Bob",...

Erlang drop messages

erlang,message
I have a proxy that prevents the server from getting overloaded with requests. Clients sends their requests to the proxy and the proxy determine wether or not to pass the requests to the server. NrOfReq is the current number of requests that the server is handling. MaxReq is the maximum...

Is ++ operator more expensive than | operator in Erlang?

erlang
I was reading Learn You Some Erlang and I came upon this example in the Recursion chapter. tail_sublist(_, 0, SubList) -> SubList; tail_sublist([], _, SubList) -> SubList; tail_sublist([H|T], N, SubList) when N > 0 -> tail_sublist(T, N-1, [H|SubList]). As the author goes on to explain that there is a fatal...

erlang otp application is not restarted when it crashes

erlang
I've been reading the book Erlang and OTP In Action and trying the source code in chapter 4 which builds an OTP application. There is a gen_server that has these call back methods (full source): %%%=================================================================== %%% gen_server callbacks %%%=================================================================== init([Port]) -> {ok, LSock} = gen_tcp:listen(Port, [{active, true}]), {ok, #state{port...

Jabber user going offline: Why the two different scenarios?

android,erlang,xmpp,ejabberd,user-presence
I have an Android client working in tandem with ejabberd XMPP server. Observations: Scenario 1: When I swipe-right the app (kill the app), the user goes offline on the server immediately. Its status is changed to offline at that very instant. Scenario 2: However, when I simply shut-down the Wi-fi...

Erlang result in accumulator

erlang
I'm trying to write a program that collects all Pythagorean triples equal to a given number; for example, calling main(12) should return [{3,4,5}]. But when I run my code, the answer is []. Can you tell me what I am doing wrong? -module(triples). -export([main/1]). t1(A, B, C) -> {A-2*B+2*C, 2*A-B+2*C,...

How Ruby On Rails can be combined with Erlang? [closed]

ruby-on-rails,ruby,erlang,cowboy
I have the "Wappalyzer" extension installed in my browser. And several times I saw some webapps which were built with RubyOnRails and Erlang, on the Cowboy server. So, could you tell me how these technologies can be combined in one project?...

Using Hexadecimal in Erlang

erlang,hex
Is there any way to convert a list of hexadecimal caracter to a binary that correspond to the hexadecimal coding Example: [FF,AC,01]=><<255,172,1>>

How to invoke Erlang function with variable?

erlang
4> abs(1). 1 5> X = abs. abs 6> X(1). ** exception error: bad function abs 7> erlang:X(1). 1 8> Is there any particular reason why I have to use the module name when I invoke a function with a variable? This isn't going to work for me because, well,...

when erlang in detached model ,where is error log?

erlang
when add detached ,can not find error info ,eg "Can't set long node name" [email protected]:~# erl -name test {error_logger,{{2015,3,11},{12,14,0}},"Can't set long node name!\nPlease check your configuration\n",[]} ...... Crash dump was written to: erl_crash.dump Kernel pid terminated (application_controller) ({application_start_failure,kernel,{{shutdown,{failed_to_start_child,net_sup,{shutdown,{failed_to_start_child,net_kernel,{'EXIT',nodistribution}}}}},{k [email protected]:~# [email protected]:~# [email protected]:~# [email protected]:~# [email protected]:~# [email protected]:~#...

Modifying an Erlang Record [duplicate]

erlang,record,erl
This question already has an answer here: Adding to an existing value in Erlang 2 answers I know that a record in Erlang cannot be changed once it has been set. I am attempting to use a record to increase a value. add_new_num() -> Number = random:uniform(6), STR =...

Distributed decentralized ring

erlang
I am trying to implement a distributed ring in Erlang, in which each node will store data. My idea was create a gen_server module node_ring which will provide state of node in ring: -record(nodestate, {id, hostname, previd, nextid, prevnodename, nextnodename, data}). Next, I created virtual hosts via: werl -sname node...

Mnesia pagination with fragmented table

pagination,erlang,mnesia
I have a mnesia table configured as follow: -record(space, {id, t, s, a, l}). mnesia:create_table(space, [ {disc_only_copies, nodes()}, {frag_properties, [ {n_fragments, 400}, {n_disc_copies, 1}]}, {attributes, record_info(fields, space)}]), I have at least 4 million records for test purposes on this table. I have implemented something like this Pagination search in Erlang...

Pid as erlang maps key?

erlang
Can Pid be maps key ? Build maps from #{} syntax, The error says Pid can not be key. Bug build with maps module, Pid can be key. 18> 18> Pid = self(). <0.39.0> 19> #{Pid => 1}. * 1: illegal use of variable 'Pid' in map 20> 20> M1...

Can I match against a string that contains non-ASCII characters?

erlang
I am writing an program in which I am dealing with strings in the form, e.g., of "\001SOURCE\001". That is, the strings contained alphanumeric text with an ASCII character of value 1 at each end. I am trying to write a function to match strings like these. I have tried...

how mature is SD erlang project?

erlang
do you have any experience with SD Erlang project? There seems to be implemented many interesting concepts regarding the comm mesh optimalizations and I'm just curious if some of you used those in production already or in some real project at least. SD erlang repo Thanks!...

Erlang driver erl_errno issue

erlang,erlang-driver
I am playing with erl_driver. Start callback of my driver is below: ErlDrvData drv_start(ErlDrvPort port, char* command) { char* file_name = command + sizeof(drv_name); GenTtyData* port_data = (GenTtyData*)driver_alloc(sizeof(GenTtyData)); erl_errno = gt_open(file_name, &port_data->file); if (erl_errno != 0) { // Assertion there is just to show you my intention assert(erl_errno == ENOENT);...

Fetching and updating data in mnesia

erlang,mnesia
I have multiple mnesia tuples like (GroupID is the primary key) {GroupID, GroupName, GroupType, GroupDescription, GroupTag, CreatorID, AdminID, MemberList, Counter}. MemberList = "[email protected],[email protected],[email protected]". GroupName = "Any String Value". % e.g.: "basketball" GroupTag = "comma separated values". % e.g.: "Sports,Cricket,Fifa,Ronaldo" I will pass a character or word to a function. This...

how to handle low_entropy exception of crypto:strong_rand_bytes(N)?

openssl,erlang
I want to generate cryptographically strong pseudorandom numbers in erlang for session IDs. There is crypto:strong_rand_bytes(N). What if it throws the low_entropy exception? From http://www.erlang.org/doc/man/crypto.html#strong_rand_bytes-1 strong_rand_bytes(N) -> binary() Types: N = integer() Generates N bytes randomly uniform 0..255, and returns the result in a binary. Uses a cryptographically secure prng...

Erlang: runing custom module

import,module,erlang,otp
Windows 7 x64, Erlang-OTP 17. I wrote simple module like this: -module (somequery). -export ([fbquery/2]). fbquery(P1,P2) -> inets:start(), ssl:start(), token = "78a8shd67tyajsndweiu03hr83h19j", Encoded = {"Authorization","Basic " ++ base64:encode_to_string(lists:append([token,":",""]))}, ContentType = "application/xml", Headers = [Encoded, {"Content-Type",ContentType}], Options = [{body_format,binary}], {ok, File}=file:read_file(P1), Res = httpc:request(post, {"https://datapi.com/api/xml4-8", Headers, ContentType, File}, [], Options),...

Erlang syntax error unclear

function,variables,if-statement,functional-programming,erlang
I just got started with Erlang. I am trying if statement. I found out one particular behavior which I do not understand. the following statement does work perfectly. some_comp(Arg1) -> if (cal(Arg1)>50000)->'reached'; true -> 'invalid' end. cal(Arg2)-> %% some calculation. However the following shows an error syntax near if: some_comp(Arg1)...

erlang message passing architecture

process,erlang,messaging
In erlang if two processes A and B are sending message to a process C simultaneously. Will there be a race condition? C ! {very large message} sent by A C ! {very large message} sent by B Will C receive the complete message from A and then proceed for...

Erlang basic syntax error

syntax,erlang
I try to learn Erlang. I've installed a runtime but cannot get it working. The following code: X=3. works, but the following doesn't f(X)->X. or F() ->0. or F([])->[]. etc. all produce "1: syntax error before: '->'" I tried the "word_count" from this tutorial: http://www.ybrikman.com/writing/2012/11/04/seven-languages-in-seven-weeks-erlang/ and I get the same...

Why message passing in Erlang?

erlang
Message passing between processes is one of Erlang concepts. But it seems that message passing makes big time overhead because of process context switching. Is that right? If it is right why do we use this concept?

Does Erlang has Map?

erlang
It seems that Erlang introduced maps in version R17A. But, if I go to downloads I only see version 17.5, there's no version R17A. So, is it released and stable yet? Does the latest stable Erlang has Map support?...

Multiple specifications for same function in Erlang header file

erlang
I'm trying to specify a function in a header file. Like so: -spec update(pid(), tuple(tuple(), integer(), atom()), tuple(atom(), atom())) -> tuple(tuple(), integer(), atom()). Now I want to add some extra specification for this function because it has multiple different parameters. update(_Pid, {Specs, infinity, _State}, {Step}) -> timer:sleep(10000), {{Specs, infinity}, {Step}};...

Properly managing Erlang concurrency

multithreading,erlang
I'm putting together some Erlang code with the following process: - Spawn a number of threads - Each thread scans an IP address - Report back to the main thread the results I've got the main thread running this: cve_receive() -> receive Msg -> io:fwrite("~s~n", [Msg]), cve_receive() after 5000 ->...

Type errors in dialyzer in function with specified type

erlang,dialyzer
I am receiving an error in dialyzer when it analyzes the following function. -spec do_request(Method, Type, Url, Expect, Headers, Body, Client) -> Response::client_response() when Method :: method(), Type :: content_type(), Url :: url(), Expect :: status_codes(), Headers :: headers(), Body :: body(), Client :: #client{}. do_request(Method, Type, Url, Expect, Headers,...