-module(dk_stem_SUITE).
-include_lib("common_test/include/ct.hrl").

-compile(export_all).

-define(value(Key,Config), proplists:get_value(Key,Config)).

all() ->
    [{group, integration_tests}].

groups() ->
    [{integration_tests, [test_en, test_nl]}].

test_en(Config) ->
    vocab_stemmed("en", Config),
    ok.

test_nl(Config) ->
    vocab_stemmed("nl", Config),
    ok.

vocab_stemmed(Lang, Config) ->
    DataDir = ?value(data_dir, Config),
    {ok, Binary} =
        file:read_file(DataDir ++ "vocabulary_stemmed_" ++ Lang ++ ".txt"),
    Lines = re:split(Binary, <<"\n">>, [trim]),
    {ok, Re} = re:compile(<<"^([^ ]*) *([^ ]*)$">>, [unicode]),
    Options = [{capture, all_but_first, binary}],
    Mod = list_to_atom("dk_stem_" ++ Lang),
    lists:foreach(
      fun(Line) ->
              {match, [Word, Stem]} = re:run(Line, Re, Options),
              Stem = apply(Mod, stem, [Word])
      end,
      Lines).

%%% Local variables:
%%% mode: erlang
%%% fill-column: 78
%%% coding: latin-1
%%% End:

Use variable instead of `apply`

-module(dk_stem_SUITE).
-include_lib("common_test/include/ct.hrl").

-compile(export_all).

-define(value(Key,Config), proplists:get_value(Key,Config)).

all() ->
    [{group, integration_tests}].

groups() ->
    [{integration_tests, [test_en, test_nl]}].

test_en(Config) ->
    vocab_stemmed("en", Config),
    ok.

test_nl(Config) ->
    vocab_stemmed("nl", Config),
    ok.

vocab_stemmed(Lang, Config) ->
    DataDir = ?value(data_dir, Config),
    {ok, Binary} =
        file:read_file(DataDir ++ "vocabulary_stemmed_" ++ Lang ++ ".txt"),
    Lines = re:split(Binary, <<"\n">>, [trim]),
    {ok, Re} = re:compile(<<"^([^ ]*) *([^ ]*)$">>, [unicode]),
    Options = [{capture, all_but_first, binary}],
    Mod = list_to_atom("dk_stem_" ++ Lang),
    lists:foreach(
      fun(Line) ->
              {match, [Word, Stem]} = re:run(Line, Re, Options),
              Stem = Mod:stem(Word)
      end,
      Lines).

%%% Local variables:
%%% mode: erlang
%%% fill-column: 78
%%% coding: latin-1
%%% End:


%% A mapping containing the chunks tracking
-record(chunk, {idt, % {id, piece_number, state} tuple
                     % state is fetched | {assigned, Pid} | not_fetched,
                chunks}). % {offset, size}

Write down a specification for the chunk_tbl.

%% A mapping containing the chunks tracking
-record(chunk, {idt :: {integer() | '_' | '$1',
			integer() | '_' | '$1',
			not_fetched | fetched | {assigned, pid() | '_'} | '_'},
                chunks :: [integer() | {integer(), integer(), [term()]}] | '_' | '$2'}).


-module(autocluster_sup_tests).

-include_lib("eunit/include/eunit.hrl").

start_link_test_() ->
  {
    foreach,
    fun() ->
      meck:new(supervisor, [passthrough, unstick])
    end,
    fun(_) ->
      meck:unload(supervisor)
    end,
    [
      {
        "supervisor start_link", fun() ->
          meck:expect(supervisor, start_link, fun(_, _, _) -> {ok, test_result} end),
          ?assertEqual({ok, test_result}, autocluster_sup:start_link()),
          meck:validate(supervisor)
        end}
    ]
  }.

init_test_() ->
  {
    foreach,
    fun autocluster_testing:on_start/0,
    fun autocluster_testing:on_finish/1,
    [
      {
        "default",
        fun() ->
          Expectation = {ok, {{one_for_one, 3, 10}, []}},
          ?assertEqual(Expectation, autocluster_sup:init([]))
        end
      },
      {
        "cluster cleanup enabled",
        fun() ->
          os:putenv("AUTOCLUSTER_CLEANUP", "true"),
          Expectation = {ok, {{one_for_one, 3, 10},
                              [{autocluster_cleanup,
                                {autocluster_cleanup, start_link, []},
                                permanent, 10000, worker,
                                [autocluster_cleanup]}]}},
          ?assertEqual(Expectation, autocluster_sup:init([]))
        end
      }
    ]
  }.

Validate the use of supervisor

-module(autocluster_sup_tests).

-include_lib("eunit/include/eunit.hrl").

start_link_test_() ->
  {
    foreach,
    fun() ->
      meck:new(supervisor, [passthrough, unstick])
    end,
    fun(_) ->
      meck:unload(supervisor)
    end,
    [
      {
        "supervisor start_link", fun() ->
          meck:expect(supervisor, start_link, fun(_, _, _) -> {ok, test_result} end),
          ?assertEqual({ok, test_result}, autocluster_sup:start_link()),
          ?assert(meck:validate(supervisor))
        end}
    ]
  }.

init_test_() ->
  {
    foreach,
    fun autocluster_testing:on_start/0,
    fun autocluster_testing:on_finish/1,
    [
      {
        "default",
        fun() ->
          Expectation = {ok, {{one_for_one, 3, 10}, []}},
          ?assertEqual(Expectation, autocluster_sup:init([]))
        end
      },
      {
        "cluster cleanup enabled",
        fun() ->
          os:putenv("AUTOCLUSTER_CLEANUP", "true"),
          Expectation = {ok, {{one_for_one, 3, 10},
                              [{autocluster_cleanup,
                                {autocluster_cleanup, start_link, []},
                                permanent, 10000, worker,
                                [autocluster_cleanup]}]}},
          ?assertEqual(Expectation, autocluster_sup:init([]))
        end
      }
    ]
  }.


%%% -*- erlang-indent-level:4; indent-tabs-mode: nil -*-
%%%-------------------------------------------------------------------
%%% @copyright (C) 2018, Aeternity Anstalt
%%% @doc Test Sophia language compiler.
%%%
%%% @end
%%%-------------------------------------------------------------------

-module(aeso_compiler_tests).

-include_lib("eunit/include/eunit.hrl").

%% simple_compile_test_() -> ok.
%%  Very simply test compile the given contracts. Only basic checks
%%  are made on the output, just that it is a binary which indicates
%%  that the compilation worked.

simple_compile_test_() ->
    {setup,
     fun () -> ok end,                          %Setup
     fun (_) -> ok end,                         %Cleanup
     [ {"Testing the " ++ ContractName ++ " contract",
        fun() ->
                ContractString = aeso_test_utils:read_contract(ContractName),
                ?assertMatch(Code when is_binary(Code),
                                       aeso_compiler:from_string(ContractString, []))

        end} ||
         ContractName <- compilable_contracts() ]}.

%% compilable_contracts() -> [ContractName].
%%  The currently compilable contracts.

compilable_contracts() ->
    ["complex_types",
     "counter",
     "dutch_auction",
     "environment",
     "factorial",
     "identity",
     "remote_call",
     "simple",
     "simple_storage",
     "spend_test",
     "stack",
     "test"
    ].

Include fundme example among compiler tests

%%% -*- erlang-indent-level:4; indent-tabs-mode: nil -*-
%%%-------------------------------------------------------------------
%%% @copyright (C) 2018, Aeternity Anstalt
%%% @doc Test Sophia language compiler.
%%%
%%% @end
%%%-------------------------------------------------------------------

-module(aeso_compiler_tests).

-include_lib("eunit/include/eunit.hrl").

%% simple_compile_test_() -> ok.
%%  Very simply test compile the given contracts. Only basic checks
%%  are made on the output, just that it is a binary which indicates
%%  that the compilation worked.

simple_compile_test_() ->
    {setup,
     fun () -> ok end,                          %Setup
     fun (_) -> ok end,                         %Cleanup
     [ {"Testing the " ++ ContractName ++ " contract",
        fun() ->
                ContractString = aeso_test_utils:read_contract(ContractName),
                ?assertMatch(Code when is_binary(Code),
                                       aeso_compiler:from_string(ContractString, []))

        end} ||
         ContractName <- compilable_contracts() ]}.

%% compilable_contracts() -> [ContractName].
%%  The currently compilable contracts.

compilable_contracts() ->
    ["complex_types",
     "counter",
     "dutch_auction",
     "environment",
     "factorial",
     "fundme",
     "identity",
     "remote_call",
     "simple",
     "simple_storage",
     "spend_test",
     "stack",
     "test"
    ].


-module(sum_of_multiples_tests).
-import(sum_of_multiples, [sumOfMultiplesDefault/1, sumOfMultiples/2]).

-include_lib("eunit/include/eunit.hrl").

sum_to_1_test() ->
  ?assertEqual(0, sumOfMultiplesDefault(1)).

sum_to_3_test() ->
  ?assertEqual(3, sumOfMultiplesDefault(4)).

sum_to_10_test() ->
  ?assertEqual(23, sumOfMultiplesDefault(10)).

sum_to_1000_test() ->
  ?assertEqual(233168, sumOfMultiplesDefault(1000)).

sum_of_configurable_to_20_test() ->
  ?assertEqual(51, sumOfMultiples([7,13,17], 20)).

sum_of_configurable_to_10000_test() ->
  ?assertEqual(2203160, sumOfMultiples([43,47], 10000)).

Add missing test to sum-of-multiples exercise

-module(sum_of_multiples_tests).
-import(sum_of_multiples, [sumOfMultiplesDefault/1, sumOfMultiples/2]).

-include_lib("eunit/include/eunit.hrl").

sum_to_1_test() ->
  ?assertEqual(0, sumOfMultiplesDefault(1)).

sum_to_3_test() ->
  ?assertEqual(3, sumOfMultiplesDefault(4)).

sum_to_10_test() ->
  ?assertEqual(23, sumOfMultiplesDefault(10)).

sum_to_100_test() ->
  ?assertEqual(2318, sumOfMultiplesDefault(100)).

sum_to_1000_test() ->
  ?assertEqual(233168, sumOfMultiplesDefault(1000)).

sum_of_configurable_to_20_test() ->
  ?assertEqual(51, sumOfMultiples([7,13,17], 20)).

sum_of_configurable_to_10000_test() ->
  ?assertEqual(2203160, sumOfMultiples([43,47], 10000)).


-module(aecore_sup).

-behaviour(supervisor).

%% API
-export([start_link/0]).

%% Supervisor callbacks
-export([init/1]).

-include("common.hrl").
-include("blocks.hrl").

-define(SERVER, ?MODULE).
-define(CHILD(Mod,N,Type), {Mod,{Mod,start_link,[]},permanent,N,Type,[Mod]}).
-define(CHILD(Mod,N,Type,Params), {Mod,{Mod,start_link,Params},permanent,N,Type,[Mod]}).

%%====================================================================
%% API functions
%%====================================================================

start_link() ->
    supervisor:start_link({local, ?SERVER}, ?MODULE, []).

%%====================================================================
%% Supervisor callbacks
%%====================================================================

init([]) ->
    {ok, {{one_for_one, 5, 10}, [?CHILD(aec_peers, 5000, worker),
                                 ?CHILD(aec_persistence, 5000, worker),
                                 ?CHILD(aec_tx_pool, 5000, worker),
                                 ?CHILD(aec_chain, 5000, worker),
                                 ?CHILD(aec_keys, 5000, worker),
                                 ?CHILD(aec_sync, 5000, worker),
                                 ?CHILD(aec_miner, 5000, worker)]
         }}.

Fix race between chain and keys services when starting with persisted chain


%% -*- mode: nitrogen -*-
-module (mt_index).

-export([
  main/0,
  title/0,
  body/0,
  event/1,
  author/0,
  url/0
]).

-include_lib("nitrogen_core/include/wf.hrl").

-include_lib("metalkia_core/include/mt_log.hrl").

main() -> #template { file="./site/templates/metalkia/bare.html" }.

title() -> "Metalkia".

author() ->
  ?DBG("Author", []),
  "Metachord".

url() ->
  ?DBG("URL", []),
  "http://metalkia.com".

body() ->
  ?DBG("Cookies:~n~p", [wf_context:cookies()]),
  #container_12 { body=[
    #grid_8 { alpha=true, prefix=2, suffix=2, omega=true, body=inner_body() }
  ]}.

inner_body() ->
  #panel{body=[
    #panel{body = #template{file = "./site/templates/metalkia/facebook_service.html"}}
    %%#button{id=submit, text="LogOff",postback="logoff"}
  ]}.

