%%------------------------------------------------------------------------------
%% Copyright (c) 2013 Vasil Kolarov
%%
%% 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.
%%------------------------------------------------------------------------------

-record(res_eval_state, { stmt,
			  recno = 1,
			  aggrno = 1,
			  aggr_nodes = orddict:new(),
			  result = dict:new()

	 }).

Build graph from the event pattern

%%------------------------------------------------------------------------------
%% Copyright (c) 2013 Vasil Kolarov
%%
%% 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.
%%------------------------------------------------------------------------------

-record(res_eval_state, { stmt,
			  recno = 1,
			  aggrno = 1,
			  aggr_nodes = orddict:new(),
			  result = dict:new()
	 }).

-record(query_ast,{
	  select,
	  from,
	  where,
	  within
	 }).

-record(query_plan, {
	  join_keys = orddict:new()
	 }).  %%will be extended later

-record(slide,{size,
	       reservoir = rivus_cep_slide_ets:new(rivus_slide, [duplicate_bag, {write_concurrency, true}, public]),
	       server}).


%% Feel free to use, reuse and abuse the code in this file.

-module(websocket_handler_init_shutdown).
-behaviour(cowboy_http_handler).
-behaviour(cowboy_http_websocket_handler).
-export([init/3, handle/2, terminate/2]).
-export([websocket_init/3, websocket_handle/3,
	websocket_info/3, websocket_terminate/3]).

init(_Any, _Req, _Opts) ->
	{upgrade, protocol, cowboy_http_websocket}.

handle(_Req, _State) ->
	exit(badarg).

terminate(_Req, _State) ->
	exit(badarg).

websocket_init(_TransportName, Req, _Opts) ->
	Req2 = cowboy_http_req:reply(403, Req),
	{shutdown, Req2}.

websocket_handle(_Frame, _Req, _State) ->
	exit(badarg).

websocket_info(_Info, _Req, _State) ->
	exit(badarg).

websocket_terminate(_Reason, _Req, _State) ->
	exit(badarg).

Fix a websocket test handler that was throwing an unwanted error

%% Feel free to use, reuse and abuse the code in this file.

-module(websocket_handler_init_shutdown).
-behaviour(cowboy_http_handler).
-behaviour(cowboy_http_websocket_handler).
-export([init/3, handle/2, terminate/2]).
-export([websocket_init/3, websocket_handle/3,
	websocket_info/3, websocket_terminate/3]).

init(_Any, _Req, _Opts) ->
	{upgrade, protocol, cowboy_http_websocket}.

handle(_Req, _State) ->
	exit(badarg).

terminate(_Req, _State) ->
	exit(badarg).

websocket_init(_TransportName, Req, _Opts) ->
	{ok, Req2} = cowboy_http_req:reply(403, Req),
	{shutdown, Req2}.

websocket_handle(_Frame, _Req, _State) ->
	exit(badarg).

websocket_info(_Info, _Req, _State) ->
	exit(badarg).

websocket_terminate(_Reason, _Req, _State) ->
	exit(badarg).


-module(volume).
-behaviour(gen_server).

-export([start/1]).
-export([get/0, set/1]).
-export([init/1, handle_call/3]).

%---------------------------------------------------------------------------

start(Sconf) ->
    io:format("Starting volume control.~n"),
    gen_server:start_link({local, volume}, volume, [], []).

%---------------------------------------------------------------------------

get() -> gen_server:call(volume, get).
set(NewVol) -> gen_server:call(volume, {set, NewVol}).

%---------------------------------------------------------------------------

init(_Args) ->
    {ok, unknown}.

handle_call(Request, From, unknown) ->
    handle_call(Request, From, hmix_get_volume());
handle_call(get, _From, Volume) ->
    {reply, Volume, Volume};
handle_call({set, VolArg}, _From, _Volume) ->
    NewVol = hmix_set_volume(VolArg),
    {reply, NewVol, unknown}.

hmix_get_volume() ->
    Out = os:cmd("hmix | grep MASTER"),
    case lists:prefix("MASTER", Out) of
	true ->
	    {match, Start, Length} = regexp:match(Out, "[0-9]+"),
	    VolStr = string:substr(Out, Start, Length),
	    list_to_integer(VolStr);
	false ->
	    unavailable
    end.

hmix_set_volume(NewVol) ->
    os:cmd("hmix -master " ++ integer_to_list(NewVol)),
    hmix_get_volume().

Use "null" instead of "unavailable" for hmix

-module(volume).
-behaviour(gen_server).

-export([start/1]).
-export([get/0, set/1]).
-export([init/1, handle_call/3]).

%---------------------------------------------------------------------------

start(Sconf) ->
    io:format("Starting volume control.~n"),
    gen_server:start_link({local, volume}, volume, [], []).

%---------------------------------------------------------------------------

get() -> gen_server:call(volume, get).
set(NewVol) -> gen_server:call(volume, {set, NewVol}).

%---------------------------------------------------------------------------

init(_Args) ->
    {ok, unknown}.

handle_call(Request, From, unknown) ->
    handle_call(Request, From, hmix_get_volume());
handle_call(get, _From, Volume) ->
    {reply, Volume, Volume};
handle_call({set, VolArg}, _From, _Volume) ->
    NewVol = hmix_set_volume(VolArg),
    {reply, NewVol, unknown}.

hmix_get_volume() ->
    Out = os:cmd("hmix | grep MASTER"),
    case lists:prefix("MASTER", Out) of
	true ->
	    {match, Start, Length} = regexp:match(Out, "[0-9]+"),
	    VolStr = string:substr(Out, Start, Length),
	    list_to_integer(VolStr);
	false ->
	    null
    end.

hmix_set_volume(NewVol) ->
    os:cmd("hmix -master " ++ integer_to_list(NewVol)),
    hmix_get_volume().


%% -------------------------------------------------------------------
%%
%% rebar: Erlang Build Tools
%%
%% Copyright (c) 2009 Dave Smith (dizzyd@dizzyd.com)
%%
%% 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.
%% -------------------------------------------------------------------
-module(rebar).

-export([main/1]).

main(Args) ->
    rebar_core:run(Args).

Make sure to bail w/ return code of 1 when error has occurred

%% -------------------------------------------------------------------
%%
%% rebar: Erlang Build Tools
%%
%% Copyright (c) 2009 Dave Smith (dizzyd@dizzyd.com)
%%
%% 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.
%% -------------------------------------------------------------------
-module(rebar).

-export([main/1]).

main(Args) ->
    case catch(rebar_core:run(Args)) of
        ok ->
            ok;
        _ ->
            halt(1)
    end.


-module(amoc_always_null_ssl_session_cache).

-behaviour(ssl_session_cache_api).

-export([delete/2,
         foldl/3,
         init/1,
         lookup/2,
         select_session/2,
         terminate/1,
         update/3]).

init(_) -> invalid.

terminate(_) -> ok.

lookup(_,_) -> undefined.

update(_,_,_) -> ok.

delete(_,_) -> ok.

foldl(_,Acc,_) -> Acc.

select_session(_,_) -> [].

Add specs to always null ssl cache

-module(amoc_always_null_ssl_session_cache).

-behaviour(ssl_session_cache_api).

-export([delete/2,
         foldl/3,
         init/1,
         lookup/2,
         select_session/2,
         terminate/1,
         update/3]).

%% not exported by ssl
%% only defined in "ssl_internal.hrl", we redefine it
-type db_handle() :: any().
-type key() :: tuple().
-type session() :: tuple().

-spec init(list()) -> invalid.
init(_) -> invalid.

-spec terminate(db_handle()) -> ok.
terminate(_) -> ok.

-spec lookup(db_handle(), key()) -> undefined.
lookup(_, _) -> undefined.

-spec update(db_handle(), key(), session()) -> ok.
update(_, _, _) -> ok.

-spec delete(db_handle(), key()) -> ok.
delete(_, _) -> ok.

-spec foldl(fun(), any(), db_handle()) -> any().
foldl(_, Acc, _) -> Acc.

-spec select_session(db_handle(), tuple() | inet:port_number()) -> [].
select_session(_, _) -> [].


% A reall % First line is ignored when running with escript
main(_) ->
  X = 38,

  Temperature1 = case X of
    _ when X < 0 -> cold;
    _ when X < 20 -> cool;
    _ when X < 45 -> fine;
    _ -> hot
  end,

  Temperature2 = if
    X < 0 -> cold;
    X < 20 -> cool;
    X < 45 -> fine;
    true -> hot
  end,

  % Test
  [fine, fine] = [Temperature1, Temperature2].

Fix a typo in comment


-module(unimate_tcp_server).

-behaviour(gen_nb_server).

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

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

-define(SOCKET_OPTS, [binary, {packet, 0}, {active, false}]).

-record(state, {}).

start_link() ->
  gen_nb_server:start_link(?MODULE, "127.0.0.1", 10101, []).

sock_opts() ->
  ?SOCKET_OPTS.

new_connection(Sock, State) ->
  P = spawn(fun() -> unimate_command2:handle(Sock) end),
  gen_tcp:controlling_process(Sock, P),
  {ok, State}.