event("logoff") ->
  wf:redirect("http://metalkia.com/logoff").

Add link to Twitter login

%% -*- mode: nitrogen -*-
-module (mt_index).

-export([
  main/0,
  title/0,
  body/0,
  event/1,
  author/0,
  url/0
]).

-include_lib("nitrogen_core/include/wf.hrl").

-include_lib("metalkia_core/include/mt_log.hrl").

main() -> #template { file="./site/templates/metalkia/bare.html" }.

title() -> "Metalkia".

author() ->
  ?DBG("Author", []),
  "Metachord".

url() ->
  ?DBG("URL", []),
  "http://metalkia.com".

body() ->
  ?DBG("Cookies:~n~p", [wf_context:cookies()]),
  #container_12 { body=[
    #grid_8 { alpha=true, prefix=2, suffix=2, omega=true, body=inner_body() }
  ]}.

inner_body() ->
  #panel{body=[
    #panel{body = #template{file = "./site/templates/metalkia/facebook_service.html"}},
    #panel{body = #link{id="twitter-login-button", text="Login with Twitter", postback="twitter-login-button"}}
    %%#button{id=submit, text="LogOff",postback="logoff"}
  ]}.

event("logoff") ->
  wf:redirect(mtc:get_env(url) ++ "/logoff");
event("twitter-login-button") ->
  ?DBG("Login with twitter", []),
  wf:redirect(mtc:get_env(url) ++ "/twitter").


%% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
%% ex: ts=4 sw=4 et

-module(rebar_prv_state).

-behaviour(provider).

-export([init/1,
         do/1,
         format_error/1]).

-include("rebar.hrl").

-define(PROVIDER, state).
-define(DEPS, []).

%% ===================================================================
%% Public API
%% ===================================================================

-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
    Provider = providers:create(
        [{name, ?PROVIDER},
         {module, ?MODULE},
         {bare, true},
         {deps, ?DEPS},
         {example, "rebar3 state"},
         {short_desc, "Print current configuration state"},
         {desc, "Display rebar configuration for debugging purpose"},
         {opts, []}]),
    State1 = rebar_state:add_provider(State, Provider),
    {ok, State1}.

-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State) ->
    L = rebar_state:to_list(State),
    io:put_chars("State:\n"),
    [io:format("  ~w: ~p\n", [K, V]) || {K,V} <- L],
    {ok, State}.

-spec format_error(any()) -> iolist().
format_error(Reason) ->
    io_lib:format("~p", [Reason]).

Change output to use ?CONSOLE marco

%% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
%% ex: ts=4 sw=4 et

-module(rebar_prv_state).

-behaviour(provider).

-export([init/1,
         do/1,
         format_error/1]).

-include("rebar.hrl").

-define(PROVIDER, state).
-define(DEPS, []).

%% ===================================================================
%% Public API
%% ===================================================================

-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
    Provider = providers:create(
        [{name, ?PROVIDER},
         {module, ?MODULE},
         {bare, true},
         {deps, ?DEPS},
         {example, "rebar3 state"},
         {short_desc, "Print current configuration state"},
         {desc, "Display rebar configuration for debugging purpose"},
         {opts, []}]),
    State1 = rebar_state:add_provider(State, Provider),
    {ok, State1}.

-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State) ->
    L = rebar_state:to_list(State),
    io:put_chars("State:\n"),
    [?CONSOLE("  ~w: ~p\n", [K, V]) || {K,V} <- L],
    {ok, State}.

-spec format_error(any()) -> iolist().
format_error(Reason) ->
    io_lib:format("~p", [Reason]).


-module(element_upload).
-compile(export_all).
-include_lib("nitro/include/nitro.hrl").

render_element(#upload{id=Id} = U) ->
    Uid = case Id of undefined -> wf:temp_id(); I -> I end,
    bind(ftp_open,  click,  "qi('upload').click(); e.preventDefault();"),
    bind(ftp_start, click,  "ftp.start();"),
    bind(ftp_stop,  click,  "ftp.stop();"),
    bind(nitro:to_atom(Uid), change, "ftp.init(this.files[0],1);"),
    Upload = #panel  { body = [
             #input  { id   = Uid,         type    = <<"file">>, style = "display:none" },
             #span   { id   = ftp_status,  body    = [] },
             #span   { body = [
             #button { id   = ftp_open,    body = "Browse" },
             #button { id   = ftp_start,   body = "Upload" },
             #button { id   = ftp_stop,    body = "Stop" }
    ] } ] }, wf:render(Upload).

bind(Control,Event,Code) ->
    wf:wire(#bind{target=Control,type=Event,postback=Code}).

Fix for autostart option in ftp.js

-module(element_upload).
-compile(export_all).
-include_lib("nitro/include/nitro.hrl").

render_element(#upload{id=Id} = U) ->
    Uid = case Id of undefined -> wf:temp_id(); I -> I end,
    bind(ftp_open,  click,  "qi('upload').click(); e.preventDefault();"),
    bind(ftp_start, click,  "ftp.start();"),
    bind(ftp_stop,  click,  "ftp.stop();"),
    bind(nitro:to_atom(Uid), change, "ftp.init(this.files[0],false);"),
    Upload = #panel  { body = [
             #input  { id   = Uid,         type    = <<"file">>, style = "display:block" },
             #span   { id   = ftp_status,  body    = [] },
             #span   { body = [
             #button { id   = ftp_open,    body = "Browse" },
             #button { id   = ftp_start,   body = "Upload" },
             #button { id   = ftp_stop,    body = "Stop" }
    ] } ] }, wf:render(Upload).

bind(Control,Event,Code) ->
    wf:wire(#bind{target=Control,type=Event,postback=Code}).


-module(ev8cache).

-export([
  start/0,
  eval_file/2
  ]).

start() ->
  ets:new(ev8cache_lookup, [set, public, named_table, {read_concurrency, true}]).

eval_file(Context, File) ->
  eval_file(ev8txn:vm(Context), Context, File).

eval_file({ok, Vm}, Context, File) ->
  try_cache(Vm, Context, File);
eval_file({error, Reason}, _Context, _File) -> {error, Reason}.

% Internal functions

try_cache(Vm, Context, File) ->
  case lookup(Vm, File) of
    {ok, Result} -> Result;
    {error, not_found} -> cache_miss(Vm, Context, File)
  end.

cache_miss(Vm, Context, File) ->
  case ev8:eval_file(Context, File) of
    {error, Reason} -> {error, Reason};
    Result ->
      insert(Vm, File, Result),
      Result
  end.

insert(Vm, File, Result) ->
  ets:insert(ev8cache_lookup, {{Vm, File}, Result}).

lookup(Vm, File) ->
  lookup(ets:lookup(ev8cache_lookup, {Vm, File})).

lookup([{{_Vm, _File}, Result}]) ->
  {ok, Result};
lookup([]) ->
  {error, not_found}.

Make caching more accessible to other ev8 modules.

-module(ev8cache).

-export([
  start/0,
  eval_file/2,
  insert/3,
  lookup/2
  ]).

start() ->
  ets:new(ev8cache_lookup, [set, public, named_table, {read_concurrency, true}]).

eval_file(Context, File) ->
  eval_file(ev8txn:vm(Context), Context, File).

eval_file({error, not_found}, _Context, _File) ->
  {error, badcontext};
eval_file({ok, Vm}, Context, File) ->
  try_cache(Vm, Context, File).

try_cache(Vm, Context, File) ->
  try_cache(lookup(Vm, {eval_file, File}), Vm, Context, File).

try_cache({ok, Result}, _Vm, _Context, _File) ->
  Result;
try_cache(cache_miss, Vm, Context, File) ->
  Result = ev8:eval_file(Context, File),
  insert(Vm, {eval_file, File}, Result),
  Result.

insert(Vm, Key, Result) ->
  ets:insert(ev8cache_lookup, {{Vm, Key}, Result}).

lookup(Vm, Key) ->
  lookup(ets:lookup(ev8cache_lookup, {Vm, Key})).

lookup([{{_, _}, Result}]) ->
  {ok, Result};
lookup([]) ->
  cache_miss.


%% vim: ts=4 sw=4 et
-module (element_fa).
-include_lib ("nitrogen_core/include/wf.hrl").
-include("records.hrl").
-export([
    reflect/0,
    render_element/1
]).

reflect() -> record_info(fields, fa).

-spec render_element(#fa{}) -> body().
render_element(_Record = #fa{text = Text,
                            body = Body,
                            class = Class0,
                            size = Size,
                            fa = Icon,
                            fw = FixedWidth}) ->

    Class = [
        "fa fa-" ++ wf:to_list(Icon),
        ?WF_IF(Size, "fa-" ++ wf:to_list(Size)),
        ?WF_IF(FixedWidth, "fa-fw")
        | Class0
    ],

    UniversalAttributes = [
                            {class, Class},
                            {"aria-hidden", "true"}
                           ],

    wf_tags:emit_tag(i, [Body, Text], UniversalAttributes).

Add Htmlid and Style attributes

%% vim: ts=4 sw=4 et
-module (element_fa).
-include_lib ("nitrogen_core/include/wf.hrl").
-include("records.hrl").
-export([
    reflect/0,
    render_element/1
]).

reflect() -> record_info(fields, fa).

-spec render_element(#fa{}) -> body().
render_element(_Record = #fa{text = Text,
                            body = Body,
                            class = Class0,
                            style = Style,
                            size = Size,
                            html_id = Htmlid,
                            fa = Icon,
                            fw = FixedWidth}) ->

    Class = [
        "fa fa-" ++ wf:to_list(Icon),
        ?WF_IF(Size, "fa-" ++ wf:to_list(Size)),
        ?WF_IF(FixedWidth, "fa-fw")
        | Class0
    ],

    UniversalAttributes = [
                            {class, Class},
                            {"aria-hidden", "true"},
                            {style, Style},
                            {id, Htmlid}
                           ],

    wf_tags:emit_tag(i, [Body, Text], UniversalAttributes).


-define(SET, riak_dt_orswot).
-define(APP, partisan).
-define(PEER_IP, {127,0,0,1}).
-define(PEER_PORT, 9000).
-define(PEER_SERVICE_SERVER, partisan_peer_service_server).
-define(FANOUT, 5).
-define(GOSSIP_INTERVAL, 300).

-type node_spec() :: {node(), inet:ip_address(), non_neg_integer()}.

Add comment to remember to change TTL.

-define(SET, riak_dt_orswot).
-define(APP, partisan).
-define(PEER_IP, {127,0,0,1}).
-define(PEER_PORT, 9000).
-define(PEER_SERVICE_SERVER, partisan_peer_service_server).
-define(FANOUT, 5).

%% @todo Reduce me.
-define(GOSSIP_INTERVAL, 300).

-type node_spec() :: {node(), inet:ip_address(), non_neg_integer()}.


-module(slack_channel).

-export([handle/2]).

handle(Config, Message) ->
    Targets = maps:get(channels, Config),
    HookUrl = maps:get(url, Config),
    %% FIXME emoji and username should be default when blank
    BasePayload = #{
      text => Message,
      username => maps:get(username, Config, <<"Holiday Reminder">>),
      icon_emoji => maps:get(emoji, Config, <<":calendar:">>)
     },

    lists:foreach(
      fun (Target) ->
              Payload = BasePayload#{channel => Target},
              lager:debug("Sending request to slack: ~p", [Payload]),
              {ok, 200, _, _} = hp_request:post_json(HookUrl, Payload)
      end, Targets).

Use default slack config when values are empty

-module(slack_channel).

-export([handle/2]).

handle(Config, Message) ->
    Targets = maps:get(channels, Config),
    HookUrl = maps:get(url, Config),

    BasePayload = #{
      text => Message,
      username => get_not_empty(username, Config, <<"Holiday Reminder">>),
      icon_emoji => get_not_empty(emoji, Config, <<":calendar:">>)
     },

    lists:foreach(
      fun (Target) ->
              Payload = BasePayload#{channel => Target},
              lager:debug("Sending request to slack: ~p", [Payload]),
              {ok, 200, _, _} = hp_request:post_json(HookUrl, Payload)
      end, Targets).

get_not_empty(Key, Map, Default) ->
    Value = maps:get(Key, Map, Default),
    case re:replace(Value, "\\s+", "", [global,{return,binary}]) of
        <<"">> ->
            Default;
        V -> V
    end.


-module(reia_operators).
-export([ast/2, ast/3]).

ast('-' = Op, Ast) ->
  {op, 1, Op, {integer, 1, 0}, Ast}.
%ast('~' = Op, Ast) ->
%  erl_syntax:prefix_expr(erl_syntax:operator('bnot'), Ast).

ast('*' = Op, Ast1, Ast2) ->
  {op, 1, Op, Ast1, Ast2};
ast('**', Ast1, Ast2) ->
  {call,1,{remote,1,{atom,1,math},{atom,1,pow}},[Ast1, Ast2]};
ast('/' = Op, Ast1, Ast2) ->
  {op, 1, Op, Ast1, Ast2};
ast('+' = Op, Ast1, Ast2) ->
  {op, 1, Op, Ast1, Ast2};
ast('-' = Op, Ast1, Ast2) ->
  {op, 1, Op, Ast1, Ast2}.

Use proper unary for negative numbers in Erlang AST

-module(reia_operators).
-export([ast/2, ast/3]).

ast('-' = Op, Ast) ->
  {op, 1, Op, Ast}.
%ast('~' = Op, Ast) ->
%  erl_syntax:prefix_expr(erl_syntax:operator('bnot'), Ast).

ast('*' = Op, Ast1, Ast2) ->
  {op, 1, Op, Ast1, Ast2};
ast('**', Ast1, Ast2) ->
  {call,1,{remote,1,{atom,1,math},{atom,1,pow}},[Ast1, Ast2]};
ast('/' = Op, Ast1, Ast2) ->
  {op, 1, Op, Ast1, Ast2};
ast('+' = Op, Ast1, Ast2) ->
  {op, 1, Op, Ast1, Ast2};
ast('-' = Op, Ast1, Ast2) ->
  {op, 1, Op, Ast1, Ast2}.


-module(rabbit_auth_backend_kerberos).

-include_lib("rabbit_common/include/rabbit.hrl").
-behaviour(rabbit_auth_backend).

-export([description/0, check_user_login/2, check_vhost_access/2, check_resource_access/3]).

description() ->
  [{name, <<"Kerberos">>},
    {description, <<"Kerberos authentication">>}].

check_user_login(Username, AuthProps) ->
  true.