init([]) ->
  {ok, #state{}}.

handle_call(_msg, _From, State) ->
  {stop, unhandled_call, State}.

handle_cast(_Msg, State) ->
  {stop, unhandled_cast, State}.

handle_info(_Info, State) ->
  {noreply, State}.

terminate(_Reason, _State) ->
  ok.

code_change(_OldVsn, State, _Extra) ->
  {ok, State}.

Fix old test module name left in

-module(unimate_tcp_server).

-behaviour(gen_nb_server).

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

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

-define(SOCKET_OPTS, [binary, {packet, 0}, {active, false}]).

-record(state, {}).

start_link() ->
  gen_nb_server:start_link(?MODULE, "127.0.0.1", 10101, []).

sock_opts() ->
  ?SOCKET_OPTS.

new_connection(Sock, State) ->
  P = spawn(fun() -> unimate_command:handle(Sock) end),
  gen_tcp:controlling_process(Sock, P),
  {ok, State}.

init([]) ->
  {ok, #state{}}.

handle_call(_msg, _From, State) ->
  {stop, unhandled_call, State}.

handle_cast(_Msg, State) ->
  {stop, unhandled_cast, State}.

handle_info(_Info, State) ->
  {noreply, State}.

terminate(_Reason, _State) ->
  ok.

code_change(_OldVsn, State, _Extra) ->
  {ok, State}.


%% -------------------------------------------------------------------
%%
%% basho_bench: Benchmarking Suite
%%
%% Copyright (c) 2009-2010 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(basho_bench_driver_null).

-export([new/1,
         run/4]).

-include("basho_bench.hrl").

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

new(_Id) ->
    {ok, undefined}.

run(get, KeyGen, _ValueGen, _State) ->
    Key = KeyGen(),
    {ok, Key};
run(put, KeyGen, ValueGen, _State) ->
    Key = KeyGen(),
    ValueGen(),
    {ok, Key};
run(delete, KeyGen, _ValueGen, _State) ->
    Key = KeyGen(),
    {ok, Key}.

Fix usage of run() in null driver

%% -------------------------------------------------------------------
%%
%% basho_bench: Benchmarking Suite
%%
%% Copyright (c) 2009-2010 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(basho_bench_driver_null).

-export([new/1,
         run/4]).

-include("basho_bench.hrl").

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

new(_Id) ->
    {ok, undefined}.

run(get, KeyGen, _ValueGen, State) ->
    Key = KeyGen(),
    {ok, State};
run(put, KeyGen, ValueGen, State) ->
    Key = KeyGen(),
    ValueGen(),
    {ok, State};
run(delete, KeyGen, _ValueGen, State) ->
    Key = KeyGen(),
    {ok, State}.


-module(rets_app).

-behaviour(application).

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

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

start(_StartType, _StartArgs) ->
  start_cowboy_instance(),
  rets_sup:start_link([application:get_all_env(rets)]).

stop(_State) ->
  ok.

start_cowboy_instance() ->
  start_cowboy().

start_cowboy() ->
  Opts = rets:cowboy_opts(),
  Dispatch = cowboy_router:compile(proplists:get_value(routes,Opts)),
  cowboy:start_http(proplists:get_value(name,Opts),
                    proplists:get_value(acceptors,Opts),
                    proplists:get_value(opts,Opts),
                    [{env,[{dispatch,Dispatch}]}]).

Stop the http server when terminating rets

%% -*- mode: erlang; erlang-indent-level: 2 -*-
-module(rets_app).

-behaviour(application).

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

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

start(_StartType, _StartArgs) ->
  start_cowboy_instance(),
  case rets_sup:start_link([application:get_all_env(rets)]) of
    {ok, _Pid} = OK ->
      OK;
    Error ->
      stop_cowboy_instance(),
      Error
  end.

stop(_State) ->
  stop_cowboy_instance(),
  ok.

start_cowboy_instance() ->
  {ok, _} = start_cowboy().

stop_cowboy_instance() ->
  Opts = rets:cowboy_opts(),
  cowboy:stop_listener(proplists:get_value(name,Opts)).

start_cowboy() ->
  Opts = rets:cowboy_opts(),
  Dispatch = cowboy_router:compile(proplists:get_value(routes,Opts)),
  cowboy:start_http(proplists:get_value(name,Opts),
                    proplists:get_value(acceptors,Opts),
                    proplists:get_value(opts,Opts),
                    [{env,[{dispatch,Dispatch}]}]).


-module(xmerlsec_util).
-export([coerce_c_string/1]).

coerce_c_string(S) when is_list(S) ->
    coerce_c_string(list_to_binary(S));
coerce_c_string(S) ->
    case binary:last(S) of
        0 -> S;
        _ -> <<S/binary, 0>>
    end.

Add atoms support to coerce_c_string

-module(xmerlsec_util).
-export([coerce_c_string/1]).

coerce_c_string(S) when is_atom(S) ->
    coerce_c_string(atom_to_list(S));
coerce_c_string(S) when is_list(S) ->
    coerce_c_string(list_to_binary(S));
coerce_c_string(S) ->
    case binary:last(S) of
        0 -> S;
        _ -> <<S/binary, 0>>
    end.


-module(eventsource_emitter).
-behaviour(cowboy_loop_handler).

-export([init/3]).
-export([info/3]).
-export([terminate/3]).

-record(state, {}).

init({_Any, http}, Req, _Opts) ->
    timer:send_after(0, {message, [":ok", "\n\n"]}),
    timer:send_after(40000, shutdown),
    Headers = [
        {<<"content-type">>, <<"text/event-stream">>},
        {<<"cache-control">>, <<"no-cache">>},
        {<<"connection">>, <<"keep-alive">>}
    ],
    {ok, Req2} = cowboy_req:chunked_reply(200, Headers, Req),
    {loop, Req2, #state{}, hibernate}.

info(shutdown, Req, State) ->
    {ok, Req, State};

info({message, Msg}, Req, State) ->
    ok = cowboy_req:chunk(Msg, Req),
    timer:send_after(1000, {message, ["data: ", id(), "\n\n"]}),
    {loop, Req, State, hibernate}.

terminate(_Reason, _Req, _State) ->
    ok.

id() ->
    {Mega, Sec, _Micro} = os:timestamp(),
    Id = ((Mega * 1000000 + Sec) * 1000), % + Micro,
    integer_to_list(Id).

Remove the disonnect after 40 seconds.

-module(eventsource_emitter).
-behaviour(cowboy_loop_handler).

-export([init/3]).
-export([info/3]).
-export([terminate/3]).

-record(state, {}).

init({_Any, http}, Req, _Opts) ->
    timer:send_after(0, {message, [":ok", "\n\n"]}),
    Headers = [
        {<<"content-type">>, <<"text/event-stream">>},
        {<<"cache-control">>, <<"no-cache">>},
        {<<"connection">>, <<"keep-alive">>}
    ],
    {ok, Req2} = cowboy_req:chunked_reply(200, Headers, Req),
    {loop, Req2, #state{}, hibernate}.

info(shutdown, Req, State) ->
    {ok, Req, State};

info({message, Msg}, Req, State) ->
    ok = cowboy_req:chunk(Msg, Req),
    timer:send_after(1000, {message, ["data: ", id(), "\n\n"]}),
    {loop, Req, State, hibernate}.

terminate(_Reason, _Req, _State) ->
    ok.

id() ->
    {Mega, Sec, _Micro} = os:timestamp(),
    Id = ((Mega * 1000000 + Sec) * 1000),
    integer_to_list(Id).


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

-export([start/0, override_resolver/0]).

start() ->
    try
        ok = application:start(sasl),
        application:start(os_mon),
        ok = application:start(ns_server)
    catch T:E ->
            timer:sleep(500),
            erlang:T(E)
    end.

override_resolver() ->
    inet_db:set_lookup([file, dns]),
    start().

Set disksup check interval to 1 minute.

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

-export([start/0, override_resolver/0]).

start() ->
    try
        %% Check disk space every minute instead of every 30
        application:set_env(os_mon, disk_space_check_interval, 1),
        ok = application:start(sasl),
        application:start(os_mon),
        ok = application:start(ns_server)
    catch T:E ->
            timer:sleep(500),
            erlang:T(E)
    end.

override_resolver() ->
    inet_db:set_lookup([file, dns]),
    start().


%% -------------------------------------------------------------------
%%
%% Copyright (c) 2014 SyncFree Consortium.  All Rights Reserved.
%%
%% 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(lasp_storage_backend).
-author("Christopher Meiklejohn <cmeiklejohn@basho.com>").

-include("lasp.hrl").

-callback start(atom())-> {ok, store()} | ignore | {error, term()}.

-callback put(store(), id(), variable()) -> ok | {error, atom()}.

-callback get(store(), id()) ->
    {ok, variable()} | {error, not_found} | {error, atom()}.

-callback update(store(), id(), function()) ->
    {ok, any()} | error | {error, atom()}.

-callback fold(store(), function(), term()) -> {ok, term()}.

-callback reset(store()) -> ok.

Add update_all/2 to callback module.

%% -------------------------------------------------------------------
%%
%% Copyright (c) 2014 SyncFree Consortium.  All Rights Reserved.
%%
%% 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(lasp_storage_backend).
-author("Christopher Meiklejohn <cmeiklejohn@basho.com>").

-include("lasp.hrl").

-callback start(atom())-> {ok, store()} | ignore | {error, term()}.

-callback put(store(), id(), variable()) -> ok | {error, atom()}.

-callback get(store(), id()) ->
    {ok, variable()} | {error, not_found} | {error, atom()}.

-callback update(store(), id(), function()) ->
    {ok, any()} | error | {error, atom()}.

-callback update_all(store(), function()) ->
    {ok, any()} | error | {error, atom()}.

-callback fold(store(), function(), term()) -> {ok, term()}.

-callback reset(store()) -> ok.


-define(PRINT(Var), io:format("DEBUG: ~p:~p - ~p~n~n ~p~n~n", [?MODULE, ?LINE, ??Var, Var])).

-define(BUCKET, <<"saturn_leaf">>).

-define(PROXY_MASTER, saturn_proxy_vnode_master).
-define(PROXY_SERVICE, saturn_proxy).
-define(SIMPLE_MASTER, saturn_simple_backend_vnode_master).
-define(SIMPLE_SERVICE, saturn_simple_backend).

-define(GROUPSFILE, "data/manager/groups_file_simple.saturn").
-define(TREEFILE, "data/manager/tree_file_simple.saturn").
-define(TREEFILE_TEST, "../include/tree_file_test.saturn").
-define(GROUPSFILE_TEST, "../include/groups_file_test.saturn").

-define(BACKEND, simple_backend).
-define(BACKEND_CONNECTOR_FSM, simple_backend_connector_fsm).

-define(MYIDPREFIX, {prefix, myid_prefix}).
-define(MYIDKEY, myid_key).

-define(HEARTBEAT_FREQ, 1000).

Change conector to not be FSM

-define(PRINT(Var), io:format("DEBUG: ~p:~p - ~p~n~n ~p~n~n", [?MODULE, ?LINE, ??Var, Var])).

-define(BUCKET, <<"saturn_leaf">>).

-define(PROXY_MASTER, saturn_proxy_vnode_master).
-define(PROXY_SERVICE, saturn_proxy).
-define(SIMPLE_MASTER, saturn_simple_backend_vnode_master).
-define(SIMPLE_SERVICE, saturn_simple_backend).

-define(GROUPSFILE, "data/manager/groups_file_simple.saturn").
-define(TREEFILE, "data/manager/tree_file_simple.saturn").
-define(TREEFILE_TEST, "../include/tree_file_test.saturn").
-define(GROUPSFILE_TEST, "../include/groups_file_test.saturn").

-define(BACKEND, simple_backend).
-define(BACKEND_CONNECTOR, simple_backend_connector).

-define(MYIDPREFIX, {prefix, myid_prefix}).
-define(MYIDKEY, myid_key).

-define(HEARTBEAT_FREQ, 1000).


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

%% General indices
-define(INDEX_SEP, <<"$">>).
-define(UINDEX_SEP, <<"%">>).
-define(INDEX_PAGE_LIMIT, 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).

%% Storage ETS tables inside antidote_pvc_vnode
-define(DECIDE_TABLE, pvc_decide_table).
-define(MRVC_TABLE, most_recent_vc).
-define(LAST_VSN_TABLE, last_vsn).
-define(PENDING_DATA_TABLE, pending_tx_data).
-define(PENDING_READS_TABLE, pending_reads).
-define(PENDING_WRITES_TABLE, pending_writes).
-define(RC_STORAGE, rc_storage).

Decrease dequeue event interval to 1ms.

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

%% General indices
-define(INDEX_SEP, <<"$">>).
-define(UINDEX_SEP, <<"%">>).
-define(INDEX_PAGE_LIMIT, 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, 1).

%% Storage ETS tables inside antidote_pvc_vnode
-define(DECIDE_TABLE, pvc_decide_table).
-define(MRVC_TABLE, most_recent_vc).
-define(LAST_VSN_TABLE, last_vsn).
-define(PENDING_DATA_TABLE, pending_tx_data).
-define(PENDING_READS_TABLE, pending_reads).
-define(PENDING_WRITES_TABLE, pending_writes).
-define(RC_STORAGE, rc_storage).


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

-module (nprocreg_registry_handler).
-behaviour (process_registry_handler).
-include_lib ("wf.hrl").
-export ([
    init/2,
    finish/2,
    get_pid/3,
    get_pid/4
]).

init(_Config, State) ->
    {ok, State}.

finish(_Config, State) ->
    {ok, State}.

get_pid(Key, _Config, State) ->
    Pid = mprocreg:get_pid(Key),
    {ok, Pid, State}.

get_pid(Key, Function, _Config, State) ->
    Pid = nprocreg:get_pid(Key, Function),
    {ok, Pid, State}.

Fix a typo in nprocreg process registry handler

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

-module (nprocreg_registry_handler).
-behaviour (process_registry_handler).
-include_lib ("wf.hrl").
-export ([
    init/2,
    finish/2,
    get_pid/3,
    get_pid/4
]).

init(_Config, State) ->
    {ok, State}.

finish(_Config, State) ->
    {ok, State}.

get_pid(Key, _Config, State) ->
    Pid = nprocreg:get_pid(Key),
    {ok, Pid, State}.

get_pid(Key, Function, _Config, State) ->
    Pid = nprocreg:get_pid(Key, Function),
    {ok, Pid, State}.


-module(elli_bench_sup).

-behaviour(supervisor).

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

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

%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).

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

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

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

init([]) ->
    crypto:start(),
    application:start(emysql),
    emysql:add_pool(test_pool, 32,
       "benchmarkdbuser", "benchmarkdbpass", "localhost", 3306,
       "hello_world", utf8),
    emysql:prepare(db_stmt, <<"SELECT * FROM World where id = ?">>),
    ElliOpts = [{callback, elli_bench_cb}, {port, 8080}],
    ElliSpec = {
        fancy_http,
        {elli, start_link, [ElliOpts]},
        permanent,
        5000,
        worker,
        [elli]},

    {ok, { {one_for_one, 5, 10}, [ElliSpec]} }.

Update client connection pool to mirror benchmark's MySQL pool limit of 5k

-module(elli_bench_sup).

-behaviour(supervisor).

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

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

%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).

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

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

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

init([]) ->
    crypto:start(),
    application:start(emysql),
    emysql:add_pool(test_pool, 5000,
       "benchmarkdbuser", "benchmarkdbpass", "localhost", 3306,
       "hello_world", utf8),
    emysql:prepare(db_stmt, <<"SELECT * FROM World where id = ?">>),
    ElliOpts = [{callback, elli_bench_cb}, {port, 8080}],
    ElliSpec = {
        fancy_http,
        {elli, start_link, [ElliOpts]},
        permanent,
        5000,
        worker,
        [elli]},

    {ok, { {one_for_one, 5, 10}, [ElliSpec]} }.


-module(beamjs_mod_repl).
-export([exports/1,init/1]).
-behaviour(erlv8_module).
-include_lib("erlv8/include/erlv8.hrl").

init(_VM) ->
	ok.

exports(_VM) ->
	erlv8_object:new([{"start", fun start/2}]).

start(#erlv8_fun_invocation{} = Invocation, []) ->
	start(Invocation,["beam.js> "]);
start(#erlv8_fun_invocation{ vm = VM } = _Invocation, [Prompt]) ->
	supervisor:start_child(beamjs_repl_sup,[Prompt, beamjs_repl_console, VM]),
	receive X ->
			X
	end.

Make REPL show node name in the prompt if it is a distributed node.

-module(beamjs_mod_repl).
-export([exports/1,init/1]).
-behaviour(erlv8_module).
-include_lib("erlv8/include/erlv8.hrl").

init(_VM) ->
	ok.

exports(_VM) ->
	erlv8_object:new([{"start", fun start/2}]).

start(#erlv8_fun_invocation{} = Invocation, []) ->
	case node() of
		nonode@nohost ->
			start(Invocation,["beam.js> "]);
		Node ->
			start(Invocation,[lists:flatten(io_lib:format("(~p)beam.js> ",[Node]))])
	end;

start(#erlv8_fun_invocation{ vm = VM } = _Invocation, [Prompt]) ->
	supervisor:start_child(beamjs_repl_sup,[Prompt, beamjs_repl_console, VM]),
	receive X ->
			X
	end.


-module(er_crawler).

-behaviour(gen_server).

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

-record(state, {feed}).

start_link(Feed) ->
    gen_server:start_link(?MODULE, [Feed], []).

init([Feed]) ->
    io:format("~p starting~n", [?MODULE]),
    {ok, #state{feed=Feed}, 0}.

handle_call(_, _From, State) ->
    {reply, ok, State}.

handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(timeout, State) ->
    io:format("timeout~n"),
    {stop, normal, State};

handle_info(_Msg, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    io:format("~p stopping~n", [?MODULE]),
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

Check for updates in crawler

-module(er_crawler).

-behaviour(gen_server).

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

-include("erl_reader.hrl").

-record(state, {feed}).

start_link(Feed) ->
    gen_server:start_link(?MODULE, [Feed], []).

init([Feed]) ->
    io:format("~p starting~n", [?MODULE]),
    gen_server:cast(self(), check_for_updates),
    {ok, #state{feed=Feed}}.

handle_call(_, _From, State) ->
    {reply, ok, State}.

handle_cast(check_for_updates, State = #state{feed=Feed}) ->
    io:format("Checking for updates: ~p~n", [Feed#er_feed.feed]),
    {stop, normal, State};

handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(_Msg, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    io:format("~p stopping~n", [?MODULE]),
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.


%% Feel free to use, reuse and abuse the code in this file.

%% @doc EventSource emitter.
-module(eventsource_handler).

-export([init/2]).
-export([info/3]).

init(Req, Opts) ->
	Headers = [{<<"content-type">>, <<"text/event-stream">>}],
	Req2 = cowboy_req:chunked_reply(200, Headers, Req),
	erlang:send_after(1000, self(), {message, "Tick"}),
	{cowboy_loop, Req2, Opts, 5000}.

info({message, Msg}, Req, State) ->
	cowboy_req:chunk(["id: ", id(), "\ndata: ", Msg, "\n\n"], Req),
	erlang:send_after(1000, self(), {message, "Tick"}),
	{ok, Req, State}.

id() ->
	{Mega, Sec, Micro} = erlang:now(),
	Id = (Mega * 1000000 + Sec) * 1000000 + Micro,
	integer_to_list(Id, 16).

Use the new unique_integer function to generate IDs

%% Feel free to use, reuse and abuse the code in this file.

%% @doc EventSource emitter.
-module(eventsource_handler).

-export([init/2]).
-export([info/3]).

init(Req, Opts) ->
	Headers = [{<<"content-type">>, <<"text/event-stream">>}],
	Req2 = cowboy_req:chunked_reply(200, Headers, Req),
	erlang:send_after(1000, self(), {message, "Tick"}),
	{cowboy_loop, Req2, Opts, 5000}.

info({message, Msg}, Req, State) ->
	cowboy_req:chunk(["id: ", id(), "\ndata: ", Msg, "\n\n"], Req),
	erlang:send_after(1000, self(), {message, "Tick"}),
	{ok, Req, State}.

id() ->
	integer_to_list(erlang:unique_integer([positive, monotonic]), 16).


-module(wsecli_handshake).
-include_lib("espec/include/espec.hrl").
-include_lib("hamcrest/include/hamcrest.hrl").

-include("wsecli.hrl").

spec() ->
  describe("wsecli_handshake", fun() ->
        it("should return a valid handshake request", fun() ->
              Resource  = "/",
              Host     = "localhost",
              Port      = 8080,

              HandShake = wsecli_handshake:build(Resource, Host, Port),
              assert_that(HandShake#handshake.version, is(13)),

              RequestLine = HandShake#handshake.request_line,
              assert_that(proplists:get_value("method", RequestLine), is("GET")),
              assert_that(proplists:get_value("version", RequestLine), is("1.1")),
              assert_that(proplists:get_value("resource", RequestLine), is(Resource)),

              Headers = HandShake#handshake.headers,
              assert_that(proplists:get_value("host", Headers), is(Host ++ ":" ++ integer_to_list(Port))),
              assert_that(proplists:get_value("upgrade", Headers), is("websocket")),
              assert_that(proplists:get_value("connection", Headers), is("upgrade")),
              assert_that(proplists:get_value("sec-websocket-key", Headers), is_not(undefined)),
              assert_that(proplists:get_value("sec-websocket-version", Headers), is("13"))
          end)
    end).

Rename spec module or shit happens

-module(wsecli_handshake_spec).
-include_lib("espec/include/espec.hrl").
-include_lib("hamcrest/include/hamcrest.hrl").

-include("wsecli.hrl").

spec() ->
  describe("wsecli_handshake", fun() ->
        it("should return a valid handshake request", fun() ->
              Resource  = "/",
              Host     = "localhost",
              Port      = 8080,

              HandShake = wsecli_handshake:build(Resource, Host, Port),
              assert_that(HandShake#handshake.version, is(13)),

              RequestLine = HandShake#handshake.request_line,
              assert_that(proplists:get_value("method", RequestLine), is("GET")),
              assert_that(proplists:get_value("version", RequestLine), is("1.1")),
              assert_that(proplists:get_value("resource", RequestLine), is(Resource)),

              Headers = HandShake#handshake.headers,
              assert_that(proplists:get_value("host", Headers), is(Host ++ ":" ++ integer_to_list(Port))),
              assert_that(proplists:get_value("upgrade", Headers), is("websocket")),
              assert_that(proplists:get_value("connection", Headers), is("upgrade")),
              assert_that(proplists:get_value("sec-websocket-key", Headers), is_not(undefined)),
              assert_that(proplists:get_value("sec-websocket-version", Headers), is("13"))
          end)
    end).


%% @doc The module contains the definition of agent environment operator callbacks to be implemented.

-module (mas_agent_env).

-include ("mas.hrl").

-type agent() :: mas:agent().
-type sim_params() :: mas:sim_params().
-type agent_behaviour() :: mas:agent_behaviour().

-callback start(model(), pos_integer()) -> ok.

-callback initial_agent(sim_params()) -> [agent()].

-callback behaviour_function(agent(), sim_params()) -> agent_behaviour().

-callback behaviours() -> [agent_behaviour()].

-callback meeting_function({agent_behaviour(), [agent()]}, sim_params()) -> [agent()].

-callback stats() -> [funstat()].

Fix dialyzer errors coming from emas usecase

%% @doc The module contains the definition of agent environment operator callbacks to be implemented.

-module (mas_agent_env).

-include ("mas.hrl").

-type agent() :: mas:agent().
-type sim_params() :: mas:sim_params().
-type agent_behaviour() :: mas:agent_behaviour().

-callback start(model(), pos_integer()) -> agent().

-callback initial_agent(sim_params()) -> agent().

-callback behaviour_function(agent(), sim_params()) -> agent_behaviour().

-callback behaviours() -> [agent_behaviour()].

-callback meeting_function({agent_behaviour(), [agent()]}, sim_params()) -> [agent()].

-callback stats() -> [funstat()].


-module(workorder_root_handler).

Implement empty work order collection

-module(workorder_root_handler).

-export([init/3]).
-export([content_types_provided/2]).
-export([work_order_collection_to_json/2]).

init(_Transport, _Req, []) ->
  {upgrade, protocol, cowboy_rest}.

content_types_provided(Req, State) ->
  {[
    {<<"application/json">>, work_order_collection_to_json}
  ], Req, State}.

work_order_collection_to_json(Req, State) ->
  Body = <<"{}">>,
  {Body, Req, State}.


-module(pgsql_listen_sup).

-behaviour(mirrored_supervisor).

-define(WORKER, pgsql_listen_worker).

-rabbit_boot_step({pgsql_listen_supervisor,
                   [{description, "PgSQL Listen Supervisor"},
                    {mfa,         {rabbit_sup, start_child, [?MODULE]}},
                    {requires,    kernel_ready},
                    {enables,     pgsql_listen_exchange}]}).

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

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

init([]) ->
    {ok, {{one_for_one, 3, 10},
          [{?WORKER,
           {?WORKER, start_link, []},
           permanent, ?MAX_WAIT, worker, [?WORKER]}]}}.

start_link() ->
     mirrored_supervisor:start_link(
       {local, ?MODULE}, ?MODULE,
       fun rabbit_misc:execute_mnesia_transaction/1,
       ?MODULE, []).

Add comments, reorder functions, consolidate exports

%%==============================================================================
%% @author Gavin M. Roy <gavinr@aweber.com>
%% @copyright 2014 AWeber Communications
%% @end
%%==============================================================================

%% @doc Supervisor for the PgSQL LISTEN Exchange worker
%% @end

-module(pgsql_listen_sup).

-behaviour(mirrored_supervisor).

-define(WORKER, pgsql_listen_worker).

-rabbit_boot_step({pgsql_listen_supervisor,
                   [{description, "PgSQL Listen Supervisor"},
                    {mfa,         {rabbit_sup, start_child, [?MODULE]}},
                    {requires,    kernel_ready},
                    {enables,     pgsql_listen_exchange}]}).

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

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

start_link() ->
     mirrored_supervisor:start_link(
       {local, ?MODULE}, ?MODULE,
       fun rabbit_misc:execute_mnesia_transaction/1,
       ?MODULE, []).

init([]) ->
    {ok, {{one_for_one, 3, 10},
          [{?WORKER,
           {?WORKER, start_link, []},
           permanent, ?MAX_WAIT, worker, [?WORKER]}]}}.


%% machi merkle tree records

-record(naive, {
          chunk_size = 1048576   :: pos_integer(), %% default 1 MB
          recalc = true          :: boolean(),
          root                   :: 'undefined' | binary(),
          lvl1 = []              :: [ binary() ],
          lvl2 = []              :: [ binary() ],
          lvl3 = []              :: [ binary() ],
          leaves = []            :: [ { Offset :: pos_integer(),
                                        Size :: pos_integer(),
                                        Csum :: binary()} ]
         }).

-record(mt, {
          filename               :: string(),
          tree                   :: #naive{}|merklet:tree(),
          backend = 'merklet'    :: 'naive'|'merklet'
         }).

Remove merklet from header file too.

%% machi merkle tree records

-record(naive, {
          chunk_size = 1048576   :: pos_integer(), %% default 1 MB
          recalc = true          :: boolean(),
          root                   :: 'undefined' | binary(),
          lvl1 = []              :: [ binary() ],
          lvl2 = []              :: [ binary() ],
          lvl3 = []              :: [ binary() ],
          leaves = []            :: [ { Offset :: pos_integer(),
                                        Size :: pos_integer(),
                                        Csum :: binary()} ]
         }).

-record(mt, {
          filename               :: string(),
          tree                   :: #naive{},
          backend = 'naive'      :: 'naive'
         }).


%%% Add erlang apache license here as a lot of this code
%%% is copy pasta

-module('crypto2').
-on_load(on_load/0).

%% API exports
-export([
         sha256_init/0,
         hash_update/2,
         hash_final/1
        ]).

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

sha256_init() -> "Undefined".
hash_update(_Context, _Data) -> "Undefined".
hash_final(_Context) -> "Undefined".

%%====================================================================
%% Internal functions
%%====================================================================

%on_load() ->
  %case code:priv_dir(crypto2) of
    %Path when is_list(Path) ->
      %erlang:load_nif(filename:join(Path, "crypto2"));
  %end.

on_load() ->
  case code:priv_dir(crypto2) of
    Path when is_list(Path) ->
      erlang:load_nif(filename:join(Path, "crypto2"), []);
    _ ->
      {error, "Could not find library"}
  end.

Add hash_init. Only sha256 implementation


% vim: sw=4 ts=4 et ft=erlang
% Nitrogen Web Framework for Erlang
% Copyright (c) 2008-2010 Rusty Klophaus
% See MIT-LICENSE for licensing information.

-module (default_config_handler).
-include("wf.hrl").
-behaviour (config_handler).
-export ([
    init/2,
    finish/2,
    get_value/4,
    get_values/4
]).

init(_Config, _State) ->
    {ok, []}.

finish(_Config, _State) ->
    {ok, []}.

get_value(Key, DefaultValue, Config, State) ->
    case get_values(Key, [DefaultValue], Config, State) of
        [Value] ->
            Value;
        Values ->
            error_logger:error_msg("Too many matching config values for key: ~p~n", [Key]),
            throw({nitrogen_error, too_many_matching_values, Key, Values})
    end.

get_values(Key, DefaultValue, _Config, _State) ->
    case application:get_env(nitrogen, Key) of
        {ok, Value} ->
            [Value];
        undefined ->
            DefaultValue
    end.

Update config handler to also use nitrogen_core

% vim: sw=4 ts=4 et ft=erlang
% Nitrogen Web Framework for Erlang
% Copyright (c) 2008-2010 Rusty Klophaus
% See MIT-LICENSE for licensing information.

-module (default_config_handler).
-include("wf.hrl").
-behaviour (config_handler).
-export ([
    init/2,
    finish/2,
    get_value/4,
    get_values/4
]).

init(_Config, _State) ->
    {ok, []}.

finish(_Config, _State) ->
    {ok, []}.

get_value(Key, DefaultValue, Config, State) ->
    case get_values(Key, [DefaultValue], Config, State) of
        [Value] ->
            Value;
        Values ->
            error_logger:error_msg("Too many matching config values for key: ~p~n", [Key]),
            throw({nitrogen_error, too_many_matching_values, Key, Values})
    end.

get_values(Key, DefaultValue, Config, State) ->
    %% By default, use nitrogen_core as the app (for Nitrogen 2.4+), however,
    %% for backwards compatibility, also check for the nitrogen app.
    Apps = [nitrogen_core, nitrogen],
    get_values(Apps, Key, DefaultValue, Config, State).

get_values([], _Key, DefaultValue, _Config, _State) ->
    DefaultValue;
get_values([App|Apps], Key, DefaultValue, _Config, _State) ->
    case application:get_env(App, Key) of
        {ok, Value} ->
            [Value];
        undefined ->
            get_values(Apps, Key, DefaultValue, _Config, _State)
    end.


-module(beamup_project).

-export([new/1]).

new(Path) ->
  #{path => Path,
    name => path_to_name(Path),
    commit => beamup_git:commit_hash(Path),
    tool => beamup_build_tool:detect(Path),
    branch => beamup_git:branch(Path)}.

path_to_name(Path) ->
  lists:last(string:tokens(Path,"/")).

Add notion of architecture to project metadata

-module(beamup_project).

-export([new/1]).

new(Path) ->
  #{path => Path,
    name => name_from_path(Path),
    architecture => architecture(),
    branch => beamup_git:branch(Path),
    version => beamup_git:commit_hash(Path),
    tool => beamup_build_tool:detect(Path)}.

name_from_path(Path) ->
  lists:last(string:lexemes(Path,"/")).

architecture() ->
  list_to_binary(erlang:system_info(system_architecture)).


%% -*- erlang-indent-level: 2 -*-
%%-------------------------------------------------------------------------
%% The guard in f/3 revealed a problem in the translation of the 'bs_add'
%% BEAM instruction to Icode. The fail label was not properly translated.
%% Fixed 3/2/2011. Then in 2015 we found another issue: g/2.  Also fixed.
%%-------------------------------------------------------------------------
-module(bs_add).

-export([test/0]).

test() ->
  42 = f(<<12345:16>>, 4711, <<42>>),
  true = g(<<1:13>>, 3),  %% was handled OK, but
  false = g(<<>>, gurka), %% this one leaked badarith
  ok.

f(Bin, A, B) when <<A:9, B:7/binary>> == Bin ->
  gazonk;
f(Bin, _, _) when is_binary(Bin) ->
  42.

%% Complex way of testing (bit_size(Bin) + Len) rem 8 =:= 0
g(Bin, Len) when is_binary(<<Bin/binary-unit:1, 123:Len>>) ->
    true;
g(_, _) ->
    false.


-module(fsevents).
-include("api.hrl").
-export(?API).

find_executable() ->
    fs:find_executable("mac_listener", "deps/fs/priv/mac_listener").

known_events() ->
    [mustscansubdirs,userdropped,kerneldropped,eventidswrapped,historydone,rootchanged,
        mount,unmount,created,removed,inodemetamod,renamed,modified,finderinfomod,changeowner,
        xattrmod,isfile,isdir,issymlink,ownevent].

start_port(Path, Cwd) ->
    erlang:open_port({spawn_executable, find_executable()},
        [stream, exit_status, {line, 16384}, {args, ["-F", Path]}, {cd, Cwd}]).

line_to_event(Line) ->
    [_EventId, Flags1, Path] = string:tokens(Line, [$\t]),
    [_, Flags2] = string:tokens(Flags1, [$=]),
    {ok, T, _} = erl_scan:string(Flags2 ++ "."),
    {ok, Flags} = erl_parse:parse_term(T),
    {Path, Flags}.

Use :fs, :project_dir to set absolute path to mac_listener (useful when launching app from escript)

-module(fsevents).
-include("api.hrl").
-export(?API).

find_executable() ->
    case application:get_env(fs, project_dir) of
        {ok, P} -> fs:find_executable("mac_listener", lists:append([P, "deps/fs/priv/mac_listener"]));
        undefined -> fs:find_executable("mac_listener", "deps/fs/priv/mac_listener") end.

known_events() ->
    [mustscansubdirs,userdropped,kerneldropped,eventidswrapped,historydone,rootchanged,
        mount,unmount,created,removed,inodemetamod,renamed,modified,finderinfomod,changeowner,
        xattrmod,isfile,isdir,issymlink,ownevent].

start_port(Path, Cwd) ->
    erlang:open_port({spawn_executable, find_executable()},
        [stream, exit_status, {line, 16384}, {args, ["-F", Path]}, {cd, Cwd}]).

line_to_event(Line) ->
    [_EventId, Flags1, Path] = string:tokens(Line, [$\t]),
    [_, Flags2] = string:tokens(Flags1, [$=]),
    {ok, T, _} = erl_scan:string(Flags2 ++ "."),
    {ok, Flags} = erl_parse:parse_term(T),
    {Path, Flags}.


%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1997-2017. All Rights Reserved.
%%
%% 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.
%%
%% %CopyrightEnd%
%%
%% This record is returned by inet:gethostbyaddr/2 and inet:gethostbyname/2.

-record(hostent,
	{
	 h_name		  :: inet:hostname(),	 %% official name of host
	 h_aliases = []   :: [inet:hostname()],	 %% alias list
	 h_addrtype	  :: inet | inet6 | caa | cname | gid | hinfo | ns | mb | md | mg
	               | mf | minfo | mx | naptr | null | ptr | soa | spf | srv | txt
	               | uid | uinfo | unspec | uri | wks, %% host address type
	 h_length	  :: non_neg_integer(),	 %% length of address
	 h_addr_list = [] :: [inet:ip_address()] %% list of addresses from name server
	}).

Revert "Correct hostent_addr h_addrtype typespec"

%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1997-2017. All Rights Reserved.
%%
%% 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.
%%
%% %CopyrightEnd%
%%
%% This record is returned by inet:gethostbyaddr/2 and inet:gethostbyname/2.

-record(hostent,
	{
	 h_name		  :: inet:hostname(),	%% official name of host
	 h_aliases = []   :: [inet:hostname()],	%% alias list
	 h_addrtype	  :: 'inet' | 'inet6',	%% host address type
	 h_length	  :: non_neg_integer(),	%% length of address
	 h_addr_list = [] :: [inet:ip_address()]%% list of addresses from name server
	}).


-module(test_utils).

-export([test_cleanup/1,
         nuke_nodes_from_solr/0]).

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

%% @doc graceful shutdown of apps started by tests
%%
%% This seems to get rid of the following error reports otherwise seen at the end of a test run:
%%
%% =ERROR REPORT==== 21-Sep-2011::09:16:50 ===
%% ** Generic server inet_gethost_native_sup terminating
%% ** Last message in was {'EXIT',<0.136.0>,killed}
%% ** When Server state == {state,inet_gethost_native,undefined,<0.136.0>,
%%                                {local,inet_gethost_native_sup}}
test_cleanup(_State) ->
    application:stop(emysql),
    application:stop(public_key),
    application:stop(ssl),
    case whereis(inet_gethost_native_sup) of
        P when is_pid(P) ->
            inet_gethost_native:terminate(shutdown, P);
        _ ->
            ok
    end.

nuke_nodes_from_solr() ->
    error_logger:info_msg("nuking nodes from solr~n"),
    Body = <<"<delete><query>X_CHEF_type_CHEF_X:node</query></delete>">>,
    Got = ibrowse:send_req("http://localhost:8983/solr/update",
                           [{"content-type", "application/xml"}],
                           post,
                           Body).

Add ibrowse clean shutdown for integration test

-module(test_utils).

-export([test_cleanup/1,
         nuke_nodes_from_solr/0]).

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

%% @doc graceful shutdown of apps started by tests
%%
%% This seems to get rid of the following error reports otherwise seen at the end of a test run:
%%
%% =ERROR REPORT==== 21-Sep-2011::09:16:50 ===
%% ** Generic server inet_gethost_native_sup terminating
%% ** Last message in was {'EXIT',<0.136.0>,killed}
%% ** When Server state == {state,inet_gethost_native,undefined,<0.136.0>,
%%                                {local,inet_gethost_native_sup}}
test_cleanup(_State) ->
    application:stop(emysql),
    application:stop(public_key),
    application:stop(ssl),
    application:stop(ibrowse),
    case whereis(inet_gethost_native_sup) of
        P when is_pid(P) ->
            inet_gethost_native:terminate(shutdown, P);
        _ ->
            ok
    end.

nuke_nodes_from_solr() ->
    error_logger:info_msg("nuking nodes from solr~n"),
    Body = <<"<delete><query>X_CHEF_type_CHEF_X:node</query></delete>">>,
    Got = ibrowse:send_req("http://localhost:8983/solr/update",
                           [{"content-type", "application/xml"}],
                           post,
                           Body).


-module(mod_beeldenzoeker).
-author("Driebit <tech@driebit.nl>").

-mod_title("Beeldenzoeker").
-mod_description("Media collections powered by Elasticsearch").
-mod_prio(200).
-mod_depends([mod_ginger_base]).
-mod_schema(4).

-include_lib("zotonic.hrl").
-include_lib("mod_elasticsearch/include/elasticsearch.hrl").

-export([
    manage_schema/2
]).

manage_schema(_Version, _Context) ->
    #datamodel{
        categories = [
            {beeldenzoeker_query, elastic_query, [
                {title, {trans, [
                    {nl, <<"Zoekopdracht in Beeldenzoeker">>},
                    {en, <<"Media discovery search query">>}
                ]}},
                {is_unfindable, true}
            ]}
        ],
        resources = [
            {beeldenzoeker, collection, [
                {title, {trans, [{nl, <<"Beeldenzoeker">>},
                    {en, <<"Media discovery">>}]}},
                {language, [en, nl]},
                {is_unfindable, true}
            ]},
            {beeldenzoeker, menu, [
                {title, "Beeldenzoeker menu"}
            ]}
        ]
    }.

Make sure beeldenzoeker_query is findable

-module(mod_beeldenzoeker).
-author("Driebit <tech@driebit.nl>").

-mod_title("Beeldenzoeker").
-mod_description("Media collections powered by Elasticsearch").
-mod_prio(200).
-mod_depends([mod_ginger_base]).
-mod_schema(4).

-include_lib("zotonic.hrl").
-include_lib("mod_elasticsearch/include/elasticsearch.hrl").

-export([
    manage_schema/2
]).

manage_schema(_Version, _Context) ->
    #datamodel{
        categories = [
            {beeldenzoeker_query, elastic_query, [
                {title, {trans, [
                    {nl, <<"Zoekopdracht in Beeldenzoeker">>},
                    {en, <<"Media discovery search query">>}
                ]}},
                {is_unfindable, false}
            ]}
        ],
        resources = [
            {beeldenzoeker, collection, [
                {title, {trans, [{nl, <<"Beeldenzoeker">>},
                    {en, <<"Media discovery">>}]}},
                {language, [en, nl]},
                {is_unfindable, true}
            ]},
            {beeldenzoeker, menu, [
                {title, "Beeldenzoeker menu"}
            ]}
        ]
    }.


-module(ginger_geo_search).

-export([search_query/2]).

-include_lib("zotonic.hrl").

%% @doc Supports all the usual query model arguments
%% Selects and filters locations data.
search_query(#search_query{search={ginger_geo, Args}}, Context) ->

    GingerArgs = ginger_search:merge_ginger_args(Args, Context),
    BaseSearch = search_query:search(GingerArgs, Context),

    WhereStr = "rsc.pivot_location_lat IS NOT NULL AND rsc.pivot_location_lng IS NOT NULL",

    Where = case BaseSearch#search_sql.where of
        [] ->
            [WhereStr];
        OldWhere ->
            lists:append(OldWhere, " And " ++ WhereStr)
    end,

    BaseSearch#search_sql{
        select="rsc.id, rsc.pivot_location_lat, rsc.pivot_location_lng, rsc.pivot_category_nr",
        limit="Limit ALL",
        where=Where
    };

%% @doc Similar to z_geo_search:search_query/2 but result set includes locations and category
search_query(#search_query{search={ginger_geo_nearby, Args}}, Context) ->
    BaseSearch = z_geo_search:search_query(#search_query{search={geo_nearby, Args}}, Context),
    BaseSearch#search_sql{
        select="r.id, r.pivot_location_lat, r.pivot_location_lng, r.pivot_category_nr",
        limit="Limit ALL"
    }.

Make ginger_geo work with filters option

-module(ginger_geo_search).

-export([search_query/2]).

-include_lib("zotonic.hrl").

%% @doc Supports all the usual query model arguments
%% Selects and filters locations data.
search_query(#search_query{search={ginger_geo, Args}}, Context) ->

    BaseSearch = ginger_search:search_query(#search_query{search={ginger_search, Args}}, Context),

    WhereStr = "rsc.pivot_location_lat IS NOT NULL AND rsc.pivot_location_lng IS NOT NULL",

    Where = case BaseSearch#search_sql.where of
        [] ->
            [WhereStr];
        OldWhere ->
            lists:append(OldWhere, " And " ++ WhereStr)
    end,

    BaseSearch#search_sql{
        select="rsc.id, rsc.pivot_location_lat, rsc.pivot_location_lng, rsc.pivot_category_nr",
        limit="Limit ALL",
        where=Where
    };

%% @doc Similar to z_geo_search:search_query/2 but result set includes locations and category
search_query(#search_query{search={ginger_geo_nearby, Args}}, Context) ->
    BaseSearch = z_geo_search:search_query(#search_query{search={geo_nearby, Args}}, Context),
    BaseSearch#search_sql{
        select="r.id, r.pivot_location_lat, r.pivot_location_lng, r.pivot_category_nr",
        limit="Limit ALL"
    }.


% 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.

-module(config_app).

-behaviour(application).

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

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

start(_StartType, _StartArgs) ->
    config_sup:start_link(get_ini_files()).

stop(_State) ->
    ok.

get_ini_files() ->
    Etc = filename:join(code:root_dir(), "etc"),
    Default = [filename:join(Etc,"default.ini"), filename:join(Etc,"local.ini")],
    case init:get_argument(couch_ini) of
    error ->
        Default;
    {ok, [[]]} ->
        Default;
    {ok, [Values]} ->
        Values
    end.

Check that default config files exist

% 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.

-module(config_app).

-behaviour(application).

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

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

start(_StartType, _StartArgs) ->
    config_sup:start_link(get_ini_files()).

stop(_State) ->
    ok.

get_ini_files() ->
    Etc = filename:join(code:root_dir(), "etc"),
    Default = [filename:join(Etc,"default.ini"), filename:join(Etc,"local.ini")],
    DefaultExists = lists:filter(fun filelib:is_file/1, Default),
    case init:get_argument(couch_ini) of
    error ->
        DefaultExists;
    {ok, [[]]} ->
        DefaultExists;
    {ok, [Values]} ->
        Values
    end.


%%
%%
%%

-record(triple, {
    type,
    subject,
    object,
    property
}).

Add some documentation on the fields.

%%
%%
%%

-record(triple, {
    type     :: resource | literal,
    subject  :: binary(),
    object   :: binary(),
    property :: binary()
}).


-define(PARAM_CALLBACK         , <<"oauth_callback">>).
-define(PARAM_CONSUMER_KEY     , <<"oauth_consumer_key">>).
-define(PARAM_NONCE            , <<"oauth_nonce">>).
-define(PARAM_REALM            , <<"realm">>).
-define(PARAM_SIGNATURE        , <<"oauth_signature">>).
-define(PARAM_SIGNATURE_METHOD , <<"oauth_signature_method">>).
-define(PARAM_TIMESTAMP        , <<"oauth_timestamp">>).
-define(PARAM_TOKEN            , <<"oauth_token">>).
-define(PARAM_VERIFIER         , <<"oauth_verifier">>).
-define(PARAM_VERSION          , <<"oauth_version">>).

Define name macro for parameter: "oauth_token_secret".

-define(PARAM_CALLBACK         , <<"oauth_callback">>).
-define(PARAM_CONSUMER_KEY     , <<"oauth_consumer_key">>).
-define(PARAM_NONCE            , <<"oauth_nonce">>).
-define(PARAM_REALM            , <<"realm">>).
-define(PARAM_SIGNATURE        , <<"oauth_signature">>).
-define(PARAM_SIGNATURE_METHOD , <<"oauth_signature_method">>).
-define(PARAM_TIMESTAMP        , <<"oauth_timestamp">>).
-define(PARAM_TOKEN            , <<"oauth_token">>).
-define(PARAM_TOKEN_SECRET     , <<"oauth_token_secret">>).
-define(PARAM_VERIFIER         , <<"oauth_verifier">>).
-define(PARAM_VERSION          , <<"oauth_version">>).


%% 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).

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, 10).
-define(MAX_VERSIONS, 5).

%% 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).


% Copyright (c) 2010, NorthScale, Inc.
% All rights reserved.

-module(mc_info).

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

-include("mc_constants.hrl").

-include("mc_entry.hrl").

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

version() ->
    VA = case catch(ns_info:version()) of
             X when is_list(X) -> X;
             _                 -> []
         end,
    V = case proplists:get_value(ns_server, VA) of
            undefined -> case proplists:get_value(emoxi, VA) of
                             undefined -> "unknown";
                             X2        -> X2
                         end;
            X3 -> X3
        end,
    "northscale_proxy-" ++ V.

Make emoxi report the product version proper.

% Copyright (c) 2010, NorthScale, Inc.
% All rights reserved.

-module(mc_info).

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

-include("mc_constants.hrl").

-include("mc_entry.hrl").

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

version() ->
    VA = case catch(ns_info:version()) of
             X when is_list(X) -> X;
             _                 -> []
         end,
    V = case proplists:get_value(ns_server, VA) of
            undefined -> case proplists:get_value(ns_server, VA) of
                             undefined -> "unknown";
                             X2        -> X2
                         end;
            X3 -> X3
        end,
    "northscale_proxy-" ++ V.


-record(config, { dir,
                  opts }).

-record(global_state, { working_dir }).

-define(FAIL, throw({error, failed})).

-define(ABORT(Str, Args), ?ERROR(Str, Args), halt(1)).

-define(CONSOLE(Str, Args), io:format(Str, Args)).

-define(DEBUG(Str, Args), rebar_log:log(debug, Str, Args)).
-define(INFO(Str, Args), rebar_log:log(info, Str, Args)).
-define(WARN(Str, Args), rebar_log:log(warn, Str, Args)).
-define(ERROR(Str, Args), rebar_log:log(error, Str, Args)).

-define(FMT(Str, Args), lists:flatten(io_lib:format(Str, Args))).

Use init:stop/1 over halt/1 to ensure all I/O gets a chance to flush

-record(config, { dir,
                  opts }).

-record(global_state, { working_dir }).

-define(FAIL, throw({error, failed})).

-define(ABORT(Str, Args), ?ERROR(Str, Args), init:stop(1)).

-define(CONSOLE(Str, Args), io:format(Str, Args)).

-define(DEBUG(Str, Args), rebar_log:log(debug, Str, Args)).
-define(INFO(Str, Args), rebar_log:log(info, Str, Args)).
-define(WARN(Str, Args), rebar_log:log(warn, Str, Args)).
-define(ERROR(Str, Args), rebar_log:log(error, Str, Args)).

-define(FMT(Str, Args), lists:flatten(io_lib:format(Str, Args))).


-module(teles_data_manager_sup).
-behaviour(supervisor).
-export([start_link/1, init/1, start_agents/2]).

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

init([NumAgents]) ->
    Manager = {data_manager, {teles_data_manager, start_link, [NumAgents]},
            permanent, 5000, worker, dynamic},

    % Start no agents, as they are added dynamically
    % when needed
    {ok, {{one_for_one, 10, 10}, [Manager]}}.

% Starts a number of agents
start_agents(Num, Space) ->
    start_agents(Num, Space, []).

start_agents(0, _, Results) -> Results;
start_agents(Num, Space, Results) ->
    AgentSpec = {{agent, Space, Num},
                {teles_data_agent, start_link, [Num, Space]},
                permanent, 5000, worker, dynamic},

    % Start the child
    Res = case supervisor:start_child({local, ?MODULE}, AgentSpec) of
        {ok, Pid} -> Pid;
        {error, {already_started, Pid}} -> Pid;
        {error, _} -> error
    end,
    start_agents(Num - 1, Space, [Res | Results]).

Change how data agents are started

-module(teles_data_manager_sup).
-behaviour(supervisor).
-export([start_link/1, init/1, start_agents/2]).

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

init([NumAgents]) ->
    Manager = {data_manager, {teles_data_manager, start_link, [NumAgents]},
            permanent, 5000, worker, dynamic},

    % Start no agents, as they are added dynamically
    % when needed
    {ok, {{one_for_one, 10, 10}, [Manager]}}.

% Starts a number of agents
start_agents(Num, Space) ->
    start_agents(Num, Space, []).

start_agents(0, _, Results) -> Results;
start_agents(Num, Space, Results) ->
    AgentSpec = {{agent, Space, Num},
                {teles_data_agent, start_link, [Num, Space]},
                temporary, 5000, worker, dynamic},

    % Start the child
    Res = case supervisor:start_child(?MODULE, AgentSpec) of
        {ok, Pid} -> Pid;
        {error, {already_started, Pid}} -> Pid;
        {error, _} -> error
    end,
    start_agents(Num - 1, Space, [Res | Results]).


%%% @author Jean Parpaillon <jean.parpaillon@free.fr>
%%% @copyright (C) 2014, Jean Parpaillon
%%% @doc
%%%
%%% @end
%%% Created : 5 Jul 2014 by Jean Parpaillon <jean.parpaillon@free.fr>

-module(dbus_auth_external).
-compile([{parse_transform, lager_transform}]).

-behaviour(dbus_auth).

% dbus_auth callbacks
-export([init/0,
	 challenge/2]).

init() ->
    {ok, <<"AUTH EXTERNAL 31303030\r\n">>}.

challenge(_, _) ->
    {error, invalid_challenge}.

Allow to set external authentication cookie from application env

%%% @author Jean Parpaillon <jean.parpaillon@free.fr>
%%% @copyright (C) 2014, Jean Parpaillon
%%% @doc
%%%
%%% @end
%%% Created : 5 Jul 2014 by Jean Parpaillon <jean.parpaillon@free.fr>

-module(dbus_auth_external).
-compile([{parse_transform, lager_transform}]).

-behaviour(dbus_auth).

% dbus_auth callbacks
-export([init/0,
	 challenge/2]).

-define(cookie, <<"31303030">>).

init() ->
    Cookie = get_cookie(),
    {ok, <<"AUTH EXTERNAL ", Cookie/binary, "\r\n">>}.

challenge(_, _) ->
    {error, invalid_challenge}.

%%%
%%% Priv
%%%
get_cookie() ->
    case application:get_env(dbus, external_cookie) of
	undefined -> ?cookie;
	{ok, Val} when is_list(Val) ->
	    list_to_binary(Val);
	{ok, Val} when is_binary(Val) ->
	    Val;
	{ok, Val} when is_integer(Val) ->
	    integer_to_binary(Val)
    end.


-module(mumq_tcpd).

-behaviour(gen_tcpd).

-export([start_link/0,
         init/1,
         handle_connection/2,
         handle_info/2,
         terminate/2]).

start_link() ->
    % TODO: Add tcp options nodelay and keepalive
    gen_tcpd:start_link({local, ?MODULE}, ?MODULE, [], tcp, 61613,
                        [{socket_options, [{reuseaddr, true}]}]).

init(_Args) ->
    {ok, none}.

handle_connection(Socket, State) ->
    mumq_conn:handle_connection(Socket, State).

handle_info(_Info, _State) ->
    noreply.

terminate(_Reason, _State) ->
    ok.

Set the TCP socket options

-module(mumq_tcpd).

-behaviour(gen_tcpd).

-export([start_link/0,
         init/1,
         handle_connection/2,
         handle_info/2,
         terminate/2]).

start_link() ->
    gen_tcpd:start_link({local, ?MODULE}, ?MODULE, [], tcp, 61613,
                        [{socket_options, [{reuseaddr, true},
                                           {nodelay, true},
                                           {keepalive, true}]}]).

init(_Args) ->
    {ok, none}.

handle_connection(Socket, State) ->
    mumq_conn:handle_connection(Socket, State).

handle_info(_Info, _State) ->
    noreply.

terminate(_Reason, _State) ->
    ok.


%% @doc This module starts the mas framework with given environment,
%% time and parameters

-module (mas).
-export ([start/4]).
-export_type([agent/0,
              agent/1,
              sim_params/0,
              sim_params/1,
              agent_behaviour/0,
              agent_behaviour/1]).

-include ("mas.hrl").

-type agent(Any) :: Any.
-type agent() :: agent(any()).

-type sim_params(Any) :: Any.
-type sim_params() :: sim_params(any()).

-type agent_behaviour(Any) :: Any.
-type agent_behaviour() :: agent_behaviour(any()).

-spec start(atom(), pos_integer(), sim_params(), [tuple()]) -> [agent()].
start(Module, Time, SP, Options) ->
    ConfigRecord =
        mas_config:proplist_to_record([{agent_env, Module} |
                                       Options]),
    io:format("### ConfigRecord: ~p~n", [ConfigRecord]),
    Model = ConfigRecord#config.model,
    Model:start(Time, SP, ConfigRecord).

Move `agent_env` from argument to options.

%% @doc This module starts the mas framework with given environment,
%% time and parameters

-module (mas).
-export ([start/3]).
-export_type([agent/0,
              agent/1,
              sim_params/0,
              sim_params/1,
              agent_behaviour/0,
              agent_behaviour/1]).

-include ("mas.hrl").

-type agent(Any) :: Any.
-type agent() :: agent(any()).

-type sim_params(Any) :: Any.
-type sim_params() :: sim_params(any()).

-type agent_behaviour(Any) :: Any.
-type agent_behaviour() :: agent_behaviour(any()).

-spec start(pos_integer(), sim_params(), [tuple()]) -> [agent()].
start(Time, SP, Options) ->
    ConfigRecord = mas_config:proplist_to_record(Options),
    io:format("### ConfigRecord: ~p~n", [ConfigRecord]),
    Model = ConfigRecord#config.model,
    Model:start(Time, SP, ConfigRecord).


%% Copyright 2010-2011 Tuncer Ayaz. All Rights Reserved.
%% Use of this source code is governed by a BSD-style
%% license that can be found in the LICENSE file.

-module(re2).
-author(tuncerayaz).

-export([compile/1,
         compile/2,
         match/2,
         match/3,
         replace/3,
         replace/4]).

-on_load(load_nif/0).

-define(nif_stub, nif_stub_error(?LINE)).
nif_stub_error(Line) ->
  erlang:nif_error({nif_not_loaded,module,?MODULE,line,Line}).

load_nif() ->
  PrivDir = case code:priv_dir(?MODULE) of
              {error, _} ->
                EbinDir = filename:dirname(code:which(?MODULE)),
                AppPath = filename:dirname(EbinDir),
                filename:join(AppPath, "priv");
              Path ->
                Path
            end,
  erlang:load_nif(filename:join(PrivDir, "re2_nif"), 0).

compile(_) ->
  ?nif_stub.
compile(_,_) ->
  ?nif_stub.
match(_,_) ->
  ?nif_stub.
match(_,_,_) ->
  ?nif_stub.
replace(_,_,_) ->
  ?nif_stub.
replace(_,_,_,_) ->
  ?nif_stub.

Use correct code:priv_dir/1 error code

%% Copyright 2010-2011 Tuncer Ayaz. All Rights Reserved.
%% Use of this source code is governed by a BSD-style
%% license that can be found in the LICENSE file.

-module(re2).
-author(tuncerayaz).

-export([compile/1,
         compile/2,
         match/2,
         match/3,
         replace/3,
         replace/4]).

-on_load(load_nif/0).

-define(nif_stub, nif_stub_error(?LINE)).
nif_stub_error(Line) ->
  erlang:nif_error({nif_not_loaded,module,?MODULE,line,Line}).

load_nif() ->
  PrivDir = case code:priv_dir(?MODULE) of
              {error, bad_name} ->
                EbinDir = filename:dirname(code:which(?MODULE)),
                AppPath = filename:dirname(EbinDir),
                filename:join(AppPath, "priv");
              Path ->
                Path
            end,
  erlang:load_nif(filename:join(PrivDir, "re2_nif"), 0).

compile(_) ->
  ?nif_stub.
compile(_,_) ->
  ?nif_stub.
match(_,_) ->
  ?nif_stub.
match(_,_,_) ->
  ?nif_stub.
replace(_,_,_) ->
  ?nif_stub.
replace(_,_,_,_) ->
  ?nif_stub.


-module(mover_phase_2_migration_callback).

-export([
         migration_start_worker_args/2,
         migration_action/2,
         migration_type/0,
         supervisor/0,
         error_halts_migration/0,
         reconfigure_object/2
         ]).

-include("mover.hrl").
-include_lib("moser/include/moser.hrl").

migration_start_worker_args(Object, AcctInfo) ->
    [Object, AcctInfo].

migration_action(OrgName, AcctInfo) ->
    OrgInfo = moser_acct_processor:expand_org_info(#org_info{org_name = OrgName, account_info = AcctInfo}),
    moser_utils:load_process_org(OrgInfo,
                     fun moser_group_converter:insert/1,
                     fun moser_chef_processor:cleanup_org_info/1,
                     "READ"),
    [{ok, done}].

migration_type() ->
    <<"phase_2_migration">>.

supervisor() ->
    mover_org_migrator_sup.

error_halts_migration() ->
    true.

reconfigure_object(ObjectId, _AcctInfo) ->
    mover_org_darklaunch:org_to_sql(ObjectId, ?PHASE_2_MIGRATION_COMPONENTS).

Remove [{ok, done}] so we catch crash on moser_utils:load_process_org.

-module(mover_phase_2_migration_callback).

-export([
         migration_start_worker_args/2,
         migration_action/2,
         migration_type/0,
         supervisor/0,
         error_halts_migration/0,
         reconfigure_object/2
         ]).

-include("mover.hrl").
-include_lib("moser/include/moser.hrl").

migration_start_worker_args(Object, AcctInfo) ->
    [Object, AcctInfo].

migration_action(OrgName, AcctInfo) ->
    OrgInfo = moser_acct_processor:expand_org_info(#org_info{org_name = OrgName, account_info = AcctInfo}),
    moser_utils:load_process_org(OrgInfo,
                     fun moser_group_converter:insert/1,
                     fun moser_chef_processor:cleanup_org_info/1,
                     "READ").

migration_type() ->
    <<"phase_2_migration">>.

supervisor() ->
    mover_org_migrator_sup.

error_halts_migration() ->
    true.

reconfigure_object(ObjectId, _AcctInfo) ->
    mover_org_darklaunch:org_to_sql(ObjectId, ?PHASE_2_MIGRATION_COMPONENTS).


%% -------------------------------------------------------------------
%%
%% 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_driver_null).

-export([new/0,
         run/4]).

-include("riak_bench.hrl").

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

new() ->
    {ok, undefined}.

run(get, KeyGen, ValueGen, State) ->
    Key = KeyGen(),
    {ok, Key};
run(put, KeyGen, ValueGen, State) ->
    Key = KeyGen(),
%    Value = ValueGen(),
    {ok, Key};
run(delete, KeyGen, ValueGen, State) ->
    Key = KeyGen(),
    {ok, Key}.

Make sure to evaluate value gen on put op to get a realistic perspective of overhead

%% -------------------------------------------------------------------
%%
%% 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_driver_null).

-export([new/0,
         run/4]).

-include("riak_bench.hrl").

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

new() ->
    {ok, undefined}.

run(get, KeyGen, ValueGen, State) ->
    Key = KeyGen(),
    {ok, Key};
run(put, KeyGen, ValueGen, State) ->
    Key = KeyGen(),
    Value = ValueGen(),
    {ok, Key};
run(delete, KeyGen, ValueGen, State) ->
    Key = KeyGen(),
    {ok, Key}.


%%%-------------------------------------------------------------------
%%% File : sm_data.hrl
%%% Author : Nicolas R Dufour <nrdufour@gmail.com>
%%% Created : 2009/05/19
%%% Description :
%%%     Basic record containing the simulation data.
%%%
%%% 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.
%%%-------------------------------------------------------------------

-record(sm_data,
	{

	%%% {EvTree; R;E;Current; RealTime; SList; Trace}

	events = [],
	resources = [],
	processes = [],
	actives = [],
	time,
	props = [],
	trace = false

	}
).

%%%

Set the time to 0.

%%%-------------------------------------------------------------------
%%% File : sm_data.hrl
%%% Author : Nicolas R Dufour <nrdufour@gmail.com>
%%% Created : 2009/05/19
%%% Description :
%%%     Basic record containing the simulation data.
%%%
%%% 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.
%%%-------------------------------------------------------------------

-record(sm_data,
	{

	%%% {EvTree; R;E;Current; RealTime; SList; Trace}

	events = [],
	resources = [],
	processes = [],
	actives = [],
	time = 0,
	props = [],
	trace = false

	}
).

%%%


-module(dk_ifi_sup).

-behaviour(supervisor).

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

%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).

%%% API

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

%%% Supervisor callbacks

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

Add child (dk_ifi gen_server) to supervisor

-module(dk_ifi_sup).

-behaviour(supervisor).

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

%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).

%%% API

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

%%% Supervisor callbacks

init([]) ->
    {ok, {{one_for_one, 5, 10}, [?CHILD(dk_ifi, worker)]}}.


-module(worker_throttle).
-export([init/0, handle/1]).

-define(MAX_EVENTS_PER_SECOND, 5).

-opaque state() :: queue().
-type throttle() :: {ok, non_neg_integer(), state()} | {error, term()}.

-export_type([state/0]).

-spec init() -> state().
init() ->
    queue:new().

-spec handle(state()) -> throttle().
handle(Q) ->
    Now = now(),
    Q1 = queue:in(Now, Q),
    Diff = timer:now_diff(Now, queue:get(Q1)) / 1000,
    if Diff > 1000 ->
        Q2 = queue:drop(Q1),
        throttle(Q2, queue:len(Q2));
    true ->
        throttle(Q1, queue:len(Q1))
    end.

-spec throttle(queue(), non_neg_integer()) -> throttle().
throttle(_Q, N) when N >= ?MAX_EVENTS_PER_SECOND * 2 ->
    {error, ["Worker is behaving badly: Sent ",
             integer_to_list(N), " events in a second, ignoring replies."]};

throttle(Q, N) when N > ?MAX_EVENTS_PER_SECOND ->
    {ok, 1000 div ?MAX_EVENTS_PER_SECOND, Q};

throttle(Q, _N) ->
    {ok, 0, Q}.

Use a macro instead of the magic numbers.

-module(worker_throttle).
-export([init/0, handle/1]).

-define(MAX_EVENTS_PER_SECOND, 5).
-define(MICROSECONDS_IN_SECOND, 1000000).

-opaque state() :: queue().
-type throttle() :: {ok, non_neg_integer(), state()} | {error, term()}.

-export_type([state/0]).

-spec init() -> state().
init() ->
    queue:new().

-spec handle(state()) -> throttle().
handle(Q) ->
    Now = now(),
    Q1 = queue:in(Now, Q),
    Diff = timer:now_diff(Now, queue:get(Q1)),
    if Diff > ?MICROSECONDS_IN_SECOND ->
        Q2 = queue:drop(Q1),
        throttle(Q2, queue:len(Q2));
    true ->
        throttle(Q1, queue:len(Q1))
    end.

-spec throttle(queue(), non_neg_integer()) -> throttle().
throttle(_Q, N) when N >= ?MAX_EVENTS_PER_SECOND * 2 ->
    {error, ["Worker is behaving badly: Sent ",
             integer_to_list(N), " events in a second, ignoring replies."]};

throttle(Q, N) when N > ?MAX_EVENTS_PER_SECOND ->
    {ok, 1000 div ?MAX_EVENTS_PER_SECOND, Q};

throttle(Q, _N) ->
    {ok, 0, Q}.


%% ---------------------------------------------------------------------
%%
%% Copyright (c) 2007-2013 Basho Technologies, Inc.  All Rights Reserved.
%%
%% 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(list_objects_v2_test).

%% @doc Integration test for list the contents of a bucket

-export([confirm/0]).

confirm() ->
    Config = [{riak, rtcs:ee_config()}, {stanchion, rtcs:stanchion_config()},
              {cs, rtcs:cs_config([{fold_objects_for_list_keys, true}])}],
    {UserConfig, {_RiakNodes, _CSNodes, _Stanchion}} = rtcs:setup(4, Config),
    list_objects_test_helper:test(UserConfig).

Use new riak_test helper API

%% ---------------------------------------------------------------------
%%
%% Copyright (c) 2007-2013 Basho Technologies, Inc.  All Rights Reserved.
%%
%% 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(list_objects_v2_test).

%% @doc Integration test for list the contents of a bucket

-export([confirm/0]).

confirm() ->
    Config = [{riak, rtcs:riak_config()}, {stanchion, rtcs:stanchion_config()},
              {cs, rtcs:cs_config([{fold_objects_for_list_keys, true}])}],
    {UserConfig, {_RiakNodes, _CSNodes, _Stanchion}} = rtcs:setup(4, Config),
    list_objects_test_helper:test(UserConfig).


%%%-------------------------------------------------------------------
%%% File : similar_data.hrl
%%% Author : Nicolas R Dufour <nrdufour@gmail.com>
%%% Created : 2009/05/19
%%% Description :
%%%     Basic record containing the simulation data.
%%%
%%% 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.
%%%-------------------------------------------------------------------

-record(sm_data,
	{

	%%% {EvTree; R;E;Current; RealTime; SList; Trace}

	events = [],
	resources = [],
	processes = [],
	actives = [],
	time = 0,
	props = [],
	trace = false

	}
).

%%%

Add a few comments in the data structure.

%%%-------------------------------------------------------------------
%%% File : similar_data.hrl
%%% Author : Nicolas R Dufour <nrdufour@gmail.com>
%%% Created : 2009/05/19
%%% Description :
%%%     Basic record containing the simulation data.
%%%
%%% 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.
%%%-------------------------------------------------------------------

-record(sm_data,
	{

	%%% {EvTree; R;E;Current; RealTime; SList; Trace}

	%% Events to be scheduled
	events = [],
	%% Resources list
	resources = [],
	%% Alive processes in the simulation
	processes = [],
	%% Active processes in the simulation
	actives = [],
	%% Simulation time
	time = 0,
	%% Properties
	props = [],
	%% Activate the traces or not
	trace = false

	}
).

%%%


-module(main).
-export([start/1]).
-import(conversions, [bitstr_to_list/1, list_to_bitstr/1]).

start([Name]) ->
    random:seed(now()),
    Geno = (one_max:random_genotype_fn([20]))(),
    io:format("~w~nHello ~s!~n", [Geno, Name]).

fetch_fns(Module, Opts) ->
    Rand_gtype = Module:random_genotype_fn(Opts),
    PtoG = Module:phenotype_to_genotype_fn(Opts),
    GtoP = Module:genotype_to_phenotype_fn(Opts),
    Fitness = Module:fitness_fn(Opts),
    Crossfn = Module:crossover_fn(Opts),
    Mutfn = Module:mutation_fn(Opts),
    {rand, Rand_gtype, p_to_g, PtoG, g_to_p, GtoP,
     fitness, Fitness, cross, Crossfn, mut, Mutfn}.

%% (1) choose a genetic representation
%% (2) build a population
%% (3) design a fitness function
%% (4) choose a selection operator
%% (5) choose a recombination operator
%% (6) choose a mutation operator
%% (7) devise a data analysis procedure.

Implement highly abstracted genetic loop.

-module(main).
-export([start/1]).
-import(conversions, [bitstr_to_list/1, list_to_bitstr/1]).

start([Name]) ->
    random:seed(now()),
    Geno = (one_max:random_genotype_fn([20]))(),
    io:format("~w~nHello ~s!~n", [Geno, Name]).
genetica_loop(0, Pop, Develop_and_select) ->
    done;
genetica_loop(Iters, Pop, Develop_and_select) ->
    Newpop = Develop_and_select(Pop),
    genetica_loop(Iters - 1, Newpop, Develop_and_select).

fetch_fns(Module, Opts) ->
    Rand_gtype = Module:random_genotype_fn(Opts),
    PtoG = Module:phenotype_to_genotype_fn(Opts),
    GtoP = Module:genotype_to_phenotype_fn(Opts),
    Fitness = Module:fitness_fn(Opts),
    Crossfn = Module:crossover_fn(Opts),
    Mutfn = Module:mutation_fn(Opts),
    {rand, Rand_gtype, p_to_g, PtoG, g_to_p, GtoP,
     fitness, Fitness, cross, Crossfn, mut, Mutfn}.

%% (1) choose a genetic representation
%% (2) build a population
%% (3) design a fitness function
%% (4) choose a selection operator
%% (5) choose a recombination operator
%% (6) choose a mutation operator
%% (7) devise a data analysis procedure.


%% Feel free to use, reuse and abuse the code in this file.

%% @doc EventSource emitter.
-module(eventsource_handler).

-export([init/2]).
-export([info/3]).

init(Req0, Opts) ->
	Req = cowboy_req:stream_reply(200, #{
		<<"content-type">> => <<"text/event-stream">>
	}, Req0),
	erlang:send_after(1000, self(), {message, "Tick"}),
	{cowboy_loop, Req, Opts}.

info({message, Msg}, Req, State) ->
	cowboy_req:stream_body(["id: ", id(), "\ndata: ", Msg, "\n\n"], nofin, Req),
	erlang:send_after(1000, self(), {message, "Tick"}),
	{ok, Req, State}.

id() ->
	integer_to_list(erlang:unique_integer([positive, monotonic]), 16).

Use cowboy_req:stream_events in the eventsource example

%% Feel free to use, reuse and abuse the code in this file.

%% @doc EventSource emitter.
-module(eventsource_handler).

-export([init/2]).
-export([info/3]).

init(Req0, Opts) ->
	Req = cowboy_req:stream_reply(200, #{
		<<"content-type">> => <<"text/event-stream">>
	}, Req0),
	erlang:send_after(1000, self(), {message, "Tick"}),
	{cowboy_loop, Req, Opts}.

info({message, Msg}, Req, State) ->
	cowboy_req:stream_events(#{
		id => id(),
		data => Msg
	}, nofin, Req),
	erlang:send_after(1000, self(), {message, "Tick"}),
	{ok, Req, State}.

id() ->
	integer_to_list(erlang:unique_integer([positive, monotonic]), 16).


%%% @author Andreas Pauley
%%% @copyright © 2013 Andreas Pauley https://github.com/apauley/erlcdt/blob/master/LICENSE.md
%%% @doc
%%% The definition of the behaviour that erlcdt library implementations should conform to.
%%%
%%% This code is part of the "Erlang Concrete Data Types" library:
%%% https://github.com/apauley/erlcdt
%%% @end
%%% Created : 5 Sct 2013 by Andreas Pauley

-module(erlcdt_parser).

-export([behaviour_info/1]).

behaviour_info(callbacks) ->
  [{from_str,1},
   {to_str, 1}];
behaviour_info(_Other) ->
  undefined.

Change behaviour to -callback attributes

%%% @author Andreas Pauley
%%% @copyright © 2013 Andreas Pauley https://github.com/apauley/erlcdt/blob/master/LICENSE.md
%%% @doc
%%% The definition of the behaviour that erlcdt library implementations should conform to.
%%%
%%% This code is part of the "Erlang Concrete Data Types" library:
%%% https://github.com/apauley/erlcdt
%%% @end
%%% Created : 5 Sct 2013 by Andreas Pauley

-module(erlcdt_parser).

-callback from_str(String :: string()) ->
  {ok, Type :: term()} | {error, Reason :: term()}.

-callback to_str(Type :: term()) ->
  string() | {error, Reason :: term()}.


-module(element_image_test).
-compile([export_all]).

-author("michael@mullistechnologies.com").

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

-include("wf.inc").

new_image_1() ->
  Rec_image = #image{},
  lists:flatten(element_image:render("1",Rec_image)).

new_image_2() ->
  Rec_image = #image{class="t_image"},
  lists:flatten(element_image:render("2",Rec_image)).

new_image_3() ->
  Rec_image = #image{class="t_image", style="color: cyan;", image="http://an_image.com/sample/image.jpg"},
  lists:flatten(element_image:render("3",Rec_image)).

basic_test_() ->
  [?_assertEqual("",new_image_1()),
   ?_assertEqual("",new_image_2()),
   ?_assertEqual("",new_image_3()),
   ?_assertEqual([module,id,actions,show_if,class,style,image],
	 element_image:reflect())
  ].

Update image unit test to account for new 'alt' attribute.

-module(element_image_test).
-compile([export_all]).

-author("michael@mullistechnologies.com").

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

-include("wf.inc").

new_image_1() ->
  Rec_image = #image{},
  lists:flatten(element_image:render("1",Rec_image)).

new_image_2() ->
  Rec_image = #image{class="t_image"},
  lists:flatten(element_image:render("2",Rec_image)).

new_image_3() ->
  Rec_image = #image{class="t_image", style="color: cyan;", image="http://an_image.com/sample/image.jpg"},
  lists:flatten(element_image:render("3",Rec_image)).

basic_test_() ->
  [?_assertEqual("",new_image_1()),
   ?_assertEqual("",new_image_2()),
   ?_assertEqual("",new_image_3()),
   ?_assertEqual([module,id,actions,show_if,class,style,image,alt],
	 element_image:reflect())
  ].


-module(docsh_SUITE).
-compile(export_all).

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

-define(TESTED, example).

-define(eq(Expected, Actual), ?assertEqual(Expected, Actual)).

all() ->
    [edoc_example,
     recon].

%%
%% Tests
%%

edoc_example(C) ->
    h0(C, edoc_example),
    h2(C, edoc_example).

recon(C) ->
    h0(C, recon),
    h2(C, recon).

%%
%% Helpers
%%

h0(_, Module) ->
    code:ensure_loaded(Module),
    ?eq(true, erlang:function_exported(Module, h, 0)),
    ?eq(ok, Module:h()).

h2(_, Module) ->
    code:ensure_loaded(Module),
    ?eq(true, erlang:function_exported(Module, h, 2)),
    {Fun, Arity} = hd(recon:module_info(exports) -- [{h,0}, {h,2}]),
    ?eq(ok, Module:h(Fun, Arity)).

Use more descriptive test names

-module(docsh_SUITE).
-compile(export_all).

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

-define(TESTED, example).

-define(eq(Expected, Actual), ?assertEqual(Expected, Actual)).

all() ->
    [edoc_example_has_helpers,
     recon_has_helpers].

%%
%% Tests
%%

edoc_example_has_helpers(C) ->
    h0(C, edoc_example),
    h2(C, edoc_example).

recon_has_helpers(C) ->
    h0(C, recon),
    h2(C, recon).

%%
%% Helpers
%%

h0(_, Module) ->
    code:ensure_loaded(Module),
    ?eq(true, erlang:function_exported(Module, h, 0)),
    ?eq(ok, Module:h()).

h2(_, Module) ->
    code:ensure_loaded(Module),
    ?eq(true, erlang:function_exported(Module, h, 2)),
    {Fun, Arity} = hd(recon:module_info(exports) -- [{h,0}, {h,2}]),
    ?eq(ok, Module:h(Fun, Arity)).


-module(reia_ssa).
-export([transform/2]).
-include("reia_nodes.hrl").
-include("reia_compile_options.hrl").
-include("reia_bindings.hrl").

% Lists of expressions
transform(Exprs, Options) ->
  {ok, BAExprs} = reia_bindings:transform(Exprs, Options#compile_options.scope),
  reia_bindings:revert(BAExprs).

Handle reverting from binding annotated form in the SSA transform itself

-module(reia_ssa).
-export([transform/2]).
-include("reia_nodes.hrl").
-include("reia_compile_options.hrl").
-include("reia_bindings.hrl").

% Lists of expressions
transform(Exprs, Options) ->
  {ok, BAExprs} = reia_bindings:transform(Exprs, Options#compile_options.scope),
  reia_syntax:map_subtrees(fun transform_node/1, BAExprs).

transform_node(#bindings{node=Node}) ->
  reia_syntax:map_subtrees(fun transform_node/1, Node);
transform_node(Node) ->
  reia_syntax:map_subtrees(fun transform_node/1, Node).