check_vhost_access(#user{username = Username}, VHost) ->
  true.

check_resource_access(#user{username = Username},
  #resource{virtual_host = VHost, kind = Type, name = Name},
  Permission) ->
  true.

Use correct reply for check_user_login

-module(rabbit_auth_backend_kerberos).

-include_lib("rabbit_common/include/rabbit.hrl").
-behaviour(rabbit_auth_backend).

-export([description/0, check_user_login/2, check_vhost_access/2, check_resource_access/3]).

description() ->
  [{name, <<"Kerberos">>},
    {description, <<"Kerberos authentication">>}].

check_user_login(Username, AuthProps) ->
  {'ok', Username}.

check_vhost_access(#user{username = Username}, VHost) ->
  true.

check_resource_access(#user{username = Username},
  #resource{virtual_host = VHost, kind = Type, name = Name},
  Permission) ->
  true.


-module(mousetrap_app_tests).

-include_lib("eunit/include/eunit.hrl").

fixture_startup_test() ->
  application:set_env(mousetrap, slack_token, "test_token"),
  meck:expect(notification_library, notify, 1, {ok, 200, [long_list]}).

startup_message_sent_test() ->
  mousetrap_app:start("", ""),
  ?assert(meck:called(notification_library, notify, ["Mousetrap starting"])).

Test start of mousetrap supervisor.

-module(mousetrap_app_tests).

-include_lib("eunit/include/eunit.hrl").

fixture_startup_test() ->
  application:set_env(mousetrap, slack_token, "test_token"),
  meck:expect(notification_library, notify, 1, {ok, 200, [long_list]}),
  meck:expect(mousetrap_sup, start_link, 0, {ok, pid}).

start_sends_notification_test() ->
  mousetrap_app:start("", ""),
  ?assert(meck:called(notification_library, notify, ["Mousetrap starting"])).

start_starts_mousetrap_supervisor_test() ->
  ?assert(meck:called(mousetrap_sup, start_link, [])).

fixture_teardown_test() ->
  meck:unload().


% vim: sw=4 ts=4 et ft=erlang
% Nitrogen Web Framework for Erlang
% See MIT-LICENSE for licensing information.

-module (element_time).
-include("wf.hrl").
-export([
    reflect/0,
    render_element/1
]).

-spec reflect() -> [atom()].
reflect() -> record_info(fields, time).

-spec render_element(#time{}) -> body().
render_element(Record) ->
    Text = wf:html_encode(Record#time.text, Record#time.html_encode),
    wf_tags:emit_tag(time, [Text, Record#time.body], [
        {id, Record#time.html_id},
        {class, ["time", Record#time.class]},
        {title, Record#time.title},
        {style, Record#time.style},
        {role, Record#time.role},
        {data_fields, Record#time.data_fields},
        ?WF_IF(Record#time.datetime, {datetime, Record#time.datetime})
    ]).

Change to the way time is outputed

% vim: sw=4 ts=4 et ft=erlang
% Nitrogen Web Framework for Erlang
% See MIT-LICENSE for licensing information.

-module (element_time).
-include("wf.hrl").
-export([
    reflect/0,
    render_element/1
]).

-spec reflect() -> [atom()].
reflect() -> record_info(fields, time).

-spec render_element(#time{}) -> body().
render_element(Record) ->
    Text = wf:html_encode(Record#time.text, Record#time.html_encode),
    wf_tags:emit_tag(input, [Text, Record#time.body], [
        {type, time},
        {id, Record#time.html_id},
        {class, ["time", Record#time.class]},
        {title, Record#time.title},
        {style, Record#time.style},
        {role, Record#time.role},
        {data_fields, Record#time.data_fields},
        ?WF_IF(Record#time.datetime, {datetime, Record#time.datetime})
    ]).


-module(erlcfg_data, [Node]).
-export([
        raw/0,
        get/1
    ]).

raw() ->
    Node.

get(Key) ->
    erlcfg_node:get(Node, Key).

Convert <<"A string as binary">> back into "A string as binary"

-module(erlcfg_data, [Node]).
-export([
        raw/0,
        get/1
    ]).

raw() ->
    Node.

get(Key) ->
    convert(erlcfg_node:get(Node, Key)).

convert({value, Value}) when is_binary(Value) ->
    {value, binary_to_list(Value)};

convert(Value) ->
    Value.


%% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
%% ex: ts=4 sw=4 et

-module(rebar_prv_state).

-behaviour(provider).

-export([init/1,
         do/1,
         format_error/1]).

-include("rebar.hrl").

-define(PROVIDER, state).
-define(DEPS, []).

%% ===================================================================
%% Public API
%% ===================================================================

-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
    Provider = providers:create(
        [{name, ?PROVIDER},
         {module, ?MODULE},
         {bare, true},
         {deps, ?DEPS},
         {example, "rebar3 state"},
         {short_desc, "Print current configuration state"},
         {desc, "Display rebar configuration for debugging purpose"},
         {opts, []}]),
    State1 = rebar_state:add_provider(State, Provider),
    {ok, State1}.

-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State) ->
    L = rebar_state:to_list(State),
    ?CONSOLE("State:", []),
    [?CONSOLE("  ~w: ~p", [K, V]) || {K,V} <- L],
    {ok, State}.

-spec format_error(any()) -> iolist().
format_error(Reason) ->
    io_lib:format("~p", [Reason]).

Make state provider {bare, false}

%% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
%% ex: ts=4 sw=4 et

-module(rebar_prv_state).

-behaviour(provider).

-export([init/1,
         do/1,
         format_error/1]).

-include("rebar.hrl").

-define(PROVIDER, state).
-define(DEPS, []).

%% ===================================================================
%% Public API
%% ===================================================================

-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
    Provider = providers:create(
        [{name, ?PROVIDER},
         {module, ?MODULE},
         {bare, false},
         {deps, ?DEPS},
         {example, "rebar3 state"},
         {short_desc, "Print current configuration state"},
         {desc, "Display rebar configuration for debugging purpose"},
         {opts, []}]),
    State1 = rebar_state:add_provider(State, Provider),
    {ok, State1}.

-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State) ->
    L = rebar_state:to_list(State),
    ?CONSOLE("State:", []),
    [?CONSOLE("  ~w: ~p", [K, V]) || {K,V} <- L],
    {ok, State}.

-spec format_error(any()) -> iolist().
format_error(Reason) ->
    io_lib:format("~p", [Reason]).


-module(service_goldenage_userinfo).
-svc_needauth(true).

-export([process_get/2, info/2]).

-include_lib("zotonic.hrl").

process_get(_, Context) ->
    info(Context#context.user_id, Context).

info(UserId, Context) ->
    ga_util:rsc_json(UserId, [title, email, image], Context).

Add liked cards to user info

-module(service_goldenage_userinfo).
-svc_needauth(true).

-export([process_get/2, info/2]).

-include_lib("zotonic.hrl").

process_get(_, Context) ->
    info(Context#context.user_id, Context).

info(UserId, Context) ->
    ga_util:rsc_json(UserId, [title, email, image, {edge, likes}], Context).


-module(sd_notify_test).

-include_lib("eunit/include/eunit.hrl").

sd_notify_test_() ->
	sd_notify_test_local(erlang:system_info(otp_release)).

sd_notify_test_local("19") ->
	{ok, CWD} = file:get_cwd(),
	FakeNotifyUnixSockName = CWD ++ "/fake-notify-udp-sock-" ++ integer_to_list(erlang:phash2(make_ref())),
	TestMessage = integer_to_list(erlang:phash2(make_ref())),
	{ok, FakeNotifyUnixSock} = gen_udp:open(0, [{ifaddr, {local, FakeNotifyUnixSockName}}, {active, false}, list]),
	os:putenv("NOTIFY_SOCKET", FakeNotifyUnixSockName),

	{setup,
		fun() -> ok end,
		fun(_) -> ok = gen_udp:close(FakeNotifyUnixSock), ok = file:delete(FakeNotifyUnixSockName)  end,
		[
			{
				"Try sending message",
				fun() ->
					sd_notify:sd_pid_notify_with_fds(0, 0, TestMessage, [1, 2, 3]),
					{ok, {_Address, _Port, Packet}} = gen_udp:recv(FakeNotifyUnixSock, length(TestMessage), 1000),
					?assertEqual(TestMessage, Packet)
				end
			}

		]

	};
sd_notify_test_local(_) ->
	[].

Move test message creation to where it belongs

-module(sd_notify_test).

-include_lib("eunit/include/eunit.hrl").

sd_notify_test_() ->
	sd_notify_test_local(erlang:system_info(otp_release)).

sd_notify_test_local("19") ->
	{ok, CWD} = file:get_cwd(),
	FakeNotifyUnixSockName = CWD ++ "/fake-notify-udp-sock-" ++ integer_to_list(erlang:phash2(make_ref())),
	{ok, FakeNotifyUnixSock} = gen_udp:open(0, [{ifaddr, {local, FakeNotifyUnixSockName}}, {active, false}, list]),
	os:putenv("NOTIFY_SOCKET", FakeNotifyUnixSockName),

	{setup,
		fun() -> ok end,
		fun(_) -> ok = gen_udp:close(FakeNotifyUnixSock), ok = file:delete(FakeNotifyUnixSockName)  end,
		[
			{
				"Try sending message",
				fun() ->
					TestMessage = integer_to_list(erlang:phash2(make_ref())),
					sd_notify:sd_pid_notify_with_fds(0, 0, TestMessage, [1, 2, 3]),
					{ok, {_Address, _Port, Packet}} = gen_udp:recv(FakeNotifyUnixSock, length(TestMessage), 1000),
					?assertEqual(TestMessage, Packet)
				end
			}

		]

	};
sd_notify_test_local(_) ->
	[].


-module(escalus_story).

% Public API
-export([story/3]).

-include_lib("test_server/include/test_server.hrl").

%%--------------------------------------------------------------------
%% Public API
%%--------------------------------------------------------------------

story(Config, ResourceCounts, Test) ->
    UserSpecs = escalus_users:get_users(all),
    Clients = [start_clients(Config, UserSpec, ResCount) ||
               {{_, UserSpec}, ResCount} <- lists:zip(UserSpecs,
                                                 ResourceCounts)],
    ClientList = lists:flatten(Clients),
    prepare_clients(Config, ClientList),
    apply(Test, ClientList).

%%--------------------------------------------------------------------
%% Helpers
%%--------------------------------------------------------------------

start_clients(Config, UserSpec, ResourceCount) ->
    [start_client(Config, UserSpec, ResNo) ||
     ResNo <- lists:seq(1, ResourceCount)].

start_client(Config, UserSpec, ResNo) ->
    escalus_client:start_wait(Config, UserSpec,
                              "res" ++ integer_to_list(ResNo)).

prepare_clients(Config, ClientList) ->
    case proplists:get_bool(escalus_save_initial_history, Config) of
        true ->
            do_nothing;
        false ->
            lists:foreach(fun escalus_client:drop_history/1, ClientList)
    end.

Add random tail to client's resources

-module(escalus_story).

% Public API
-export([story/3]).

-include_lib("test_server/include/test_server.hrl").

%%--------------------------------------------------------------------
%% Public API
%%--------------------------------------------------------------------

story(Config, ResourceCounts, Test) ->
    UserSpecs = escalus_users:get_users(all),
    Clients = [start_clients(Config, UserSpec, ResCount) ||
               {{_, UserSpec}, ResCount} <- lists:zip(UserSpecs,
                                                 ResourceCounts)],
    ClientList = lists:flatten(Clients),
    prepare_clients(Config, ClientList),
    apply(Test, ClientList).

%%--------------------------------------------------------------------
%% Helpers
%%--------------------------------------------------------------------

start_clients(Config, UserSpec, ResourceCount) ->
    [start_client(Config, UserSpec, ResNo) ||
     ResNo <- lists:seq(1, ResourceCount)].

start_client(Config, UserSpec, ResNo) ->
    RandPart = base64:encode_to_string(crypto:rand_bytes(10)),
    Res = "res" ++ integer_to_list(ResNo) ++ "-" ++ RandPart,
    escalus_client:start_wait(Config, UserSpec, Res).

prepare_clients(Config, ClientList) ->
    case proplists:get_bool(escalus_save_initial_history, Config) of
        true ->
            do_nothing;
        false ->
            lists:foreach(fun escalus_client:drop_history/1, ClientList)
    end.


%% -------------------------------------------------------------------
%%
%% riak_bench: Benchmarking Suite for Riak
%%
%% Copyright (c) 2009 Basho Techonologies
%%
%% This file is provided to you under the Apache License,
%% Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License.  You may obtain
%% a copy of the License at
%%
%%   http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing,
%% software distributed under the License is distributed on an
%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied.  See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(riak_bench_keygen).

-export([new/2,
         dimension/1]).

-include("riak_bench.hrl").

%% ====================================================================
%% API
%% ====================================================================

new({uniform_int, MaxKey}, _Id) ->
    fun() -> Key = random:uniform(MaxKey), <<Key:32/native>> end;
new(Other, _Id) ->
    ?FAIL_MSG("Unsupported key generator requested: ~p\n", [Other]).

dimension({uniform_int, MaxKey}) ->
    MaxKey;
dimension(Other) ->
    ?FAIL_MSG("Unsupported key generator dimension requested: ~p\n", [Other]).

Add non-binary encode uniform int keygen

%% -------------------------------------------------------------------
%%
%% riak_bench: Benchmarking Suite for Riak
%%
%% Copyright (c) 2009 Basho Techonologies
%%
%% This file is provided to you under the Apache License,
%% Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License.  You may obtain
%% a copy of the License at
%%
%%   http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing,
%% software distributed under the License is distributed on an
%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied.  See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(riak_bench_keygen).

-export([new/2,
         dimension/1]).

-include("riak_bench.hrl").

%% ====================================================================
%% API
%% ====================================================================

new({uniform_int_bin, MaxKey}, _Id) ->
    fun() -> Key = random:uniform(MaxKey), <<Key:32/native>> end;
new({uniform_int, MaxKey}, _Id) ->
    fun() -> random:uniform(MaxKey) end;
new(Other, _Id) ->
    ?FAIL_MSG("Unsupported key generator requested: ~p\n", [Other]).

dimension({uniform_int_bin, MaxKey}) ->
    MaxKey;
dimension({uniform_int, MaxKey}) ->
    MaxKey;
dimension(Other) ->
    ?FAIL_MSG("Unsupported key generator dimension requested: ~p\n", [Other]).


%% Calculate score for bowling game
%% Assumes valid and complete input
-module(game_happy).
-export([score/1]).

score(Rolls) -> frame(Rolls, 1, 0).

% Game complete.
frame(_BonusRolls, 11, Score) -> Score;

%% Strike.
frame([10|Rest], Frame, Score) ->
    frame(Rest, Frame + 1, Score + 10 + strike_bonus(Rest));

%% Spare.
frame([First,Second|Rest], Frame, Score) when (First + Second == 10) ->
    frame(Rest, Frame + 1, Score + 10 + spare_bonus(Rest));

%% Normal.
frame([First,Second|Rest], Frame, Score) ->
    frame(Rest, Frame + 1, Score + First + Second).

%% spare & strike bonus calculations.
spare_bonus([First|_Rest]) -> First.
strike_bonus([First,Second|_Rest]) -> First + Second.

Change parameter order to match Erlang idiom

%% Calculate score for bowling game
%% Assumes valid and complete input
-module(game_happy).
-export([score/1]).

score(Rolls) -> frame(1, 0, Rolls).

% Game complete.
frame(11, Score, _BonusRolls) -> Score;

%% Strike.
frame(Frame, Score, [10|Rest]) ->
    frame(Frame + 1, Score + 10 + strike_bonus(Rest), Rest);

%% Spare.
frame(Frame, Score, [First,Second|Rest]) when (First + Second == 10) ->
    frame(Frame + 1, Score + 10 + spare_bonus(Rest), Rest);

%% Normal.
frame(Frame, Score, [First,Second|Rest]) ->
    frame(Frame + 1, Score + First + Second, Rest).

%% spare & strike bonus calculations.
spare_bonus([First|_Rest]) -> First.
strike_bonus([First,Second|_Rest]) -> First + Second.


% Licensed under the Apache License, Version 2.0 (the "License"); you may not
% use this file except in compliance with the License. You may obtain a copy of
% the License at
%
%   http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
% License for the specific language governing permissions and limitations under
% the License.

% This is named couch_event_sup2 to avoid
% naming collisions with the couch_event_sup
% module contained in the couch app. When
% that supervisor is removed we'll be free
% to rename this one.

-module(couch_event_sup2).
-behavior(supervisor).

-export([
    start_link/0,
    init/1
]).

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, nil).

init(_) ->
    Children = [
        {couch_event_registry,
            {couch_event_registry, start_link, []},
            permanent,
            5000,
            worker,
            [couch_event_register]
        },
        {couch_event_dist,
            {couch_event_dist, start_link, []},
            permanent,
            5000,
            worker,
            [couch_event_dist]
        }
    ],
    {ok, {{one_for_one, 5, 10}, Children}}.

Fix callback module name for couch_event_registry

% Licensed under the Apache License, Version 2.0 (the "License"); you may not
% use this file except in compliance with the License. You may obtain a copy of
% the License at
%
%   http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
% License for the specific language governing permissions and limitations under
% the License.

% This is named couch_event_sup2 to avoid
% naming collisions with the couch_event_sup
% module contained in the couch app. When
% that supervisor is removed we'll be free
% to rename this one.

-module(couch_event_sup2).
-behavior(supervisor).

-export([
    start_link/0,
    init/1
]).

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, nil).

init(_) ->
    Children = [
        {couch_event_registry,
            {couch_event_registry, start_link, []},
            permanent,
            5000,
            worker,
            [couch_event_registry]
        },
        {couch_event_dist,
            {couch_event_dist, start_link, []},
            permanent,
            5000,
            worker,
            [couch_event_dist]
        }
    ],
    {ok, {{one_for_one, 5, 10}, Children}}.


%%%-------------------------------------------------------------------
%%% @copyright (C) 2017, Aeternity Anstalt
%%% @doc
%%% ADT for keeping the state of contracts
%%% @end
%%%-------------------------------------------------------------------

-module(aect_state_tree).

%% API
-export([ empty/0
        , insert_contract/2
        , root_hash/1]).

-export_type([tree/0]).

%%%===================================================================
%%% Types
%%%===================================================================

-type contract_tree() :: aeu_mtrees:tree(aect_contracts:id(), aect_contracts:serialized()).
-type call_tree()     :: aeu_mtrees:tree(aect_call:id(), aect_call:serialized()).
-type call_trees()    :: gb_trees:tree(aect_contracts:id(), call_tree()).

-record(contract_tree, {
    contracts = aeu_mtrees:empty() :: contract_tree(),
    calls     = gb_trees:empty()   :: call_trees()
        %% Keep calls in separate trees to avoid having to serialize/deserialize the
        %% entire call history every time we're adding a call.
    }).

-opaque tree() :: #contract_tree{}.

%%%===================================================================
%%% API
%%%===================================================================

-spec empty() -> tree().
empty() ->
    #contract_tree{}.

-spec insert_contract(aect_contracts:contract(), tree()) -> tree().
insert_contract(_Contract, Tree) ->
    %% PLACEHOLDER
    Tree.

-spec root_hash(tree()) -> {ok, aeu_mtrees:root_hash()} | {error, empty}.
root_hash(#contract_tree{contracts = CtTree}) ->
    %% The contract tree references the hashes of the call trees so we only
    %% need the hash of the contract tree here.
    aeu_mtrees:root_hash(CtTree).


-module(unicode_helpers).

-export([normalize_unicode/1]).

% Convert strange unicode character like e' to é
normalize_unicode(Input) -> unicode:characters_to_list(binary:list_to_bin(Input), unicode).

Add boilerplate on top of the file.

%%
%%  U.C.Engine - Unified Colloboration Engine
%%  Copyright (C) 2011 af83
%%
%%  This program is free software: you can redistribute it and/or modify
%%  it under the terms of the GNU Affero General Public License as published by
%%  the Free Software Foundation, either version 3 of the License, or
%%  (at your option) any later version.
%%
%%  This program is distributed in the hope that it will be useful,
%%  but WITHOUT ANY WARRANTY; without even the implied warranty of
%%  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%%  GNU Affero General Public License for more details.
%%
%%  You should have received a copy of the GNU Affero General Public License
%%  along with this program.  If not, see <http://www.gnu.org/licenses/>.
%%
-module(unicode_helpers).

-export([normalize_unicode/1]).

% Convert strange unicode character like e' to é
normalize_unicode(Input) -> unicode:characters_to_list(binary:list_to_bin(Input), unicode).


-module(frontend_app).
-behaviour(application).

%% API.
-export([start/2]).
-export([stop/1]).

%% API.

start(_Type, _Args) ->
	Dispatch = frontend:dispatchers(),
	{ok, _} = cowboy:start_http(http, 100, [{port, 8080}], [
		{env, [{dispatch, Dispatch}]}
	]),
    frontend_sup:start_link().

stop(_State) ->
	ok.

Use the application variable instead of hard coding the port.

-module(frontend_app).
-behaviour(application).

%% API.
-export([start/2]).
-export([stop/1]).

%% API.

start(_Type, _Args) ->
	Dispatch = frontend:dispatchers(),
	{ok, Port} = application:get_env(port),
	{ok, _} = cowboy:start_http(http, 100, [{port, Port}], [
		{env, [{dispatch, Dispatch}]}
	]),
    frontend_sup:start_link().

stop(_State) ->
	ok.


-module(boss_compiler_adapter_lfe).
-compile(export_all).

file_extensions() -> ["lfe"].

controller_module(AppName, Controller) -> lists:concat([AppName, "_", Controller, "_controller"]).

module_name_for_file(_AppName, File) -> filename:basename(File, ".lfe").

compile_controller(File, Options) ->
    do_compile(File, Options).

compile(File, Options) ->
    do_compile(File, Options).

do_compile(File, Options) ->
    case lfe_comp:file(File, lfe_compiler_options(Options)) of
        {ok, Module, _Warnings} ->
            {ok, Module};
        Other ->
            Other
    end.

lfe_compiler_options(Options) ->
    CompilerOptions = [verbose, return, proplists:get_value(compiler_options, Options, [])],
    case proplists:get_value(out_dir, Options) of
        undefined -> CompilerOptions;
        OutDir -> [{outdir, OutDir} | CompilerOptions]
    end.

Write BEAM files in dev mode to /tmp

-module(boss_compiler_adapter_lfe).
-compile(export_all).

file_extensions() -> ["lfe"].

controller_module(AppName, Controller) -> lists:concat([AppName, "_", Controller, "_controller"]).

module_name_for_file(_AppName, File) -> filename:basename(File, ".lfe").

compile_controller(File, Options) ->
    do_compile(File, Options).

compile(File, Options) ->
    do_compile(File, Options).

do_compile(File, Options) ->
    {OutFile, CompilerOptions} = lfe_compiler_options(File, Options),
    case lfe_comp:file(File, CompilerOptions) of
        {ok, Module, _Warnings} ->
            io:format("Loading ~p~n", [OutFile]),
            {module, Module} = code:load_abs(OutFile),
            {ok, Module};
        Other ->
            Other
    end.

lfe_compiler_options(File, Options) ->
    CompilerOptions = [verbose, return, proplists:get_value(compiler_options, Options, [])],
    WriteDir = case proplists:get_value(out_dir, Options) of
        undefined -> "/tmp";
        Dir -> Dir
    end,
    WriteFile = filename:join([WriteDir, filename:basename(File, ".lfe")]),
    {WriteFile, [{outdir, WriteDir}|CompilerOptions]}.


%% ------------------------------------------------------------------
%%
%% Copyright (c) 2011 Basho Technologies, Inc.
%%
%% This file is provided to you under the Apache License,
%% Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License.  You may obtain
%% a copy of the License at
%%
%%   http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing,
%% software distributed under the License is distributed on an
%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied.  See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% ------------------------------------------------------------------
%%
%% @doc Application.

-module(riak_control_app).

-behaviour(application).

%% Application callbacks
-export([start/2,
         stop/1]).

%% ==================================================================
%% Application callbacks
%% ==================================================================

start(_StartType, _StartArgs) ->
    case riak_control_sup:start_link() of
        {error, Reason} ->
            {error, Reason};
        {ok, Pid} ->
            riak_core_capability:register({riak_control, member_info_version},
                                          [v0, v1],
                                          v0),
            {ok, Pid}
    end.

stop(_State) ->
    ok.

Resolve incorrect capability negotation order.

%% ------------------------------------------------------------------
%%
%% Copyright (c) 2011 Basho Technologies, Inc.
%%
%% This file is provided to you under the Apache License,
%% Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License.  You may obtain
%% a copy of the License at
%%
%%   http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing,
%% software distributed under the License is distributed on an
%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied.  See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% ------------------------------------------------------------------
%%
%% @doc Application.

-module(riak_control_app).

-behaviour(application).

%% Application callbacks
-export([start/2,
         stop/1]).

%% ==================================================================
%% Application callbacks
%% ==================================================================

start(_StartType, _StartArgs) ->
    case riak_control_sup:start_link() of
        {error, Reason} ->
            {error, Reason};
        {ok, Pid} ->
            riak_core_capability:register({riak_control, member_info_version},
                                          [v1, v0],
                                          v0),
            {ok, Pid}
    end.

stop(_State) ->
    ok.


-module(builderl_build_handler).
-behaviour(cowboy_handler).
-compile({parse_transform, lager_transform}).

-export([init/2]).

init(Req0=#{method := <<"GET">>}, State) ->
    Org = cowboy_req:binding(org, Req0),
    Repo = cowboy_req:binding(repo, Req0),
    lager:info("Org/Repo ~p/~p", [Org, Repo]),
    Project = string:join([binary:bin_to_list(Org), binary:bin_to_list(Repo)], "/"),
    {ok, [BuildID| _]} = builderl_build_registry:get_builds(Project),
    lager:info("build ~p", [BuildID]),
    {ok, Objects} = builderl_build_registry:get_build(Project, BuildID),
    {ok, Logs} = builderl:get_build_logs(Project, BuildID),
    lager:info("Objects ~p", [Objects]),
    _Data = jsx:encode(#{logs => Logs}),
    Reply = cowboy_req:reply(200,
        #{<<"content-type">> => <<"text/plain">>},
        Logs,
        Req0),
    {ok, Reply, State}.

Use build ID to get logs

-module(builderl_build_handler).
-behaviour(cowboy_handler).
-compile({parse_transform, lager_transform}).

-export([init/2]).

init(Req0=#{method := <<"GET">>}, State) ->
    Org = cowboy_req:binding(org, Req0),
    Repo = cowboy_req:binding(repo, Req0),
    BuildID = binary:bin_to_list(cowboy_req:binding(build, Req0)),
    lager:info("Org/Repo ~p/~p", [Org, Repo]),
    Project = string:join([binary:bin_to_list(Org), binary:bin_to_list(Repo)], "/"),
    lager:info("build ~p", [BuildID]),
    {ok, Objects} = builderl_build_registry:get_build(Project, BuildID),
    {ok, Logs} = builderl:get_build_logs(Project, BuildID),
    lager:info("Objects ~p", [Objects]),
    _Data = jsx:encode(#{logs => Logs}),
    Reply = cowboy_req:reply(200,
        #{<<"content-type">> => <<"text/plain">>},
        Logs,
        Req0),
    {ok, Reply, State}.


%%%-------------------------------------------------------------------
%%% This file is part of the CernVM File System.
%%%
%%% @doc cvmfs_fe - CVMFS repo services HTTP front-end
%%%
%%% @end
%%%-------------------------------------------------------------------

-module(cvmfs_fe).

-export([start_link/1, api_version/0]).

-define(API_VERSION, 1).
-define(API_ROOT, "/api/v" ++ integer_to_list(?API_VERSION)).

%%--------------------------------------------------------------------
%% @doc
%% Starts the front-end HTTP listener process.
%%
%% @end
%%--------------------------------------------------------------------
start_link([TcpPort]) ->
    %% Compile a routing table, for dispatching requests for different resources
    %% to a set of handler modules. The handler modules implement the init/2 callback
    %% required by Cowboy
    Dispatch = cowboy_router:compile([{'_', [
                                             {?API_ROOT, cvmfs_root_handler, []},
                                             {?API_ROOT ++ "/repos/[:id]", cvmfs_repos_handler, []},
                                             {?API_ROOT ++ "/leases/[:token]", cvmfs_leases_handler, []},
                                             {?API_ROOT ++ "/payloads/[:id]", cvmfs_payloads_handler, []}
                                            ]}]),
    %% Start the HTTP listener process configured with the routing table
    %% TODO: Port and other parameters should not be hard-coded and should moved to
    %%       the release configuration file
    cowboy:start_clear(cvmfs_fe, 100,
                       [{port, TcpPort}],
                       #{env => #{dispatch => Dispatch}}).

-spec api_version() -> integer().
api_version() ->
    ?API_VERSION.

Fix compilation for Cowboy 2.0.0-rc.1

%%%-------------------------------------------------------------------
%%% This file is part of the CernVM File System.
%%%
%%% @doc cvmfs_fe - CVMFS repo services HTTP front-end
%%%
%%% @end
%%%-------------------------------------------------------------------

-module(cvmfs_fe).

-export([start_link/1, api_version/0]).

-define(API_VERSION, 1).
-define(API_ROOT, "/api/v" ++ integer_to_list(?API_VERSION)).

%%--------------------------------------------------------------------
%% @doc
%% Starts the front-end HTTP listener process.
%%
%% @end
%%--------------------------------------------------------------------
start_link([TcpPort]) ->
    %% Compile a routing table, for dispatching requests for different resources
    %% to a set of handler modules. The handler modules implement the init/2 callback
    %% required by Cowboy
    Dispatch = cowboy_router:compile([{'_', [
                                             {?API_ROOT, cvmfs_root_handler, []},
                                             {?API_ROOT ++ "/repos/[:id]", cvmfs_repos_handler, []},
                                             {?API_ROOT ++ "/leases/[:token]", cvmfs_leases_handler, []},
                                             {?API_ROOT ++ "/payloads/[:id]", cvmfs_payloads_handler, []}
                                            ]}]),
    %% Start the HTTP listener process configured with the routing table
    cowboy:start_clear(cvmfs_fe,
                       [{port, TcpPort}],
                       #{env => #{dispatch => Dispatch}}).

-spec api_version() -> integer().
api_version() ->
    ?API_VERSION.


-module(etorrent_endgame).
-behaviour(gen_server).

%% gen_server callbacks
-export([init/1,
        handle_call/3,
        handle_cast/2,
        handle_info/2,
        terminate/2,
        code_change/3]).

init('_') -> ok.
handle_call('_', '_', '_') -> ok.
handle_cast('_', '_') -> ok.
handle_info('_', '_') -> ok.
terminate('_', '_') -> ok.
code_change('_', '_', '_') -> ok.

Add register_peer callback to endgame server

-module(etorrent_endgame).
-behaviour(gen_server).

%% gen_server callbacks
-export([init/1,
        handle_call/3,
        handle_cast/2,
        handle_info/2,
        terminate/2,
        code_change/3]).

init('_') -> ok.

handle_call({register_peer, Pid}, _, State) ->
    %% Initialize peer data structures
    {reply, ok, State}.

handle_cast('_', '_') -> ok.
handle_info('_', '_') -> ok.
terminate('_', '_') -> ok.
code_change('_', '_', '_') -> ok.


-module(erlcfg_schema_analyser1).
-include("schema.hrl").
-export([analyse/1]).

analyse([]) ->
    ?DEFAULT_TYPE_MAP;
analyse([Head|Rest]) ->
    Types = ?DEFAULT_TYPE_MAP,
    analyse(Head, Rest, Types).

analyse(Current, [Head|Rest], Types0) ->
    Types1 = eval(Current, Types0),
    analyse(Head, Rest, Types1);

analyse(Current, [], Types0) ->
    Types1 = eval(Current, Types0),
    Types1.

eval(#typedef{name=Name, options=OptionAst}, Types) ->
    Options = cons(OptionAst),
    [{Name, Options}|Types];
eval(_Other, Types) ->
    Types.

cons(#cons{}=Cons) ->
    cons(Cons, []).

cons(#cons{head=Head, tail=nil}, Accm) ->
    lists:reverse([Head|Accm]);
cons(#cons{head=Head, tail=Tail}, Accm) ->
    cons(Tail, [Head|Accm]).

Build a proper validator for type defs

-module(erlcfg_schema_analyser1).
-include("schema.hrl").
-export([analyse/1]).

analyse([]) ->
    ?DEFAULT_TYPE_MAP;
analyse([Head|Rest]) ->
    Types = ?DEFAULT_TYPE_MAP,
    analyse(Head, Rest, Types).

analyse(Current, [Head|Rest], Types0) ->
    Types1 = eval(Current, Types0),
    analyse(Head, Rest, Types1);

analyse(Current, [], Types0) ->
    Types1 = eval(Current, Types0),
    Types1.

eval(#typedef{name=Name, options=OptionAst}, Types) ->
    Options = cons(OptionAst),
    Fun = fun(Val) ->
            lists:member(Val, Options)
    end,
    TypeTest = #type_test{type=Name, test=Fun},
    [{Name, TypeTest}|Types];
eval(_Other, Types) ->
    Types.

cons(#cons{}=Cons) ->
    cons(Cons, []).

cons(#cons{head=Head, tail=nil}, Accm) ->
    lists:reverse([Head|Accm]);
cons(#cons{head=Head, tail=Tail}, Accm) ->
    cons(Tail, [Head|Accm]).


-define(ertsvsn,"4.4").
-define(kernelvsn,"2.14.3").
-define(stdlibvsn,"1.17.3").

Update "old vsn" in sasl test to R15 instead of R14 (two back from R17)


%% ``The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved via the world wide web at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
%% AB. All Rights Reserved.''
%%
%%     $Id$
%%
-module(docb_SUITE).

-export([all/1,html/1]).

-include("test_server.hrl").

-include_lib("kernel/include/file.hrl").

all(suite) -> [html].

html(suite) -> [];
html(Config) when is_list(Config) ->
    ok.

Update docbuilder tests to conform with common_test standard

%% ``The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved via the world wide web at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
%% AB. All Rights Reserved.''
%%
%%     $Id$
%%
-module(docb_SUITE).

-export([all/0,groups/0,init_per_group/2,end_per_group/2,html/1]).

-include_lib("common_test/include/ct.hrl").

-include_lib("kernel/include/file.hrl").

all() ->
[html].

groups() ->
    [].

init_per_group(_GroupName, Config) ->
	Config.

end_per_group(_GroupName, Config) ->
	Config.

html(suite) -> [];
html(Config) when is_list(Config) ->
    ok.


-module(beamjs_repl_console).

-export([read/1,print/1]).

read(Prompt) ->
	io:get_line(Prompt).

print({finished, Result}) ->
	io:format(">>> ~p~n",[Result]);
print({exception, Exception}) ->
	io:format("    Exception: ~p~n",[Exception]).

Make copying results off console REPL easier

-module(beamjs_repl_console).

-export([read/1,print/1]).

read(Prompt) ->
	io:get_line(Prompt).

print({finished, Result}) ->
	io:format("~p~n",[Result]);
print({exception, Exception}) ->
	io:format("    Exception: ~p~n",[Exception]).


-module(starter_tests).
-include_lib("eunit/include/eunit.hrl").
-export([name_service/0]).

name_service() ->
  receive
    terminate -> ok
  end.

withRedefedNameService(Name) ->
  PID = spawn(?MODULE, name_service, []),
  yes = global:register_name(Name, PID),
  PID.

logging_test() ->
  Expected = list_to_atom(lists:concat(["ggt42@", atom_to_list(node()), ".log"])),
  ?assert(Expected =:= starter:log([{starterid, 42}], ["foobar"])).

bind_nameService_test() ->
  Expected = withRedefedNameService(foobar),
  ?assertEqual(Expected, starter:bind_nameservice([{starterid, 42}, {nameservicenode, node()}, {nameservicename, foobar}])),
  Expected ! terminate.

%%simple_test() ->
%%  werkzeug:ensureNameserviceStarted(),
%%  koordinator:start("./test-config/koordinator.cfg"),
%%  StarterNumber = list_to_atom(integer_to_list(1)),
%%  starter:start(StarterNumber),
%%  ClientName = list_to_atom(lists:append(integer_to_list(4881), "1")),
%%  ClientName ! {setpm, 3456},
%%  ClientName ! {self(), tellmi},
%%  receive
%%    {mi, Mi} -> ?assert(Mi =:= 3456)
%%  end
%%.

Rename bind name service function

-module(starter_tests).
-include_lib("eunit/include/eunit.hrl").
-export([name_service/0]).

name_service() ->
  receive
    terminate -> ok
  end.

withRedefedNameService(Name) ->
  PID = spawn(?MODULE, name_service, []),
  yes = global:register_name(Name, PID),
  PID.

logging_test() ->
  Expected = list_to_atom(lists:concat(["ggt42@", atom_to_list(node()), ".log"])),
  ?assert(Expected =:= starter:log([{starterid, 42}], ["foobar"])).

bind_name_service_test() ->
  Expected = withRedefedNameService(foobar),
  ?assertEqual(Expected, starter:bind_nameservice([{starterid, 42}, {nameservicenode, node()}, {nameservicename, foobar}])),
  Expected ! terminate.

%%simple_test() ->
%%  werkzeug:ensureNameserviceStarted(),
%%  koordinator:start("./test-config/koordinator.cfg"),
%%  StarterNumber = list_to_atom(integer_to_list(1)),
%%  starter:start(StarterNumber),
%%  ClientName = list_to_atom(lists:append(integer_to_list(4881), "1")),
%%  ClientName ! {setpm, 3456},
%%  ClientName ! {self(), tellmi},
%%  receive
%%    {mi, Mi} -> ?assert(Mi =:= 3456)
%%  end
%%.


%% -*- erlang-indent-level: 4;indent-tabs-mode: nil; fill-column: 92-*-
%% ex: ts=4 sw=4 et
%% @author James Casey <james@opscode.com>
%% @copyright 2012 Opscode, Inc.

%% @doc Handle org_name to org_guid mappings by calling out to
%% opscode-account
-module(pushy_org).

-define(POC_ORG_ID, <<"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">>).

-export([
          fetch_org_id/1
        ]).

%% Stub it out for now
-spec fetch_org_id(OrgName :: string()) -> binary().
fetch_org_id(_OrgName) ->
  ?POC_ORG_ID.

Update the spec for fetch_org_id

%% -*- erlang-indent-level: 4;indent-tabs-mode: nil; fill-column: 92-*-
%% ex: ts=4 sw=4 et
%% @author James Casey <james@opscode.com>
%% @copyright 2012 Opscode, Inc.

%% @doc Handle org_name to org_guid mappings by calling out to
%% opscode-account
-module(pushy_org).

-define(POC_ORG_ID, <<"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">>).

-export([
          fetch_org_id/1
        ]).

%% Stub it out for now
-spec fetch_org_id(OrgName :: string()) -> binary() | not_found.
fetch_org_id(_OrgName) ->
  ?POC_ORG_ID.


%%%'   HEADER
%%% @author {{author_name}} <{{author_email}}>
%%% @since {{date}}
%%% @copyright {{copyright_year}} {{author_name}}
%%% @doc {{description}}
%%% @end
-module(tint_sup).

-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
%%%.
%%%'   PUBLIC API
start_link() ->
  supervisor:start_link({local, ?MODULE}, ?MODULE, []).

%%%.
%%%'   CALLBACKS
init([]) ->
  {ok, { {one_for_one, 5, 10}, []} }.

%%%.
%%% vim: set filetype=erlang tabstop=2 foldmarker=%%%',%%%. foldmethod=marker:

Fix finapp supervisor's module name

%%%'   HEADER
%%% @author {{author_name}} <{{author_email}}>
%%% @since {{date}}
%%% @copyright {{copyright_year}} {{author_name}}
%%% @doc {{description}}
%%% @end
-module({{name}}_sup).

-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).

-define(SERVER, ?MODULE).
%%%.
%%%'   PUBLIC API
start_link() ->
  supervisor:start_link({local, ?SERVER}, ?MODULE, []).

%%%.
%%%'   CALLBACKS
init([]) ->
  {ok, { {one_for_one, 5, 10}, []} }.

%%%.
%%% vim: set filetype=erlang tabstop=2 foldmarker=%%%',%%%. foldmethod=marker:


%% @doc Defoult configurion and config-parsing functions.

-module(mas_config).
-include("mas.hrl").

-export([proplist_to_record/1]).

-define(LOAD(Prop, Dict), Prop = dict:fetch(Prop,Dict)).

%% @doc Transform a proplist with config properties to a record
-spec proplist_to_record([tuple()]) -> config().
proplist_to_record(Proplist) ->
    Dict = dict:from_list(Proplist),
    #config{?LOAD(agent_env, Dict),
            ?LOAD(topology, Dict),
            ?LOAD(migration_probability, Dict),
            ?LOAD(log_dir, Dict),
            ?LOAD(islands, Dict),
            ?LOAD(population_size, Dict),
            ?LOAD(write_interval, Dict),
            ?LOAD(skel_workers, Dict),
            ?LOAD(arena_timeout, Dict),
            ?LOAD(skel_split_size, Dict),
            ?LOAD(skel_pull, Dict)}.

Use Proplist in fawor of dict.

%% @doc Defoult configurion and config-parsing functions.

-module(mas_config).
-include("mas.hrl").

-export([proplist_to_record/1]).

-define(LOAD(Prop, Proplist),
        Prop = proplists:get_value(Prop,Proplist)).

%% @doc Transform a proplist with config properties to a record
-spec proplist_to_record([tuple()]) -> config().
proplist_to_record(Proplist) ->
    #config{?LOAD(agent_env, Proplist),
            ?LOAD(topology, Proplist),
            ?LOAD(migration_probability, Proplist),
            ?LOAD(log_dir, Proplist),
            ?LOAD(islands, Proplist),
            ?LOAD(population_size, Proplist),
            ?LOAD(write_interval, Proplist),
            ?LOAD(skel_workers, Proplist),
            ?LOAD(arena_timeout, Proplist),
            ?LOAD(skel_split_size, Proplist),
            ?LOAD(skel_pull, Proplist)}.


-module( lurch_device_driver ).

% API functions
-export(
    [ start_driver/2
	] ).

% API functions

start_driver( _Driver, _Parameters ) ->
	Port = undefined,
	{ ok, Port }.

driver_path( Driver ) ->
	filename:join( [ code:lib_dir( lurch, drivers ), Driver ] ).

Add sanity checks for driver path

-module( lurch_device_driver ).

% API functions
-export(
    [ start_driver/2
	] ).

% API functions

start_driver( _Driver, _Parameters ) ->
	Port = undefined,
	{ ok, Port }.

driver_path( Driver ) ->
	case filename:pathtype(Driver) of
		relative -> ok;
		_ -> throw({error, bad_driver})
	end,
	case lists:member("..", filename:split(Driver)) of
		true -> throw({error, bad_driver});
		false -> ok
	end,
	filename:join( [ driver_dir( ), Driver ] ).

driver_dir( ) ->
	code:lib_dir( lurch, drivers ).

%% ===================================================================
%% Tests
%% ===================================================================
-ifdef( TEST ).
-include_lib( "eunit/include/eunit.hrl" ).

driver_path_test_( ) ->
	{ "Driver filename sanity checks",
		[ ?_assertThrow({error, bad_driver}, driver_path("/absolute/path"))
		, ?_assertThrow({error, bad_driver}, driver_path("dots/../in/path"))
		, ?_assertThrow({error, bad_driver}, driver_path("dots/end/.."))
		]
	}.

-endif. % TEST


%% @copyright Geoff Cant
%% @author Geoff Cant <nem@erlang.geek.nz>
%% @version {@vsn}, {@date} {@time}
%% @doc Syslog message formatting utilities.
%% @end
-module(logplex_syslog_utils).

-export([to_msg/1
         ,frame/1]).

-type syslog_msg() :: {0..128, 0..7,
                       Time::iolist(), Source::iolist(),
                       Process::iolist(), Msg::iolist()}.

-export_type([ syslog_msg/0 ]).

-spec to_msg(syslog_msg()) -> iolist().
to_msg({Facility, Severity, Time, Source, Process, Msg})
  when is_integer(Facility), is_integer(Severity) ->
    [ <<"<">>, pri(Facility, Severity), <<">">>,
      Time, $\s, Source, $\s, Process, <<" -- ">>, Msg ].

pri(Facility, Severity)
  when is_integer(Facility),
       is_integer(Severity),
       0 =< Severity, Severity =< 7 ->
    integer_to_list(Facility * 8 + Severity).

-spec frame(Msg::iolist()) -> iolist().
frame(Msg) when is_binary(Msg); is_list(Msg) ->
    Length = iolist_size(Msg),
    [ integer_to_list(Length),
      " ",
      Msg ].

Add syslog version to msg formatter.

%% @copyright Geoff Cant
%% @author Geoff Cant <nem@erlang.geek.nz>
%% @version {@vsn}, {@date} {@time}
%% @doc Syslog message formatting utilities.
%% @end
-module(logplex_syslog_utils).

-export([to_msg/1
         ,frame/1]).

-type syslog_msg() :: {0..128, 0..7,
                       Time::iolist(), Source::iolist(),
                       Process::iolist(), Msg::iolist()}.

-export_type([ syslog_msg/0 ]).

-spec to_msg(syslog_msg()) -> iolist().
to_msg({Facility, Severity, Time, Source, Process, Msg})
  when is_integer(Facility), is_integer(Severity) ->
    [ <<"<">>, pri(Facility, Severity), <<">1 ">>,
      Time, $\s, Source, $\s, Process, <<" -- ">>, Msg ].

-spec to_msg(syslog_msg(), Token::iolist()) -> iolist().
to_msg({Facility, Severity, Time, Source, Process, Msg}, Token) ->
    [ <<"<">>, pri(Facility, Severity), <<">1 ">>,
      Time, $\s, Token, $\s, Source, $\s, Process, <<" -- ">>, Msg ].

pri(Facility, Severity)
  when is_integer(Facility),
       is_integer(Severity),
       0 =< Severity, Severity =< 7 ->
    integer_to_list(Facility * 8 + Severity).

-spec frame(Msg::iolist()) -> iolist().
frame(Msg) when is_binary(Msg); is_list(Msg) ->
    Length = iolist_size(Msg),
    [ integer_to_list(Length),
      " ",
      Msg ].


#!/usr/bin/env escript
%%! -noinput -pa ../encurses/ebin +A 10
-include_lib("encurses/include/encurses.hrl").
main(_) -> encurses_demo:go().

Make so that demo can work whatever repo`s name.

#!/usr/bin/env escript
%%! -noinput -pa ./ebin +A 10
-include_lib("include/encurses.hrl").
main(_) -> encurses_demo:go().


%%% The MIT License (MIT)
%%%
%%% Copyright (c) 2014 Quinlan Pfiffer, Kyle Terry
%%%
%%% Permission is hereby granted, free of charge, to any person obtaining a copy
%%% of this software and associated documentation files (the "Software"), to deal
%%% in the Software without restriction, including without limitation the rights
%%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
%%% copies of the Software, and to permit persons to whom the Software is
%%% furnished to do so, subject to the following conditions:
%%%
%%% The above copyright notice and this permission notice shall be included in
%%% all copies or substantial portions of the Software.
%%%
%%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
%%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
%%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
%%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
%%% THE SOFTWARE.
-record(ol_record, {database,
                    key,
                    content_type=nil,
                    content_length=nil,
                    value}).

Change default content-type to application/octet-stream

%%% The MIT License (MIT)
%%%
%%% Copyright (c) 2014 Quinlan Pfiffer, Kyle Terry
%%%
%%% Permission is hereby granted, free of charge, to any person obtaining a copy
%%% of this software and associated documentation files (the "Software"), to deal
%%% in the Software without restriction, including without limitation the rights
%%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
%%% copies of the Software, and to permit persons to whom the Software is
%%% furnished to do so, subject to the following conditions:
%%%
%%% The above copyright notice and this permission notice shall be included in
%%% all copies or substantial portions of the Software.
%%%
%%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
%%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
%%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
%%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
%%% THE SOFTWARE.
-record(ol_record, {database,
                    key,
                    content_type="application/octet-stream",
                    content_length=nil,
                    value}).


% vim: sw=4 ts=4 et ft=erlang
% Nitrogen Web Framework for Erlang
% See MIT-LICENSE for licensing information.

-module (element_html5_header).
-include("wf.hrl").
-export([
    reflect/0,
    render_element/1
]).

-spec reflect() -> [atom()].
reflect() -> record_info(fields, html5_header).

-spec render_element(#html5_header{}) -> body().
render_element(Record) ->
    CheckHeaderOrFooter =   fun (X) ->
                                if
                                    is_record(X, html5_header) ->
                                        true;
                                    is_record(X, html5_footer) ->
                                        true;
                                    true ->
                                        false
                                end
                            end,
    Y = lists:any(CheckHeaderOrFooter, Record#html5_header.body),
    if
        Y ->
            "<b style=\"color: red;\">html5_header cannot have another html5_header or html5_footer as child element</b>";
        true ->
            wf_tags:emit_tag('header', Record#html5_header.body, [
                {id, Record#html5_header.html_id},
                {class, ["html5_header", Record#html5_header.class]},
                {title, Record#html5_header.title},
                {style, Record#html5_header.style},
                {role, Record#html5_header.role},
                {data_fields, Record#html5_header.data_fields}
            ])
    end.

Remove enforcement rules from html5_header

% vim: sw=4 ts=4 et ft=erlang
% Nitrogen Web Framework for Erlang
% See MIT-LICENSE for licensing information.

-module (element_html5_header).
-include("wf.hrl").
-export([
    reflect/0,
    render_element/1
]).

-spec reflect() -> [atom()].
reflect() -> record_info(fields, html5_header).

-spec render_element(#html5_header{}) -> body().
render_element(Record) ->
    wf_tags:emit_tag('header', Record#html5_header.body, [
        {id, Record#html5_header.html_id},
        {class, ["html5_header", Record#html5_header.class]},
        {title, Record#html5_header.title},
        {style, Record#html5_header.style},
        {role, Record#html5_header.role},
        {data_fields, Record#html5_header.data_fields}
    ]).


%% Rubis
-define(GROUPING_SEP, <<"+">>).
-define(ID_SEP, <<"@">>).
-define(FIELD_SEP, <<"/">>).

%% General indices
-define(INDEX_SEP, <<"$">>).
-define(UINDEX_SEP, <<"%">>).
-define(INDEX_PAGE_LIMIT, 25).

%% Amount of Transaction metadata kept for the Version and Commit log
%%
%% VERSION_THRESHOLD specifies the point where the logs will perform a GC
%% The lower this number is set, the more common GC will become.
%%
%% MAX_VERSIONS specifies the number of versions kept in the logs after a GC
%%
%% So, every time VERSION_THRESHOLD versions are reached, we will remove all
%% versions, except for last MAX_VERSIONS.
-define(VERSION_THRESHOLD, 100).
-define(MAX_VERSIONS, 50).

%% Size of active listener pool for the protocol buffer server
-define(COORD_PB_POOL, (1 * erlang:system_info(schedulers_online))).
%% Port number for protocol buffer sever
-define(COORD_PB_PORT, 7878).

%% Defines how often partition vnodes try to dequeue ready transactions
-define(DEQUEUE_INTERVAL, 5).

Purge version/commit logs more often

%% Rubis
-define(GROUPING_SEP, <<"+">>).
-define(ID_SEP, <<"@">>).
-define(FIELD_SEP, <<"/">>).

%% General indices
-define(INDEX_SEP, <<"$">>).
-define(UINDEX_SEP, <<"%">>).
-define(INDEX_PAGE_LIMIT, 25).

%% Amount of Transaction metadata kept for the Version and Commit log
%%
%% VERSION_THRESHOLD specifies the point where the logs will perform a GC
%% The lower this number is set, the more common GC will become.
%%
%% MAX_VERSIONS specifies the number of versions kept in the logs after a GC
%%
%% So, every time VERSION_THRESHOLD versions are reached, we will remove all
%% versions, except for last MAX_VERSIONS.
-define(VERSION_THRESHOLD, 50).
-define(MAX_VERSIONS, 25).

%% Size of active listener pool for the protocol buffer server
-define(COORD_PB_POOL, (1 * erlang:system_info(schedulers_online))).
%% Port number for protocol buffer sever
-define(COORD_PB_PORT, 7878).

%% Defines how often partition vnodes try to dequeue ready transactions
-define(DEQUEUE_INTERVAL, 5).


-module(cowmachine_websocket_upgrade).

-export([
    upgrade/2
    ]).

%% @doc Upgrade the request to a websocket request
-spec upgrade(atom(), cowmachine_req:context()) -> {ok, cowboy_req:req(), cowboy_middleware:env()}.
upgrade(Handler, Context) ->
    Req = cowmachine_req:req(Context),
    Env = #{},
    cowboy_websocket:upgrade(Req, Env, Handler, Context, infinity, run).

Fix websocket upgrade for cowboy 2.0.0-pre.10

-module(cowmachine_websocket_upgrade).

-export([
    upgrade/2
    ]).

%% @doc Upgrade the request to a websocket request
-spec upgrade(atom(), cowmachine_req:context()) -> {ok, cowboy_req:req(), cowboy_middleware:env()}.
upgrade(Handler, Context) ->
    Req = cowmachine_req:req(Context),
    Env = #{},
    Opts = #{
        idle_timeout => infinity
    },
    cowboy_websocket:upgrade(Req, Env, Handler, Context, Opts).


-module(erldns_app).
-behavior(application).

% Application hooks
-export([start/2, stop/1]).

start(Type, Args) ->
  lager:info("~p:start(~p, ~p)~n", [?MODULE, Type, Args]),
  random:seed(erlang:now()),
  optionally_start_debugger(),
  enable_metrics(),
  erldns_sup:start_link().

stop(State) ->
  lager:info("~p:stop(~p)~n", [?MODULE, State]),
  ok.

optionally_start_debugger() ->
  case application:get_env(erldns, debugger) of
    {ok, true} -> erldns_debugging:start();
    _ -> ok
  end.

enable_metrics() ->
  folsom_metrics:new_histogram(packet_cache_hit, slide),
  folsom_metrics:new_histogram(packet_cache_miss, slide),
  ok.

Add folsom metric for lookup time

-module(erldns_app).
-behavior(application).

% Application hooks
-export([start/2, stop/1]).

start(Type, Args) ->
  lager:info("~p:start(~p, ~p)~n", [?MODULE, Type, Args]),
  random:seed(erlang:now()),
  optionally_start_debugger(),
  enable_metrics(),
  erldns_sup:start_link().

stop(State) ->
  lager:info("~p:stop(~p)~n", [?MODULE, State]),
  ok.

optionally_start_debugger() ->
  case application:get_env(erldns, debugger) of
    {ok, true} -> erldns_debugging:start();
    _ -> ok
  end.

enable_metrics() ->
  folsom_metrics:new_histogram(packet_cache_hit, slide),
  folsom_metrics:new_histogram(packet_cache_miss, slide),
  folsom_metrics:new_histogram(mysql_responder_lookup_time, slide),
  ok.


-module(nitrogen_main_handler).
-export([run/0]).

run() ->
	%% Put any custom handlers here
	%% See http://nitrogenproject.com/doc/handlers.html
	%% Example:
	%%
	%%   wf_handler:set_handler(MySecurityHandler, HandlerConfig),
	%%
	wf_core:run().

Fix default main handler with ws_init

%% vim: ts=4 sw=4 et
-module(nitrogen_main_handler).
-export([
    run/0,
    ws_init/0
]).

handlers() ->
    %% Put any custom handlers here
    %% See http://nitrogenproject.com/doc/handlers.html
    %% Example:
    %%
    %%   wf_handler:set_handler(MySecurityHandler, HandlerConfig),
    %%
    ok.

ws_init() ->
    handlers().

run() ->
    handlers(),
    wf_core:run().


-type ensemble_id() :: term().
-type peer_id() :: {term(), node()}.
-type leader_id() :: undefined | peer_id().
-type fixme() :: any().
-type views() :: [[peer_id()]].
-type peer_change() :: term(). %% FIXME
-type change_error() :: already_member | not_member.
-type std_reply() :: timeout | failed | unavailable | nack | {ok, term()}.
-type maybe_pid() :: pid() | undefined.
-type peer_pids() :: [{peer_id(), maybe_pid()}].
-type peer_reply() :: {peer_id(), term()}.
-type epoch() :: integer().
-type seq() :: integer().
-type vsn() :: {epoch(), seq()}.
-type orddict(Key,Val) :: [{Key, Val}].
-type ordsets(Val) :: [Val].

-record(ensemble_info, {vsn                                   :: vsn(),
                        mod     = riak_ensemble_basic_backend :: module(),
                        args    = []                          :: [any()],
                        leader                                :: leader_id(),
                        views                                 :: [[peer_id()]],
                        seq                                   :: {integer(), integer()}
                       }).
-type ensemble_info() :: #ensemble_info{}.

%% -type ensemble_info() :: {leader_id(), [peer_id()], {integer(), integer()}, module(), [any()]}.

-define(ENSEMBLE_TICK, 200).

Increase ensemble tick from 200ms to 500ms

-type ensemble_id() :: term().
-type peer_id() :: {term(), node()}.
-type leader_id() :: undefined | peer_id().
-type fixme() :: any().
-type views() :: [[peer_id()]].
-type peer_change() :: term(). %% FIXME
-type change_error() :: already_member | not_member.
-type std_reply() :: timeout | failed | unavailable | nack | {ok, term()}.
-type maybe_pid() :: pid() | undefined.
-type peer_pids() :: [{peer_id(), maybe_pid()}].
-type peer_reply() :: {peer_id(), term()}.
-type epoch() :: integer().
-type seq() :: integer().
-type vsn() :: {epoch(), seq()}.
-type orddict(Key,Val) :: [{Key, Val}].
-type ordsets(Val) :: [Val].

-record(ensemble_info, {vsn                                   :: vsn(),
                        mod     = riak_ensemble_basic_backend :: module(),
                        args    = []                          :: [any()],
                        leader                                :: leader_id(),
                        views                                 :: [[peer_id()]],
                        seq                                   :: {integer(), integer()}
                       }).
-type ensemble_info() :: #ensemble_info{}.

%% -type ensemble_info() :: {leader_id(), [peer_id()], {integer(), integer()}, module(), [any()]}.

-define(ENSEMBLE_TICK, 500).


-module(check_riak_kv_up).

-export([run/2]).

run(Options, _) ->
    Node = proplists:get_value(node, Options),
    check_riak_kv_up(Node).

check_riak_kv_up(Node) ->
    Services = rpc:call(Node, riak_core_node_watcher, services, []),
    case lists:member(riak_kv, Services) of
        true ->
            {ok, "riak_kv is running on ~s", [Node]};
        false ->
            {critical, "riak_kv not found in running services on ~s: ~p", [Node, Services]}
    end.

Check that rpc returned a list before calling lists:member

-module(check_riak_kv_up).

-export([run/2]).

run(Options, _) ->
    Node = proplists:get_value(node, Options),
    check_riak_kv_up(Node).

check_riak_kv_up(Node) ->
    Services = rpc:call(Node, riak_core_node_watcher, services, []),
    check_riak_kv_services(Node, Services).

check_riak_kv_services(Node, Services) when is_list(Services) ->
    case lists:member(riak_kv, Services) of
        true ->
            {ok, "riak_kv is running on ~s", [Node]};
        false ->
            {critical, "riak_kv not found in running services on ~s: ~p", [Node, Services]}
    end;
check_riak_kv_services(Node, Services) ->
    {critical, "Unable to get list of services running on ~s: ~p", [Node, Services]}.


% lex.erl
% Lexer implementation for Jrlscript Compiler
-module(jrl_lex).
-compile(export_all).

lex() ->
	io:format("Usage - lex(Input<String>).~n", []).

lex(Input) ->
	SplitInput = re:split(Input, "", [{return, binary}]),
	scan(SplitInput).

% Scanner Functions:
% Scans a list in the form [<<char>...] and generates Lexemes which will be returned
scan(Input) ->
	[Head|Tail] = Input,
	scan(Tail, []).

scan([], Lexemes) ->
	Lexemes;

scan([<<"(">>|Tail], Lexemes) ->
	scan(Tail, Lexemes ++ [paren_l]);

scan([<<")">>|Tail], Lexemes) ->
	scan(Tail, Lexemes ++ [paren_r]);

scan([_|Tail], Lexemes) ->
	scan(Tail, Lexemes).

% Lexical Error Reporting
err({Emsg, Eline}) ->
	io:format("Error: ~s~nOn line ~s ~n", [Emsg, Eline]).

Test because my commits seemingly aren't being tracked

% lex.erl
% Lexer implementation for Jrlscript Compiler
-module(jrl_lex).
-compile(export_all).

lex() ->
	io:format("Usage - lex(Input<String>).~n", []).

lex(Input) ->
	SplitInput = re:split(Input, "", [{return, binary}]),
	scan(SplitInput).

% Scanner Functions:
% Scans a list in the form [<<char>...] and generates Lexemes which will be returned
scan(Input) ->
	[Head|Tail] = Input,
	scan(Tail, []).

scan([], Lexemes) ->
	Lexemes;

scan([<<"(">>|Tail], Lexemes) ->
	scan(Tail, Lexemes ++ [paren_l]);

scan([<<")">>|Tail], Lexemes) ->
	scan(Tail, Lexemes ++ [paren_r]);

scan([_|Tail], Lexemes) ->
	scan(Tail, Lexemes).

% Lexical Error Reporting
err({Emsg, Eline}) ->
	io:format("Error: ~s~nOn line ~s ~n", [Emsg, Eline]),
	io.format("TEST");


% Nitrogen Web Framework for Erlang
% Copyright (c) 2008-2009 Rusty Klophaus
% See MIT-LICENSE for licensing information.

-module (element_radiogroup).
-include ("wf.inc").
-compile(export_all).

reflect() -> record_info(fields, radiogroup).

render(ControlID, Record) ->
	% Set the group to the current ControlID...

	F = fun(X) ->
		case is_record(X, radio) of
			true -> X#radio { name=ControlID };
			false -> X
		end
	end,
	Body = [F(X) || X <- Record#radiogroup.body],

	% Render the record...
	element_panel:render(ControlID, #panel {
		class="radiogroup " ++ wf:to_list(Record#radiogroup.class),
		style=Record#radiogroup.style,
		body=Body
	}).

Allow radiogroup name to recurse through a binding

% Nitrogen Web Framework for Erlang
% Copyright (c) 2008-2009 Rusty Klophaus
% See MIT-LICENSE for licensing information.

-module (element_radiogroup).
-include ("wf.inc").
-compile(export_all).

reflect() -> record_info(fields, radiogroup).

render(ControlID, Record) ->
	% Set the group to the current ControlID...
	Body = apply_name(ControlID, Record#radiogroup.body),

	% Render the record...
	element_panel:render(ControlID, #panel {
		class="radiogroup " ++ wf:to_list(Record#radiogroup.class),
		style=Record#radiogroup.style,
		body=Body
	}).

apply_name(Name, Terms) ->
    [do_apply(Name, X) || X <- Terms].

do_apply(Name, X) when is_record(X, radio) ->
    X#radio {name = Name};
do_apply(Name, X) when is_record(X, bind) ->
    Body2 = apply_name(Name, X#bind.body),
    X#bind{body = Body2};
do_apply(_Name, X) ->
    X.


%%%-------------------------------------------------------------------
%%% This file is part of the CernVM File System.
%%%
%%% @doc cvmfs_fe - CVMFS repo services HTTP front-end
%%%
%%% @end
%%%-------------------------------------------------------------------

-module(cvmfs_fe).

-export([start_link/1, api_version/0]).

-define(API_VERSION, 1).
-define(API_ROOT, "/api/v" ++ integer_to_list(?API_VERSION)).

%%--------------------------------------------------------------------
%% @doc
%% Starts the front-end HTTP listener process.
%%
%% @end
%%--------------------------------------------------------------------
start_link([TcpPort]) ->
    %% Compile a routing table, for dispatching requests for different resources
    %% to a set of handler modules. The handler modules implement the init/2 callback
    %% required by Cowboy
    Dispatch = cowboy_router:compile([{'_', [
                                             {?API_ROOT, cvmfs_root_handler, []},
                                             {?API_ROOT ++ "/repos/[:id]", cvmfs_repos_handler, []},
                                             {?API_ROOT ++ "/leases/[:token]", cvmfs_leases_handler, []},
                                             {?API_ROOT ++ "/payloads/[:id]", cvmfs_payloads_handler, []}
                                            ]}]),
    %% Start the HTTP listener process configured with the routing table
    cowboy:start_clear(cvmfs_fe,
                       [{port, TcpPort}],
                       #{env => #{dispatch => Dispatch}}).

-spec api_version() -> integer().
api_version() ->
    ?API_VERSION.

Use much larger request timeouts for the Cowboy server

%%%-------------------------------------------------------------------
%%% This file is part of the CernVM File System.
%%%
%%% @doc cvmfs_fe - CVMFS repo services HTTP front-end
%%%
%%% @end
%%%-------------------------------------------------------------------

-module(cvmfs_fe).

-export([start_link/1, api_version/0]).

-define(API_VERSION, 1).
-define(API_ROOT, "/api/v" ++ integer_to_list(?API_VERSION)).

-define(REQUEST_TIMEOUT, 10800000).

%%--------------------------------------------------------------------
%% @doc
%% Starts the front-end HTTP listener process.
%%
%% @end
%%--------------------------------------------------------------------
start_link([TcpPort]) ->
    %% Compile a routing table, for dispatching requests for different resources
    %% to a set of handler modules. The handler modules implement the init/2 callback
    %% required by Cowboy
    Dispatch = cowboy_router:compile([{'_', [
                                             {?API_ROOT, cvmfs_root_handler, []},
                                             {?API_ROOT ++ "/repos/[:id]", cvmfs_repos_handler, []},
                                             {?API_ROOT ++ "/leases/[:token]", cvmfs_leases_handler, []},
                                             {?API_ROOT ++ "/payloads/[:id]", cvmfs_payloads_handler, []}
                                            ]}]),
    %% Start the HTTP listener process configured with the routing table
    cowboy:start_clear(cvmfs_fe,
                       [{port, TcpPort}],
                       #{env => #{dispatch => Dispatch},
                         idle_timeout => ?REQUEST_TIMEOUT,
                         inactivity_timeout => ?REQUEST_TIMEOUT}).

-spec api_version() -> integer().
api_version() ->
    ?API_VERSION.


-module(iota_utils).

-export([ get/2,
          get/3,
          with_xref/1
        ]).

get(Key, List) ->
  case lists:keyfind(Key, 1, List) of
    false        -> throw(key_not_found);
    {Key, Value} -> Value
  end.

get(Key, List, Default) ->
  case lists:keyfind(Key, 1, List) of
    false        -> Default;
    {Key, Value} -> Value
  end.

with_xref(Fun) ->
  xref:start(iota),
  try
    Fun()
  after
    xref:stop(iota)
  end.

Rename iota xref server to iota_xref

-module(iota_utils).

-export([ get/2,
          get/3,
          with_xref/1
        ]).

get(Key, List) ->
  case lists:keyfind(Key, 1, List) of
    false        -> throw(key_not_found);
    {Key, Value} -> Value
  end.

get(Key, List, Default) ->
  case lists:keyfind(Key, 1, List) of
    false        -> Default;
    {Key, Value} -> Value
  end.

with_xref(Fun) ->
  xref:start(iota_xref),
  try
    Fun()
  after
    xref:stop(iota_xref)
  end.


-module(eventsource_app).
-behaviour(application).

-export([start/2]).
-export([stop/1]).

start(_Type, _Args) ->
    Dispatch = cowboy_router:compile([
        {'_', [
            {"/sse", eventsource_emitter, []},
            {"/connections", connections_handler, []}
        ]}
    ]),
    cowboy:start_http(sse_handler, 100, [
            {port, 8080},
            {max_connections, infinity}
        ],
        [{env, [{dispatch, Dispatch}]}]
    ),
    eventsource_sup:start_link().

stop(_State) ->
    ok.

Make it listen to port 1942 instead of 8080.

-module(eventsource_app).
-behaviour(application).

-export([start/2]).
-export([stop/1]).

start(_Type, _Args) ->
    Dispatch = cowboy_router:compile([
        {'_', [
            {"/sse", eventsource_emitter, []},
            {"/connections", connections_handler, []}
        ]}
    ]),
    cowboy:start_http(sse_handler, 100, [
            {port, 1942},
            {max_connections, infinity}
        ],
        [{env, [{dispatch, Dispatch}]}]
    ),
    eventsource_sup:start_link().

stop(_State) ->
    ok.


%%%-------------------------------------------------------------------
%%% File : terminal_logger.erl
%%% Author : Nicolas R Dufour <nrdufour@gmail.com>
%%% Created : 2009/06/01
%%% Description :
%%%     Simple terminal logger from the erlang documentation.
%%%
%%% Copyright 2009 Nicolas R Dufour <nrdufour@gmail.com>
%%%
%%% This software is licensed as described in the file LICENSE, which
%%% you should have received as part of this distribution.
%%%-------------------------------------------------------------------
-module(terminal_logger).
-behaviour(gen_event).

-export([init/1, handle_event/2, terminate/2]).

%% trace is enabled by default
init(_Args) ->
	{ok, true}.

%% activate or not the trace
handle_event({trace, Trace}, _State) ->
	{ok, Trace};

%% display the message
handle_event(Msg, State) ->
	if
		State ->
			io:format(" -> ~p~n", [Msg]);
		true ->
			true
	end,
	{ok, State}.

terminate(_Args, _State) ->
	ok.

%%% END

Add a better logger with io:format capabilities.

%%%-------------------------------------------------------------------
%%% File : terminal_logger.erl
%%% Author : Nicolas R Dufour <nrdufour@gmail.com>
%%% Created : 2009/06/01
%%% Description :
%%%     Simple terminal logger from the erlang documentation.
%%%
%%% Copyright 2009 Nicolas R Dufour <nrdufour@gmail.com>
%%%
%%% This software is licensed as described in the file LICENSE, which
%%% you should have received as part of this distribution.
%%%-------------------------------------------------------------------
-module(terminal_logger).
-behaviour(gen_event).

-export([init/1, handle_event/2, terminate/2]).

%% trace is enabled by default
init(_Args) ->
	{ok, true}.

%% activate or not the trace
handle_event({trace, Trace}, _State) ->
	{ok, Trace};

%% display a simple message
handle_event({Msg, Args}, State) ->
	if
		State ->
			Format = string:concat(Msg, "~n"),
			io:format(Format, Args);
		true ->
			true
	end,
	{ok, State}.

terminate(_Args, _State) ->
	ok.

%%% END


-module(ucp_utils_tests).

-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").

to_hex_test_() ->
  [{"int to hexstr",
    fun () ->
        ?assertEqual("0F", ucp_utils:to_hexstr(15))
    end},
   {"list to hexstr",
    ?_test(?assertEqual("081E", ucp_utils:to_hexstr([8,30])))},
   {"str to hexstr",
    ?_test(?assertEqual("74657374", ucp_utils:to_hexstr("test")))}].

-endif.

Add new hex string conversion tests

-module(ucp_utils_tests).

-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").

to_hex_test_() ->
  [{"int to hexstr",
    fun () ->
        ?assertEqual("0F", ucp_utils:to_hexstr(15))
    end},
   {"list to hexstr",
    ?_test(?assertEqual("081E", ucp_utils:to_hexstr([8,30])))},
   {"binary to hexstr",
    ?_test(?assertEqual("1E12", ucp_utils:to_hexstr(<<30,18>>)))},
   {"unicode to hexstr",
       ?_test(?assertEqual("001E01420105006B0061", ucp_utils:to_hexstr([30,322,261,107,97])))},
   {"str to hexstr",
    ?_test(?assertEqual("74657374", ucp_utils:to_hexstr("test")))}].

-endif.